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
client/text editor/canvas: allow context menus to overflow the canvas surface
Adorian Doran4e2eea0f295b
diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.cssindex 6acbd853c9..cafbcb4a95 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.css@@ -89,6 +89,19 @@}}+/* Excalidraw's context menu in the top layer, placed by `useTopLayerContextMenu()`. */+.canvas-drawing-editor .excalidraw .popover[popover] {+ position: fixed;+}++/* Resets the user agent style of a popover below the themes, which style the menu. */+:where(.canvas-drawing-editor .popover[popover]) {+ inset: auto;+ margin: 0;+ overflow: visible;+ color: inherit;+}+/* Excalidraw narrows its controls for a docked library, which is beside the drawing instead. */.canvas-drawing-editor:has(.default-sidebar[data-side-panel]) .layer-ui__wrapper {width: 100% !important;diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsxindex 6139378c49..dbeb3a6a90 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.spec.tsx@@ -1,4 +1,5 @@import { exportToSvg } from "@excalidraw/excalidraw";+import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";import { type ComponentChildren, render, toChildArray, type VNode } from "preact";import { useEffect, useRef, useState } from "preact/hooks";import { act } from "preact/test-utils";@@ -50,7 +51,7 @@ globalThis.ResizeObserver = class {const {default: CanvasDrawing, CanvasDrawingDetail, renderCanvasDrawingPicture, useIsToolbarOverPanel,- useSidePanels+ useSidePanels, useTopLayerContextMenu} = await import("./CanvasDrawing");const { default: CanvasDrawingMenu } = await import("./CanvasDrawingMenu");const { default: CanvasEmbedTools } = await import("./CanvasEmbedTools");@@ -310,6 +311,167 @@ describe("useSidePanels", () => {});});+describe("useTopLayerContextMenu", () => {+ type ContextMenuState = { top: number; left: number } | null;++ let container: HTMLElement;+ let showPopover: ReturnType<typeof vi.fn>;+ let contextMenu: ContextMenuState;+ let drawing: { left: number; top: number };+ let menuSize: { width: number; height: number };+ const api = {+ getAppState: () => ({ contextMenu }),+ updateScene: vi.fn(({ appState }: { appState: { contextMenu: ContextMenuState } }) => {+ contextMenu = appState.contextMenu;+ })+ };++ function ContextMenuProbe() {+ const rootRef = useRef<HTMLDivElement>(null);+ const apiRef = useRef(api as unknown as ExcalidrawImperativeAPI);+ useTopLayerContextMenu(rootRef, apiRef);+ return (+ <div className="scrolling-container">+ <div ref={rootRef}>+ <div className="excalidraw excalidraw-container" tabIndex={0} />+ </div>+ </div>+ );+ }++ beforeEach(async () => {+ // A window of 1280 × 900 and a 1rem of 16px.+ Object.defineProperties(document.documentElement, {+ clientWidth: { value: 1280, configurable: true },+ clientHeight: { value: 900, configurable: true }+ });+ contextMenu = null;+ drawing = { left: 340, top: 200 };+ menuSize = { width: 200, height: 500 };+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect")+ .mockImplementation(function (this: HTMLElement) {+ const box = this.classList.contains("popover")+ ? { left: 0, top: 0, ...menuSize }+ : { ...drawing, width: 500, height: 320 };+ const edges = { right: box.left + box.width, bottom: box.top + box.height };+ return { ...box, ...edges } as DOMRect;+ });+ vi.spyOn(window, "getComputedStyle")+ .mockReturnValue({ fontSize: "16px" } as CSSStyleDeclaration);+ // happy-dom has no Popover API.+ showPopover = vi.fn();+ Object.defineProperty(HTMLElement.prototype, "showPopover", {+ value: showPopover,+ configurable: true+ });+ api.updateScene.mockClear();+ container = document.createElement("div");+ document.body.appendChild(container);+ await act(async () => {+ render(<ContextMenuProbe />, container);+ });+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ vi.restoreAllMocks();+ Reflect.deleteProperty(HTMLElement.prototype, "showPopover");+ Reflect.deleteProperty(document.documentElement, "clientWidth");+ Reflect.deleteProperty(document.documentElement, "clientHeight");+ });++ /** Opens the menu at `left` and `top` in the drawing, as fitted in it by Excalidraw. */+ async function openMenu(left: number, top: number) {+ container.querySelector(".popover")?.remove();+ contextMenu = { left, top };+ const menu = document.createElement("div");+ menu.className = "popover";+ menu.tabIndex = -1;+ menu.style.cssText = `left: ${left}px; top: 10px; height: 300px; overflow-y: scroll;`;+ menu.innerHTML = `<ul class="context-menu"><li></li></ul>`;+ await act(async () => {+ container.querySelector(".excalidraw-container")?.append(menu);+ await Promise.resolve();+ });+ return menu;+ }++ /** The place and the size of `menu`, empty where Excalidraw's own style is gone. */+ function getStyle(menu: HTMLElement) {+ expect(menu.getAttribute("popover")).toBe("manual");+ const { left, top, width, height, overflowX, overflowY } = menu.style;+ return { left, top, width, height, overflowX, overflowY };+ }++ const FREE = { width: "", height: "", overflowX: "", overflowY: "" };++ it("shows the menu at its point in the window, moved up or left into the window", async () => {+ const menu = await openMenu(100, 50);+ expect(getStyle(menu)).toEqual({ left: "440px", top: "250px", ...FREE });+ expect(showPopover).toHaveBeenCalledTimes(1);++ // 450 + 500 reaches past the bottom edge of 892.+ expect(getStyle(await openMenu(450, 250)))+ .toEqual({ left: "790px", top: "392px", ...FREE });++ drawing = { left: 1000, top: 200 };+ expect(getStyle(await openMenu(250, 50)))+ .toEqual({ left: "1072px", top: "250px", ...FREE });+ expect(showPopover).toHaveBeenCalledTimes(3);+ });++ it("places the menu once for each opening, which Excalidraw can render in place", async () => {+ const menu = await openMenu(100, 50);+ menu.style.left = "0px";+ await act(async () => {+ menu.querySelector("ul")?.append(document.createElement("li"));+ await Promise.resolve();+ });+ expect(menu.style.left).toBe("0px");++ contextMenu = { left: 200, top: 50 };+ await act(async () => {+ menu.querySelector("ul")?.append(document.createElement("li"));+ await Promise.resolve();+ });+ expect(getStyle(menu)).toEqual({ left: "540px", top: "250px", ...FREE });+ });++ it("shrinks a menu larger than the window, and scrolls it", async () => {+ menuSize = { width: 1300, height: 1000 };+ expect(getStyle(await openMenu(100, 50))).toEqual({+ left: "8px",+ top: "8px",+ width: "1264px",+ height: "884px",+ overflowX: "auto",+ overflowY: "auto"+ });+ });++ it("closes the menu when the note scrolls, keeping the focus in the drawing", async () => {+ const menu = await openMenu(100, 50);+ menu.focus();+ const elsewhere = document.createElement("div");+ document.body.append(elsewhere);++ menu.dispatchEvent(new Event("scroll"));+ elsewhere.dispatchEvent(new Event("scroll"));+ expect(api.updateScene).not.toHaveBeenCalled();++ container.querySelector(".scrolling-container")?.dispatchEvent(new Event("scroll"));+ expect(api.updateScene)+ .toHaveBeenCalledExactlyOnceWith({ appState: { contextMenu: null } });+ expect(document.activeElement).toBe(container.querySelector(".excalidraw-container"));++ // Nothing is left to close.+ document.dispatchEvent(new Event("scroll"));+ expect(api.updateScene).toHaveBeenCalledTimes(1);+ elsewhere.remove();+ });+});+describe("CanvasDrawing", () => {const ATTACHMENT = { attachmentId: "a1" } as never;let box: HTMLElement;diff --git a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsxindex d4003164f5..b8e4b63292 100644--- a/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx+++ b/apps/client/src/widgets/type_widgets/canvas/CanvasDrawing.tsx@@ -1,7 +1,7 @@import "./CanvasDrawing.css";import { exportToSvg } from "@excalidraw/excalidraw";-import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";+import type { AppState, ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";import clsx from "clsx";import type { RefObject } from "preact";import { useEffect, useRef, useState } from "preact/hooks";@@ -48,6 +48,7 @@ export default function CanvasDrawing({ attachment, editor }: CanvasDrawingPropsconst isToolbarOverPanel = useIsToolbarOverPanel(rootRef);useFocusFromEmbedBox(rootRef);useSidePanels(rootRef, isEditable);+ useTopLayerContextMenu(rootRef, apiRef);return (<div@@ -195,8 +196,11 @@ export function useIsToolbarOverPanel(rootRef: RefObject<HTMLElement>) {return isOver;}-/** The space between the drawing, the panels beside it and the edges of the window, in rem. */-const SIDE_PANEL_GAP_REM = 0.5;+/**+ * The space between the drawing, the panels beside it and the edges of the window, which the+ * context menu keeps too, in rem.+ */+const WINDOW_GAP_REM = 0.5;/** The least height of a panel as tall as the drawing, in rem. */const SIDE_PANEL_MIN_HEIGHT_REM = 20;@@ -309,7 +313,7 @@ function getSideLayout(root: HTMLElement, viewport: HTMLElement): SideLayout | nreturn {drawing,area: getWindowArea(),- gap: SIDE_PANEL_GAP_REM * rem,+ gap: WINDOW_GAP_REM * rem,minHeight: SIDE_PANEL_MIN_HEIGHT_REM * rem};}@@ -358,17 +362,17 @@ function placePanel(panel: HTMLElement, position: SidePanelPosition | null) {}/**- * Moves `panel` into the top layer, or back into the drawing. The `popover` attribute is present- * exactly while the panel is in the top layer; removing it hides the popover.+ * Moves `element` into the top layer, or back into the drawing. The `popover` attribute is present+ * exactly while the element is in the top layer; removing it hides the popover.*/-function setTopLayer(panel: HTMLElement, isMoved: boolean) {- if (isMoved === panel.hasAttribute("popover")) return;+function setTopLayer(element: HTMLElement, isMoved: boolean) {+ if (isMoved === element.hasAttribute("popover")) return;if (isMoved) {- panel.setAttribute("popover", "manual");- panel.showPopover();+ element.setAttribute("popover", "manual");+ element.showPopover();} else {- panel.removeAttribute("popover");+ element.removeAttribute("popover");}}@@ -421,3 +425,108 @@ function getSidePanelLeft(}return null;}++/** The inline styles with which Excalidraw fits its context menu in the drawing. */+export const FITTED_MENU_STYLES = [+ "left", "top", "width", "height", "overflowX", "overflowY"+] as const;++/**+ * Shows Excalidraw's context menu in the top layer, so that no clip of the note cuts it, fitted+ * in the window instead of the drawing. Closes it when the note scrolls.+ */+export function useTopLayerContextMenu(+ rootRef: RefObject<HTMLElement>,+ apiRef: RefObject<ExcalidrawImperativeAPI>+) {+ useEffect(() => {+ const root = rootRef.current;+ if (!root) return;++ let menu: HTMLElement | null = null;+ // Excalidraw sets a new `contextMenu` each time the menu opens.+ let placedState: AppState["contextMenu"] = null;++ const watchMenu = () => {+ menu = root.querySelector(".context-menu")?.closest<HTMLElement>(".popover") ?? null;+ const state = apiRef.current?.getAppState().contextMenu ?? null;+ const container = root.querySelector(".excalidraw-container");+ if (!menu || !state || !container || state === placedState) return;++ placedState = state;+ placeContextMenu(menu, state, container.getBoundingClientRect());+ };++ const closeOnScroll = (event: Event) => {+ const api = apiRef.current;+ const isDrawingMoved = event.target instanceof Node && event.target.contains(root);+ if (!isDrawingMoved || !api?.getAppState().contextMenu) return;++ // Excalidraw also focuses its container when the menu closes.+ if (menu?.contains(document.activeElement)) {+ root.querySelector<HTMLElement>(".excalidraw-container")+ ?.focus({ preventScroll: true });+ }+ api.updateScene({ appState: { contextMenu: null } });+ };++ const observer = new MutationObserver(watchMenu);+ observer.observe(root, { childList: true, subtree: true });+ // Scroll events do not bubble, so the capture phase sees those of every ancestor.+ document.addEventListener("scroll", closeOnScroll, { capture: true, passive: true });++ return () => {+ observer.disconnect();+ document.removeEventListener("scroll", closeOnScroll, { capture: true });+ if (menu) setTopLayer(menu, false);+ };+ }, [ rootRef, apiRef ]);+}++/**+ * Moves Excalidraw's context `menu` into the top layer, at the point where Excalidraw opened it in+ * the `drawing`. A menu that reaches past the window moves back into it, and one larger than the+ * window shrinks to it and scrolls.+ */+function placeContextMenu(+ menu: HTMLElement,+ point: { left: number; top: number },+ drawing: DOMRect+) {+ for (const property of FITTED_MENU_STYLES) {+ menu.style[property] = "";+ }+ setTopLayer(menu, true);+ // Measured at the corner of the window, where nothing narrows the menu.+ menu.style.left = "0px";+ menu.style.top = "0px";+ const { width, height } = menu.getBoundingClientRect();++ const area = getWindowArea();+ const gap = WINDOW_GAP_REM * parseFloat(getComputedStyle(document.documentElement).fontSize);+ const x = fitSpan(drawing.left + point.left, width, area.left + gap, area.right - gap);+ const y = fitSpan(drawing.top + point.top, height, area.top + gap, area.bottom - gap);+ menu.style.left = `${x.start}px`;+ menu.style.top = `${y.start}px`;+ if (x.size !== null) {+ menu.style.width = `${x.size}px`;+ menu.style.overflowX = "auto";+ }+ if (y.size !== null) {+ menu.style.height = `${y.size}px`;+ menu.style.overflowY = "auto";+ }+}++/**+ * Where a span `size` long from `start` fits between `min` and `max`: moved back from `max` when it+ * reaches past it, and shrunk to the space between them when longer. `size` is `null` while the+ * span keeps its own.+ */+function fitSpan(start: number, size: number, min: number, max: number) {+ const fittedSize = Math.min(size, max - min);+ return {+ start: Math.max(min, Math.min(start, max - fittedSize)),+ size: fittedSize < size ? fittedSize : null+ };+}diff --git a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.tsindex 471b0da53f..a3229765a1 100644--- a/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts+++ b/apps/client/src/widgets/type_widgets/canvas/excalidraw_contract.spec.ts@@ -10,6 +10,7 @@ const {EXTRA_TOOLS, HISTORY_ACTIONS, LOCK, MAIN_TOOLS, MAX_ZOOM, MIN_ZOOM, ZOOM_STEP, ZOOMS} = await import("./CanvasEmbedTools");const { LIBRARY_SIDEBAR } = await import("./CanvasDrawingMenu");+const { FITTED_MENU_STYLES } = await import("./CanvasDrawing");/** The classes of Trilium that `CanvasDrawing.css` selects. Every other class is Excalidraw's. */const TRILIUM_CLASSES = new Set([@@ -20,7 +21,8 @@ const TRILIUM_CLASSES = new Set([/** The classes of Excalidraw that `CanvasDrawing.tsx` and `CanvasEmbedTools.tsx` look up. */const CODE_CLASSES = [- "excalidraw", "excalidraw-container", "App-menu__left", "App-toolbar-container"+ "excalidraw", "excalidraw-container", "App-menu__left", "App-toolbar-container",+ "context-menu", "popover"];/**@@ -90,6 +92,22 @@ describe("Excalidraw contract of the canvas drawing", () => {expect(source).toContain(`varDEFAULT_SIDEBAR={name:"${LIBRARY_SIDEBAR}"`);});+ it("fits the context menu in its container with the styles that the top layer replaces", () => {+ const source = readBundle(developmentDir, [ ".js" ]);+ const popover = source.split("// components/Popover.tsx")[1]+ ?.split("// components/ContextMenu.tsx")[0] ?? "";+ const styles = [ ...popover.matchAll(/container\.style\.(\w+) =/g) ]+ .map((match) => match[1]);+ expect(new Set(styles)).toEqual(new Set(FITTED_MENU_STYLES));++ // `useTopLayerContextMenu()` adds the position of the container to the point of the menu.+ expect(source.replace(/\s+/g, "")).toContain([+ "constcontainer=this.excalidrawContainerRef.current;",+ "const{top:offsetTop,left:offsetLeft}=container.getBoundingClientRect();",+ "constleft=event.clientX-offsetLeft;consttop=event.clientY-offsetTop;"+ ].join(""));+ });+it("takes the layout from `UIOptions.getFormFactor`, which the Trilium patch adds", () => {const unpatched = [ productionDir, developmentDir ].filter((dir) => {const source = readBundle(dir, [ ".js" ]).replace(/\s+/g, "");