Skip to content

Build your personal knowledge base with Trilium Notes

fix(geomap): say why there is no map, rather than leaving the panel blank

Elian Doran9061c66f4920
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index e696072195..a31680cde4 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2742,6 +2742,7 @@
"create-child-note-instruction": "Click on the map to create a new note at that location or press Escape to dismiss.",
"create-child-note-toast-title": "New note",
"unable-to-load-map": "Unable to load map.",
+ "webgl-unavailable": "This map can't be drawn because WebGL isn't available. Check that hardware acceleration is enabled and that your graphics drivers are up to date.",
"zoom-in": "Zoom in",
"zoom-out": "Zoom out",
"fullscreen": "Fullscreen",
diff --git a/apps/client/src/widgets/collections/geomap/map.init.spec.tsx b/apps/client/src/widgets/collections/geomap/map.init.spec.tsx
new file mode 100644
index 0000000000..76725570c9
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/map.init.spec.tsx
@@ -0,0 +1,144 @@
+/**
+ * The map that cannot be built at all.
+ *
+ * MapLibre draws through WebGL and has no other way to draw, so a browser that will not give it a
+ * context — WebGL turned off, or a GPU that is unavailable with no software fallback — makes the
+ * constructor throw. Nothing caught it, and since the throw happens inside an effect with no error
+ * 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 { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { type MapLayer } from "./map_layer";
+
+/** What MapLibre throws when it cannot get a context, message and all. */
+const WEBGL_FAILURE_MESSAGE = JSON.stringify({
+ statusMessage: "Could not create a WebGL context, GL_VENDOR = Disabled, GL_RENDERER = Disabled",
+ type: "webglcontextcreationerror",
+ message: "Failed to initialize WebGL"
+});
+
+/** The constructor of a browser that will not give MapLibre a context. */
+function failingMap(): never {
+ throw new Error(WEBGL_FAILURE_MESSAGE);
+}
+
+const { MapConstructor } = vi.hoisted(() => ({ MapConstructor: vi.fn() }));
+
+vi.mock("maplibre-gl", () => ({
+ Map: MapConstructor,
+ ScaleControl: class {},
+ AttributionControl: class {}
+}));
+
+vi.mock("maplibre-gl/dist/maplibre-gl.css", () => ({}));
+
+// t() returns the key, so the assertion below is on which message is shown rather than on its
+// English wording.
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+const LAYER: MapLayer = {
+ name: "OpenStreetMap",
+ type: "raster",
+ url: "https://tile.example.org/{z}/{x}/{y}.png",
+ attribution: "© Example"
+};
+
+/**
+ * A map that builds, recording only the little the component asks of it.
+ *
+ * A `function` rather than an arrow: the component calls this through `new`, and Vitest refuses to
+ * construct a mock whose implementation is not constructible.
+ */
+function workingMap(this: unknown) {
+ return {
+ addControl: vi.fn(),
+ removeControl: vi.fn(),
+ on: vi.fn(),
+ off: vi.fn(),
+ once: vi.fn(),
+ remove: vi.fn(),
+ resize: vi.fn(),
+ setStyle: vi.fn(),
+ setCenter: vi.fn(),
+ setZoom: vi.fn(),
+ getCenter: () => ({ lat: 0, lng: 0 }),
+ getZoom: () => 2
+ };
+}
+
+describe("Map initialization", () => {
+ let container: HTMLElement;
+ let Map: typeof import("./map").default;
+ let warn: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(async () => {
+ ({ default: Map } = await import("./map"));
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ vi.clearAllMocks();
+ warn.mockRestore();
+ });
+
+ /** Puts the map up, with whatever the mocked constructor has been told to do. */
+ function renderMap() {
+ act(() => {
+ render(
+ <Map
+ coordinates={{ lat: 0, lng: 0 }}
+ zoom={2}
+ layerData={LAYER}
+ viewportChanged={vi.fn()}
+ scale={false}
+ >
+ <div className="map-child">A child of the map</div>
+ </Map>,
+ container
+ );
+ });
+ }
+
+ it("says why there is no map, rather than leaving the panel blank", () => {
+ MapConstructor.mockImplementation(failingMap);
+
+ renderMap();
+
+ // The placeholder stands where the map would have been...
+ const placeholder = container.querySelector(".no-items");
+ expect(placeholder).not.toBeNull();
+ // i18next is not initialized in the client tests, so a key renders as itself.
+ expect(placeholder?.textContent).toContain("geo-map.webgl-unavailable");
+
+ // ...the children are not rendered, since they have no map to draw on...
+ expect(container.querySelector(".map-child")).toBeNull();
+
+ // ...and the reason is reported once, without a stack.
+ expect(warn).toHaveBeenCalledOnce();
+ expect(warn.mock.calls[0][0]).toContain("Could not create a WebGL context");
+ });
+
+ it("keeps the container, so a remount has somewhere to build", () => {
+ MapConstructor.mockImplementation(failingMap);
+
+ renderMap();
+
+ expect(container.querySelector(".geo-map-container")).not.toBeNull();
+ });
+
+ it("draws the children and no placeholder when the map builds", () => {
+ MapConstructor.mockImplementation(workingMap);
+
+ renderMap();
+
+ expect(container.querySelector(".no-items")).toBeNull();
+ expect(container.querySelector(".map-child")).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/map.tsx b/apps/client/src/widgets/collections/geomap/map.tsx
index b81793b2c0..2a3c83e8d4 100644
--- a/apps/client/src/widgets/collections/geomap/map.tsx
+++ b/apps/client/src/widgets/collections/geomap/map.tsx
@@ -4,8 +4,10 @@ import { AttributionControl, type ErrorEvent as MapErrorEvent, Map as MapLibreGL
import { ComponentChildren, createContext, RefObject } from "preact";
import { useEffect, useImperativeHandle, useRef, useState } from "preact/hooks";
+import { t } from "../../../services/i18n";
import { getMeasurementSystem } from "../../../utils/formatters";
import { useElementSize, useSyncedRef, useTriliumOption } from "../../react/hooks";
+import NoItems from "../../react/NoItems";
import { type MapLayer } from "./map_layer";
export interface GeoMouseEvent {
@@ -91,6 +93,8 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi
// What the style this map was last given was made of, which is how the sources and layers on it
// that are its own are told from the ones a child added. See `keepAdditions`.
const appliedStyle = useRef<StyleContents>();
+ // Whether there is no map to be had here at all — see the catch below.
+ const [ unsupported, setUnsupported ] = useState(false);
// Initialize the map.
useEffect(() => {
@@ -99,23 +103,21 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi
const initialStyle = buildSyncStyle(layerData);
appliedStyle.current = typeof initialStyle === "string" ? undefined : styleContents(initialStyle);
- const mapInstance = new MapLibreGLMap({
- container: containerRef.current,
- style: initialStyle,
- center: toCenter(coordinates),
- zoom,
- minZoom: 2,
- // No explicit maxBounds: a bounds whose longitude range spans the full world
- // (-180..180) crashes MapLibre — the east edge wraps to -180, collapsing the range
- // to zero width and making the constrain zoom infinite (a singular-matrix null
- // deref). With renderWorldCopies disabled, MapLibre itself constrains panning to a
- // single world (substituting an almost-full-world longitude range that avoids the
- // collapse) and clamps latitude to the Mercator limit, which is the Leaflet-parity
- // behavior we want.
- renderWorldCopies: false,
- // Added by hand below, in the corner opposite the one MapLibre keeps it in.
- attributionControl: false
- });
+ let mapInstance: MapLibreGLMap;
+ try {
+ mapInstance = createMap(containerRef.current, initialStyle, toCenter(coordinates), zoom);
+ } catch (e) {
+ // MapLibre draws through WebGL and has no other way to draw, so a context it cannot get
+ // is the end of it: the constructor throws rather than firing the "error" event handled
+ // below, and nothing here is ever built. This is not the tile server being unreachable —
+ // it is a browser with WebGL turned off, or one whose GPU is unavailable and which will
+ // not fall back to software rendering. Say so where the map would have been, since an
+ // empty container explains nothing.
+ console.warn(`Geo map: ${summarizeMapError(e).message}`);
+ setUnsupported(true);
+ return;
+ }
+ setUnsupported(false);
// 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
@@ -222,18 +224,50 @@ export default function Map({ coordinates, zoom, layerData, viewportChanged, chi
map?.resize();
}, [ map, size?.width, size?.height ]);
+ // The container stays in place either way: it is what the effect above is handed, so taking it
+ // away would leave nothing to build the map in should the component be mounted again.
return (
<div
ref={containerRef}
className={`geo-map-container ${layerData.isDarkTheme ? "dark" : ""}`}
>
- <ParentMap.Provider value={map}>
- {children}
- </ParentMap.Provider>
+ {unsupported
+ ? <NoItems icon="bx bx-error-circle" text={t("geo-map.webgl-unavailable")} />
+ : (
+ <ParentMap.Provider value={map}>
+ {children}
+ </ParentMap.Provider>
+ )}
</div>
);
}
+/**
+ * Builds the map itself.
+ *
+ * Separate from the effect that calls it so that the throw it is wrapped in covers the constructor
+ * and nothing else: everything the effect goes on to do is on a map that exists.
+ */
+function createMap(container: HTMLDivElement, style: StyleSpecification | string, center: [number, number], zoom: number) {
+ return new MapLibreGLMap({
+ container,
+ style,
+ center,
+ zoom,
+ minZoom: 2,
+ // No explicit maxBounds: a bounds whose longitude range spans the full world
+ // (-180..180) crashes MapLibre — the east edge wraps to -180, collapsing the range
+ // to zero width and making the constrain zoom infinite (a singular-matrix null
+ // deref). With renderWorldCopies disabled, MapLibre itself constrains panning to a
+ // single world (substituting an almost-full-world longitude range that avoids the
+ // collapse) and clamps latitude to the Mercator limit, which is the Leaflet-parity
+ // behavior we want.
+ renderWorldCopies: false,
+ // Added by hand by the caller, in the corner opposite the one MapLibre keeps it in.
+ attributionControl: false
+ });
+}
+
/** An HTTP failure as MapLibre reports one: what {@link summarizeMapError} reads off an `AJAXError`. */
interface HttpFailure {
status: number;