Skip to content

Build your personal knowledge base with Trilium Notes

fix(geomap): hold a style that arrives before the last one has loaded

Elian Doran2862651bcf2e
diff --git a/apps/client/src/widgets/collections/geomap/map.init.spec.tsx b/apps/client/src/widgets/collections/geomap/map.init.spec.tsx
index 3395e57caf..cd88393f31 100644
--- a/apps/client/src/widgets/collections/geomap/map.init.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/map.init.spec.tsx
@@ -7,6 +7,7 @@
* boundary over the widgets, what the user got was the empty container the map would have filled:
* a blank panel and a console message they never see. It says what happened now.
*/
+import type { StyleSpecification } from "maplibre-gl";
import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -68,6 +69,7 @@ function workingMap(this: unknown) {
*/
function buildWorkingMap() {
const controls = new Set<unknown>();
+ const listeners = new Map<string, Set<(payload?: unknown) => void>>();
let removed = false;
return {
@@ -84,9 +86,21 @@ function buildWorkingMap() {
removed = true;
controls.clear();
}),
- on: vi.fn(),
- off: vi.fn(),
+ on: vi.fn((event: string, handler: (payload?: unknown) => void) => {
+ const handlers = listeners.get(event) ?? new Set();
+ handlers.add(handler);
+ listeners.set(event, handlers);
+ }),
+ off: vi.fn((event: string, handler: (payload?: unknown) => void) => {
+ listeners.get(event)?.delete(handler);
+ }),
once: vi.fn(),
+ /** Fires an event as MapLibre would, for the tests that need one to have happened. */
+ fire(event: string, payload?: unknown) {
+ for (const handler of [ ...(listeners.get(event) ?? []) ]) {
+ handler(payload);
+ }
+ },
resize: vi.fn(),
setStyle: vi.fn(),
setCenter: vi.fn(),
@@ -256,6 +270,67 @@ describe("Map initialization", () => {
});
});
+ /**
+ * The style switch and the frame it kept losing.
+ *
+ * MapLibre swaps styles by diffing, which keeps the painted map on screen — but it cannot diff
+ * against a style that has not finished loading, and every style is still loading for at least
+ * one animation frame after it is handed over. Rather than wait that frame out it tears the
+ * whole style down and rebuilds: a "Unable to perform style diff" warning and a map that blinks
+ * blank. The vector styles import asynchronously and routinely resolve inside that first frame,
+ * so whether the map blinked came down to which of the two won. A style that arrives early is
+ * held until `style.load` says the one before it is ready to be diffed against.
+ */
+ describe("a style that arrives before the last one has loaded", () => {
+ /** The style a vector layer's import resolves to, recognizable by identity. */
+ const VECTOR_STYLE: StyleSpecification = { version: 8, sources: {}, layers: [] };
+
+ /** A vector layer whose style import resolves as fast as a cached chunk does. */
+ const VECTOR_LAYER: MapLayer = {
+ name: "VersaTiles Colorful",
+ type: "vector",
+ style: async () => VECTOR_STYLE,
+ styleFallback: { version: 8, sources: {}, layers: [] }
+ };
+
+ beforeEach(() => {
+ MapConstructor.mockImplementation(workingMap);
+ });
+
+ it("is held until then, and applied the moment it is safe to diff", async () => {
+ renderMap({ layer: VECTOR_LAYER });
+ // The import resolves before the browser's next frame, which is the race this is about.
+ await act(async () => {});
+ expect(lastMap?.setStyle).not.toHaveBeenCalled();
+
+ act(() => lastMap?.fire("style.load"));
+
+ expect(lastMap?.setStyle).toHaveBeenCalledOnce();
+ expect(lastMap?.setStyle.mock.calls[0][0]).toBe(VECTOR_STYLE);
+ });
+
+ it("is applied straight away once the style before it has loaded", () => {
+ renderMap();
+ act(() => lastMap?.fire("style.load"));
+ lastMap?.setStyle.mockClear();
+
+ renderMap({ layer: { ...LAYER, url: "https://other.example.org/{z}/{x}/{y}.png" } });
+
+ expect(lastMap?.setStyle).toHaveBeenCalledOnce();
+ });
+
+ it("is dropped when a later switch overtakes it before it was ever applied", () => {
+ renderMap();
+ const overtakingUrl = "https://other.example.org/{z}/{x}/{y}.png";
+ renderMap({ layer: { ...LAYER, url: overtakingUrl } });
+
+ act(() => lastMap?.fire("style.load"));
+
+ expect(lastMap?.setStyle).toHaveBeenCalledOnce();
+ expect(lastMap?.setStyle.mock.calls[0][0].sources["raster-tiles"].tiles).toEqual([ overtakingUrl ]);
+ });
+ });
+
/**
* Leaving a geo map for another note, which used to throw where nobody could catch it: the scale
* was taken off a map that had already gone, and a control given its notice twice reaches for the
diff --git a/apps/client/src/widgets/collections/geomap/map.tsx b/apps/client/src/widgets/collections/geomap/map.tsx
index 2ff803fa73..300c22cf15 100644
--- a/apps/client/src/widgets/collections/geomap/map.tsx
+++ b/apps/client/src/widgets/collections/geomap/map.tsx
@@ -143,6 +143,36 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi
const [ unsupported, setUnsupported ] = useState(false);
// See MapStyleLoaded.
const [ styleLoaded, setStyleLoaded ] = useState(false);
+ // The same answer again as a ref, so applyStyle can read it from whichever closure it is
+ // called in, and the style applyStyle is holding until it turns true.
+ const styleLoadedRef = useRef(false);
+ const pendingStyle = useRef<StyleSpecification | string | null>(null);
+
+ /**
+ * Puts a style on the map, carrying what the children added to the last one across — or, while
+ * the style already there has not finished loading, holds it instead.
+ *
+ * MapLibre swaps styles by diffing the new one against the current one, which is what keeps the
+ * painted map on screen through the switch. But it cannot diff against a style that is still
+ * loading — and every style still is for at least a frame, since even one handed over as plain
+ * JSON is only taken up on the next animation frame. Rather than wait that frame out, MapLibre
+ * gives up: "Unable to perform style diff" on the console, the whole style torn down, and the
+ * map blinking blank until the replacement and its tiles arrive. The vector styles here import
+ * asynchronously and routinely resolve inside that first frame, so the blink was a matter of
+ * which of the two won.
+ *
+ * Held styles are applied by the `style.load` listener below, where the diff cannot lose the
+ * race. Only the latest is kept — a style overtaken before it was ever applied is a style
+ * nobody asked to see.
+ */
+ function applyStyle(mapInstance: MapLibreGLMap, style: StyleSpecification | string) {
+ if (!styleLoadedRef.current) {
+ pendingStyle.current = style;
+ return;
+ }
+ mapInstance.setStyle(style, { transformStyle: keepAdditions(appliedStyle.current) });
+ appliedStyle.current = typeof style === "string" ? undefined : styleContents(style);
+ }
// Initialize the map.
useEffect(() => {
@@ -171,7 +201,17 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi
// own: a style begins loading inside the constructor and `style.load` fires once, so a
// listener attached even one render later can already be too late. Never unlatched — a style
// that has loaded is followed only by another style loading, and each of those fires again.
- mapInstance.on("style.load", () => setStyleLoaded(true));
+ // Also where a style that arrived too early to be applied gets its turn — see applyStyle.
+ mapInstance.on("style.load", () => {
+ styleLoadedRef.current = true;
+ setStyleLoaded(true);
+
+ const held = pendingStyle.current;
+ if (held) {
+ pendingStyle.current = null;
+ applyStyle(mapInstance, held);
+ }
+ });
// The attribution stands at the foot of the map beside its scale, rather than in the corner
// where the zoom buttons now are (see MapToolbar): a bar of buttons is reached for, and it
@@ -202,36 +242,34 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi
mapInstance.remove();
setMap(null);
setStyleLoaded(false);
+ styleLoadedRef.current = false;
+ pendingStyle.current = null;
};
}, []);
- // React to layer changes. Also runs after the initial map creation, which is a no-op for the
- // synchronous styles (setStyle diffs against the current style) but loads the asynchronous
- // vector styles for the first time.
+ // React to layer changes. Also runs after the initial map creation, which for the synchronous
+ // styles re-applies the style the map was built with (a diff with nothing in it) but loads the
+ // asynchronous vector styles for the first time.
useEffect(() => {
if (!map) return;
let cancelled = false;
- /** Puts a style on the map, carrying what the children added to the last one across. */
- function apply(style: StyleSpecification | string) {
- map?.setStyle(style, { transformStyle: keepAdditions(appliedStyle.current) });
- appliedStyle.current = typeof style === "string" ? undefined : styleContents(style);
- }
-
if (layerData.type === "vector" && typeof layerData.style !== "string") {
layerData.style().then(asyncStyle => {
// Guard against the layer changing again or the map being torn down while the
// style was still loading.
if (cancelled) return;
- apply(asyncStyle);
+ applyStyle(map, asyncStyle);
});
} else {
- apply(buildSyncStyle(layerData));
+ applyStyle(map, buildSyncStyle(layerData));
}
return () => {
cancelled = true;
+ // A style still being held is this run's; the run for the next layer brings its own.
+ pendingStyle.current = null;
};
}, [ map, layerData ]);