fix(maps): default the Leaflet basemap to OpenFreeMap

CARTO started stamping "API KEY REQUIRED" across every keyless basemap tile
on 26.08.2026. #2060 added a key field as the immediate answer, but it leaves
a self-hosted instance needing an email exchange with CARTO before its maps
look right, and every default in the client still pointed at CARTO. Default
to OpenFreeMap Positron instead: no key, no account, no request limit,
commercial use allowed, attribution required.

OpenFreeMap serves vector tiles only, so the Leaflet basemap is a MapLibre
style document rather than an XYZ template. maplibre-gl-leaflet hangs a GL
canvas into Leaflet's own tile pane, which leaves everything above it alone -
markers, GeoJSON, clusters, plugin layers, the custom panes, and the click
handling, since Leaflet's CSS already puts pointer-events:none on that layer.
maplibre-gl still arrives only through a dynamic import, so no chunk that
draws a map grows by a megabyte.

Switched: the trip planner, the MapView fallback every preview goes through,
the journey map, collections, the atlas, the shared trip page and the offline
tile prefetch. OpenFreeMap Positron and Bright join the tile presets in
settings, the admin defaults and both mobile screens.

A CARTO template that is already saved keeps working when a key backs it -
that stays a supported choice. Without a key it is not drawn at all:
resolveTileUrl falls back to the default rather than to a watermark, so an
instance that upgrades with one in its settings sees the new basemap
immediately and needs no migration. The stored value is left as it is, so the
Map settings tab still shows what was chosen and the warning underneath it
explains why - one sentence appended, in all 23 locales.

OpenFreeMap asks for a credit of its own; OpenStreetMap alone under its tiles
is wrong and a licence problem. attributionForTile() derives it from the URL
rather than from a flag at each call site, and the shared trip map, which
carried no attribution at all, now gets one.

Offline maps keep working and get cheaper. A vector style is four things
instead of one, so sync/glPrefetcher.ts walks the style document, its sprite,
the Latin glyph ranges of each font stack it uses, the TileJSON - the planet
path is versioned, so guessing it answers 200 with an empty body - and then
the .pbf tiles. Over the Berlin bounding box TREK computes, raster z10-16 is
2237 requests and 34.6 MB and gives up above z16; vector z10-14 is 177
requests and 32.1 MB and stays sharp above that, because MapLibre scales the
z14 tile rather than asking for another. The Workbox rule for
tiles.openfreemap.org moves to CacheFirst and shares the prefetcher's cache,
so browsing tops a downloaded region up instead of filling a second copy
beside it - a versioned tile path can never be stale. Clearing offline maps
clears it too.

The atlas loses its second raster layer. It existed to warm the HTTP cache of
neighbouring zoom levels, which a vector basemap does not need; a second one
would only cost a second WebGL context. OpenFreeMap has no label-free style,
so its labels are switched off on the live map instead - they are all symbol
layers, while borders and coastlines are line and fill - re-armed on
style.load so a theme switch keeps them off.

