Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(geomap): ask a raster server for its finer tiles, and stop where it ends
Elian Doranf9e4b5ce789d
diff --git a/apps/client/src/widgets/collections/geomap/map.init.spec.tsx b/apps/client/src/widgets/collections/geomap/map.init.spec.tsxindex 9b21122c5c..3e46b02445 100644--- a/apps/client/src/widgets/collections/geomap/map.init.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/map.init.spec.tsx@@ -115,13 +115,13 @@ describe("Map initialization", () => {});/** Puts the map up, with whatever the mocked constructor has been told to do. */- function renderMap({ scale = false } = {}) {+ function renderMap({ scale = false, layer = LAYER }: { scale?: boolean; layer?: MapLayer } = {}) {act(() => {render(<Mapcoordinates={{ lat: 0, lng: 0 }}zoom={2}- layerData={LAYER}+ layerData={layer}viewportChanged={vi.fn()}scale={scale}>@@ -188,6 +188,54 @@ describe("Map initialization", () => {});});+ describe("the raster source a custom map is drawn from", () => {+ /** The raster source of the style the map was built with. */+ function rasterSource() {+ return MapConstructor.mock.calls[0][0].style.sources["raster-tiles"];+ }++ // A block body: `mockImplementation` returns the mock, and a hook that returns a function is+ // taken for one that has handed back its own teardown — which Vitest then calls, recording a+ // constructor call with no arguments where the next test looks for its own.+ beforeEach(() => {+ MapConstructor.mockImplementation(workingMap);+ });++ /**+ * A URL typed into `#map:style` is copied from Leaflet Providers, where a server with+ * double-resolution tiles is written with Leaflet's `{r}`. MapLibre calls it `{ratio}` and+ * passes anything else through, so the letter itself went out in the request.+ */+ it("asks for the double-resolution tiles a Leaflet URL knows how to ask for", () => {+ renderMap({ layer: { ...LAYER, url: "https://tile.example.org/{z}/{x}/{y}{r}.png" } });++ expect(rasterSource().tiles).toEqual([ "https://tile.example.org/{z}/{x}/{y}{ratio}.png" ]);+ });++ it("leaves a URL that asks for no such thing exactly as it was given", () => {+ renderMap();++ expect(rasterSource().tiles).toEqual([ LAYER.url ]);+ // Never the level below drawn small: that is sharper, but it halves the labels and the+ // road widths the tile was drawn with, and reads as a map one zoom further out.+ expect(rasterSource().tileSize).toBe(256);+ });++ it("stops where the server stops, rather than asking for a level it has not got", () => {+ // OpenStreetMap answers 400 past z19, and a tile that fails leaves a hole where+ // stretching the level above would have done.+ renderMap();++ expect(rasterSource().maxzoom).toBe(19);+ });++ it("believes a layer that says where its own tiles stop", () => {+ renderMap({ layer: { ...LAYER, maxZoom: 22 } });++ expect(rasterSource().maxzoom).toBe(22);+ });+ });+/*** Leaving a geo map for another note, which used to throw where nobody could catch it: the scale* was taken off a map that had already gone, and a control given its notice twice reaches for thediff --git a/apps/client/src/widgets/collections/geomap/map.tsx b/apps/client/src/widgets/collections/geomap/map.tsxindex e205d7bc42..2666c2a3a4 100644--- a/apps/client/src/widgets/collections/geomap/map.tsx+++ b/apps/client/src/widgets/collections/geomap/map.tsx@@ -8,7 +8,7 @@ import { t } from "../../../services/i18n";import { getMeasurementSystem } from "../../../utils/formatters";import { useElementSize, useSyncedRef, useTriliumOption } from "../../react/hooks";import NoItems from "../../react/NoItems";-import { type MapLayer } from "./map_layer";+import { DEFAULT_RASTER_MAX_ZOOM, type MapLayer } from "./map_layer";export interface GeoMouseEvent {latlng: { lat: number; lng: number };@@ -77,8 +77,18 @@ function buildSyncStyle(layerData: MapLayer): StyleSpecification | string {sources: {"raster-tiles": {type: "raster",- tiles: [ layerData.url ],+ tiles: [ toMapLibreUrl(layerData.url) ],+ // The size the tiles are drawn at, which is also the size they are designed at: a+ // raster tile carries its labels and its road widths in the picture, sized for this.+ // Taking the level below and drawing it at 128 would be sharper on a fine screen —+ // Leaflet's `detectRetina` did exactly that — but it halves the cartography with it,+ // and a map whose every label is half-size reads as one zoom further out. A server+ // with real `@2x` tiles is the only way to have both, which is what `{r}` is for.tileSize: 256,+ // Where the server's own tiles stop. Past it MapLibre stretches the deepest one it+ // has rather than asking for a level that does not exist, which is a blurry map+ // rather than a blank one.+ maxzoom: layerData.maxZoom ?? DEFAULT_RASTER_MAX_ZOOM,attribution: layerData.attribution}},@@ -92,6 +102,23 @@ function buildSyncStyle(layerData: MapLayer): StyleSpecification | string {};}+/**+ * A tile URL as MapLibre spells it.+ *+ * The user guide sends anyone wanting a custom map to Leaflet Providers, whose URLs are written in+ * Leaflet's templates. `{r}` is where a server that draws tiles twice over wants `@2x` put, and+ * MapLibre asks for the same thing under the name `{ratio}` — it knows nothing of `{r}`, so the+ * three characters went out in the request and the server was asked for a tile named after a letter.+ *+ * This is the one way a raster map is sharp on a fine screen and still the map it was drawn as: an+ * `@2x` tile is twice the picture of the same ground, with the labels drawn twice the size to match.+ * Nothing can be done for a server that has no such tiles — OpenStreetMap answers 400 — which is why+ * this is left to the URL to ask for rather than done to every map.+ */+function toMapLibreUrl(url: string) {+ return url.replaceAll("{r}", "{ratio}");+}+function toCenter(coordinates: { lat: number; lng: number } | [number, number]): [number, number] {return Array.isArray(coordinates)? [ coordinates[1], coordinates[0] ]diff --git a/apps/client/src/widgets/collections/geomap/map_layer.ts b/apps/client/src/widgets/collections/geomap/map_layer.tsindex 3859122f28..309f7326ba 100644--- a/apps/client/src/widgets/collections/geomap/map_layer.ts+++ b/apps/client/src/widgets/collections/geomap/map_layer.ts@@ -8,6 +8,8 @@ export type MapLayer = ({type: "raster";url: string;attribution: string;+ /** The deepest zoom the server draws tiles for, past which the last one is stretched instead. */+ maxZoom?: number;}) & {// Common propertiesname: string;@@ -17,12 +19,21 @@ export type MapLayer = ({// Minimal empty style used as a placeholder while the real style loads asynchronously.const EMPTY_STYLE: StyleSpecification = { version: 8, sources: {}, layers: [] };+/**+ * Where a raster server is assumed to stop when it has not said, which is where most of them do.+ * Guessing is better than not: MapLibre's own default of 22 has the map ask for levels almost no+ * server draws, and a tile that 404s leaves a hole where stretching the level above would not.+ */+export const DEFAULT_RASTER_MAX_ZOOM = 19;+export const MAP_LAYERS: Record<string, MapLayer> = {"openstreetmap": {name: "OpenStreetMap",type: "raster",url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",- attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'+ attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',+ // Where their standard layer stops: z20 is answered 400, not drawn.+ maxZoom: 19},"versatiles-colorful": {name: "VersaTiles Colorful",