diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.json index dca273456..41d1c3937 100644 --- a/client/scripts/eslint-baseline.json +++ b/client/scripts/eslint-baseline.json @@ -12,7 +12,7 @@ "react-hooks/set-state-in-effect": 188, "@typescript-eslint/no-floating-promises": 162, "react-hooks/exhaustive-deps": 112, - "@typescript-eslint/no-unused-vars": 99, + "@typescript-eslint/no-unused-vars": 95, "react-hooks/immutability": 26, "max-lines-per-function": 126, "react-hooks/static-components": 38, @@ -30,7 +30,7 @@ "no-useless-escape": 1 }, "suppressed": { - "@typescript-eslint/no-explicit-any": 38, + "@typescript-eslint/no-explicit-any": 37, "react-hooks/exhaustive-deps": 44 }, "tests": { diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index 504389679..90b552934 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -456,6 +456,19 @@ describe('App — on-mount effects', () => { await waitFor(() => expect(setManaged).toHaveBeenCalledWith(false)) }) + it("FE-COMP-APP-018d: the operator's map hosts reach the store the map engine reads", async () => { + server.use( + http.get('/api/auth/app-config', () => HttpResponse.json({ map_extra_connect_hosts: ['tiles.example.com'] })) + ) + useAuthStore.setState({ + isLoading: false, + isAuthenticated: false, + loadUser: vi.fn().mockResolvedValue(undefined), + }) + renderApp('/') + await waitFor(() => expect(useAuthStore.getState().mapExtraConnectHosts).toEqual(['tiles.example.com'])) + }) + it('FE-COMP-APP-018c: app-config is asked again after a failed answer, so managed is not lost', async () => { // A page opened while the server restarts got a 502 here and kept every // default for the session, which brought back the operator's settings. diff --git a/client/src/App.tsx b/client/src/App.tsx index f4f474b23..6e1a76e4f 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -372,7 +372,7 @@ export default function App() { }, Math.min(30_000, 1_000 * 2 ** attempt)) }) }) - fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; atlas_compare_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record }) => { + fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; map_extra_connect_hosts?: string[]; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; atlas_compare_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record }) => { setManaged(!!config?.managed) setDemoMode(!!config?.demo_mode) if (config?.dev_mode) setDevMode(true) @@ -380,6 +380,7 @@ export default function App() { if (config?.version) setAppVersion(config.version) if (config?.has_maps_key !== undefined) setHasMapsKey(config.has_maps_key) if (config?.has_amap_key !== undefined) setHasAmapKey(config.has_amap_key) + if (Array.isArray(config?.map_extra_connect_hosts)) useAuthStore.getState().setMapExtraConnectHosts(config.map_extra_connect_hosts) if (config?.places_provider) setPlacesProvider(config.places_provider) if (config?.timezone) setServerTimezone(config.timezone) if (config?.require_mfa !== undefined) setAppRequireMfa(!!config.require_mfa) diff --git a/client/src/components/Journey/JourneyMap.tsx b/client/src/components/Journey/JourneyMap.tsx index 6119871a6..c8bafdd06 100644 --- a/client/src/components/Journey/JourneyMap.tsx +++ b/client/src/components/Journey/JourneyMap.tsx @@ -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. diff --git a/client/src/components/Journey/JourneyMapAuto.tsx b/client/src/components/Journey/JourneyMapAuto.tsx index 654f652af..b02024ef3 100644 --- a/client/src/components/Journey/JourneyMapAuto.tsx +++ b/client/src/components/Journey/JourneyMapAuto.tsx @@ -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(null) const glRef = useRef(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 = // 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 - }> - - {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */} - - - - ) - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return + return ( + <> + {useGL ? ( + // 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 */} + + + + ) : leaflet} + + + ) } export default JourneyMapAuto diff --git a/client/src/components/Journey/JourneyMapGL.test.tsx b/client/src/components/Journey/JourneyMapGL.test.tsx index 31934a8a3..4ae1e29f9 100644 --- a/client/src/components/Journey/JourneyMapGL.test.tsx +++ b/client/src/components/Journey/JourneyMapGL.test.tsx @@ -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() + const options = vi.mocked(maplibregl.Map).mock.calls[0][0] as unknown as Record + 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() diff --git a/client/src/components/Journey/JourneyMapGL.tsx b/client/src/components/Journey/JourneyMapGL.tsx index f88fd0e04..153c6b50b 100644 --- a/client/src/components/Journey/JourneyMapGL.tsx +++ b/client/src/components/Journey/JourneyMapGL.tsx @@ -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(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(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 diff --git a/client/src/components/Map/BasemapPill.tsx b/client/src/components/Map/BasemapPill.tsx new file mode 100644 index 000000000..1a523463f --- /dev/null +++ b/client/src/components/Map/BasemapPill.tsx @@ -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 ( + + ); + } + const Icon = state.kind === 'classic' ? Layers : CloudOff; + return ( +
+
+ ); +} diff --git a/client/src/components/Map/MapViewAuto.tsx b/client/src/components/Map/MapViewAuto.tsx index 57f5ca0ac..f71e40723 100644 --- a/client/src/components/Map/MapViewAuto.tsx +++ b/client/src/components/Map/MapViewAuto.tsx @@ -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' - ? ( - - ) - : pillState && + const pill = // 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 ( - - ) - } - return ( -
-
- ) -} diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index bebf2672c..860359857 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -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(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({ diff --git a/client/src/components/Map/basemapSpec.test.ts b/client/src/components/Map/basemapSpec.test.ts index 1f52aa2ce..372142bc2 100644 --- a/client/src/components/Map/basemapSpec.test.ts +++ b/client/src/components/Map/basemapSpec.test.ts @@ -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); + }); +}); diff --git a/client/src/components/Map/basemapSpec.ts b/client/src/components/Map/basemapSpec.ts index d68442d18..ee4e164aa 100644 --- a/client/src/components/Map/basemapSpec.ts +++ b/client/src/components/Map/basemapSpec.ts @@ -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)); + }); +} diff --git a/client/src/components/Map/glBasemap.test.ts b/client/src/components/Map/glBasemap.test.ts new file mode 100644 index 000000000..29b3cd950 --- /dev/null +++ b/client/src/components/Map/glBasemap.test.ts @@ -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); + }); +}); diff --git a/client/src/components/Map/glBasemap.ts b/client/src/components/Map/glBasemap.ts new file mode 100644 index 000000000..a9e7537c7 --- /dev/null +++ b/client/src/components/Map/glBasemap.ts @@ -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): 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 }; +} diff --git a/client/src/components/Map/glLazy.tsx b/client/src/components/Map/glLazy.tsx index 3207bc48b..789a238cd 100644 --- a/client/src/components/Map/glLazy.tsx +++ b/client/src/components/Map/glLazy.tsx @@ -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 } /** diff --git a/client/src/components/Map/glMapOptions.test.ts b/client/src/components/Map/glMapOptions.test.ts index 7a253110a..084c00b96 100644 --- a/client/src/components/Map/glMapOptions.test.ts +++ b/client/src/components/Map/glMapOptions.test.ts @@ -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); diff --git a/client/src/components/Map/glMapOptions.ts b/client/src/components/Map/glMapOptions.ts index c3e1f04e8..548554d38 100644 --- a/client/src/components/Map/glMapOptions.ts +++ b/client/src/components/Map/glMapOptions.ts @@ -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 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 * 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); diff --git a/client/src/components/Map/glProviders.test.ts b/client/src/components/Map/glProviders.test.ts index 899c9f83a..3524c5fe9 100644 --- a/client/src/components/Map/glProviders.test.ts +++ b/client/src/components/Map/glProviders.test.ts @@ -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) + }) }) diff --git a/client/src/components/Map/glProviders.ts b/client/src/components/Map/glProviders.ts index 3cf5c3825..d483c11b6 100644 --- a/client/src/components/Map/glProviders.ts +++ b/client/src/components/Map/glProviders.ts @@ -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' diff --git a/client/src/components/Map/glSupport.test.ts b/client/src/components/Map/glSupport.test.ts index 31238012b..bd7ed4aed 100644 --- a/client/src/components/Map/glSupport.test.ts +++ b/client/src/components/Map/glSupport.test.ts @@ -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', () => { diff --git a/client/src/components/Map/glSupport.ts b/client/src/components/Map/glSupport.ts index 93a42a11d..03a91a87e 100644 --- a/client/src/components/Map/glSupport.ts +++ b/client/src/components/Map/glSupport.ts @@ -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(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(construct: () => T): T | null { +export function buildGlMap(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; diff --git a/client/src/components/Map/mapViewContract.ts b/client/src/components/Map/mapViewContract.ts index d5566df8a..c4e77dd39 100644 --- a/client/src/components/Map/mapViewContract.ts +++ b/client/src/components/Map/mapViewContract.ts @@ -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; /** diff --git a/client/src/components/Map/mapboxSetup.ts b/client/src/components/Map/mapboxSetup.ts index a77fa2d03..35aaca8fb 100644 --- a/client/src/components/Map/mapboxSetup.ts +++ b/client/src/components/Map/mapboxSetup.ts @@ -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' } diff --git a/client/src/components/Map/offlineBasemap.test.ts b/client/src/components/Map/offlineBasemap.test.ts index 873e2e642..665d59b84 100644 --- a/client/src/components/Map/offlineBasemap.test.ts +++ b/client/src/components/Map/offlineBasemap.test.ts @@ -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); + }); }); diff --git a/client/src/components/Map/offlineBasemap.ts b/client/src/components/Map/offlineBasemap.ts index 89ac0f0cc..3313dd1a9 100644 --- a/client/src/components/Map/offlineBasemap.ts +++ b/client/src/components/Map/offlineBasemap.ts @@ -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)); } /** diff --git a/client/src/components/Map/rasterHealth.test.ts b/client/src/components/Map/rasterHealth.test.ts new file mode 100644 index 000000000..4b76cc102 --- /dev/null +++ b/client/src/components/Map/rasterHealth.test.ts @@ -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 = {}; + 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); + }); +}); diff --git a/client/src/components/Map/rasterHealth.ts b/client/src/components/Map/rasterHealth.ts new file mode 100644 index 000000000..61656e10b --- /dev/null +++ b/client/src/components/Map/rasterHealth.ts @@ -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(); +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 | 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++; +} diff --git a/client/src/components/Map/useEffectiveMapEngine.test.ts b/client/src/components/Map/useEffectiveMapEngine.test.ts index 344d84f05..d363791fa 100644 --- a/client/src/components/Map/useEffectiveMapEngine.test.ts +++ b/client/src/components/Map/useEffectiveMapEngine.test.ts @@ -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 }).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' }, + }); + }); + }); +}); diff --git a/client/src/components/Map/useEffectiveMapEngine.ts b/client/src/components/Map/useEffectiveMapEngine.ts index 95559283b..1d9e26b36 100644 --- a/client/src/components/Map/useEffectiveMapEngine.ts +++ b/client/src/components/Map/useEffectiveMapEngine.ts @@ -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 +): { 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 }; +} diff --git a/client/src/components/Map/useGlStyle.ts b/client/src/components/Map/useGlStyle.ts new file mode 100644 index 000000000..854352504 --- /dev/null +++ b/client/src/components/Map/useGlStyle.ts @@ -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); +} diff --git a/client/src/store/authStore.ts b/client/src/store/authStore.ts index 9d17a0994..320ca39e1 100644 --- a/client/src/store/authStore.ts +++ b/client/src/store/authStore.ts @@ -64,6 +64,9 @@ interface AuthState { * into one "has a search key": which of the two is missing decides what the * admin has to go and do. */ hasAmapKey: boolean + /** The operator's own map hosts (MAP_EXTRA_CONNECT_HOSTS), which the CSP lets a + * GL map fetch from beside the shipped ones; empty until app-config answers. */ + mapExtraConnectHosts: string[] /** The admin's places provider choice, as app-config normalises it: 'auto', * 'google', 'amap' or 'openstreetmap'. Read with hasMapsKey to tell whether * a search can reach Google at all (utils/placeSource googleHoldsSlot). */ @@ -101,6 +104,7 @@ interface AuthState { setAppVersion: (val: string) => void setHasMapsKey: (val: boolean) => void setHasAmapKey: (val: boolean) => void + setMapExtraConnectHosts: (hosts: string[]) => void setPlacesProvider: (val: string) => void setServerTimezone: (tz: string) => void setAppRequireMfa: (val: boolean) => void @@ -158,6 +162,7 @@ export const useAuthStore = create()( appVersion: '', hasMapsKey: false, hasAmapKey: false, + mapExtraConnectHosts: [], placesProvider: 'auto', serverTimezone: browserTimeZone() ?? '', appRequireMfa: false, @@ -447,6 +452,7 @@ export const useAuthStore = create()( setAppVersion: (val: string) => set({ appVersion: val }), setHasMapsKey: (val: boolean) => set({ hasMapsKey: val }), setHasAmapKey: (val: boolean) => set({ hasAmapKey: val }), + setMapExtraConnectHosts: (hosts: string[]) => set({ mapExtraConnectHosts: hosts }), setPlacesProvider: (val: string) => set({ placesProvider: val }), setServerTimezone: (tz: string) => set({ serverTimezone: tz }), setAppRequireMfa: (val: boolean) => set({ appRequireMfa: val }), diff --git a/shared/src/i18n/ar/map.ts b/shared/src/i18n/ar/map.ts index f9b3b5251..8f85c3ef0 100644 --- a/shared/src/i18n/ar/map.ts +++ b/shared/src/i18n/ar/map.ts @@ -58,5 +58,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'يحتاج العرض ثلاثي الأبعاد إلى WebGL2، وهذا المتصفح لا يوفّره. تبقى الخريطة ثنائية الأبعاد.', 'map.offlineBasemap': 'خريطة دون اتصال', 'map.offlineShowStored': 'عرض الخريطة دون اتصال', + 'map.templateClassic': 'قالب الخريطة بعرض ثنائي الأبعاد كلاسيكي', }; export default map; diff --git a/shared/src/i18n/az/map.ts b/shared/src/i18n/az/map.ts index bd4c34188..e6fbc00eb 100644 --- a/shared/src/i18n/az/map.ts +++ b/shared/src/i18n/az/map.ts @@ -56,6 +56,7 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D üçün WebGL2 lazımdır, bu brauzer isə onu təqdim etmir. Xəritə 2D olaraq qalır.', 'map.offlineBasemap': 'Oflayn xəritə', 'map.offlineShowStored': 'Oflayn xəritəni göstər', + 'map.templateClassic': 'Xəritə şablonu klassik 2D-də', }; export default map; diff --git a/shared/src/i18n/br/map.ts b/shared/src/i18n/br/map.ts index 362c0cc87..f85ffa041 100644 --- a/shared/src/i18n/br/map.ts +++ b/shared/src/i18n/br/map.ts @@ -53,5 +53,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'O 3D precisa de WebGL2, que este navegador não oferece. O mapa continua em 2D.', 'map.offlineBasemap': 'Mapa offline', 'map.offlineShowStored': 'Mostrar mapa offline', + 'map.templateClassic': 'Modelo de mapa no 2D clássico', }; export default map; diff --git a/shared/src/i18n/ca/map.ts b/shared/src/i18n/ca/map.ts index 7e667fbec..6f2088539 100644 --- a/shared/src/i18n/ca/map.ts +++ b/shared/src/i18n/ca/map.ts @@ -51,5 +51,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'El 3D necessita WebGL2, que aquest navegador no ofereix. El mapa es queda en 2D.', 'map.offlineBasemap': 'Mapa fora de línia', 'map.offlineShowStored': 'Mostra el mapa fora de línia', + 'map.templateClassic': 'Plantilla del mapa en 2D clàssic', }; export default map; diff --git a/shared/src/i18n/cs/map.ts b/shared/src/i18n/cs/map.ts index 5f63bffe6..5a0258233 100644 --- a/shared/src/i18n/cs/map.ts +++ b/shared/src/i18n/cs/map.ts @@ -52,5 +52,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D potřebuje WebGL2, které tento prohlížeč nenabízí. Mapa zůstává ve 2D.', 'map.offlineBasemap': 'Offline mapa', 'map.offlineShowStored': 'Zobrazit offline mapu', + 'map.templateClassic': 'Šablona mapy v klasickém 2D', }; export default map; diff --git a/shared/src/i18n/de/map.ts b/shared/src/i18n/de/map.ts index 813754d24..e2b3ae25b 100644 --- a/shared/src/i18n/de/map.ts +++ b/shared/src/i18n/de/map.ts @@ -53,5 +53,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D braucht WebGL2, das dieser Browser nicht bietet. Die Karte bleibt in 2D.', 'map.offlineBasemap': 'Offline-Karte', 'map.offlineShowStored': 'Offline-Karte zeigen', + 'map.templateClassic': 'Karten-Vorlage in klassischem 2D', }; export default map; diff --git a/shared/src/i18n/en/map.ts b/shared/src/i18n/en/map.ts index fdfe8bddf..c17f35fc1 100644 --- a/shared/src/i18n/en/map.ts +++ b/shared/src/i18n/en/map.ts @@ -51,5 +51,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D needs WebGL2, which this browser does not offer. The map stays in 2D.', 'map.offlineBasemap': 'Offline map', 'map.offlineShowStored': 'Show offline map', + 'map.templateClassic': 'Map template in classic 2D', }; export default map; diff --git a/shared/src/i18n/es/map.ts b/shared/src/i18n/es/map.ts index cf44acd22..ed44fa0b6 100644 --- a/shared/src/i18n/es/map.ts +++ b/shared/src/i18n/es/map.ts @@ -50,5 +50,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'El 3D necesita WebGL2, que este navegador no ofrece. El mapa se queda en 2D.', 'map.offlineBasemap': 'Mapa sin conexión', 'map.offlineShowStored': 'Mostrar mapa sin conexión', + 'map.templateClassic': 'Plantilla del mapa en 2D clásico', }; export default map; diff --git a/shared/src/i18n/et/map.ts b/shared/src/i18n/et/map.ts index c9bcc0b53..ea5915971 100644 --- a/shared/src/i18n/et/map.ts +++ b/shared/src/i18n/et/map.ts @@ -49,5 +49,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D vajab WebGL2-te, mida see brauser ei paku. Kaart jääb 2D-vaatesse.', 'map.offlineBasemap': 'Võrguühenduseta kaart', 'map.offlineShowStored': 'Näita võrguühenduseta kaarti', + 'map.templateClassic': 'Kaardimall klassikalises 2D-s', }; export default map; diff --git a/shared/src/i18n/fr/map.ts b/shared/src/i18n/fr/map.ts index 195acb596..e794aedf4 100644 --- a/shared/src/i18n/fr/map.ts +++ b/shared/src/i18n/fr/map.ts @@ -52,5 +52,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'La 3D nécessite WebGL2, que ce navigateur ne propose pas. La carte reste en 2D.', 'map.offlineBasemap': 'Carte hors ligne', 'map.offlineShowStored': 'Afficher la carte hors ligne', + 'map.templateClassic': 'Modèle de carte en 2D classique', }; export default map; diff --git a/shared/src/i18n/gr/map.ts b/shared/src/i18n/gr/map.ts index 17b6fd33e..9fb0ccf21 100644 --- a/shared/src/i18n/gr/map.ts +++ b/shared/src/i18n/gr/map.ts @@ -52,5 +52,6 @@ const map: TranslationStrings = { 'Το 3D χρειάζεται WebGL2, που αυτό το πρόγραμμα περιήγησης δεν προσφέρει. Ο χάρτης μένει σε 2D.', 'map.offlineBasemap': 'Χάρτης εκτός σύνδεσης', 'map.offlineShowStored': 'Εμφάνιση χάρτη εκτός σύνδεσης', + 'map.templateClassic': 'Πρότυπο χάρτη σε κλασικό 2D', }; export default map; diff --git a/shared/src/i18n/he/map.ts b/shared/src/i18n/he/map.ts index 931f62cdb..fa41cb832 100644 --- a/shared/src/i18n/he/map.ts +++ b/shared/src/i18n/he/map.ts @@ -51,6 +51,7 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'תלת-ממד דורש WebGL2, והדפדפן הזה לא תומך בו. המפה נשארת בדו-ממד.', 'map.offlineBasemap': 'מפה לא מקוונת', 'map.offlineShowStored': 'הצגת מפה לא מקוונת', + 'map.templateClassic': 'תבנית המפה בתצוגת 2D קלאסית', }; export default map; diff --git a/shared/src/i18n/hu/map.ts b/shared/src/i18n/hu/map.ts index 1f8c9574e..573625a9c 100644 --- a/shared/src/i18n/hu/map.ts +++ b/shared/src/i18n/hu/map.ts @@ -50,5 +50,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'A 3D-hez WebGL2 kell, amelyet ez a böngésző nem kínál. A térkép 2D-ben marad.', 'map.offlineBasemap': 'Offline térkép', 'map.offlineShowStored': 'Offline térkép megjelenítése', + 'map.templateClassic': 'Térkép sablon klasszikus 2D-ben', }; export default map; diff --git a/shared/src/i18n/id/map.ts b/shared/src/i18n/id/map.ts index 8304d573f..480623852 100644 --- a/shared/src/i18n/id/map.ts +++ b/shared/src/i18n/id/map.ts @@ -49,5 +49,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D membutuhkan WebGL2, yang tidak disediakan browser ini. Peta tetap dalam 2D.', 'map.offlineBasemap': 'Peta offline', 'map.offlineShowStored': 'Tampilkan peta offline', + 'map.templateClassic': 'Template peta dalam 2D klasik', }; export default map; diff --git a/shared/src/i18n/it/map.ts b/shared/src/i18n/it/map.ts index 8a01dfcd3..e4122422b 100644 --- a/shared/src/i18n/it/map.ts +++ b/shared/src/i18n/it/map.ts @@ -53,5 +53,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'Il 3D richiede WebGL2, che questo browser non offre. La mappa resta in 2D.', 'map.offlineBasemap': 'Mappa offline', 'map.offlineShowStored': 'Mostra mappa offline', + 'map.templateClassic': 'Modello mappa in 2D classico', }; export default map; diff --git a/shared/src/i18n/ja/map.ts b/shared/src/i18n/ja/map.ts index a9ba3b030..e2b0021f9 100644 --- a/shared/src/i18n/ja/map.ts +++ b/shared/src/i18n/ja/map.ts @@ -49,5 +49,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D には WebGL2 が必要ですが、このブラウザーは対応していません。地図は 2D のままです。', 'map.offlineBasemap': 'オフライン地図', 'map.offlineShowStored': 'オフライン地図を表示', + 'map.templateClassic': '地図テンプレートをクラシック 2D で表示', }; export default map; diff --git a/shared/src/i18n/ko/map.ts b/shared/src/i18n/ko/map.ts index 25fa76568..5f06e7e67 100644 --- a/shared/src/i18n/ko/map.ts +++ b/shared/src/i18n/ko/map.ts @@ -48,5 +48,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D에는 WebGL2가 필요하지만 이 브라우저는 지원하지 않습니다. 지도는 2D로 유지됩니다.', 'map.offlineBasemap': '오프라인 지도', 'map.offlineShowStored': '오프라인 지도 보기', + 'map.templateClassic': '지도 템플릿을 클래식 2D로 표시', }; export default map; diff --git a/shared/src/i18n/nl/map.ts b/shared/src/i18n/nl/map.ts index 5840664cb..778bef3a8 100644 --- a/shared/src/i18n/nl/map.ts +++ b/shared/src/i18n/nl/map.ts @@ -52,5 +52,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D heeft WebGL2 nodig, dat deze browser niet biedt. De kaart blijft in 2D.', 'map.offlineBasemap': 'Offline kaart', 'map.offlineShowStored': 'Offline kaart tonen', + 'map.templateClassic': 'Kaartsjabloon in klassiek 2D', }; export default map; diff --git a/shared/src/i18n/pl/map.ts b/shared/src/i18n/pl/map.ts index 26be7e1f5..87626bdee 100644 --- a/shared/src/i18n/pl/map.ts +++ b/shared/src/i18n/pl/map.ts @@ -55,5 +55,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'Tryb 3D wymaga WebGL2, którego ta przeglądarka nie obsługuje. Mapa pozostaje w 2D.', 'map.offlineBasemap': 'Mapa offline', 'map.offlineShowStored': 'Pokaż mapę offline', + 'map.templateClassic': 'Szablon mapy w klasycznym 2D', }; export default map; diff --git a/shared/src/i18n/ru/map.ts b/shared/src/i18n/ru/map.ts index 4a4b6cd13..96072709c 100644 --- a/shared/src/i18n/ru/map.ts +++ b/shared/src/i18n/ru/map.ts @@ -56,5 +56,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'Для 3D нужен WebGL2, а этот браузер его не поддерживает. Карта остаётся в 2D.', 'map.offlineBasemap': 'Офлайн-карта', 'map.offlineShowStored': 'Показать офлайн-карту', + 'map.templateClassic': 'Шаблон карты в классическом 2D', }; export default map; diff --git a/shared/src/i18n/sk/map.ts b/shared/src/i18n/sk/map.ts index 68272b85f..b39309c70 100644 --- a/shared/src/i18n/sk/map.ts +++ b/shared/src/i18n/sk/map.ts @@ -52,5 +52,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D potrebuje WebGL2, ktoré tento prehliadač neponúka. Mapa zostáva v 2D.', 'map.offlineBasemap': 'Offline mapa', 'map.offlineShowStored': 'Zobraziť offline mapu', + 'map.templateClassic': 'Šablóna mapy v klasickom 2D', }; export default map; diff --git a/shared/src/i18n/sv/map.ts b/shared/src/i18n/sv/map.ts index aebedf289..08d1f1a8a 100644 --- a/shared/src/i18n/sv/map.ts +++ b/shared/src/i18n/sv/map.ts @@ -50,5 +50,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D kräver WebGL2, som den här webbläsaren inte erbjuder. Kartan stannar i 2D.', 'map.offlineBasemap': 'Offlinekarta', 'map.offlineShowStored': 'Visa offlinekarta', + 'map.templateClassic': 'Kartmall i klassisk 2D', }; export default map; diff --git a/shared/src/i18n/th/map.ts b/shared/src/i18n/th/map.ts index 8e75cb5d8..53de7c906 100644 --- a/shared/src/i18n/th/map.ts +++ b/shared/src/i18n/th/map.ts @@ -47,5 +47,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'โหมด 3D ต้องใช้ WebGL2 ซึ่งเบราว์เซอร์นี้ไม่รองรับ แผนที่จึงยังคงเป็น 2D', 'map.offlineBasemap': 'แผนที่ออฟไลน์', 'map.offlineShowStored': 'แสดงแผนที่ออฟไลน์', + 'map.templateClassic': 'แม่แบบแผนที่แบบ 2D คลาสสิก', }; export default map; diff --git a/shared/src/i18n/tr/map.ts b/shared/src/i18n/tr/map.ts index bece92017..26efedecc 100644 --- a/shared/src/i18n/tr/map.ts +++ b/shared/src/i18n/tr/map.ts @@ -50,5 +50,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D için WebGL2 gerekir, bu tarayıcı ise onu sunmuyor. Harita 2D olarak kalır.', 'map.offlineBasemap': 'Çevrimdışı harita', 'map.offlineShowStored': 'Çevrimdışı haritayı göster', + 'map.templateClassic': 'Klasik 2D harita şablonu', }; export default map; diff --git a/shared/src/i18n/uk/map.ts b/shared/src/i18n/uk/map.ts index a0c5d97a5..086d20366 100644 --- a/shared/src/i18n/uk/map.ts +++ b/shared/src/i18n/uk/map.ts @@ -54,5 +54,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'Для 3D потрібен WebGL2, а цей браузер його не підтримує. Карта залишається у 2D.', 'map.offlineBasemap': 'Офлайн-карта', 'map.offlineShowStored': 'Показати офлайн-карту', + 'map.templateClassic': 'Шаблон карти в класичному 2D', }; export default map; diff --git a/shared/src/i18n/vi/map.ts b/shared/src/i18n/vi/map.ts index 42ec11251..f419661df 100644 --- a/shared/src/i18n/vi/map.ts +++ b/shared/src/i18n/vi/map.ts @@ -50,5 +50,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': 'Chế độ 3D cần WebGL2, nhưng trình duyệt này không hỗ trợ. Bản đồ vẫn ở dạng 2D.', 'map.offlineBasemap': 'Bản đồ ngoại tuyến', 'map.offlineShowStored': 'Hiện bản đồ ngoại tuyến', + 'map.templateClassic': 'Mẫu bản đồ ở chế độ 2D cổ điển', }; export default map; diff --git a/shared/src/i18n/zh-TW/map.ts b/shared/src/i18n/zh-TW/map.ts index 47ca8afba..403f5ab50 100644 --- a/shared/src/i18n/zh-TW/map.ts +++ b/shared/src/i18n/zh-TW/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D 需要 WebGL2,而此瀏覽器不支援。地圖維持 2D。', 'map.offlineBasemap': '離線地圖', 'map.offlineShowStored': '顯示離線地圖', + 'map.templateClassic': '地圖模板以經典 2D 顯示', }; export default map; diff --git a/shared/src/i18n/zh/map.ts b/shared/src/i18n/zh/map.ts index 4ad60814b..e791b41b5 100644 --- a/shared/src/i18n/zh/map.ts +++ b/shared/src/i18n/zh/map.ts @@ -46,5 +46,6 @@ const map: TranslationStrings = { 'map.webgl2.terrain': '3D 需要 WebGL2,而此浏览器不支持。地图保持 2D。', 'map.offlineBasemap': '离线地图', 'map.offlineShowStored': '显示离线地图', + 'map.templateClassic': '地图模板以经典 2D 显示', }; export default map;