Theme changes call setStyle in place rather than rebuilding the layer: a swap
per toggle would leak a WebGL context, and browsers cap those in the low
teens.
This commit is contained in:
Maurice
2026-08-29 00:02:12 +02:00
committed by Maurice
parent 1d12535b1b
commit b401da2264
53 changed files with 1342 additions and 168 deletions
+19
View File
@@ -9,6 +9,7 @@ import { buildUser, buildSettings } from '../../tests/helpers/factories';
import { useAuthStore } from '../store/authStore';
import { useSettingsStore } from '../store/settingsStore';
import AtlasPage from './AtlasPage';
import { maplibreGL } from '@maplibre/maplibre-gl-leaflet';
// ── Captured style() results, for tests asserting fill/border on a specific
// feature (e.g. the wishlist hatch pattern) without duplicating the mock's
@@ -16,6 +17,24 @@ import AtlasPage from './AtlasPage';
const { capturedStyles } = vi.hoisted(() => ({ capturedStyles: [] as { feature: any; result: any }[] }));
// ── Leaflet mock ──────────────────────────────────────────────────────────────
// maplibre-gl-leaflet hangs the vector basemap into Leaflet's tile pane. The mock
// only has to be callable and hand back a layer with the three methods the callers
// use, since nothing here renders WebGL.
vi.mock('@maplibre/maplibre-gl-leaflet', () => ({
maplibreGL: vi.fn(() => {
// One GL map per layer, kept stable: a fresh object per call would hand the
// assertions a different spy than the code just used.
const gl = {
setStyle: vi.fn(), on: vi.fn(), isStyleLoaded: () => false,
getStyle: () => ({ layers: [] }), setLayoutProperty: vi.fn(),
}
const layer: Record<string, unknown> = { remove: vi.fn(), getMaplibreMap: vi.fn(() => gl) }
layer.addTo = vi.fn(() => layer)
return layer
}),
}));
vi.mock('../components/Map/engines/maplibre', () => ({ default: {} }));
vi.mock('leaflet', () => {
// Mock layer returned by onEachFeature — supports event registration
const makeMockLayer = () => {
+25 -1
View File
@@ -14,7 +14,7 @@ vi.mock('react-leaflet', () => ({
MapContainer: ({ children }: { children: React.ReactNode }) => (
<div data-testid="map-container">{children}</div>
),
TileLayer: () => null,
TileLayer: ({ url }: { url: string }) => <div data-testid="raster-tiles" data-url={url} />,
Marker: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
Polyline: () => <div data-testid="route-line" />,
Tooltip: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
@@ -24,6 +24,13 @@ vi.mock('react-leaflet', () => ({
}),
}));
// The basemap is a MapLibre style now, and the real component reaches for
// maplibre-gl through a dynamic import. The page test only cares that it is the
// thing being rendered.
vi.mock('../components/Map/VectorBasemap', () => ({
default: ({ style }: { style: string }) => <div data-testid="vector-basemap" data-style={style} />,
}));
vi.mock('leaflet', () => {
const L = {
divIcon: vi.fn(() => ({})),
@@ -931,6 +938,23 @@ describe('SharedTripPage', () => {
});
});
describe('FE-PAGE-SHARED-041: a share link visitor gets a basemap that needs no key', () => {
const louvre = { id: 201, name: 'Louvre', lat: 48.86, lng: 2.33, category: null };
it('draws the OpenFreeMap style rather than raster tiles', async () => {
// A visitor has no settings of their own, so the map falls back to the app
// default. CARTO stamps "API KEY REQUIRED" over keyless tiles since
// 26.08.2026, and a share link is exactly where nobody has a key.
await open('basemap-token', payload({ days: [], places: [louvre], assignments: {} }));
expect(screen.getByTestId('vector-basemap')).toHaveAttribute(
'data-style',
'https://tiles.openfreemap.org/styles/positron',
);
expect(screen.queryByTestId('raster-tiles')).toBeNull();
});
});
describe('FE-PAGE-SHARED-040: trip-wide markers keep their category colour', () => {
// The payload nests the category on a day's assignments but sends it flat on the
// trip-wide pool, so reading only the nested shape painted every marker indigo.
+18 -9
View File
@@ -19,7 +19,8 @@ import { createElement, useEffect, useRef } from 'react';
import { renderIconMarkup } from '../utils/iconMarkup';
import { MapContainer, Marker, Polyline, TileLayer, Tooltip, useMap } from 'react-leaflet';
import { getCategoryIcon } from '../components/shared/categoryIcons';
import { CARTO_LIGHT, DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../constants/mapDefaults';
import { OFM_POSITRON, DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, attributionForTile } from '../constants/mapDefaults';
import VectorBasemap from '../components/Map/VectorBasemap';
import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n';
import { useSettingsStore } from '../store/settingsStore';
import { avatarSrc } from '../utils/avatarSrc';
@@ -29,7 +30,7 @@ import { isDayInAccommodationRange } from '../utils/dayOrder';
import { getFlightLegs, getTrainLegs } from '../utils/flightLegs';
import { splitReservationDateTime } from '../utils/formatters';
import { computeMapViewport, TILE_SIZE_RASTER } from '../utils/mapViewport';
import { resolveTileUrl } from '../utils/tileUrl';
import { resolveBasemap } from '../utils/tileUrl';
import { useSharedTrip } from './sharedTrip/useSharedTrip';
const TRANSPORT_ICONS = { flight: Plane, train: Train, bus: Bus, car: Car, cruise: Ship };
@@ -185,9 +186,12 @@ export default function SharedTripPage() {
});
const initialView = framed ?? { center: DEFAULT_MAP_CENTER, zoom: DEFAULT_MAP_ZOOM };
// A visitor of a share link has no settings of their own, so the key travels in
// the payload; without it CARTO stamps "API KEY REQUIRED" across every tile.
const tileUrl = resolveTileUrl(null, CARTO_LIGHT, cartoApiKey);
// A visitor of a share link has no settings of their own, so the basemap is the
// app default: OpenFreeMap, a vector style that needs no key at all. The owner's
// CARTO key still travels in the payload and is still applied, because the
// fallback is only a fallback — a raster template reaching this page keeps
// working, and without the key CARTO would stamp "API KEY REQUIRED" over it.
const basemap = resolveBasemap(null, OFM_POSITRON, cartoApiKey);
return (
<div className="bg-surface-secondary" style={{ minHeight: '100vh', fontFamily: 'var(--font-system)' }}>
@@ -487,10 +491,15 @@ export default function SharedTripPage() {
zoomControl={false}
style={{ width: '100%', height: '100%' }}
>
<TileLayer
url={tileUrl}
referrerPolicy="strict-origin-when-cross-origin"
/>
{basemap.kind === 'vector' ? (
<VectorBasemap style={basemap.style} />
) : (
<TileLayer
url={basemap.url}
attribution={attributionForTile(basemap.url)}
referrerPolicy="strict-origin-when-cross-origin"
/>
)}
<FitBoundsToPlaces places={mapPlaces} framedOnMount={framed !== null} />
{selectedDay && mapPlaces.length > 1 && (
<Polyline
+38 -19
View File
@@ -9,6 +9,7 @@ import { useSettingsStore } from '../../store/settingsStore';
import L from 'leaflet';
import { A2_TO_A3 } from './atlasModel';
import { useAtlas } from './useAtlas';
import { maplibreGL } from '@maplibre/maplibre-gl-leaflet';
// FE-HOOK-ATLAS-001 to FE-HOOK-ATLAS-035
@@ -59,6 +60,24 @@ const lf = vi.hoisted(() => ({
},
}));
// maplibre-gl-leaflet hangs the vector basemap into Leaflet's tile pane. The mock
// only has to be callable and hand back a layer with the three methods the callers
// use, since nothing here renders WebGL.
vi.mock('@maplibre/maplibre-gl-leaflet', () => ({
maplibreGL: vi.fn(() => {
// One GL map per layer, kept stable: a fresh object per call would hand the
// assertions a different spy than the code just used.
const gl = {
setStyle: vi.fn(), on: vi.fn(), isStyleLoaded: () => false,
getStyle: () => ({ layers: [] }), setLayoutProperty: vi.fn(),
}
const layer: Record<string, unknown> = { remove: vi.fn(), getMaplibreMap: vi.fn(() => gl) }
layer.addTo = vi.fn(() => layer)
return layer
}),
}));
vi.mock('../../components/Map/engines/maplibre', () => ({ default: {} }));
vi.mock('leaflet', () => {
// The bounds a country layer reports carry its own code, so the map's bounds can
// answer `intersects` per country instead of all-or-nothing.
@@ -708,32 +727,32 @@ describe('useAtlas', () => {
expect(lf.mapsRemoved).toBeGreaterThan(0);
});
it('FE-HOOK-ATLAS-043: a CARTO key arriving after mount retiles instead of rebuilding the map (#2097)', async () => {
// Sliced from here: L.tileLayer's mock results carry over from earlier tests.
const madeBefore = vi.mocked(L.tileLayer).mock.results.length;
it('FE-HOOK-ATLAS-043: the basemap is a single label-free vector layer and the map is still built once', async () => {
// Sliced from here: the mock results carry over from earlier tests.
const madeBefore = vi.mocked(maplibreGL).mock.results.length;
await mountAtlas({ geo: geoCountries });
await waitFor(() => expect(lf.geoJson.length).toBeGreaterThan(0));
const tiles = vi.mocked(L.tileLayer).mock.results
.slice(madeBefore)
.map((r) => r.value as { setUrl: ReturnType<typeof vi.fn> });
expect(tiles.length).toBeGreaterThan(0);
const layersBefore = lf.geoJson.length;
act(() => {
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false, carto_api_key: 'k1' }) });
// One basemap layer, not two: the second raster layer only warmed the cache
// of neighbouring zoom levels, which a vector basemap does not need.
const layers = await waitFor(() => {
const made = vi.mocked(maplibreGL).mock.results.slice(madeBefore);
expect(made.length).toBe(1);
return made.map((r) => r.value as { getMaplibreMap: () => { setStyle: ReturnType<typeof vi.fn>; on: ReturnType<typeof vi.fn> } });
});
// It is a vector style, and it is the label-free variant the country fills
// need: OpenFreeMap has no nolabels style, so the symbol layers are switched
// off on the live map instead, re-armed on every style.load.
const calls = vi.mocked(maplibreGL).mock.calls;
const call = calls[calls.length - 1]?.[0] as { style: string };
expect(call.style).toContain('openfreemap.org');
expect(layers[0].getMaplibreMap().on).toHaveBeenCalledWith('style.load', expect.any(Function));
// The key reaches the tiles that are already on the map...
await waitFor(() => {
for (const t of tiles) expect(t.setUrl).toHaveBeenCalledWith(expect.stringContaining('key=k1'));
});
// ...and nothing else is torn down: rebuilding the map dropped the country layer
// (only redrawn when its own data changes) and left Leaflet redrawing a canvas
// renderer whose map had gone.
// And the map is still built once with its country layer on it: the basemap
// swap must not reintroduce the teardown #2097 removed.
expect(lf.mapsCreated).toBe(1);
expect(lf.mapsRemoved).toBe(0);
expect(lf.geoJson.length).toBe(layersBefore);
expect(lf.geoJson.length).toBeGreaterThan(0);
});
it('FE-HOOK-ATLAS-027: a plugin layer naming no country in the map draws nothing', async () => {
+40 -25
View File
@@ -3,7 +3,9 @@ import { useNavigate } from 'react-router'
import { getIntlLanguage, getLocaleForLanguage, useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore'
import { useTileUrl } from '../../hooks/useTileUrl'
import { CARTO_DARK_NOLABELS, CARTO_LIGHT_NOLABELS } from '../../constants/mapDefaults'
import { OFM_DARK, OFM_POSITRON } from '../../constants/mapDefaults'
import { attachVectorBasemap, hideLabelLayers, type GlLeafletLayer } from '../../components/Map/VectorBasemap'
import { isVectorStyle } from '../../utils/tileUrl'
import apiClient, { mapsApi, pluginsApi, type PluginAtlasLayer } from '../../api/client'
import L from 'leaflet'
import type { GeoJsonFeatureCollection } from '../../types'
@@ -83,13 +85,16 @@ export function useAtlas() {
const dark = dm === true || dm === 'dark' || (dm === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
// Label-free tiles on purpose (the country fills carry the names here), so the
// user's own template is deliberately not read, only their CARTO key.
const tileUrl = useTileUrl(dark ? CARTO_DARK_NOLABELS : CARTO_LIGHT_NOLABELS, true)
const tileUrl = useTileUrl(dark ? OFM_DARK : OFM_POSITRON, true)
// The template is read through a ref inside the map effect so a template change —
// the CARTO key arriving after the first render is the usual one — retiles the
// layers below instead of tearing the whole map down and building it again (#2097).
const tileUrlRef = useRef(tileUrl)
tileUrlRef.current = tileUrl
const tileLayersRef = useRef<L.TileLayer[]>([])
const glLayerRef = useRef<GlLeafletLayer | null>(null)
// The vector basemap loads async; a map torn down before it lands must not get one.
const cancelledRef = useRef(false)
const mapRef = useRef<HTMLDivElement>(null)
const mapInstance = useRef<L.Map | null>(null)
const geoLayerRef = useRef<L.GeoJSON | null>(null)
@@ -373,29 +378,27 @@ export function useAtlas() {
L.control.zoom({ position: 'bottomright' }).addTo(map)
const baseTiles = L.tileLayer(tileUrlRef.current, {
maxZoom: 10,
keepBuffer: 25,
updateWhenZooming: true,
updateWhenIdle: false,
tileSize: 256,
zoomOffset: 0,
crossOrigin: true,
referrerPolicy: 'strict-origin-when-cross-origin',
} as any)
baseTiles.addTo(map)
// Preload adjacent zoom level tiles
const preloadTiles = L.tileLayer(tileUrlRef.current, {
maxZoom: 10,
keepBuffer: 10,
opacity: 0,
tileSize: 256,
crossOrigin: true,
referrerPolicy: 'strict-origin-when-cross-origin',
})
preloadTiles.addTo(map)
tileLayersRef.current = [baseTiles, preloadTiles]
// One layer, not two. The second raster layer existed to warm the HTTP cache
// of neighbouring zoom levels; a vector basemap scales what it already has, so
// a second one would only cost a second WebGL context and a second copy of the
// tiles. Labels are hidden because the country fills carry the names here.
if (isVectorStyle(tileUrlRef.current)) {
cancelledRef.current = false
void attachVectorBasemap(map, tileUrlRef.current, glLayerRef, () => cancelledRef.current, { hideLabels: true })
} else {
const baseTiles = L.tileLayer(tileUrlRef.current, {
maxZoom: 10,
keepBuffer: 25,
updateWhenZooming: true,
updateWhenIdle: false,
tileSize: 256,
zoomOffset: 0,
crossOrigin: true,
referrerPolicy: 'strict-origin-when-cross-origin',
} as any)
baseTiles.addTo(map)
tileLayersRef.current = [baseTiles]
}
// Custom pane for region layer — above overlay (z-index 400)
map.createPane('regionPane')
@@ -453,6 +456,9 @@ export function useAtlas() {
regionLayerRef.current = null
renderedRegionSigRef.current = ''
tileLayersRef.current = []
cancelledRef.current = true
glLayerRef.current?.remove()
glLayerRef.current = null
}
}, [dark, loading])
@@ -461,6 +467,15 @@ export function useAtlas() {
// would come back bare — and Leaflet keeps redrawing the torn-down canvas renderer
// for a frame after the map goes (#2097).
useEffect(() => {
if (isVectorStyle(tileUrl)) {
const layer = glLayerRef.current
if (!layer) return
layer.getMaplibreMap()?.setStyle(tileUrl)
// setStyle drops the layer list, and style.load fires again with the new
// one, so the label rule has to be re-armed rather than assumed.
hideLabelLayers(layer)
return
}
for (const layer of tileLayersRef.current) layer.setUrl(tileUrl)
}, [tileUrl])
@@ -1778,11 +1778,11 @@ describe('useTripPlanner — booking import review', () => {
})
describe('useTripPlanner — misc state', () => {
it('FE-TP-HOOK-095: the map tile url falls back to the Carto basemap', async () => {
it('FE-TP-HOOK-095: the map tile url falls back to the default basemap', async () => {
seedTrip()
const { result } = await renderPlanner()
expect(result.current.mapTileUrl).toContain('basemaps.cartocdn.com')
expect(result.current.mapTileUrl).toContain('openfreemap.org')
act(() => { setSettings({ map_tile_url: 'https://tiles/{z}/{x}/{y}.png' }) })
expect(result.current.mapTileUrl).toBe('https://tiles/{z}/{x}/{y}.png')
@@ -25,7 +25,7 @@ import { useAirtrailConnection } from '../../hooks/useAirtrailConnection'
import { useIsTouch } from '../../hooks/useIsTouch'
import { usePluginStore } from '../../store/pluginStore'
import type { Accommodation, TripMember, Day, Place, Reservation } from '../../types'
import { CARTO_LIGHT, DEFAULT_MAP_LAT, DEFAULT_MAP_LNG, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
import { OFM_POSITRON, DEFAULT_MAP_LAT, DEFAULT_MAP_LNG, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
import { useTileUrl } from '../../hooks/useTileUrl'
import { resolvePoolAssignmentId } from './tripPlannerModel'
import { isDeepLinkableTripTab, TRIP_TAB_LABEL_KEYS } from '../../constants/tripTabs'
@@ -1031,7 +1031,7 @@ export function useTripPlanner() {
return da.map(a => a.place).filter(p => p?.lat && p?.lng)
}, [selectedDayId, assignments])
const mapTileUrl = useTileUrl(CARTO_LIGHT)
const mapTileUrl = useTileUrl(OFM_POSITRON)
const fontStyle = { fontFamily: "var(--font-system)" }