diff --git a/src/components/map.tsx b/src/components/map.tsx index c0b8f8d..988494a 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 c25ce09..dfbe1ad 100644 --- a/src/components/stac-map.tsx +++ b/src/components/stac-map.tsx @@ -31,6 +31,7 @@ import UrlBootstrap from "./url-bootstrap"; export interface ExtraLayerProps { source: SourceProps; layer: LayerProps; + layers?: LayerProps[]; } export interface StacMapProps { diff --git a/src/components/visualization.tsx b/src/components/visualization.tsx index a7160fd..caad0f1 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,43 @@ 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); + + 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; + 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 +120,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 +142,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 +213,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 +240,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 +293,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 0000000..40a177b --- /dev/null +++ b/src/utils/web-map-links.ts @@ -0,0 +1,113 @@ +import type { LayerProps } from "react-map-gl/maplibre"; +import type { StacLink } from "stac-ts"; + +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(); +} + +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"); +} + +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, + }, + }, + ]); +} + +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}` }; + }); +} + +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}`; +} + +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 0000000..f7a82a9 --- /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", + ]); + }); +});