Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): gather crowded markers into bubbles, when the map asks for it

Elian Doran7d0dde60188c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index fd0b325566..9c60ecfc71 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -754,6 +754,7 @@
"map_style": "Which style a geo map is drawn in, chosen from the raster and vector styles offered in the collection properties.",
"map_scale": "Shows a scale bar on the geo map.",
"map_hide_labels": "Hides the note titles beside the markers on a geo map.",
+ "map_cluster": "Gathers markers that are drawn close together into a single numbered bubble, which opens when clicked.",
"presentation_theme": "Which theme a presentation is shown with.",
"slide_background": "The background of a slide, as a colour or as a CSS gradient.",
"tab_width": "How many spaces wide one level of indentation is in this code note.",
@@ -3062,7 +3063,8 @@
"vector_light": "Vector (Light)",
"vector_dark": "Vector (Dark)",
"show-scale": "Show scale",
- "show-labels": "Show marker names"
+ "show-labels": "Show marker names",
+ "cluster-markers": "Group nearby markers"
},
"table_context_menu": {
"delete_row": "Delete row"
diff --git a/apps/client/src/widgets/attribute_widgets/attr_help.ts b/apps/client/src/widgets/attribute_widgets/attr_help.ts
index 384cd1c86c..bbae99c8f3 100644
--- a/apps/client/src/widgets/attribute_widgets/attr_help.ts
+++ b/apps/client/src/widgets/attribute_widgets/attr_help.ts
@@ -177,6 +177,7 @@ export const ATTR_HELP: AttrHelpMap = {
"map:style": t("attribute_detail.map_style"),
"map:scale": t("attribute_detail.map_scale"),
"map:hideLabels": t("attribute_detail.map_hide_labels"),
+ "map:cluster": t("attribute_detail.map_cluster"),
"presentation:theme": t("attribute_detail.presentation_theme"),
"slide:background": t("attribute_detail.slide_background"),
tabWidth: t("attribute_detail.tab_width"),
diff --git a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
index cf888e1791..def00fbeb5 100644
--- a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
@@ -20,22 +20,33 @@ 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 { CLUSTER_COUNT_LAYER, CLUSTER_LAYER } from "./clusters";
import { ParentMap } from "./map";
-import Markers, { MARKER_LAYER } from "./Markers";
+import Markers, { MARKER_LAYER, MARKER_SOURCE } from "./Markers";
vi.mock("../../../services/icon_glyphs", () => ({
renderIconImage: vi.fn(async () => "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=")
}));
+/** What a map that gathers its notes puts up: the pins, the bubbles, and the bubbles' counts. */
+const CLUSTERED_LAYER_COUNT = 3;
+
+interface FakeLayer {
+ id: string;
+ filter?: unknown;
+ layout?: Record<string, unknown>;
+ paint?: Record<string, unknown>;
+}
+
/** 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 layers = new Map<string, FakeLayer>();
+ const sources = new Map<string, unknown>();
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>();
+ const canvas = { style: {} as Record<string, string> };
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`. */
@@ -46,10 +57,12 @@ 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); },
+ /** The filter, layout and paint a layer was added with, as `addLayer` was given them. */
+ layer(id: string) { return layers.get(id); },
+ /** What a layout or paint property of a layer has been set to since, by name. */
+ property(id: string, name: string) { return properties.get(`${id}/${name}`); },
+ /** What a source was added with, which is where the clustering options live. */
+ source(id: string) { return sources.get(id); },
fireStyleLoad() {
for (const fn of listeners.get("style.load") ?? []) fn();
},
@@ -63,16 +76,23 @@ function fakeMap() {
removed = true;
for (const fn of listeners.get("remove") ?? []) fn();
},
- on(event: string, fn: () => void) {
+ /**
+ * MapLibre lets a listener be scoped to a layer, which the cluster handlers use — the layer
+ * comes between the event and the handler when it does. Keyed by event alone here, since
+ * nothing in these tests fires a layer-scoped one.
+ */
+ on(event: string, fnOrLayer: unknown, fn?: () => void) {
+ const handler = (fn ?? fnOrLayer) as () => void;
if (!listeners.has(event)) listeners.set(event, new Set());
- listeners.get(event)?.add(fn);
+ listeners.get(event)?.add(handler);
},
- off(event: string, fn: () => void) {
- listeners.get(event)?.delete(fn);
+ off(event: string, fnOrLayer: unknown, fn?: () => void) {
+ listeners.get(event)?.delete((fn ?? fnOrLayer) as () => void);
},
isStyleLoaded: () => false,
hasImage: () => false,
addImage: () => {},
+ getCanvas: () => canvas,
getSource(id: string) {
requireStyle();
if (!sources.has(id)) return undefined;
@@ -83,20 +103,19 @@ function fakeMap() {
}
};
},
- addSource(id: string) { sources.add(id); calls.addSource++; },
+ addSource(id: string, source: unknown) { sources.set(id, source); calls.addSource++; },
removeSource(id: string) { sources.delete(id); calls.removeSource++; },
getLayer: (id: string) => {
requireStyle();
return layers.has(id) ? { id } : undefined;
},
- addLayer(layer: { id: string, layout?: Record<string, unknown>, paint?: Record<string, unknown> }) {
- layers.add(layer.id);
- lastLayer = layer;
+ addLayer(layer: FakeLayer) {
+ layers.set(layer.id, 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); }
+ setLayoutProperty(id: string, name: string, value: unknown) { properties.set(`${id}/${name}`, value); },
+ setPaintProperty(id: string, name: string, value: unknown) { properties.set(`${id}/${name}`, value); }
};
}
@@ -150,7 +169,7 @@ describe("Markers", () => {
});
/** 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 }) {
+ function mount(notes: FNote[], map: ReturnType<typeof fakeMap>, parent: Component, look?: { hideLabels?: boolean, isDarkTheme?: boolean, clustered?: boolean }) {
return act(async () => {
render(
<ParentComponent.Provider value={parent}>
@@ -159,6 +178,7 @@ describe("Markers", () => {
notes={notes}
hideLabels={look?.hideLabels ?? false}
isDarkTheme={look?.isDarkTheme ?? false}
+ clustered={look?.clustered ?? false}
/>
</ParentMap.Provider>
</ParentComponent.Provider>,
@@ -214,8 +234,8 @@ describe("Markers", () => {
await settle();
});
- expect(map.lastLayer?.paint?.["text-color"]).toBe("#333");
- expect(map.lastLayer?.layout?.["text-field"]).toEqual([ "get", "name" ]);
+ expect(map.layer(MARKER_LAYER)?.paint?.["text-color"]).toBe("#333");
+ expect(map.layer(MARKER_LAYER)?.layout?.["text-field"]).toEqual([ "get", "name" ]);
const setDataBefore = map.calls.setData;
// The map is switched to a dark style, and its titles hidden.
@@ -228,9 +248,9 @@ describe("Markers", () => {
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("");
+ expect(map.property(MARKER_LAYER, "text-color")).toBe("#fff");
+ expect(map.property(MARKER_LAYER, "text-halo-color")).toBe("rgba(0, 0, 0, 0.8)");
+ expect(map.property(MARKER_LAYER, "text-field")).toBe("");
});
it("gives a layer added after a style switch the look it is being shown with", async () => {
@@ -245,12 +265,104 @@ describe("Markers", () => {
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("");
+ expect(map.layer(MARKER_LAYER)?.paint?.["text-color"]).toBe("#fff");
+ expect(map.layer(MARKER_LAYER)?.paint?.["text-halo-color"]).toBe("rgba(0, 0, 0, 0.8)");
+ expect(map.layer(MARKER_LAYER)?.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);
+ expect(map.layer(MARKER_LAYER)?.layout?.["text-optional"]).toBe(true);
+ });
+
+ /**
+ * Regression test for crowded notes appearing to vanish as the map was zoomed.
+ *
+ * Clustering was turned on at the source without anything being drawn for the groups it makes.
+ * A clustered source hands its groups out through the same source as the notes it left alone,
+ * and a group carries none of a note's properties — no `icon`, so the pin layer had no image to
+ * stamp for one, and no `name`, so it had no title either. The pins therefore thinned out as the
+ * map zoomed and nothing took their place, which read as markers flickering in and out at random
+ * rather than as notes being gathered together.
+ */
+ it("draws a bubble for each group of notes and keeps the pins off them", async () => {
+ const notes = [
+ buildNote({ title: "One", "#geolocation": "1,2" }),
+ buildNote({ title: "Two", "#geolocation": "1.001,2.001" })
+ ];
+ const map = fakeMap();
+ const parent = new Component();
+
+ await mount(notes, map, parent, { clustered: true });
+ await act(async () => {
+ map.fireStyleLoad();
+ await settle();
+ });
+
+ // The source groups them; the pin layer is told to leave those groups alone.
+ expect(map.source(MARKER_SOURCE)).toMatchObject({ cluster: true });
+ expect(map.layer(MARKER_LAYER)?.filter).toEqual([ "!", [ "has", "point_count" ] ]);
+
+ // ...and something is drawn in their place: a bubble, and the count that gives it meaning.
+ expect(map.calls.addLayer).toBe(CLUSTERED_LAYER_COUNT);
+ expect(map.layer(CLUSTER_LAYER)?.filter).toEqual([ "has", "point_count" ]);
+ expect(map.layer(CLUSTER_COUNT_LAYER)?.filter).toEqual([ "has", "point_count" ]);
+ expect(map.layer(CLUSTER_COUNT_LAYER)?.layout?.["text-field"]).toEqual([ "get", "point_count_abbreviated" ]);
+ // A count that loses a placement contest leaves a bubble that means nothing.
+ expect(map.layer(CLUSTER_COUNT_LAYER)?.layout?.["text-allow-overlap"]).toBe(true);
+ });
+
+ it("leaves every note its own pin when the map is not set to gather them", async () => {
+ const notes = [
+ buildNote({ title: "One", "#geolocation": "1,2" }),
+ buildNote({ title: "Two", "#geolocation": "1.001,2.001" })
+ ];
+ const map = fakeMap();
+ const parent = new Component();
+
+ await mount(notes, map, parent);
+ await act(async () => {
+ map.fireStyleLoad();
+ await settle();
+ });
+
+ expect(map.source(MARKER_SOURCE)).not.toMatchObject({ cluster: true });
+ expect(map.layer(CLUSTER_LAYER)).toBeUndefined();
+ expect(map.layer(CLUSTER_COUNT_LAYER)).toBeUndefined();
+ expect(map.calls.addLayer).toBe(1);
+ // The pin layer keeps its filter either way — a source that gathers nothing produces no
+ // group for it to hide, so it passes every note through.
+ expect(map.lastFeatures).toHaveLength(2);
+ });
+
+ /**
+ * Whether a source gathers its notes is fixed when the source is made: MapLibre offers no way to
+ * set `cluster` on one already standing, so the toggle has to take the source down and put a new
+ * one up. Everything else about this component is careful *not* to rebuild; this is the one case
+ * where rebuilding is the only thing that works, and it is easy to "optimise" back into a toggle
+ * that silently does nothing.
+ */
+ it("rebuilds the source when the map is switched to gathering its notes", async () => {
+ const notes = [ buildNote({ title: "One", "#geolocation": "1,2" }) ];
+ const map = fakeMap();
+ const parent = new Component();
+
+ await mount(notes, map, parent);
+ await act(async () => {
+ map.fireStyleLoad();
+ await settle();
+ });
+ expect(map.calls.addSource).toBe(1);
+ expect(map.source(MARKER_SOURCE)).not.toMatchObject({ cluster: true });
+
+ await mount(notes, map, parent, { clustered: true });
+ await act(async () => { await settle(); });
+
+ // The old source went and a clustered one took its place, bubbles and all.
+ expect(map.calls.removeSource).toBe(1);
+ expect(map.calls.addSource).toBe(2);
+ expect(map.source(MARKER_SOURCE)).toMatchObject({ cluster: true });
+ expect(map.layer(CLUSTER_LAYER)).toBeDefined();
+ // ...and the markers are back on it rather than waiting on a fresh build.
+ expect(map.lastFeatures).toHaveLength(1);
});
it("takes the layer down when the component goes away", async () => {
diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsx
index d2220b78cf..7d559c4448 100644
--- a/apps/client/src/widgets/collections/geomap/Markers.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx
@@ -5,11 +5,12 @@ import FNote from "../../../entities/fnote";
import { getReadableTextColor } from "../../../services/css_class_manager";
import { renderIconImage } from "../../../services/icon_glyphs";
import { useTriliumEvent } from "../../react/hooks";
+import { CLUSTER_LAYERS, CLUSTER_SOURCE_OPTIONS, installClusterLayers, UNCLUSTERED_ONLY, useClusterExpansion } from "./clusters";
import { ParentMap } from "./map";
export const LOCATION_ATTRIBUTE = "geolocation";
export const MARKER_LAYER = "points-layer";
-const MARKER_SOURCE = "points";
+export const MARKER_SOURCE = "points";
const DEFAULT_MARKER_COLOR = "#2A81CB";
/** The pin, in the coordinates its SVG is drawn in. */
@@ -80,7 +81,7 @@ const HIDDEN_TEXT_FIELD = "";
* per note is what made that slow. The pin is rasterized once per colour and icon and handed to the
* map as an image, which the layer then stamps on the GPU.
*/
-export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNote[], hideLabels: boolean, isDarkTheme: boolean }) {
+export default function Markers({ notes, hideLabels, isDarkTheme, clustered }: { notes: FNote[], hideLabels: boolean, isDarkTheme: boolean, clustered: boolean }) {
const map = useContext(ParentMap);
const version = useNoteChangeVersion(notes);
// Whether the style has finished loading at least once. Held outside the effects because either
@@ -102,6 +103,11 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
* 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.
+ *
+ * `clustered` is depended on rather than read from a ref, unlike the look of the titles: whether
+ * a source gathers its notes is fixed when the source is made and cannot be set on one already
+ * standing, so turning it on or off has to take the source down and put a new one up. Rebuilding
+ * is the point here, which is why it is not kept out of the way as the others are.
*/
const install = useCallback(() => {
const data = markerData.current;
@@ -117,7 +123,8 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
if (!map.getSource(MARKER_SOURCE)) {
map.addSource(MARKER_SOURCE, {
type: "geojson",
- data: { type: "FeatureCollection", features: [] }
+ data: { type: "FeatureCollection", features: [] },
+ ...(clustered ? CLUSTER_SOURCE_OPTIONS : {})
});
}
@@ -126,6 +133,11 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
id: MARKER_LAYER,
type: "symbol",
source: MARKER_SOURCE,
+ // Only the notes the source left standing on their own — the groups it made of the
+ // rest are drawn by the cluster layers instead. Kept whether or not this map
+ // gathers its notes: a source that does not has no group to hide, so the filter
+ // passes everything, and the layer need not be built two ways.
+ filter: UNCLUSTERED_ONLY,
layout: {
"icon-image": [ "get", "icon" ],
"icon-size": 1,
@@ -155,11 +167,15 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
});
}
+ if (clustered) {
+ installClusterLayers(map, MARKER_SOURCE);
+ }
+
map.getSource<GeoJSONSource>(MARKER_SOURCE)?.setData({
type: "FeatureCollection",
features
});
- }, [ map ]);
+ }, [ map, clustered ]);
// 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
@@ -206,8 +222,12 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
map.off("remove", onMapRemove);
if (mapRemoved) return;
- if (map.getLayer(MARKER_LAYER)) {
- map.removeLayer(MARKER_LAYER);
+ // The layers before the source they all draw from: a source still in use cannot be
+ // removed.
+ for (const layer of [ MARKER_LAYER, ...CLUSTER_LAYERS ]) {
+ if (map.getLayer(layer)) {
+ map.removeLayer(layer);
+ }
}
if (map.getSource(MARKER_SOURCE)) {
map.removeSource(MARKER_SOURCE);
@@ -247,6 +267,8 @@ export default function Markers({ notes, hideLabels, isDarkTheme }: { notes: FNo
}
}, [ map, hideLabels, isDarkTheme ]);
+ useClusterExpansion(map, MARKER_SOURCE, clustered);
+
return null;
}
diff --git a/apps/client/src/widgets/collections/geomap/clusters.ts b/apps/client/src/widgets/collections/geomap/clusters.ts
new file mode 100644
index 0000000000..8ace9c34f0
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/clusters.ts
@@ -0,0 +1,160 @@
+import { AddLayerObject, type FilterSpecification, type GeoJSONSource, type GeoJSONSourceSpecification, type Map as MapLibreGLMap, type MapGeoJSONFeature, type MapMouseEvent } from "maplibre-gl";
+import { useEffect } from "preact/hooks";
+
+export const CLUSTER_LAYER = "clusters-layer";
+export const CLUSTER_COUNT_LAYER = "cluster-count-layer";
+
+/** Both layers a clustered source needs, in the order they have to come off the map. */
+export const CLUSTER_LAYERS = [ CLUSTER_LAYER, CLUSTER_COUNT_LAYER ];
+
+/**
+ * What makes a source gather the notes that are drawn too near one another.
+ *
+ * Spread into the source rather than kept here as a source of its own: the groups and the notes they
+ * are made of have to come out of the same data, so this is a property of the markers' source and
+ * not something that can stand beside it.
+ */
+export const CLUSTER_SOURCE_OPTIONS = {
+ cluster: true,
+ /**
+ * How near two notes have to be, on screen, before they are drawn as one.
+ *
+ * Tighter than MapLibre's own default of 50, which swallowed notes that were nowhere near each
+ * other and made the map look as though it were losing them as it zoomed. Obsidian's Map View,
+ * the closest thing to a reference for this, settles at 25 — worth going further still if a
+ * bubble ever feels like it is standing for notes that plainly belong apart.
+ */
+ clusterRadius: 35,
+ /** The zoom past which notes are always drawn one by one, however crowded they are. */
+ clusterMaxZoom: 14
+} satisfies Partial<GeoJSONSourceSpecification>;
+
+/**
+ * The filter a layer drawing notes one by one has to carry.
+ *
+ * A clustered source hands its groups out through the same source as the notes it left alone, and a
+ * group carries none of a note's properties — no icon to stamp, no title to place. A layer that
+ * draws every feature therefore draws nothing at all for a group, which is what made crowded notes
+ * read as vanishing rather than as being gathered up.
+ */
+export const UNCLUSTERED_ONLY: FilterSpecification = [ "!", [ "has", "point_count" ] ];
+
+/** Its opposite, for the layers that draw the groups themselves. */
+const CLUSTERED_ONLY: FilterSpecification = [ "has", "point_count" ];
+
+/** What an uncoloured pin is filled with, which a bubble starts from so the two read as a family. */
+const BASE_COLOR = "#2A81CB";
+
+/**
+ * The bubble a group of notes is drawn as, growing and deepening with how many it stands for.
+ *
+ * Unlike a title, it is not painted per theme: a saturated fill inside a pale ring carries its own
+ * contrast, and reads over a dark map as well as over a light one. The steps are what tell a pair of
+ * notes from a hundred at a glance — a bubble of one size for every group would say only "more than
+ * one here", which the map already says by drawing a bubble at all.
+ */
+const CLUSTER_PAINT = {
+ "circle-color": [ "step", [ "get", "point_count" ], BASE_COLOR, 10, "#1B5E96", 50, "#10426B" ],
+ "circle-radius": [ "step", [ "get", "point_count" ], 15, 10, 20, 50, 26 ],
+ "circle-stroke-width": 2,
+ "circle-stroke-color": "rgba(255, 255, 255, 0.9)"
+} satisfies Extract<AddLayerObject, { type: "circle" }>["paint"];
+
+/**
+ * Puts the bubbles and their counts on the map, above whatever draws the notes themselves.
+ *
+ * Called from the same place the markers are installed rather than from a component of its own: a
+ * layer cannot be added before the source it draws from, and that source is put up asynchronously,
+ * once the markers have been built and the style has loaded. A second component listening for the
+ * same style load would be racing that one for which of them ran first.
+ */
+export function installClusterLayers(map: MapLibreGLMap, source: string) {
+ // Above the pins: a bubble stands for several notes and a pin for one, so where the two overlap
+ // it is the pin that should give way.
+ if (!map.getLayer(CLUSTER_LAYER)) {
+ map.addLayer({
+ id: CLUSTER_LAYER,
+ type: "circle",
+ source,
+ filter: CLUSTERED_ONLY,
+ paint: CLUSTER_PAINT
+ });
+ }
+
+ if (!map.getLayer(CLUSTER_COUNT_LAYER)) {
+ map.addLayer({
+ id: CLUSTER_COUNT_LAYER,
+ type: "symbol",
+ source,
+ filter: CLUSTERED_ONLY,
+ layout: {
+ // Abbreviated rather than exact: past a few hundred the digits outgrow the bubble,
+ // and "1.2k" is as much as the number is being read for anyway.
+ "text-field": [ "get", "point_count_abbreviated" ],
+ "text-font": [ "Open Sans Regular" ],
+ "text-size": 12,
+ // The count is the only thing a bubble says, so it is never allowed to lose a
+ // placement contest against a neighbouring title — a bubble drawn without its number
+ // is a blob that means nothing. It takes no part in placement either, so it cannot
+ // push a title off the map in turn.
+ "text-allow-overlap": true,
+ "text-ignore-placement": true
+ },
+ paint: {
+ "text-color": "#fff",
+ // The smallest bubbles are the palest, and white on that blue alone is thin at this
+ // size. Haloed the way a title is, so the count is legible on every step of the ramp
+ // rather than only on the deep ones.
+ "text-halo-color": "rgba(0, 0, 0, 0.25)",
+ "text-halo-width": 1
+ }
+ });
+ }
+}
+
+/**
+ * Opening a group, which is the only thing that can be done to one.
+ *
+ * Without this a bubble is a dead pixel: the notes it stands for cannot be hovered, opened or
+ * right-clicked while they are inside it, so the only way at them would be to guess how far to zoom
+ * in. Safe to call before the layers are up — MapLibre keeps a listener for a layer that does not
+ * exist yet and starts delivering to it once one does.
+ *
+ * @param enabled whether this map gathers its notes at all. A map that does not has no bubbles to
+ * click, and the cursor is left to whatever else on the map wants to set it.
+ */
+export function useClusterExpansion(map: MapLibreGLMap | null, source: string, enabled: boolean) {
+ useEffect(() => {
+ if (!map || !enabled) return;
+
+ async function onClick(e: MapMouseEvent & { features?: MapGeoJSONFeature[] }) {
+ const feature = e.features?.[0];
+ const clusterSource = map?.getSource<GeoJSONSource>(source);
+ if (!feature || !clusterSource || feature.geometry.type !== "Point") return;
+
+ // The zoom at which this particular group comes apart, which only the source knows —
+ // stepping in by a fixed amount would either overshoot a loose group or leave a tight
+ // one still gathered, and a click that visibly does nothing reads as a broken map.
+ const zoom = await clusterSource.getClusterExpansionZoom(feature.properties.cluster_id);
+ map?.easeTo({ center: feature.geometry.coordinates as [number, number], zoom });
+ }
+
+ // A bubble is a thing to be clicked, and says so before it is.
+ function onEnter() {
+ if (map) map.getCanvas().style.cursor = "pointer";
+ }
+ function onLeave() {
+ if (map) map.getCanvas().style.cursor = "";
+ }
+
+ map.on("click", CLUSTER_LAYER, onClick);
+ map.on("mouseenter", CLUSTER_LAYER, onEnter);
+ map.on("mouseleave", CLUSTER_LAYER, onLeave);
+
+ return () => {
+ map.off("click", CLUSTER_LAYER, onClick);
+ map.off("mouseenter", CLUSTER_LAYER, onEnter);
+ map.off("mouseleave", CLUSTER_LAYER, onLeave);
+ };
+ }, [ map, source, enabled ]);
+}
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index ef1fe5f2cc..e2e712e752 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -48,6 +48,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
const [ zoom, setZoom ] = useState(viewConfig?.view?.zoom);
const [ hasScale ] = useNoteLabelBoolean(note, "map:scale");
const [ hideLabels ] = useNoteLabelBoolean(note, "map:hideLabels");
+ const [ clustered ] = useNoteLabelBoolean(note, "map:cluster");
const [ isReadOnly ] = useNoteLabelBoolean(note, "readOnly");
const [ includeArchived ] = useNoteLabelBoolean(note, "includeArchived");
const [ notes, setNotes ] = useState<FNote[]>([]);
@@ -174,7 +175,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
>
<Tooltips />
<ContextMenus note={note} isReadOnly={isReadOnly} />
- <Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} />
+ <Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} />
{notes.map(note => <NoteGpxTrackWrapper note={note} hideLabels={hideLabels} />)}
</Map>}
</div>
diff --git a/apps/client/src/widgets/collections/geomap/map.tsx b/apps/client/src/widgets/collections/geomap/map.tsx
index 8c784e65e1..11b87fa683 100644
--- a/apps/client/src/widgets/collections/geomap/map.tsx
+++ b/apps/client/src/widgets/collections/geomap/map.tsx
@@ -37,6 +37,9 @@ export function toGeoMouseEvent(e: MapMouseEvent): GeoMouseEvent {
};
}
+/** Where the fonts a label is drawn from come from, matching what the vector styles ask for. */
+const GLYPHS_URL = "https://tiles.versatiles.org/assets/glyphs/{fontstack}/{range}.pbf";
+
/** Builds the style that can be applied synchronously: the raster style spec, a vector style URL
* or the vector fallback style used as a placeholder until the real style loads asynchronously. */
function buildSyncStyle(layerData: MapLayer): StyleSpecification | string {
@@ -48,6 +51,12 @@ function buildSyncStyle(layerData: MapLayer): StyleSpecification | string {
return {
version: 8,
+ // Text on a map is drawn from glyphs the style has to name, and a raster style is built here
+ // rather than downloaded, so nothing else names them for it. Without this every symbol layer
+ // over a raster map loses its text and only its text: the marker titles and the count inside
+ // a cluster's bubble go silently missing, while the pins and the bubbles themselves are
+ // drawn as usual. The vector styles point at the same place (see their own `glyphs`).
+ glyphs: GLYPHS_URL,
sources: {
"raster-tiles": {
type: "raster",
diff --git a/apps/client/src/widgets/ribbon/collection-properties-config.tsx b/apps/client/src/widgets/ribbon/collection-properties-config.tsx
index f1cdfae2f3..b22ea92522 100644
--- a/apps/client/src/widgets/ribbon/collection-properties-config.tsx
+++ b/apps/client/src/widgets/ribbon/collection-properties-config.tsx
@@ -126,6 +126,12 @@ export const bookPropertiesConfig: Record<ViewTypeOptions, BookConfig> = {
type: "checkbox",
bindToLabel: "map:hideLabels",
reverseValue: true
+ },
+ {
+ label: t("book_properties_config.cluster-markers"),
+ icon: "bx bx-collection",
+ type: "checkbox",
+ bindToLabel: "map:cluster"
}
]
},
diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.ts
index a9bbc3ed5d..987408c605 100644
--- a/packages/commons/src/lib/builtin_attributes.ts
+++ b/packages/commons/src/lib/builtin_attributes.ts
@@ -294,6 +294,7 @@ const BUILTIN_ATTRIBUTES = [
{ type: "label", name: "map:style", valueType: "text", hasUserValue: true },
{ type: "label", name: "map:scale", valueType: "boolean", hasUserValue: true },
{ type: "label", name: "map:hideLabels", valueType: "boolean", hasUserValue: true },
+ { type: "label", name: "map:cluster", valueType: "boolean", hasUserValue: true },
// Reveal.js' own stock themes, which is what the presentation bundles; anything else falls back
// to `white`.
{ type: "label", name: "presentation:theme", valueType: "select", hasUserValue: true, selectOptions: [