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
fix(geomap): repaint the markers on a style switch rather than rebuild them
Elian Doran9a73269be384
diff --git a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx b/apps/client/src/widgets/collections/geomap/Markers.spec.tsxindex a472490693..cf888e1791 100644--- a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx@@ -33,7 +33,9 @@ function fakeMap() {const sources = new Set<string>();const listeners = new Map<string, Set<() => void>>();const calls = { addLayer: 0, removeLayer: 0, addSource: 0, removeSource: 0, setData: 0 };+ const properties = new Map<string, unknown>();let lastFeatures: unknown[] = [];+ let lastLayer: { layout?: Record<string, unknown>, paint?: Record<string, unknown> } | undefined;let removed = false;/** What every style-reading call becomes once the map is gone: `this.style is undefined`. */@@ -44,6 +46,10 @@ function fakeMap() {return {calls,get lastFeatures() { return lastFeatures; },+ /** The layout and paint the layer was added with, as `addLayer` was given them. */+ get lastLayer() { return lastLayer; },+ /** What a layout or paint property has been set to since, by name. */+ property(name: string) { return properties.get(name); },fireStyleLoad() {for (const fn of listeners.get("style.load") ?? []) fn();},@@ -83,8 +89,14 @@ function fakeMap() {requireStyle();return layers.has(id) ? { id } : undefined;},- addLayer({ id }: { id: string }) { layers.add(id); calls.addLayer++; },- removeLayer(id: string) { layers.delete(id); calls.removeLayer++; }+ addLayer(layer: { id: string, layout?: Record<string, unknown>, paint?: Record<string, unknown> }) {+ layers.add(layer.id);+ lastLayer = layer;+ calls.addLayer++;+ },+ removeLayer(id: string) { layers.delete(id); calls.removeLayer++; },+ setLayoutProperty(_id: string, name: string, value: unknown) { properties.set(name, value); },+ setPaintProperty(_id: string, name: string, value: unknown) { properties.set(name, value); }};}@@ -137,12 +149,17 @@ describe("Markers", () => {vi.unstubAllGlobals();});- function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, parent: Component) {+ /** Renders into the same container, so calling it again is a re-render with fresh props. */+ function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, parent: Component, look?: { hideLabels?: boolean, isDarkTheme?: boolean }) {return act(async () => {render(<ParentComponent.Provider value={parent}><ParentMap.Provider value={map as never}>- <Markers notes={notes} hideLabels={false} isDarkTheme={false} />+ <Markers+ notes={notes}+ hideLabels={look?.hideLabels ?? false}+ isDarkTheme={look?.isDarkTheme ?? false}+ /></ParentMap.Provider></ParentComponent.Provider>,container as HTMLElement@@ -184,6 +201,58 @@ describe("Markers", () => {expect(map.lastFeatures).toHaveLength(1);});+ it("repaints rather than rebuilds when the map switches between a light and a dark style", async () => {+ // The same array both times, as the view hands it over: the notes shown are keyed on the+ // note itself, and switching the style is nothing to do with them.+ const notes = [ buildNote({ title: "Somewhere", "#geolocation": "1,2" }) ];+ const map = fakeMap();+ const parent = new Component();++ await mount(notes, map, parent);+ await act(async () => {+ map.fireStyleLoad();+ await settle();+ });++ expect(map.lastLayer?.paint?.["text-color"]).toBe("#333");+ expect(map.lastLayer?.layout?.["text-field"]).toEqual([ "get", "name" ]);+ const setDataBefore = map.calls.setData;++ // The map is switched to a dark style, and its titles hidden.+ await mount(notes, map, parent, { isDarkTheme: true, hideLabels: true });+ await act(async () => { await settle(); });++ // The layer stood throughout, and the markers were never built again for it.+ expect(map.calls.removeLayer).toBe(0);+ expect(map.calls.removeSource).toBe(0);+ expect(map.calls.addLayer).toBe(1);+ expect(map.calls.setData).toBe(setDataBefore);++ expect(map.property("text-color")).toBe("#fff");+ expect(map.property("text-halo-color")).toBe("rgba(0, 0, 0, 0.8)");+ expect(map.property("text-field")).toBe("");+ });++ it("gives a layer added after a style switch the look it is being shown with", async () => {+ const note = buildNote({ title: "Somewhere", "#geolocation": "1,2" });+ const map = fakeMap();+ const parent = new Component();++ // Dark from the outset, so the first layer this map is given is the one under test.+ await mount([ note ], map, parent, { isDarkTheme: true, hideLabels: true });+ await act(async () => {+ map.fireStyleLoad();+ await settle();+ });++ expect(map.lastLayer?.paint?.["text-color"]).toBe("#fff");+ expect(map.lastLayer?.paint?.["text-halo-color"]).toBe("rgba(0, 0, 0, 0.8)");+ expect(map.lastLayer?.layout?.["text-field"]).toBe("");+ // Hiding the titles empties the field rather than dropping the layout, so the rest of it+ // still has to be there for showing them again to be a single property.+ expect(map.lastLayer?.layout?.["text-optional"]).toBe(true);+ });+it("takes the layer down when the component goes away", async () => {const note = buildNote({ title: "Somewhere else", "#geolocation": "3,4" });const map = fakeMap();diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsxindex e8cd4b7a45..d2220b78cf 100644--- a/apps/client/src/widgets/collections/geomap/Markers.tsx+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx@@ -47,6 +47,32 @@ const LABEL_LAYOUT: Extract<AddLayerObject, { type: "symbol" }>["layout"] = {"text-padding": 4};+/**+ * What a title is drawn in, over a light map and over a dark one.+ *+ * 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.+ */+const LABEL_PAINT = {+ light: {+ "text-color": "#333",+ "text-halo-color": "rgba(255, 255, 255, 0.8)"+ },+ dark: {+ "text-color": "#fff",+ "text-halo-color": "rgba(0, 0, 0, 0.8)"+ }+};++/**+ * The title of a marker whose titles are hidden.+ *+ * Hiding them empties the field rather than dropping the label layout, so that showing them again is+ * one property set on the standing layer — see the paint effect in {@link Markers}.+ */+const HIDDEN_TEXT_FIELD = "";+/*** Every note that carries a location, drawn as one symbol layer.*@@ -64,6 +90,12 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo// 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>>>();+ // How the titles are to be drawn, read rather than depended on: `install` is what builds the+ // layer, so a version of it per look would take the layer down and every marker with it for+ // what is two paint properties and a layout one. Only a layer being added fresh reads this —+ // one already standing is repainted by the effect at the end.+ const labelStyle = useRef({ hideLabels, isDarkTheme });+ labelStyle.current = { hideLabels, isDarkTheme };/*** Puts the layer and its data on the map. A style is a world of its own — switching one wipes@@ -108,19 +140,15 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo// LABEL_LAYOUT). The pins still take part in placement, so a title is never// laid over one."icon-allow-overlap": true,- ...(hideLabels ? {} : LABEL_LAYOUT)+ ...LABEL_LAYOUT,+ ...(labelStyle.current.hideLabels ? { "text-field": HIDDEN_TEXT_FIELD } : {})},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)",+ ...LABEL_PAINT[labelStyle.current.isDarkTheme ? "dark" : "light"],"text-halo-width": 2,"text-halo-blur": 1}@@ -131,12 +159,12 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNotype: "FeatureCollection",features});- }, [ map, hideLabels, isDarkTheme ]);+ }, [ map ]);- // 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.+ // The layer, which stands for as long as the map does. Neither editing a note nor changing the+ // look of a title comes 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;@@ -204,6 +232,21 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo};}, [ map, notes, version, install ]);+ // The look of the titles, set on the layer already standing. Switching the map between a light+ // and a dark style — or hiding the titles — is a repaint of three properties, not a reason to+ // build every marker again: the pins are unaffected by either, and the rebuild that used to+ // follow took the whole layer off the map for as long as it ran. Nothing to do until the layer+ // is up, since one added after this has the current look built into it (see `install`).+ useEffect(() => {+ if (!map?.getLayer(MARKER_LAYER)) return;++ map.setLayoutProperty(MARKER_LAYER, "text-field",+ hideLabels ? HIDDEN_TEXT_FIELD : LABEL_LAYOUT?.["text-field"]);+ for (const [ property, value ] of Object.entries(LABEL_PAINT[isDarkTheme ? "dark" : "light"])) {+ map.setPaintProperty(MARKER_LAYER, property, value);+ }+ }, [ map, hideLabels, isDarkTheme ]);+return null;}