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
feat(geomap): let the map take the screen, and let a menu follow it there
Elian Doran54fc1440703f
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsnew file mode 100644index 0000000000..9a9b5f59f3--- /dev/null+++ b/apps/client/src/menus/context_menu.spec.ts@@ -0,0 +1,62 @@+/**+ * The menu over an element that has the screen to itself.+ *+ * A browser showing an element fullscreen draws that element and nothing else, and this menu lives at+ * the end of the page: over a map given the screen (see the geo map's and the mind map's toolbars) a+ * right-click laid the menu out, positioned it, and painted none of it — nothing appeared to happen+ * at all. It goes wherever the screen is instead.+ */+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("../services/note_tooltip", () => ({ default: { dismissAllTooltips: vi.fn() } }));+vi.mock("../services/keyboard_actions", () => ({ default: { updateDisplayedShortcuts: vi.fn() } }));++/** The page as the shell leaves it: the menu's own element, at the end of the body. */+function buildPage() {+ document.body.innerHTML = `<div id="app"></div><div id="context-menu-container"></div>`;+ return document.getElementById("context-menu-container");+}++/** Puts an element on a screen of its own, as the browser reports one. */+function setFullscreenElement(element: Element | null) {+ Object.defineProperty(document, "fullscreenElement", { value: element, configurable: true });+}++/** A fresh menu service, built against the page as it now stands. */+async function buildContextMenu() {+ vi.resetModules();+ return (await import("./context_menu")).default;+}++const items = [ { title: "Add a marker at this location", handler: () => {} } ];++beforeEach(() => {+ setFullscreenElement(null);+});++describe("contextMenu", () => {+ it("stands at the end of the page while nothing has the screen", async () => {+ const menu = buildPage();+ const contextMenu = await buildContextMenu();++ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });++ expect(menu?.parentElement).toBe(document.body);+ });++ it("moves inside whatever has the screen, and back once nothing does", async () => {+ const menu = buildPage();+ const contextMenu = await buildContextMenu();+ const map = document.getElementById("app");++ setFullscreenElement(map);+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ // Anywhere else it would be laid out and left unpainted, which reads as a menu that never opened.+ expect(menu?.parentElement).toBe(map);++ setFullscreenElement(null);+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });++ expect(menu?.parentElement).toBe(document.body);+ });+});diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex bb3bb5ed15..94a4c650f5 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -68,10 +68,13 @@ class ContextMenu {private $cover?: JQuery<HTMLElement>;private options?: ContextMenuOptions<any>;private isMobile: boolean;+ /** Where the menu stands while nothing has the screen to itself. See {@link hostInWhateverHasTheScreen}. */+ private home: HTMLElement | null;constructor() {this.$widget = $("#context-menu-container");this.$widget.addClass("dropend");+ this.home = this.$widget[0]?.parentElement ?? null;this.isMobile = utils.isMobile();if (this.isMobile) {@@ -93,6 +96,8 @@ class ContextMenu {await this.hide();}+ this.hostInWhateverHasTheScreen();+this.$widget.toggleClass("mobile-bottom-menu", !this.options.forcePositionOnMobile);this.$cover?.addClass("show");$("body").addClass("context-menu-shown");@@ -106,6 +111,24 @@ class ContextMenu {this.positionMenu();}+ /**+ * Puts the menu inside the element that currently has the screen to itself, and back where it+ * belongs once nothing does.+ *+ * A browser showing an element fullscreen draws that element and nothing else: this menu lives at+ * the end of the page, so over a map or a diagram given the screen (see `useFullscreen`) it was+ * laid out, positioned and left unpainted — a right-click that appeared to do nothing at all.+ * Moved into whatever is being shown, it is drawn as usual; it is positioned against the viewport+ * either way, so nothing about where it lands changes.+ */+ private hostInWhateverHasTheScreen() {+ const menu = this.$widget[0];+ const host = document.fullscreenElement ?? this.home;+ if (menu && host && menu.parentElement !== host) {+ host.appendChild(menu);+ }+ }+positionMenu() {if (!this.options) {return;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c5aeae8aa0..e696072195 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2743,7 +2743,9 @@"create-child-note-toast-title": "New note","unable-to-load-map": "Unable to load map.","zoom-in": "Zoom in",- "zoom-out": "Zoom out"+ "zoom-out": "Zoom out",+ "fullscreen": "Fullscreen",+ "exit-fullscreen": "Exit fullscreen"},"geo-map-context": {"open-location": "Open location",diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsxindex abd9978574..e426dbd023 100644--- a/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.spec.tsx@@ -1,13 +1,13 @@/**- * The zoom buttons, which used to be MapLibre's own `NavigationControl` — a white box on a map that- * may well be dark, dressed in neither Trilium's buttons nor its colors. What is checked here is what- * the control did for us: the two steps, and a step that would carry the map past either end of the- * range it is allowed being refused rather than merely doing nothing.+ * The bar over a geo map, which used to be MapLibre's own controls — white boxes on a map that may+ * well be dark, dressed in neither Trilium's buttons nor its colors. What is checked here is what+ * they did for us: the two steps, a step that would carry the map past either end of the range it is+ * allowed being refused rather than merely doing nothing, and the screen being given and taken back.*/import type { Map as MapLibreGLMap } from "maplibre-gl";import { render } from "preact";import { act } from "preact/test-utils";-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { renderInto } from "../../../test/render";import { ParentMap } from "./map";@@ -16,10 +16,14 @@ import MapToolbar from "./MapToolbar";/** The order the bar lays its buttons out in. */const ZOOM_IN = 0;const ZOOM_OUT = 1;+const FULLSCREEN = 2;-/** A map that only zooms and says so, which is all this bar asks of one. */+/** A map that zooms, says so, and stands somewhere — all this bar asks of one. */function fakeMap({ zoom = 5, minZoom = 2, maxZoom = 22 } = {}) {const listeners = new Set<() => void>();+ const container = document.createElement("div");+ container.requestFullscreen = vi.fn(async () => {});+ document.body.appendChild(container);const setZoom = (value: number) => {zoom = Math.min(Math.max(value, minZoom), maxZoom);@@ -30,6 +34,7 @@ function fakeMap({ zoom = 5, minZoom = 2, maxZoom = 22 } = {}) {getZoom: () => zoom,getMinZoom: () => minZoom,getMaxZoom: () => maxZoom,+ getContainer: () => container,zoomIn: vi.fn(() => setZoom(zoom + 1)),zoomOut: vi.fn(() => setZoom(zoom - 1)),/** The map being zoomed by something other than these buttons — the wheel, or a pinch. */@@ -40,6 +45,17 @@ function fakeMap({ zoom = 5, minZoom = 2, maxZoom = 22 } = {}) {};}+/** Puts the document in or out of fullscreen and tells whoever is listening, as the browser does. */+function setFullscreenElement(element: Element | null) {+ Object.defineProperty(document, "fullscreenElement", { value: element, configurable: true });+ act(() => { document.dispatchEvent(new Event("fullscreenchange")); });+}++beforeEach(() => {+ Object.defineProperty(document, "fullscreenElement", { value: null, configurable: true });+ document.exitFullscreen = vi.fn(async () => {});+});+/** Builds the bar over a map and settles it, so that it is listening before it is spoken to. */function renderToolbar(map: ReturnType<typeof fakeMap> | null) {let container: HTMLElement | undefined;@@ -63,12 +79,13 @@ function press(container: HTMLElement, index: number) {}describe("geo map MapToolbar", () => {- it("offers the two steps the map's own control did, in one row", () => {+ it("offers what the map's own controls did, in one row", () => {const container = renderToolbar(fakeMap());expect(buttons(container).map((button) => button.className)).toEqual([expect.stringContaining("bx-zoom-in"),- expect.stringContaining("bx-zoom-out")+ expect.stringContaining("bx-zoom-out"),+ expect.stringContaining("bx-fullscreen")]);});@@ -110,6 +127,33 @@ describe("geo map MapToolbar", () => {expect(buttons(container)[ZOOM_IN].disabled).toBe(true);});+ it("gives the map the screen and takes it back, saying which it is offering", () => {+ const map = fakeMap();+ const container = renderToolbar(map);++ press(container, FULLSCREEN);+ // The map itself goes on the screen, not the note's chrome around it.+ expect(map.getContainer().requestFullscreen).toHaveBeenCalled();++ setFullscreenElement(map.getContainer());+ expect(buttons(container)[FULLSCREEN].className).toContain("bx-exit-fullscreen");++ press(container, FULLSCREEN);+ expect(document.exitFullscreen).toHaveBeenCalled();+ });++ it("follows a screen left by pressing Escape rather than by the button", () => {+ const map = fakeMap();+ const container = renderToolbar(map);++ setFullscreenElement(map.getContainer());+ expect(buttons(container)[FULLSCREEN].className).toContain("bx-exit-fullscreen");++ setFullscreenElement(null);++ expect(buttons(container)[FULLSCREEN].className).toContain("bx-fullscreen");+ });+it("stops listening to a map it is taken off", () => {const map = fakeMap();const container = renderToolbar(map);diff --git a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx b/apps/client/src/widgets/collections/geomap/MapToolbar.tsxindex fc5484de1e..d9d328bf95 100644--- a/apps/client/src/widgets/collections/geomap/MapToolbar.tsx+++ b/apps/client/src/widgets/collections/geomap/MapToolbar.tsx@@ -4,21 +4,26 @@ import type { Map as MapLibreGLMap } from "maplibre-gl";import { useContext, useEffect, useState } from "preact/hooks";import { t } from "../../../services/i18n";+import { useFullscreen } from "../../react/hooks";import OverlayToolbar, { OverlayToolbarButton } from "../../react/OverlayToolbar";import { ParentMap } from "./map";/**- * The bar standing in the corner of a geo map: how close in the map is drawn.+ * The bar standing in the corner of a geo map: how close in the map is drawn, and how much of the+ * screen it is given.*- * MapLibre offers a bar of its own for this (`NavigationControl`, which is what stood here), dressed- * in neither Trilium's buttons nor Trilium's colors — a white box with two hairline-separated squares- * in it, on a map that may well be dark. What it did is done here instead, on the surface every bar- * standing over a canvas shares (see {@link OverlayToolbar}), which is what the mind map's own bar- * stands on too.+ * MapLibre offers bars of its own for both (`NavigationControl`, which is what stood here, and+ * `FullscreenControl`), dressed in neither Trilium's buttons nor Trilium's colors — a white box with+ * hairline-separated squares in it, on a map that may well be dark. What they do is done here+ * instead, on the surface every bar standing over a canvas shares (see {@link OverlayToolbar}),+ * which is what the mind map's own bar stands on too.*/export default function MapToolbar() {const map = useContext(ParentMap);const zoom = useMapZoom(map);+ // The map itself rather than the whole view: what is around it is the note's own chrome, and+ // everything the bar above the map offers is on the map's right-click menu as well.+ const [ isFullscreen, toggleFullscreen ] = useFullscreen(map?.getContainer());if (!map) return null;@@ -42,6 +47,15 @@ export default function MapToolbar() {disabled={current <= map.getMinZoom()}onClick={() => map.zoomOut()}/>++ <OverlayToolbarButton+ icon={isFullscreen ? "bx bx-exit-fullscreen" : "bx bx-fullscreen"}+ text={isFullscreen ? t("geo-map.exit-fullscreen") : t("geo-map.fullscreen")}+ // Nothing here is measured across the change: the map keeps the middle of its view+ // through a resize of its own accord, and it is told of the new size by the view+ // itself (see `useElementSize` in map.tsx).+ onClick={() => void toggleFullscreen()}+ /></OverlayToolbar>);}diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex fc4b49d60e..82d0a6d368 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -946,6 +946,54 @@ export function useElementSize(ref: RefObject<HTMLElement>) {return size;}+/**+ * Whether an element has the screen to itself, and the way to give it or take it back.+ *+ * The state follows the browser rather than the button, so a screen left by pressing Escape — which+ * nothing asks us for — is still noticed.+ *+ * @param element the element to put on a screen of its own, or `null` while there is none yet.+ * @param onChange called once the screen has changed, either way, and after the state has been+ * updated. Where something has to be measured across the change, take it in the+ * handler passed to `toggle` and spend it here.+ * @returns whether the element is currently fullscreen, and a toggle that resolves to whether the+ * screen actually changed — a request the browser refuses (no user gesture behind it, a+ * policy against it) leaves the view exactly as it was.+ */+export function useFullscreen(element: HTMLElement | null | undefined, onChange?: () => void): [ boolean, () => Promise<boolean> ] {+ const [ isFullscreen, setFullscreen ] = useState(() => !!element && document.fullscreenElement === element);+ // Read afresh on every change rather than closed over, so that a listener bound once follows a+ // handler the caller hands over anew on each render.+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;++ useEffect(() => {+ if (!element) return;++ const onFullscreenChange = () => {+ setFullscreen(document.fullscreenElement === element);+ onChangeRef.current?.();+ };++ document.addEventListener("fullscreenchange", onFullscreenChange);+ return () => document.removeEventListener("fullscreenchange", onFullscreenChange);+ }, [ element ]);++ const toggle = useCallback(async () => {+ if (!element) return false;++ try {+ await (document.fullscreenElement ? document.exitFullscreen() : element.requestFullscreen());+ return true;+ } catch (e) {+ console.warn("Could not change the fullscreen state:", e);+ return false;+ }+ }, [ element ]);++ return [ isFullscreen, toggle ];+}+/*** Obtains the inner width and height of the window, as well as reacts to changes in size.*diff --git a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsxindex ef7999c194..2c50246293 100644--- a/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx+++ b/apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx@@ -4,6 +4,7 @@ import type { MindElixirInstance } from "mind-elixir";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n";+import { useFullscreen } from "../../react/hooks";import OverlayToolbar, { OverlayToolbarButton } from "../../react/OverlayToolbar";import { centerMapOn, type MapPoint, readMapCenter, stepZoom } from "./viewport";@@ -198,33 +199,23 @@ function useMapState<T>(mind: MindElixirInstance, read: (mind: MindElixirInstanc* not by the bar this one replaces.*/function useMapFullscreen(mind: MindElixirInstance): [ boolean, () => void ] {- const [ isFullscreen, setFullscreen ] = useState(() => document.fullscreenElement === mind.el);const center = useRef<MapPoint | null>(null);- useEffect(() => {- const onFullscreenChange = () => {- setFullscreen(document.fullscreenElement === mind.el);-- const taken = center.current;- center.current = null;- if (taken) centerMapOn(mind, taken);- };-- document.addEventListener("fullscreenchange", onFullscreenChange);- return () => document.removeEventListener("fullscreenchange", onFullscreenChange);- }, [ mind ]);+ const [ isFullscreen, toggleScreen ] = useFullscreen(mind.el, () => {+ const taken = center.current;+ center.current = null;+ if (taken) centerMapOn(mind, taken);+ });const toggle = useCallback(() => {center.current = readMapCenter(mind);- const changed = document.fullscreenElement ? document.exitFullscreen() : mind.el.requestFullscreen();// A refused request leaves the view the size it was, so there is nothing to put back — and// holding on to the point would move the map on whatever change came next.- changed?.catch((e) => {- center.current = null;- console.warn("Could not change the mind map's fullscreen state:", e);+ toggleScreen().then((changed) => {+ if (!changed) center.current = null;});- }, [ mind ]);+ }, [ mind, toggleScreen ]);return [ isFullscreen, toggle ];}