Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): stand the buildings up once the view is leaned over

Elian Doranc06ec3bddccb
diff --git a/apps/client/src/widgets/collections/geomap/Buildings.spec.tsx b/apps/client/src/widgets/collections/geomap/Buildings.spec.tsx
new file mode 100644
index 0000000000..e76f72a6cd
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/Buildings.spec.tsx
@@ -0,0 +1,229 @@
+/**
+ * The buildings of the map underneath, stood up while the view is leaned over.
+ *
+ * What is checked here is mostly what the layer must *not* do. It draws from a source only the
+ * built-in vector styles have, so a map on the raster layer has to be left alone rather than asked
+ * for footprints it has none of. It replaces the style's own flat drawing of the same buildings, so
+ * that one has to go down while it stands and come back when it does not. And it reads a height
+ * that is an experimental extension of the tile schema rather than part of it, so a build of the
+ * tiles without it must leave a town of low blocks rather than a flat grey plain.
+ */
+import type { LayerSpecification, Map as MapLibreGLMap } from "maplibre-gl";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { describe, expect, it } from "vitest";
+
+import { renderInto } from "../../../test/render";
+import Buildings, { BUILDINGS_LAYER } from "./Buildings";
+import { ParentMap } from "./map";
+
+const SHORTBREAD_SOURCE = "versatiles-shortbread";
+
+/** The built-in vector styles, in the shape this component reads them: footprints, then labels. */
+function vectorStyleLayers(): LayerSpecification[] {
+ return [
+ { id: "land", type: "fill", source: SHORTBREAD_SOURCE, "source-layer": "land" },
+ { id: "building:outline", type: "fill", source: SHORTBREAD_SOURCE, "source-layer": "buildings" },
+ { id: "building", type: "fill", source: SHORTBREAD_SOURCE, "source-layer": "buildings" },
+ { id: "poi-amenity", type: "symbol", source: SHORTBREAD_SOURCE, "source-layer": "pois" },
+ { id: "label-street", type: "symbol", source: SHORTBREAD_SOURCE, "source-layer": "street_labels" }
+ ];
+}
+
+/** The raster layer: one picture per tile, with no footprints in it to stand up. */
+function rasterStyleLayers(): LayerSpecification[] {
+ return [ { id: "raster-layer", type: "raster", source: "raster-tiles" } ];
+}
+
+/**
+ * A map holding a style whose layers are in draw order, which is what this component arranges
+ * itself within — and which tilts, since that is what it waits for.
+ */
+function fakeMap({ layers = vectorStyleLayers(), pitch = 0 } = {}) {
+ const listeners = new Map<string, Set<() => void>>();
+ const fire = (event: string) => {
+ for (const listener of listeners.get(event) ?? []) listener();
+ };
+
+ return {
+ layers,
+ getStyle: () => ({ layers }),
+ getSource: (id: string) => layers.find((layer) => layer.source === id),
+ getLayer: (id: string) => layers.find((layer) => layer.id === id),
+ addLayer(layer: LayerSpecification, beforeId?: string) {
+ const at = beforeId ? layers.findIndex((existing) => existing.id === beforeId) : -1;
+ layers.splice(at < 0 ? layers.length : at, 0, layer);
+ },
+ removeLayer(id: string) {
+ layers.splice(layers.findIndex((layer) => layer.id === id), 1);
+ },
+ setLayoutProperty(id: string, property: string, value: unknown) {
+ const layer = layers.find((existing) => existing.id === id);
+ if (!layer) throw new Error(`no such layer: ${id}`);
+ layer.layout = { ...layer.layout, [property]: value };
+ },
+ getPitch: () => pitch,
+ /** The view being leaned over, however it was — the 3D button, or Ctrl and a drag. */
+ tiltTo(value: number) {
+ pitch = value;
+ fire("pitch");
+ },
+ /** A style having finished loading, which is what wipes and rebuilds everything on it. */
+ loadStyle(replacement: LayerSpecification[]) {
+ layers = replacement;
+ this.layers = replacement;
+ fire("style.load");
+ },
+ on(event: string, listener: () => void) {
+ listeners.set(event, (listeners.get(event) ?? new Set()).add(listener));
+ },
+ off(event: string, listener: () => void) { listeners.get(event)?.delete(listener); },
+ get listenerCount() {
+ let count = 0;
+ for (const held of listeners.values()) count += held.size;
+ return count;
+ }
+ };
+}
+
+type FakeMap = ReturnType<typeof fakeMap>;
+
+function renderBuildings(map: FakeMap, isDarkTheme = false) {
+ let container: HTMLElement | undefined;
+ act(() => {
+ container = renderInto(
+ <ParentMap.Provider value={map as unknown as MapLibreGLMap}>
+ <Buildings isDarkTheme={isDarkTheme} />
+ </ParentMap.Provider>
+ );
+ });
+ if (!container) throw new Error("the buildings were not rendered");
+ return container;
+}
+
+/** The layer the component adds, or undefined while it stands down. */
+function extrusion(map: FakeMap) {
+ return map.layers.find((layer) => layer.id === BUILDINGS_LAYER);
+}
+
+/** Whether the style's own flat drawing of the same footprints is still being drawn. */
+function flatBuildingsVisible(map: FakeMap) {
+ return map.layers
+ .filter((layer) => "source-layer" in layer && layer["source-layer"] === "buildings" && layer.type === "fill")
+ .every((layer) => layer.layout?.visibility !== "none");
+}
+
+describe("geo map Buildings", () => {
+ it("stands the buildings up once the view is leaned over, and lays them back down with it", () => {
+ const map = fakeMap();
+ renderBuildings(map);
+
+ // A map looked straight down at is left exactly as the style drew it: a roof seen from
+ // above is the footprint already there, and the extrusion would only cost the draw twice.
+ expect(extrusion(map)).toBeUndefined();
+ expect(flatBuildingsVisible(map)).toBe(true);
+
+ act(() => map.tiltTo(45));
+
+ expect(extrusion(map)).toBeDefined();
+ // The flat drawing goes down as the standing one goes up — both at once would draw the
+ // same buildings twice, the fill showing through the walls at every ground floor.
+ expect(flatBuildingsVisible(map)).toBe(false);
+
+ act(() => map.tiltTo(0));
+
+ expect(extrusion(map)).toBeUndefined();
+ expect(flatBuildingsVisible(map)).toBe(true);
+ });
+
+ it("counts a lean already in force, the pitch never having been reported", () => {
+ // A map restored into a leaned-over view, whose "pitch" event fires only once something
+ // moves it — the buildings have to be up before that rather than after it.
+ const map = fakeMap({ pitch: 60 });
+ renderBuildings(map);
+
+ expect(extrusion(map)).toBeDefined();
+ });
+
+ it("stands them under the style's own labels, not over them", () => {
+ const map = fakeMap();
+ renderBuildings(map);
+
+ act(() => map.tiltTo(45));
+
+ // A place name buried behind a tower reads as a missing label.
+ const order = map.layers.map((layer) => layer.id);
+ expect(order.indexOf(BUILDINGS_LAYER)).toBeLessThan(order.indexOf("poi-amenity"));
+ expect(order.indexOf(BUILDINGS_LAYER)).toBeGreaterThan(order.indexOf("land"));
+ });
+
+ it("leaves a map with nothing to stand up alone", () => {
+ // The raster layer is a picture per tile: it carries no footprints, and asking its source
+ // for a layer of them would be an error per tile rather than a map without buildings.
+ const map = fakeMap({ layers: rasterStyleLayers() });
+ renderBuildings(map);
+
+ act(() => map.tiltTo(45));
+
+ expect(extrusion(map)).toBeUndefined();
+ expect(map.layers.map((layer) => layer.id)).toEqual([ "raster-layer" ]);
+ });
+
+ it("reads a height the tiles may one day not carry, and leaves the cut-out footprints down", () => {
+ const map = fakeMap();
+ renderBuildings(map);
+
+ act(() => map.tiltTo(45));
+ const layer = extrusion(map);
+
+ // The height is an experimental extension of the Shortbread schema rather than part of it,
+ // so the layer has to degrade to low blocks rather than to a flat plain if it is dropped.
+ expect(layer?.paint?.["fill-extrusion-height"]).toEqual([ "coalesce", [ "get", "height" ], 5 ]);
+ expect(layer?.paint?.["fill-extrusion-base"]).toEqual([ "coalesce", [ "get", "min_height" ], 0 ]);
+ // A footprint whose upper storeys are separate features would otherwise be drawn as a
+ // solid block standing in the space those features describe.
+ expect(layer?.filter).toEqual([ "!=", [ "get", "hide_3d" ], true ]);
+ expect(layer?.minzoom).toBe(14);
+ });
+
+ it("puts them back where a style switch left them, painted for the map that arrived", () => {
+ const map = fakeMap();
+ renderBuildings(map, false);
+ act(() => map.tiltTo(45));
+ const overLightMap = extrusion(map)?.paint?.["fill-extrusion-color"];
+
+ // A style switch carries the layer across (see keepAdditions in map.tsx) but appends what
+ // it carries above everything in the incoming style, labels included — and the flat fill
+ // it hid belongs to the style that has just gone.
+ const carriedOver = extrusion(map);
+ if (!carriedOver) throw new Error("nothing to carry over");
+ act(() => {
+ map.loadStyle([ ...vectorStyleLayers(), carriedOver ]);
+ render(
+ <ParentMap.Provider value={map as unknown as MapLibreGLMap}>
+ <Buildings isDarkTheme={true} />
+ </ParentMap.Provider>,
+ document.body.lastElementChild as HTMLElement
+ );
+ });
+
+ const order = map.layers.map((layer) => layer.id);
+ expect(order.filter((id) => id === BUILDINGS_LAYER)).toHaveLength(1);
+ expect(order.indexOf(BUILDINGS_LAYER)).toBeLessThan(order.indexOf("poi-amenity"));
+ expect(flatBuildingsVisible(map)).toBe(false);
+ // Repainted for the map that arrived rather than the one that left.
+ expect(extrusion(map)?.paint?.["fill-extrusion-color"]).not.toBe(overLightMap);
+ });
+
+ it("stops listening to a map it is taken off, giving the flat buildings back", () => {
+ const map = fakeMap();
+ const container = renderBuildings(map);
+ act(() => map.tiltTo(45));
+
+ act(() => { render(null, container); });
+
+ expect(extrusion(map)).toBeUndefined();
+ expect(flatBuildingsVisible(map)).toBe(true);
+ expect(map.listenerCount).toBe(0);
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/Buildings.tsx b/apps/client/src/widgets/collections/geomap/Buildings.tsx
new file mode 100644
index 0000000000..c2db3db15f
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/Buildings.tsx
@@ -0,0 +1,178 @@
+import { type AddLayerObject, type Map as MapLibreGLMap } from "maplibre-gl";
+import { useContext, useEffect } from "preact/hooks";
+
+import { ParentMap, useMapPitch } from "./map";
+
+/**
+ * The source every built-in vector style draws from, and the only one known to carry the heights
+ * below. A map on the raster layer, or on a style named by URL, has no such source and is left flat.
+ */
+const SHORTBREAD_SOURCE = "versatiles-shortbread";
+const BUILDINGS_SOURCE_LAYER = "buildings";
+export const BUILDINGS_LAYER = "buildings-3d";
+
+/** Where the tiles begin carrying footprints at all — Shortbread draws them from zoom 14. */
+const BUILDINGS_MIN_ZOOM = 14;
+
+/**
+ * The height a building whose own is missing is stood up at, in metres — a two-storey house, which
+ * is what most of an unsurveyed town turns out to be.
+ *
+ * Rarely reached: the tiles already fall back to this themselves, and every tile sampled from
+ * Manhattan to rural Iowa carried a height on all of its buildings. It is here because the height
+ * is an *experimental* extension of the Shortbread schema rather than part of it (see the note on
+ * {@link buildingsLayer}), so a build of the tiles without it must not stand every building on the
+ * map up to nothing.
+ */
+const ASSUMED_HEIGHT = 5;
+
+/**
+ * The buildings of the map underneath, stood up to the height they are in the world.
+ *
+ * Only while the view is leaned over. Standing them up on a map looked straight down at buys
+ * nothing — a roof seen from above is the footprint the style already draws — and costs the doubled
+ * draw of the flat fill this hides plus a per-building extrusion, so a map nobody tilts pays for
+ * none of it. It also means the 3D button now changes the map rather than only the angle it is seen
+ * from, which is what that button promises.
+ */
+export default function Buildings({ isDarkTheme }: { isDarkTheme: boolean }) {
+ const map = useContext(ParentMap);
+ const pitch = useMapPitch(map);
+ // However the view was leaned over — the button, or Ctrl and a drag. Before the hook's first
+ // report, which follows the very next tick, what the map already says it is.
+ const tilted = (pitch ?? map?.getPitch() ?? 0) > 0;
+
+ useEffect(() => {
+ if (!map || !tilted) return;
+
+ // A style is a world of its own and switching one takes every layer on the map with it, so
+ // this has to run again on each style load rather than only when the view is first leaned
+ // over. `keepAdditions` (see map.tsx) does carry this layer across, but it appends what it
+ // carries above everything in the incoming style — labels included — and the flat fill it
+ // hides belongs to the outgoing style and is not the one that needs hiding now. Installing
+ // again settles both.
+ const onStyleLoad = () => install(map, isDarkTheme);
+ map.on("style.load", onStyleLoad);
+
+ // A map that has been removed has no style, and asking one for a layer is not a no-op but a
+ // crash. The map is removed by the component above this one, whose cleanup Preact runs
+ // before this one's, so on a note switch this cleanup is always handed a dead map — the
+ // same reasoning as in Markers, and the same flag.
+ let mapRemoved = false;
+ const onMapRemove = () => { mapRemoved = true; };
+ map.on("remove", onMapRemove);
+
+ install(map, isDarkTheme);
+
+ return () => {
+ map.off("style.load", onStyleLoad);
+ map.off("remove", onMapRemove);
+ if (mapRemoved) return;
+ uninstall(map);
+ };
+ }, [ map, tilted, isDarkTheme ]);
+
+ return null;
+}
+
+/**
+ * Puts the layer up and takes the flat one down, on a style that has something to draw from.
+ *
+ * Removing a layer that is already there rather than leaving it be: it may have been carried over
+ * from the last style, in which case it is both in the wrong place in the draw order and painted
+ * for the wrong map. Adding it afresh settles both without a separate path for each.
+ */
+function install(map: MapLibreGLMap, isDarkTheme: boolean) {
+ if (!map.getSource(SHORTBREAD_SOURCE)) return;
+
+ if (map.getLayer(BUILDINGS_LAYER)) {
+ map.removeLayer(BUILDINGS_LAYER);
+ }
+ // Under the style's own labels rather than over them: a place name buried behind a tower reads
+ // as a missing label, and every 3D map worth copying puts its names on top. Under the markers
+ // too, as a consequence — they are symbol layers added after the style's own.
+ map.addLayer(buildingsLayer(isDarkTheme), firstSymbolLayer(map));
+
+ for (const id of flatBuildingLayers(map)) {
+ map.setLayoutProperty(id, "visibility", "none");
+ }
+}
+
+/** Takes the standing buildings back down and gives the flat ones back. */
+function uninstall(map: MapLibreGLMap) {
+ if (map.getLayer(BUILDINGS_LAYER)) {
+ map.removeLayer(BUILDINGS_LAYER);
+ }
+
+ for (const id of flatBuildingLayers(map)) {
+ map.setLayoutProperty(id, "visibility", "visible");
+ }
+}
+
+/**
+ * The layer that stands the buildings up.
+ *
+ * `height` and `min_height` are not part of the Shortbread schema the styles are built against —
+ * that documents a single `dummy` property and nothing else. They are a VersaTiles extension whose
+ * own documentation calls it experimental and reserves the right to rename or drop it without
+ * bumping the schema version, which is what the fallback height is for: the layer has to degrade to
+ * a townful of two-storey blocks rather than to a flat grey plain should that day come.
+ *
+ * `min_height` is where a building starts rather than where it stands — the upper half of a tower
+ * that widens at the base is a separate footprint beginning where the base ends. Its companion
+ * `hide_3d` marks the footprints that such parts are cut out of, which are to be left down: drawn
+ * as well, they would stand a solid block in the space the parts describe.
+ */
+function buildingsLayer(isDarkTheme: boolean): AddLayerObject {
+ return {
+ id: BUILDINGS_LAYER,
+ type: "fill-extrusion",
+ source: SHORTBREAD_SOURCE,
+ "source-layer": BUILDINGS_SOURCE_LAYER,
+ minzoom: BUILDINGS_MIN_ZOOM,
+ filter: [ "!=", [ "get", "hide_3d" ], true ],
+ paint: {
+ // Darker than it looks: MapLibre lights the walls, so the colour asked for is the
+ // shadowed side rather than the one that ends up on screen.
+ "fill-extrusion-color": isDarkTheme ? "#1b2027" : "#d8d3cc",
+ "fill-extrusion-height": [ "coalesce", [ "get", "height" ], ASSUMED_HEIGHT ],
+ "fill-extrusion-base": [ "coalesce", [ "get", "min_height" ], 0 ],
+ // Faded in across the zoom the footprints arrive at, as the flat fill this replaces is
+ // (see the styles' own `building` layer): buildings appearing all at once at a zoom
+ // boundary reads as the map glitching rather than as detail arriving.
+ "fill-extrusion-opacity": [
+ "interpolate", [ "linear" ], [ "zoom" ],
+ BUILDINGS_MIN_ZOOM, 0,
+ BUILDINGS_MIN_ZOOM + 1, 1
+ ]
+ // `fill-extrusion-vertical-gradient` is left at its default of true, which shades the
+ // walls down their height and is what keeps a block of flats from reading as a slab of
+ // one flat colour.
+ }
+ };
+}
+
+/**
+ * The style's own flat drawing of the same footprints, which the standing ones replace.
+ *
+ * Found by what they draw rather than by name: the five built-in styles do not agree on how many
+ * such layers they have — four carry an outline beneath the fill and one does not — and a style
+ * named by URL is not ours to know the names in at all.
+ */
+function flatBuildingLayers(map: MapLibreGLMap): string[] {
+ return map.getStyle().layers
+ .filter((layer) => "source-layer" in layer
+ && layer["source-layer"] === BUILDINGS_SOURCE_LAYER
+ && layer.type === "fill")
+ .map((layer) => layer.id);
+}
+
+/**
+ * What the buildings are to stand under: the first thing the style draws text or an icon with.
+ *
+ * Undefined where the style draws neither, which MapLibre reads as the top of the map — the right
+ * answer for a style with no labels to be buried behind.
+ */
+function firstSymbolLayer(map: MapLibreGLMap): string | undefined {
+ return map.getStyle().layers.find((layer) => layer.type === "symbol")?.id;
+}
diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
index a644ac766b..785ca0b687 100644
--- a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx
@@ -6,7 +6,7 @@ import { useContext, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
import { isMobile } from "../../../services/utils";
import { useFullscreen, useStaticTooltip } from "../../react/hooks";
-import { ParentMap } from "./map";
+import { ParentMap, useMapPitch } from "./map";
/**
* The controls standing in the corner of a geo map: how close in the map is drawn, and how much of
@@ -144,25 +144,3 @@ function useMapZoom(map: MapLibreGLMap | null) {
return zoom;
}
-
-/**
- * How far the view is leaned over, followed as it changes — by the tilt button, or by Ctrl and a
- * drag, which MapLibre honours without being asked. Read for which view the button should offer:
- * a tilt entered by hand is as much a 3D view as one the button gave.
- */
-function useMapPitch(map: MapLibreGLMap | null) {
- const [ pitch, setPitch ] = useState<number | null>(null);
-
- useEffect(() => {
- if (!map) return;
-
- const report = () => setPitch(map.getPitch());
- // The map may have been tilted between being built and being listened to.
- report();
-
- map.on("pitch", report);
- return () => { map.off("pitch", report); };
- }, [ map ]);
-
- return pitch;
-}
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index 605ca5d74b..345c96defe 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -14,6 +14,7 @@ import ActionButton from "../../react/ActionButton";
import { useCollectionTreeDrag, useNoteBlob, useNoteLabel, useNoteLabelBoolean, useNoteProperty, useSpacedUpdate } from "../../react/hooks";
import { ViewModeProps } from "../interface";
import { createNewNote, importGpxTrack, moveMarker } from "./api";
+import Buildings from "./Buildings";
import ContextMenus from "./ContextMenus";
import DetailPane, { PaneSelection } from "./DetailPane";
import EditToolbar from "./EditToolbar";
@@ -255,6 +256,9 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
{placement && <GhostPin note={placement.mode === "move" ? notes.find((n) => n.noteId === placement.noteId) : undefined} />}
<DetailPane notes={notes} parentNote={note} placing={!!placement} isReadOnly={isReadOnly} selection={selection} onSelect={setSelection} onRelocate={startMarkerRelocation} />
<ContextMenus parentNote={note} isReadOnly={isReadOnly} onRelocate={startMarkerRelocation} onCreateNote={createNoteAt} />
+ {/* Stood up only while the view is leaned over, so the 3D button changes the map
+ and not merely the angle it is seen from. */}
+ <Buildings isDarkTheme={layerData.isDarkTheme ?? false} />
{/* The pane above is what a click on a marker opens now, so the markers no longer
open the note themselves — the two would otherwise both answer the same click,
raising the quick editor over the pane that had just opened behind it. */}
diff --git a/apps/client/src/widgets/collections/geomap/map.tsx b/apps/client/src/widgets/collections/geomap/map.tsx
index 300c22cf15..ada546aded 100644
--- a/apps/client/src/widgets/collections/geomap/map.tsx
+++ b/apps/client/src/widgets/collections/geomap/map.tsx
@@ -351,6 +351,31 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi
);
}
+/**
+ * How far the view is leaned over, followed as it changes — by the tilt button, or by Ctrl and a
+ * drag, which MapLibre honours without being asked.
+ *
+ * Read by anything whose answer differs between a flat map and a leaned-over one: which view the
+ * tilt button should offer (see {@link MapToolbar} — a tilt entered by hand is as much a 3D view as
+ * one the button gave), and whether the buildings are worth standing up (see {@link Buildings}).
+ */
+export function useMapPitch(map: MapLibreGLMap | null) {
+ const [ pitch, setPitch ] = useState<number | null>(null);
+
+ useEffect(() => {
+ if (!map) return;
+
+ const report = () => setPitch(map.getPitch());
+ // The map may have been tilted between being built and being listened to.
+ report();
+
+ map.on("pitch", report);
+ return () => { map.off("pitch", report); };
+ }, [ map ]);
+
+ return pitch;
+}
+
/**
* Builds the map itself.
*