From c7063bd9f5d2834816084dd3cd95b47e542babc3 Mon Sep 17 00:00:00 2001 From: Jonathan Chemla Date: Sat, 21 Nov 2026 09:21:39 +0100 Subject: [PATCH 1/2] feat: draw vector TileJSON, WMS and XYZ web map links A TileJSON with vector_layers becomes a vector source, drawn with the layers of a stylesheet link when one matches, or with default fill, line and circle layers. rel: wms and rel: xyz links of the web-map-links extension become raster sources. Co-Authored-By: Claude Fable 5.2 --- src/components/map.tsx | 3 + src/components/stac-map.tsx | 2 + src/components/visualization.tsx | 110 +++++++++++++++++++++++- src/utils/web-map-links.ts | 135 ++++++++++++++++++++++++++++++ tests/utils/web-map-links.spec.ts | 130 ++++++++++++++++++++++++++++ 5 files changed, 377 insertions(+), 3 deletions(-) create mode 100644 src/utils/web-map-links.ts create mode 100644 tests/utils/web-map-links.spec.ts diff --git a/src/components/map.tsx b/src/components/map.tsx index c0b8f8d7..988494a4 100644 --- a/src/components/map.tsx +++ b/src/components/map.tsx @@ -88,6 +88,9 @@ export default function Map({ {Object.values(maplibreLayers).map((layer, i) => ( + {layer.layers?.map((extra) => ( + + ))} ))} {extraLayers && diff --git a/src/components/stac-map.tsx b/src/components/stac-map.tsx index c25ce094..5def1180 100644 --- a/src/components/stac-map.tsx +++ b/src/components/stac-map.tsx @@ -31,6 +31,8 @@ import UrlBootstrap from "./url-bootstrap"; export interface ExtraLayerProps { source: SourceProps; layer: LayerProps; + /** More layers drawn from the same source, above `layer`. */ + layers?: LayerProps[]; } export interface StacMapProps { diff --git a/src/components/visualization.tsx b/src/components/visualization.tsx index a7160fd0..da5c86e3 100644 --- a/src/components/visualization.tsx +++ b/src/components/visualization.tsx @@ -8,6 +8,15 @@ import { type SingleBandTileData, } from "@/utils/single-band"; import { getCogHref, sanitizeBbox } from "@/utils/stac"; +import { + defaultVectorLayers, + fetchJson, + getStylesheetLayers, + getVectorLayerIds, + getWmsTileUrl, + getXyzTiles, + type TileJson, +} from "@/utils/web-map-links"; import { Checkbox, HStack, @@ -21,6 +30,7 @@ import { type MosaicSource, } from "@developmentseed/deck.gl-geotiff"; import { epsgResolver } from "@developmentseed/proj"; +import { useQueries, useQuery } from "@tanstack/react-query"; import { useEffect, useMemo, useState } from "react"; import { LuEye, LuEyeOff } from "react-icons/lu"; import type { StacAsset, StacItem, StacLink } from "stac-ts"; @@ -37,6 +47,45 @@ export default function Visualization({ }) { const tilejsonLink = links.find((link) => link.rel === "tilejson"); const wmtsLink = links.find((link) => link.rel === "wmts"); + const wmsLink = links.find((link) => link.rel === "wms"); + const xyzLink = links.find((link) => link.rel === "xyz"); + const hasWebMapLink = !!(tilejsonLink || wmtsLink || wmsLink || xyzLink); + + // A TileJSON may describe vector tiles, which need a vector source + const tilejson = useQuery({ + queryKey: ["tilejson", tilejsonLink?.href], + queryFn: () => fetchJson(tilejsonLink!.href), + enabled: !!tilejsonLink, + }); + const vectorLayerIds = useMemo( + () => getVectorLayerIds(tilejson.data), + [tilejson.data] + ); + const stylesheets = useQueries({ + queries: links + .filter((link) => link.rel === "stylesheet") + .map((link) => ({ + queryKey: ["stylesheet", link.href], + queryFn: () => fetchJson(link.href), + enabled: vectorLayerIds.length > 0, + })), + combine: (results) => ({ + data: results.map((result) => result.data), + pending: results.some((result) => result.isLoading), + }), + }); + const lineColor = useStore((store) => store.lineColor); + const vectorLayers = useMemo(() => { + if (vectorLayerIds.length === 0) return undefined; + // The first stylesheet that draws these vector layers, if any + for (const style of stylesheets.data) { + const layers = getStylesheetLayers(style, vectorLayerIds); + if (layers.length > 0) return layers; + } + const [r, g, b] = lineColor; + return defaultVectorLayers(vectorLayerIds, `rgb(${r}, ${g}, ${b})`); + }, [vectorLayerIds, stylesheets.data, lineColor]); + const tilejsonPending = tilejson.isLoading || stylesheets.pending; const cogAssets = useMemo( () => Object.entries(assets) @@ -73,11 +122,17 @@ export default function Visualization({ if (wmtsLink) { items.push({ label: "wmts", value: "wmts" }); } + if (wmsLink) { + items.push({ label: "wms", value: "wms" }); + } + if (xyzLink) { + items.push({ label: "xyz", value: "xyz" }); + } for (const key of itemAssetKeys) { items.push({ label: key, value: `items:${key}` }); } return createListCollection({ items }); - }, [cogAssets, tilejsonLink, wmtsLink, itemAssetKeys]); + }, [cogAssets, tilejsonLink, wmtsLink, wmsLink, xyzLink, itemAssetKeys]); const visualization = useStore((store) => store.visualization); const setVisualization = useStore((store) => store.setVisualization); @@ -89,11 +144,11 @@ export default function Visualization({ const fallback = useMemo(() => { const bestItemKey = pickBestKeyForItems(allItems); - if (bestItemKey && cogAssets.length === 0 && !tilejsonLink && !wmtsLink) { + if (bestItemKey && cogAssets.length === 0 && !hasWebMapLink) { return `items:${bestItemKey}`; } return collection.items[0]?.value; - }, [allItems, cogAssets, tilejsonLink, wmtsLink, collection]); + }, [allItems, cogAssets, hasWebMapLink, collection]); const selected = visualization && validValues.has(visualization) ? visualization : fallback; @@ -160,6 +215,19 @@ export default function Visualization({ } if (selected === "tilejson" && tilejsonLink) { + if (tilejsonPending) return; + if (vectorLayers) { + setMaplibreLayer("visualization", { + source: { + id: "visualization", + type: "vector", + url: tilejsonLink.href, + }, + layer: vectorLayers[0], + layers: vectorLayers.slice(1), + }); + return () => setMaplibreLayer("visualization", undefined); + } setMaplibreLayer("visualization", { source: { id: "visualization", @@ -174,6 +242,38 @@ export default function Visualization({ return () => setMaplibreLayer("visualization", undefined); } + if (selected === "wms" && wmsLink) { + setMaplibreLayer("visualization", { + source: { + id: "visualization", + type: "raster", + tiles: [getWmsTileUrl(wmsLink)], + tileSize: 256, + }, + layer: { + id: "visualization", + type: "raster", + }, + }); + return () => setMaplibreLayer("visualization", undefined); + } + + if (selected === "xyz" && xyzLink) { + setMaplibreLayer("visualization", { + source: { + id: "visualization", + type: "raster", + tiles: getXyzTiles(xyzLink), + tileSize: 256, + }, + layer: { + id: "visualization", + type: "raster", + }, + }); + return () => setMaplibreLayer("visualization", undefined); + } + if (selected === "wmts" && wmtsLink) { setMaplibreLayer("visualization", { source: { @@ -195,7 +295,11 @@ export default function Visualization({ selectedCogGeotiff, bandRange, tilejsonLink, + tilejsonPending, + vectorLayers, wmtsLink, + wmsLink, + xyzLink, setLayer, setMaplibreLayer, ]); diff --git a/src/utils/web-map-links.ts b/src/utils/web-map-links.ts new file mode 100644 index 00000000..2b638152 --- /dev/null +++ b/src/utils/web-map-links.ts @@ -0,0 +1,135 @@ +import type { LayerProps } from "react-map-gl/maplibre"; +import type { StacLink } from "stac-ts"; + +/** The parts of a TileJSON document that we read. */ +export interface TileJson { + tiles?: string[]; + vector_layers?: { id: string }[]; +} + +type VectorLayerProps = Extract< + LayerProps, + { type: "fill" | "line" | "circle" } +>; + +const VECTOR_LAYER_TYPES = new Set(["fill", "line", "circle"]); + +export async function fetchJson(href: string): Promise { + const response = await fetch(href, { + headers: { Accept: "application/json" }, + }); + if (!response.ok) throw new Error(`GET ${href}: ${response.status}`); + return response.json(); +} + +/** + * The ids of a TileJSON's vector layers. + * + * TileJSON 3.0.0 requires `vector_layers` for vector tiles, so an empty list + * means raster tiles. + */ +export function getVectorLayerIds(tilejson: TileJson | undefined): string[] { + if (!Array.isArray(tilejson?.vector_layers)) return []; + return tilejson.vector_layers + .map((layer) => layer?.id) + .filter((id): id is string => typeof id === "string"); +} + +/** A fill, a line and a circle layer for each vector layer. */ +export function defaultVectorLayers( + sourceLayers: string[], + color: string +): LayerProps[] { + return sourceLayers.flatMap((sourceLayer, index): VectorLayerProps[] => [ + { + id: `visualization-${index}-fill`, + type: "fill", + "source-layer": sourceLayer, + filter: ["==", "$type", "Polygon"], + paint: { "fill-color": color, "fill-opacity": 0.25 }, + }, + { + id: `visualization-${index}-line`, + type: "line", + "source-layer": sourceLayer, + filter: ["in", "$type", "Polygon", "LineString"], + paint: { "line-color": color, "line-width": 1.5 }, + }, + { + id: `visualization-${index}-circle`, + type: "circle", + "source-layer": sourceLayer, + filter: ["==", "$type", "Point"], + paint: { + "circle-color": color, + "circle-radius": 4, + "circle-stroke-color": "#ffffff", + "circle-stroke-width": 1, + }, + }, + ]); +} + +/** + * The fill, line and circle layers of a MapLibre style that draw one of the + * given vector layers, to be added to our own source. + * + * Symbol layers are left out: they need the style's own glyphs and sprite. + */ +export function getStylesheetLayers( + style: unknown, + sourceLayers: string[] +): LayerProps[] { + const layers = (style as { layers?: unknown })?.layers; + if (!Array.isArray(layers)) return []; + return layers + .filter( + (layer) => + VECTOR_LAYER_TYPES.has(layer?.type) && + sourceLayers.includes(layer["source-layer"]) + ) + .map((layer, index) => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { source, ...rest } = layer; + return { ...rest, id: `visualization-${index}-${layer.id}` }; + }); +} + +/** + * A MapLibre raster tile URL for a `rel: wms` link of the web-map-links + * extension. + */ +export function getWmsTileUrl(link: StacLink): string { + const url = new URL(link.href); + const layers = [link["wms:layers"]].flat().filter(Boolean) as string[]; + const styles = (link["wms:styles"] as string[] | undefined) ?? []; + const dimensions = + (link["wms:dimensions"] as Record | undefined) ?? {}; + const params: Record = { + SERVICE: "WMS", + VERSION: "1.1.1", + REQUEST: "GetMap", + LAYERS: layers.join(","), + STYLES: styles.join(","), + SRS: "EPSG:3857", + FORMAT: link.type?.startsWith("image/") ? link.type : "image/png", + TRANSPARENT: link["wms:transparent"] ? "TRUE" : "FALSE", + WIDTH: "256", + HEIGHT: "256", + ...dimensions, + }; + for (const [key, value] of Object.entries(params)) { + url.searchParams.set(key, value); + } + return `${url}&BBOX={bbox-epsg-3857}`; +} + +/** + * The tile URL templates of a `rel: xyz` link of the web-map-links extension, + * one for each of its `href:servers` when the href has an `{s}` placeholder. + */ +export function getXyzTiles(link: StacLink): string[] { + const servers = link["href:servers"] as string[] | undefined; + if (!link.href.includes("{s}") || !servers?.length) return [link.href]; + return servers.map((server) => link.href.replaceAll("{s}", server)); +} diff --git a/tests/utils/web-map-links.spec.ts b/tests/utils/web-map-links.spec.ts new file mode 100644 index 00000000..f7a82a91 --- /dev/null +++ b/tests/utils/web-map-links.spec.ts @@ -0,0 +1,130 @@ +import type { StacLink } from "stac-ts"; +import { describe, expect, it } from "vitest"; +import { + defaultVectorLayers, + getStylesheetLayers, + getVectorLayerIds, + getWmsTileUrl, + getXyzTiles, +} from "../../src/utils/web-map-links"; + +describe("getVectorLayerIds", () => { + it("returns the ids of a vector TileJSON", () => { + expect( + getVectorLayerIds({ vector_layers: [{ id: "sites" }, { id: "areas" }] }) + ).toEqual(["sites", "areas"]); + }); + + it("returns nothing for a raster TileJSON", () => { + expect( + getVectorLayerIds({ tiles: ["https://example.com/{z}.png"] }) + ).toEqual([]); + expect(getVectorLayerIds(undefined)).toEqual([]); + }); +}); + +describe("defaultVectorLayers", () => { + it("gives a fill, a line and a circle layer for each vector layer", () => { + const layers = defaultVectorLayers(["sites", "areas"], "#ff0000"); + expect(layers.map((layer) => layer.type)).toEqual([ + "fill", + "line", + "circle", + "fill", + "line", + "circle", + ]); + expect(new Set(layers.map((layer) => layer.id)).size).toBe(6); + expect(layers[3]).toMatchObject({ "source-layer": "areas" }); + }); +}); + +describe("getStylesheetLayers", () => { + const style = { + version: 8, + sources: { + data: { type: "vector", url: "https://example.com/tiles.json" }, + }, + layers: [ + { id: "background", type: "background" }, + { id: "areas", type: "fill", source: "data", "source-layer": "sites" }, + { id: "labels", type: "symbol", source: "data", "source-layer": "sites" }, + { id: "roads", type: "line", source: "data", "source-layer": "roads" }, + ], + }; + + it("keeps the fill, line and circle layers of the given vector layers", () => { + const layers = getStylesheetLayers(style, ["sites"]); + expect(layers).toHaveLength(1); + expect(layers[0]).toMatchObject({ type: "fill", "source-layer": "sites" }); + expect(layers[0]).not.toHaveProperty("source"); + }); + + it("returns nothing for something that is not a style", () => { + expect(getStylesheetLayers(null, ["sites"])).toEqual([]); + expect(getStylesheetLayers({ layers: "nope" }, ["sites"])).toEqual([]); + }); +}); + +describe("getWmsTileUrl", () => { + it("builds a GetMap URL with a MapLibre bbox placeholder", () => { + const url = getWmsTileUrl({ + rel: "wms", + href: "https://example.com/wms?map=heritage", + type: "image/jpeg", + "wms:layers": ["sites", "areas"], + "wms:styles": ["default", "default"], + "wms:dimensions": { TIME: "2020" }, + "wms:transparent": true, + } as StacLink); + expect(url.endsWith("&BBOX={bbox-epsg-3857}")).toBe(true); + const params = new URL(url.replace("&BBOX={bbox-epsg-3857}", "")) + .searchParams; + expect(Object.fromEntries(params)).toEqual({ + map: "heritage", + SERVICE: "WMS", + VERSION: "1.1.1", + REQUEST: "GetMap", + LAYERS: "sites,areas", + STYLES: "default,default", + SRS: "EPSG:3857", + FORMAT: "image/jpeg", + TRANSPARENT: "TRUE", + WIDTH: "256", + HEIGHT: "256", + TIME: "2020", + }); + }); + + it("defaults to opaque PNG and empty styles", () => { + const url = getWmsTileUrl({ + rel: "wms", + href: "https://example.com/wms", + "wms:layers": ["sites"], + } as StacLink); + expect(url).toContain("STYLES=&"); + expect(url).toContain("FORMAT=image%2Fpng"); + expect(url).toContain("TRANSPARENT=FALSE"); + }); +}); + +describe("getXyzTiles", () => { + it("returns the href as it is without servers", () => { + expect( + getXyzTiles({ rel: "xyz", href: "https://example.com/{z}/{x}/{y}.png" }) + ).toEqual(["https://example.com/{z}/{x}/{y}.png"]); + }); + + it("gives one template for each server", () => { + expect( + getXyzTiles({ + rel: "xyz", + href: "https://{s}.example.com/{z}/{x}/{y}.png", + "href:servers": ["a", "b"], + } as StacLink) + ).toEqual([ + "https://a.example.com/{z}/{x}/{y}.png", + "https://b.example.com/{z}/{x}/{y}.png", + ]); + }); +}); From 2c6827c5d233da58f60ed38db1ca56c4d6ac3283 Mon Sep 17 00:00:00 2001 From: Jonathan Chemla Date: Wed, 25 Nov 2026 08:38:27 +0100 Subject: [PATCH 2/2] refactor: drop comments, let the code speak for itself --- src/components/stac-map.tsx | 1 - src/components/visualization.tsx | 2 -- src/utils/web-map-links.ts | 22 ---------------------- 3 files changed, 25 deletions(-) diff --git a/src/components/stac-map.tsx b/src/components/stac-map.tsx index 5def1180..dfbe1adc 100644 --- a/src/components/stac-map.tsx +++ b/src/components/stac-map.tsx @@ -31,7 +31,6 @@ import UrlBootstrap from "./url-bootstrap"; export interface ExtraLayerProps { source: SourceProps; layer: LayerProps; - /** More layers drawn from the same source, above `layer`. */ layers?: LayerProps[]; } diff --git a/src/components/visualization.tsx b/src/components/visualization.tsx index da5c86e3..caad0f1f 100644 --- a/src/components/visualization.tsx +++ b/src/components/visualization.tsx @@ -51,7 +51,6 @@ export default function Visualization({ const xyzLink = links.find((link) => link.rel === "xyz"); const hasWebMapLink = !!(tilejsonLink || wmtsLink || wmsLink || xyzLink); - // A TileJSON may describe vector tiles, which need a vector source const tilejson = useQuery({ queryKey: ["tilejson", tilejsonLink?.href], queryFn: () => fetchJson(tilejsonLink!.href), @@ -77,7 +76,6 @@ export default function Visualization({ const lineColor = useStore((store) => store.lineColor); const vectorLayers = useMemo(() => { if (vectorLayerIds.length === 0) return undefined; - // The first stylesheet that draws these vector layers, if any for (const style of stylesheets.data) { const layers = getStylesheetLayers(style, vectorLayerIds); if (layers.length > 0) return layers; diff --git a/src/utils/web-map-links.ts b/src/utils/web-map-links.ts index 2b638152..40a177bc 100644 --- a/src/utils/web-map-links.ts +++ b/src/utils/web-map-links.ts @@ -1,7 +1,6 @@ import type { LayerProps } from "react-map-gl/maplibre"; import type { StacLink } from "stac-ts"; -/** The parts of a TileJSON document that we read. */ export interface TileJson { tiles?: string[]; vector_layers?: { id: string }[]; @@ -22,12 +21,6 @@ export async function fetchJson(href: string): Promise { return response.json(); } -/** - * The ids of a TileJSON's vector layers. - * - * TileJSON 3.0.0 requires `vector_layers` for vector tiles, so an empty list - * means raster tiles. - */ export function getVectorLayerIds(tilejson: TileJson | undefined): string[] { if (!Array.isArray(tilejson?.vector_layers)) return []; return tilejson.vector_layers @@ -35,7 +28,6 @@ export function getVectorLayerIds(tilejson: TileJson | undefined): string[] { .filter((id): id is string => typeof id === "string"); } -/** A fill, a line and a circle layer for each vector layer. */ export function defaultVectorLayers( sourceLayers: string[], color: string @@ -70,12 +62,6 @@ export function defaultVectorLayers( ]); } -/** - * The fill, line and circle layers of a MapLibre style that draw one of the - * given vector layers, to be added to our own source. - * - * Symbol layers are left out: they need the style's own glyphs and sprite. - */ export function getStylesheetLayers( style: unknown, sourceLayers: string[] @@ -95,10 +81,6 @@ export function getStylesheetLayers( }); } -/** - * A MapLibre raster tile URL for a `rel: wms` link of the web-map-links - * extension. - */ export function getWmsTileUrl(link: StacLink): string { const url = new URL(link.href); const layers = [link["wms:layers"]].flat().filter(Boolean) as string[]; @@ -124,10 +106,6 @@ export function getWmsTileUrl(link: StacLink): string { return `${url}&BBOX={bbox-epsg-3857}`; } -/** - * The tile URL templates of a `rel: xyz` link of the web-map-links extension, - * one for each of its `href:servers` when the href has an `{s}` placeholder. - */ export function getXyzTiles(link: StacLink): string[] { const servers = link["href:servers"] as string[] | undefined; if (!link.href.includes("{s}") || !servers?.length) return [link.href];