diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx
index 2308a0a2c..dc72843f8 100644
--- a/client/src/components/Map/MapView.tsx
+++ b/client/src/components/Map/MapView.tsx
@@ -70,7 +70,7 @@ import DawarichTrailLayer from './DawarichTrailLayer'
import { OFM_POSITRON, DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, MAP_MAX_ZOOM, SATELLITE_TILE_URL, SATELLITE_TILE_MAXZOOM, AMAP_SATELLITE, attributionForTile } from '../../constants/mapDefaults'
import { tileHealthHandlers, tourRasterBaseOf } from './tourRasterBases'
import { crsForBasemap } from './gcj02Crs'
-import { isGcj02Basemap, resolveBasemap } from '../../utils/tileUrl'
+import { resolveBasemapSpec } from './basemapSpec'
import VectorBasemap from './VectorBasemap'
import { nativeRasterTemplate } from '../../native/tileCache'
import { useSettingsStore } from '../../store/settingsStore'
@@ -644,13 +644,13 @@ export const MapView = memo(function MapView({
// The caller hands over whatever the user configured; what kind of basemap
// that is decides which layer draws it. A saved raster template still wins,
// the default is a vector style.
- const basemap = useMemo(() => resolveBasemap(tileUrl, OFM_POSITRON), [tileUrl])
+ const basemap = useMemo(() => resolveBasemapSpec(tileUrl, OFM_POSITRON), [tileUrl])
/**
* Amap's tiles are drawn in GCJ-02 (see gcj02Crs.ts). The projection has to be
* decided before the map is constructed, because Leaflet cannot change a map's
* CRS afterwards — hence the whole map, not just the tile layer.
*/
- const isGcjBasemap = !tourRaster && basemap.kind === 'raster' && isGcj02Basemap(basemap.url)
+ const isGcjBasemap = !tourRaster && basemap.kind === 'raster' && basemap.datum === 'gcj02'
const gcjCrs = useMemo(() => crsForBasemap(isGcjBasemap), [isGcjBasemap])
// Leaflet draws a layer on one world copy only, so a trip across the antimeridian is
// drawn in a longitude frame that keeps it on one copy (#2975). Null for every other
@@ -910,12 +910,12 @@ export const MapView = memo(function MapView({
eventHandlers={tileHealthHandlers(tourLayers?.baseHealth, baseLayer)}
/>
) : basemap.kind === 'vector' ? (
-
+
) : (
{
+ it('FE-MAP-BASEMAPSPEC-001: an empty template draws the fallback style', () => {
+ expect(resolveBasemapSpec('', OFM_POSITRON)).toEqual({ kind: 'vector', styleUrl: OFM_POSITRON });
+ expect(resolveBasemapSpec(null, OFM_DARK)).toEqual({ kind: 'vector', styleUrl: OFM_DARK });
+ expect(resolveBasemapSpec(' ', OFM_POSITRON)).toEqual({ kind: 'vector', styleUrl: OFM_POSITRON });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-002: an OpenFreeMap or self-hosted style URL stays a style', () => {
+ const bright = 'https://tiles.openfreemap.org/styles/bright';
+ expect(resolveBasemapSpec(bright, OFM_POSITRON)).toEqual({ kind: 'vector', styleUrl: bright });
+ const own = 'https://maps.example.com/style.json';
+ expect(resolveBasemapSpec(own, OFM_POSITRON)).toEqual({ kind: 'vector', styleUrl: own });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-003: a mapbox:// URL in the template field reads as a style, as it always did', () => {
+ const mapbox = 'mapbox://styles/mapbox/streets-v12';
+ expect(resolveBasemapSpec(mapbox, OFM_POSITRON)).toEqual({ kind: 'vector', styleUrl: mapbox });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-004: CARTO without a key falls back, so no watermarked tile is drawn', () => {
+ expect(resolveBasemapSpec(CARTO_LIGHT, OFM_POSITRON)).toEqual({ kind: 'vector', styleUrl: OFM_POSITRON });
+ expect(resolveBasemapSpec(CARTO_LIGHT, OFM_DARK, '')).toEqual({ kind: 'vector', styleUrl: OFM_DARK });
+ });
+});
+
+describe('resolveBasemapSpec: raster templates', () => {
+ it('FE-MAP-BASEMAPSPEC-010: OpenStreetMap is one host, 256px tiles up to zoom 19, with its credit', () => {
+ expect(resolveBasemapSpec(OSM, OFM_POSITRON, null, 1)).toEqual({
+ kind: 'raster',
+ template: OSM,
+ tiles: [OSM],
+ tileSize: 256,
+ maxNativeZoom: 19,
+ attribution: OSM_CREDIT,
+ scheme: 'xyz',
+ datum: 'wgs84',
+ host: 'tile.openstreetmap.org',
+ });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-011: a legacy sharded OSM template collapses onto the single host', () => {
+ const spec = resolveBasemapSpec('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', OFM_POSITRON);
+ expect(spec).toMatchObject({ kind: 'raster', template: OSM, tiles: [OSM], host: 'tile.openstreetmap.org' });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-012: OSM DE draws as it is', () => {
+ expect(resolveBasemapSpec(OSM_DE, OFM_POSITRON)).toMatchObject({
+ template: OSM_DE,
+ tiles: [OSM_DE],
+ maxNativeZoom: 19,
+ attribution: OSM_CREDIT,
+ host: 'tile.openstreetmap.de',
+ });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-013: CARTO with a key keeps it in the template and in every shard', () => {
+ const spec = resolveBasemapSpec(CARTO_LIGHT, OFM_POSITRON, 'k 1', 1);
+ const keyed = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png?key=k%201';
+ expect(spec).toMatchObject({ kind: 'raster', template: keyed, host: '{s}.basemaps.cartocdn.com' });
+ expect(spec.kind === 'raster' && spec.tiles).toEqual([
+ 'https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png?key=k%201',
+ 'https://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png?key=k%201',
+ 'https://c.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png?key=k%201',
+ ]);
+ });
+
+ it.each([
+ [1, ''],
+ [1.25, '@2x'],
+ [2, '@2x'],
+ ])('FE-MAP-BASEMAPSPEC-014: {r} at a pixel ratio of %s reads %j, as Leaflet decides it', (ratio, suffix) => {
+ const spec = resolveBasemapSpec(STADIA, OFM_POSITRON, null, ratio);
+ expect(spec.kind === 'raster' && spec.tiles).toEqual([
+ `https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}${suffix}.png`,
+ ]);
+ // Leaflet still gets the placeholder and decides it itself.
+ expect(spec.kind === 'raster' && spec.template).toBe(STADIA);
+ });
+
+ it('FE-MAP-BASEMAPSPEC-015: Amap is drawn in GCJ-02 with its own credit', () => {
+ for (const amap of [AMAP_ROAD, AMAP_SATELLITE]) {
+ expect(resolveBasemapSpec(amap, OFM_POSITRON)).toMatchObject({
+ kind: 'raster',
+ template: amap,
+ tiles: [amap],
+ datum: 'gcj02',
+ attribution: AMAP_ATTRIBUTION,
+ });
+ }
+ });
+
+ it('FE-MAP-BASEMAPSPEC-016: a self-hosted raster keeps its host, at the map ceiling', () => {
+ const own = 'https://tiles.example.com/osm/{z}/{x}/{y}.png';
+ expect(resolveBasemapSpec(own, OFM_POSITRON)).toMatchObject({
+ template: own,
+ tiles: [own],
+ maxNativeZoom: 19,
+ datum: 'wgs84',
+ host: 'tiles.example.com',
+ });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-017: a template counting rows from the south reads as TMS', () => {
+ const tms = 'https://tiles.example.com/{z}/{x}/{-y}.png';
+ expect(resolveBasemapSpec(tms, OFM_POSITRON)).toMatchObject({
+ template: tms,
+ tiles: ['https://tiles.example.com/{z}/{x}/{y}.png'],
+ scheme: 'tms',
+ });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-018: a provider that stops short of the ceiling caps the source', () => {
+ expect(resolveBasemapSpec(OPENTOPOMAP_TILE_URL, OFM_POSITRON)).toMatchObject({
+ maxNativeZoom: 17,
+ host: '{s}.tile.opentopomap.org',
+ });
+ expect(resolveBasemapSpec('https://tile.openmaps.fr/openhikingmap/{z}/{x}/{y}.png', OFM_POSITRON)).toMatchObject({
+ maxNativeZoom: 18,
+ });
+ expect(
+ resolveBasemapSpec('https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png', OFM_POSITRON)
+ ).toMatchObject({ maxNativeZoom: 20 });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-019: a raster fallback (no template) is described like a chosen one', () => {
+ expect(resolveBasemapSpec('', OSM)).toMatchObject({ kind: 'raster', template: OSM });
+ });
+
+ it('FE-MAP-BASEMAPSPEC-020: the screen density is read when no ratio is passed', () => {
+ vi.stubGlobal('devicePixelRatio', 2);
+ try {
+ const spec = resolveBasemapSpec(STADIA, OFM_POSITRON);
+ expect(spec.kind === 'raster' && spec.tiles[0]).toContain('@2x.png');
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('FE-MAP-BASEMAPSPEC-021: OpenFreeMap credit follows a raster on its host', () => {
+ const ofmRaster = 'https://tiles.openfreemap.org/raster/{z}/{x}/{y}.png';
+ expect(resolveBasemapSpec(ofmRaster, OFM_POSITRON)).toMatchObject({ attribution: OFM_ATTRIBUTION });
+ });
+});
diff --git a/client/src/components/Map/basemapSpec.ts b/client/src/components/Map/basemapSpec.ts
new file mode 100644
index 000000000..e349cb67a
--- /dev/null
+++ b/client/src/components/Map/basemapSpec.ts
@@ -0,0 +1,105 @@
+import {
+ CYCLOSM_TILE_MAXZOOM,
+ MAP_MAX_ZOOM,
+ OPENHIKINGMAP_TILE_MAXZOOM,
+ OPENTOPOMAP_TILE_MAXZOOM,
+ attributionForTile,
+} from '../../constants/mapDefaults';
+import { isGcj02Basemap, resolveBasemap, templateHost } from '../../utils/tileUrl';
+
+/**
+ * The basemap a map draws, described once for every renderer.
+ *
+ * `resolveBasemap` answers what the user's template resolves to; this adds what a
+ * renderer needs to draw it without reading the URL again. Leaflet takes the
+ * raster `template` as it always did and expands its placeholders itself. A GL
+ * raster source cannot: it gets `tiles`, the same template with the shard and
+ * 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.
+ */
+export type BasemapSpec = VectorBasemapSpec | RasterBasemapSpec;
+
+interface VectorBasemapSpec {
+ kind: 'vector';
+ /** A MapLibre style document. */
+ styleUrl: string;
+}
+
+interface RasterBasemapSpec {
+ kind: 'raster';
+ /** The resolved template as Leaflet takes it: placeholders kept, the CARTO key appended. */
+ template: string;
+ /** The template expanded for a GL raster source, one URL per shard. */
+ tiles: string[];
+ /** Raster presets serve 256px tiles; GL's default of 512 would draw one zoom level too coarse. */
+ tileSize: 256;
+ /** The deepest zoom the provider serves; deeper, the map scales its last tiles. */
+ maxNativeZoom: number;
+ attribution: string;
+ /** `tms` when the template counts rows from the south (`{-y}`). */
+ scheme: 'xyz' | 'tms';
+ /** GCJ-02 tiles (Amap) only line up on a map that projects through that datum. */
+ datum: 'wgs84' | 'gcj02';
+ /** The template's host, shard placeholder kept: what a CSP check reads. */
+ host: string;
+}
+
+/** The shards Leaflet substitutes for `{s}` when a layer names none, which no TREK layer does. */
+const LEAFLET_SUBDOMAINS = ['a', 'b', 'c'];
+
+/**
+ * Providers that stop short of the map's own ceiling, by host. Asked for a deeper
+ * tile they answer an error, so the source stops there and the map scales up.
+ */
+const MAX_NATIVE_ZOOM_BY_HOST: ReadonlyArray = [
+ [/(^|\.)tile\.opentopomap\.org$/i, OPENTOPOMAP_TILE_MAXZOOM],
+ [/^tile\.openmaps\.fr$/i, OPENHIKINGMAP_TILE_MAXZOOM],
+ [/\.tile-cyclosm\.openstreetmap\.fr$/i, CYCLOSM_TILE_MAXZOOM],
+];
+
+function maxNativeZoomFor(host: string): number {
+ return MAX_NATIVE_ZOOM_BY_HOST.find(([pattern]) => pattern.test(host))?.[1] ?? MAP_MAX_ZOOM;
+}
+
+/** The screen's pixel density, 1 where there is no window to ask. */
+function currentPixelRatio(): number {
+ return typeof window !== 'undefined' && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
+}
+
+/**
+ * `{s}` becomes one URL per shard, `{r}` becomes `@2x` on any screen denser than
+ * one device pixel per CSS pixel (Leaflet's `Browser.retina`, so 1.25 counts),
+ * and `{-y}` becomes `{y}`, the row order moving into `scheme` instead.
+ */
+function glTiles(template: string, pixelRatio: number): string[] {
+ const decided = template.replace(/\{r\}/g, pixelRatio > 1 ? '@2x' : '').replace(/\{-y\}/g, '{y}');
+ if (!decided.includes('{s}')) return [decided];
+ return LEAFLET_SUBDOMAINS.map((shard) => decided.replace(/\{s\}/g, shard));
+}
+
+/**
+ * What a map should draw, given the user's template and the app's default.
+ * Same arguments and the same choice as `resolveBasemap`; `pixelRatio` is there
+ * for the tests and defaults to the screen's.
+ */
+export function resolveBasemapSpec(
+ template: string | null | undefined,
+ fallback: string,
+ cartoKey?: string | null,
+ pixelRatio: number = currentPixelRatio()
+): BasemapSpec {
+ const basemap = resolveBasemap(template, fallback, cartoKey);
+ if (basemap.kind === 'vector') return { kind: 'vector', styleUrl: basemap.style };
+ const host = templateHost(basemap.url);
+ return {
+ kind: 'raster',
+ template: basemap.url,
+ tiles: glTiles(basemap.url, pixelRatio),
+ tileSize: 256,
+ maxNativeZoom: maxNativeZoomFor(host),
+ attribution: attributionForTile(basemap.url),
+ scheme: basemap.url.includes('{-y}') ? 'tms' : 'xyz',
+ datum: isGcj02Basemap(basemap.url) ? 'gcj02' : 'wgs84',
+ host,
+ };
+}
diff --git a/client/src/utils/tileUrl.ts b/client/src/utils/tileUrl.ts
index 9fbc2c5b2..e46241da4 100644
--- a/client/src/utils/tileUrl.ts
+++ b/client/src/utils/tileUrl.ts
@@ -32,7 +32,8 @@ export function normalizeTileUrl(url: string): string {
*/
const CARTO_HOST = /^(?:\{s\}|[a-d])?\.?basemaps\.cartocdn\.com$/i
-function templateHost(url: string): string {
+/** The host a tile template or style URL names, placeholders such as `{s}.` kept. */
+export function templateHost(url: string): string {
return url.replace(/^\w*:?\/\//, '').split(/[/?#]/)[0]
}