Skip to content

Build your personal knowledge base with Trilium Notes

fix(geomap): redraw the markers on an edit rather than rebuild them

Elian Dorand59b49b977f6
diff --git a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
new file mode 100644
index 0000000000..eea4e462f5
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
@@ -0,0 +1,186 @@
+/**
+ * Regression test for every marker on a geo map blinking when a single note changed.
+ *
+ * The layer and the data it carries were built by one effect keyed on everything at once — the map,
+ * the look of a marker, and the notes. Any change ran its cleanup, which removed the layer and its
+ * source outright, and the markers only came back once all of them had been built again — a build
+ * that is asynchronous. Recolouring one note therefore took every marker on the map off and put
+ * them all back a few frames later.
+ *
+ * The two are separate now: the layer stands for as long as the map and the look do, and a note
+ * being edited reaches it as data.
+ */
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../../components/component";
+import type FNote from "../../../entities/fnote";
+import type { EntityChange } from "../../../server_types";
+import LoadResults from "../../../services/load_results";
+import { buildNote } from "../../../test/easy-froca";
+import { ParentComponent } from "../../react/react_utils";
+import { ParentMap } from "./map";
+import Markers, { MARKER_LAYER } from "./Markers";
+
+vi.mock("../../../services/icon_glyphs", () => ({
+ renderIconImage: vi.fn(async () => "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=")
+}));
+
+/** A map that records what the component does to it, standing in for MapLibre. */
+function fakeMap() {
+ const layers = new Set<string>();
+ const sources = new Set<string>();
+ const listeners = new Map<string, Set<() => void>>();
+ const calls = { addLayer: 0, removeLayer: 0, addSource: 0, removeSource: 0, setData: 0 };
+ let lastFeatures: unknown[] = [];
+
+ return {
+ calls,
+ get lastFeatures() { return lastFeatures; },
+ fireStyleLoad() {
+ for (const fn of listeners.get("style.load") ?? []) fn();
+ },
+ on(event: string, fn: () => void) {
+ if (!listeners.has(event)) listeners.set(event, new Set());
+ listeners.get(event)?.add(fn);
+ },
+ off(event: string, fn: () => void) {
+ listeners.get(event)?.delete(fn);
+ },
+ isStyleLoaded: () => false,
+ hasImage: () => false,
+ addImage: () => {},
+ getSource(id: string) {
+ if (!sources.has(id)) return undefined;
+ return {
+ setData: ({ features }: { features: unknown[] }) => {
+ calls.setData++;
+ lastFeatures = features;
+ }
+ };
+ },
+ addSource(id: string) { sources.add(id); calls.addSource++; },
+ removeSource(id: string) { sources.delete(id); calls.removeSource++; },
+ getLayer: (id: string) => (layers.has(id) ? { id } : undefined),
+ addLayer({ id }: { id: string }) { layers.add(id); calls.addLayer++; },
+ removeLayer(id: string) { layers.delete(id); calls.removeLayer++; }
+ };
+}
+
+/** Drains the awaits in buildMarkerData (icon render → svg decode → setData). */
+async function settle() {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve));
+}
+
+/** An `entitiesReloaded` carrying a colour change to one of the map's notes. */
+function colourChanged(note: FNote) {
+ const attributeId = `attr-${note.noteId}`;
+ const loadResults = new LoadResults([
+ {
+ entityName: "attributes",
+ entityId: attributeId,
+ entity: { attributeId, noteId: note.noteId, type: "label", name: "color", value: "red" },
+ componentId: "comp-1"
+ } as unknown as EntityChange
+ ]);
+ loadResults.addAttribute(attributeId, "comp-1");
+ return loadResults;
+}
+
+describe("Markers", () => {
+ let container: HTMLElement | undefined;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+
+ // A pin is drawn by handing an SVG blob to an <img> and waiting for it to load, which no DOM
+ // stand-in actually does. Without this the build never resolves and nothing is ever put on
+ // the map.
+ vi.stubGlobal("Image", class {
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ set src(_value: string) {
+ setTimeout(() => this.onload?.());
+ }
+ });
+ vi.stubGlobal("URL", { ...URL, createObjectURL: () => "blob:pin", revokeObjectURL: () => {} });
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ vi.unstubAllGlobals();
+ });
+
+ function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, parent: Component) {
+ return act(async () => {
+ render(
+ <ParentComponent.Provider value={parent}>
+ <ParentMap.Provider value={map as never}>
+ <Markers notes={notes} hideLabels={false} isDarkTheme={false} />
+ </ParentMap.Provider>
+ </ParentComponent.Provider>,
+ container as HTMLElement
+ );
+ });
+ }
+
+ it("redraws rather than rebuilds when a note changes", async () => {
+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });
+ const map = fakeMap();
+ const parent = new Component();
+
+ await mount([ note ], map, parent);
+ // The style arrives after the component is up, as it does on a real map.
+ await act(async () => {
+ map.fireStyleLoad();
+ await settle();
+ });
+
+ expect(map.getLayer(MARKER_LAYER)).toBeTruthy();
+ expect(map.calls.addLayer).toBe(1);
+ expect(map.lastFeatures).toHaveLength(1);
+ const setDataBefore = map.calls.setData;
+
+ // One note is recoloured.
+ await act(async () => {
+ await parent.handleEvent("entitiesReloaded", { loadResults: colourChanged(note) });
+ await settle();
+ });
+ // The rebuild is started by the effect act() flushes on its way out, so its promise chain
+ // only runs once act has returned.
+ await act(async () => { await settle(); });
+
+ // The layer stood throughout — it was handed fresh data rather than torn down and remade.
+ expect(map.calls.removeLayer).toBe(0);
+ expect(map.calls.removeSource).toBe(0);
+ expect(map.calls.addLayer).toBe(1);
+ expect(map.calls.setData).toBeGreaterThan(setDataBefore);
+ expect(map.lastFeatures).toHaveLength(1);
+ });
+
+ it("takes the layer down when the component goes away", async () => {
+ const note = buildNote({ title: "Somewhere else", "#geolocation": "3,4" });
+ const map = fakeMap();
+ const parent = new Component();
+
+ await mount([ note ], map, parent);
+ await act(async () => {
+ map.fireStyleLoad();
+ await settle();
+ });
+ expect(map.calls.addLayer).toBe(1);
+
+ await act(async () => {
+ render(null, container as HTMLElement);
+ });
+
+ expect(map.calls.removeLayer).toBe(1);
+ expect(map.calls.removeSource).toBe(1);
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsx
index 7e2580e398..1494d59067 100644
--- a/apps/client/src/widgets/collections/geomap/Markers.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx
@@ -1,5 +1,5 @@
import { AddLayerObject, type GeoJSONSource } from "maplibre-gl";
-import { useContext, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";
import FNote from "../../../entities/fnote";
import { getReadableTextColor } from "../../../services/css_class_manager";
@@ -57,84 +57,89 @@ const LABEL_LAYOUT: Extract<AddLayerObject, { type: "symbol" }>["layout"] = {
export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNote[], hideLabels: boolean, isDarkTheme: boolean }) {
const map = useContext(ParentMap);
const version = useNoteChangeVersion(notes);
- // Whether the style has finished loading at least once. Held outside the effect because the
- // effect re-runs whenever the notes change, and a run that starts after the style has loaded
- // has no other way to learn that it did — `style.load` fires once per style and is long gone.
+ // Whether the style has finished loading at least once. Held outside the effects because either
+ // may run after the style has loaded, and one that does has no other way to learn that it did —
+ // `style.load` fires once per style and is long gone.
const styleLoaded = useRef(false);
-
- useEffect(() => {
- if (!map) return;
-
- let cancelled = false;
- let data: Awaited<ReturnType<typeof buildMarkerData>> | undefined;
-
- /**
- * Puts the layer and its data back on the map. A style is a world of its own — switching
- * one wipes every source, layer and image added to the last — so this has to run again
- * after each style load, not only when the notes change. Does nothing until there is both a
- * loaded style to add to and something to add.
- */
- function install() {
- if (!map || !data || !styleLoaded.current) return;
- const { features, images } = data;
-
- for (const [ id, image ] of images) {
- if (!map.hasImage(id)) {
- map.addImage(id, image, { pixelRatio: window.devicePixelRatio || 1 });
- }
- }
-
- if (!map.getSource(MARKER_SOURCE)) {
- map.addSource(MARKER_SOURCE, {
- type: "geojson",
- data: { type: "FeatureCollection", features: [] }
- });
+ // The markers last built, kept where both effects can reach them: the layer has to be able to
+ // fill itself again the moment it is rebuilt, without waiting on a fresh build.
+ const markerData = useRef<Awaited<ReturnType<typeof buildMarkerData>>>();
+
+ /**
+ * Puts the layer and its data on the map. A style is a world of its own — switching one wipes
+ * every source, layer and image added to the last — so this has to run again after each style
+ * load, not only when the notes change. Does nothing until there is both a loaded style to add
+ * to and something to add.
+ */
+ const install = useCallback(() => {
+ const data = markerData.current;
+ if (!map || !data || !styleLoaded.current) return;
+ const { features, images } = data;
+
+ for (const [ id, image ] of images) {
+ if (!map.hasImage(id)) {
+ map.addImage(id, image, { pixelRatio: window.devicePixelRatio || 1 });
}
+ }
- if (!map.getLayer(MARKER_LAYER)) {
- map.addLayer({
- id: MARKER_LAYER,
- type: "symbol",
- source: MARKER_SOURCE,
- layout: {
- "icon-image": [ "get", "icon" ],
- "icon-size": 1,
- "icon-anchor": "bottom",
- // The image carries padding for the shadow, so its bottom edge sits below
- // the pin's tip. Push it back down by exactly that much, or every marker
- // would stand a shadow's width off its own coordinate.
- "icon-offset": [ 0, MARKER_SHADOW_PADDING ],
- // Every note keeps its pin, however crowded the map: a pin dropped for
- // colliding is a note that has silently left the map, and one that can no
- // longer be hovered or right-clicked. Only the titles are thinned out (see
- // LABEL_LAYOUT). The pins still take part in placement, so a title is never
- // laid over one.
- "icon-allow-overlap": true,
- ...(hideLabels ? {} : LABEL_LAYOUT)
- },
- paint: {
- // Archived notes are drawn faintly, as they were when each marker was an
- // element of its own wearing an `archived` class.
- "icon-opacity": [ "case", [ "get", "archived" ], 0.5, 1 ],
- "text-opacity": [ "case", [ "get", "archived" ], 0.5, 1 ],
- // A title is drawn the way the style draws its own place names: light on
- // the dark styles, and haloed by a soft, blurred glow rather than a hard
- // keyline. A crisp white outline stood out as a cut-out sticker on any map,
- // and on a dark one it was a white edge around dark text.
- "text-color": isDarkTheme ? "#fff" : "#333",
- "text-halo-color": isDarkTheme ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255, 0.8)",
- "text-halo-width": 2,
- "text-halo-blur": 1
- }
- });
- }
+ if (!map.getSource(MARKER_SOURCE)) {
+ map.addSource(MARKER_SOURCE, {
+ type: "geojson",
+ data: { type: "FeatureCollection", features: [] }
+ });
+ }
- map.getSource<GeoJSONSource>(MARKER_SOURCE)?.setData({
- type: "FeatureCollection",
- features
+ if (!map.getLayer(MARKER_LAYER)) {
+ map.addLayer({
+ id: MARKER_LAYER,
+ type: "symbol",
+ source: MARKER_SOURCE,
+ layout: {
+ "icon-image": [ "get", "icon" ],
+ "icon-size": 1,
+ "icon-anchor": "bottom",
+ // The image carries padding for the shadow, so its bottom edge sits below
+ // the pin's tip. Push it back down by exactly that much, or every marker
+ // would stand a shadow's width off its own coordinate.
+ "icon-offset": [ 0, MARKER_SHADOW_PADDING ],
+ // Every note keeps its pin, however crowded the map: a pin dropped for
+ // colliding is a note that has silently left the map, and one that can no
+ // longer be hovered or right-clicked. Only the titles are thinned out (see
+ // LABEL_LAYOUT). The pins still take part in placement, so a title is never
+ // laid over one.
+ "icon-allow-overlap": true,
+ ...(hideLabels ? {} : LABEL_LAYOUT)
+ },
+ paint: {
+ // Archived notes are drawn faintly, as they were when each marker was an
+ // element of its own wearing an `archived` class.
+ "icon-opacity": [ "case", [ "get", "archived" ], 0.5, 1 ],
+ "text-opacity": [ "case", [ "get", "archived" ], 0.5, 1 ],
+ // A title is drawn the way the style draws its own place names: light on
+ // the dark styles, and haloed by a soft, blurred glow rather than a hard
+ // keyline. A crisp white outline stood out as a cut-out sticker on any map,
+ // and on a dark one it was a white edge around dark text.
+ "text-color": isDarkTheme ? "#fff" : "#333",
+ "text-halo-color": isDarkTheme ? "rgba(0, 0, 0, 0.8)" : "rgba(255, 255, 255, 0.8)",
+ "text-halo-width": 2,
+ "text-halo-blur": 1
+ }
});
}
+ map.getSource<GeoJSONSource>(MARKER_SOURCE)?.setData({
+ type: "FeatureCollection",
+ features
+ });
+ }, [ map, hideLabels, isDarkTheme ]);
+
+ // The layer, which stands for as long as the map and the look of a marker do. Editing a note
+ // does not come through here: taking the layer down and putting it back is what made one note's
+ // colour blink every marker on the map off and back on, since the layer went at once and the
+ // markers only returned once all of them had been built again.
+ useEffect(() => {
+ if (!map) return;
+
function onStyleLoad() {
styleLoaded.current = true;
install();
@@ -152,14 +157,11 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
styleLoaded.current = true;
}
- buildMarkerData(notes).then((built) => {
- if (cancelled) return;
- data = built;
- install();
- });
+ // Whatever was last built goes straight back on, so a rebuilt layer is never empty while it
+ // waits for a build it does not need.
+ install();
return () => {
- cancelled = true;
map.off("style.load", onStyleLoad);
if (map.getLayer(MARKER_LAYER)) {
map.removeLayer(MARKER_LAYER);
@@ -168,7 +170,24 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
map.removeSource(MARKER_SOURCE);
}
};
- }, [ map, notes, hideLabels, isDarkTheme, version ]);
+ }, [ map, install ]);
+
+ // The markers themselves, handed to the standing layer as data. A note being edited reaches the
+ // map through here and nowhere else, so the map is redrawn rather than rebuilt.
+ useEffect(() => {
+ if (!map) return;
+
+ let cancelled = false;
+ buildMarkerData(notes).then((built) => {
+ if (cancelled) return;
+ markerData.current = built;
+ install();
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [ map, notes, version, install ]);
return null;
}