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(menu): place the context menu with Floating UI
Elian Doran11a6043c0df1
diff --git a/apps/client/package.json b/apps/client/package.jsonindex 2a3e28fd5e..51ca105ba2 100644--- a/apps/client/package.json+++ b/apps/client/package.json@@ -18,6 +18,7 @@},"dependencies": {"@excalidraw/excalidraw": "0.18.1",+ "@floating-ui/dom": "1.8.0","@fullcalendar/rrule": "7.1.0","@popperjs/core": "2.11.8","@preact/signals": "2.11.2",diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex 4372b3ef15..a28dc0ea9d 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";vi.mock("../services/note_tooltip", () => ({ default: { dismissAllTooltips: vi.fn() } }));@@ -48,19 +48,54 @@ describe("contextMenu", () => {expect(onHide).toHaveBeenCalledTimes(1);});- it("opens at the pointer and stays inside the viewport", async () => {- const container = buildPage();- const contextMenu = await buildContextMenu();- Object.defineProperty(document.documentElement, "clientWidth", { value: 1000, configurable: true });- Object.defineProperty(document.documentElement, "clientHeight", { value: 800, configurable: true });- const menu = () => container?.querySelector<HTMLElement>(".tn-menu");+ describe("placement", () => {+ /** Opens the menu with the size a browser would lay it out at; happy-dom lays out nothing. */+ async function place(options: { x: number, y: number, width: number, height: number, orientation?: "left" }) {+ const container = buildPage();+ const contextMenu = await buildContextMenu();+ // Floating UI reads the viewport from the root element's client size.+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);+ vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(options.width);+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(options.height);++ await contextMenu.show({ ...options, items, selectMenuItemHandler: () => {} });+ const menu = container?.querySelector<HTMLElement>(".tn-menu");+ if (!menu) throw new Error("expected the menu to render");+ await vi.waitFor(() => expect(menu.style.visibility).toBe("visible"));+ return menu;+ }++ afterEach(() => {+ vi.restoreAllMocks();+ });- await contextMenu.show({ x: 10, y: 20, items, selectMenuItemHandler: () => {} });- expect([ menu()?.style.left, menu()?.style.top ]).toEqual([ "10px", "20px" ]);+ it("opens at the pointer, towards the bottom right", async () => {+ const menu = await place({ x: 10, y: 20, width: 200, height: 300 });+ expect([ menu.style.left, menu.style.top ]).toEqual([ "10px", "20px" ]);+ });++ it("opens towards the left when asked to", async () => {+ const menu = await place({ x: 500, y: 20, width: 200, height: 300, orientation: "left" });+ expect([ menu.style.left, menu.style.top ]).toEqual([ "300px", "20px" ]);+ });- // happy-dom measures the menu as 0×0, so it is pushed back to the edge less the padding.- await contextMenu.show({ x: 2000, y: 2000, items, selectMenuItemHandler: () => {} });- await vi.waitFor(() => expect([ menu()?.style.left, menu()?.style.top ]).toEqual([ "995px", "795px" ]));+ it("flips to the other side of the pointer where it does not fit", async () => {+ const menu = await place({ x: 900, y: 700, width: 200, height: 300 });+ // Its bottom right corner is at the pointer, as a native menu opened in that corner.+ expect([ menu.style.left, menu.style.top ]).toEqual([ "700px", "400px" ]);+ });++ it("shifts inside the viewport where it fits on neither side", async () => {+ // 600px overflows by 155px to the right of the pointer and by 55px to its left.+ const menu = await place({ x: 550, y: 20, width: 600, height: 300 });+ expect([ menu.style.left, menu.style.top ]).toEqual([ "5px", "20px" ]);+ });++ it("caps its height to the viewport so that it scrolls", async () => {+ const menu = await place({ x: 10, y: 20, width: 200, height: 2000 });+ expect(menu.style.maxHeight).toBe("790px");+ });});it("hides on a click anywhere on the page", async () => {diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex e033ad1cde..ae3f5de09a 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -113,7 +113,7 @@ class ContextMenu {this.cover?.classList.add("show");document.body.classList.add("context-menu-shown");- render(h(Menu, { x: options.x, y: options.y }), this.container);+ render(h(Menu, { x: options.x, y: options.y, orientation: options.orientation }), this.container);}/**diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.tsindex 5682e39604..bd8f60570d 100644--- a/apps/client/src/menus/context_menu_legacy.ts+++ b/apps/client/src/menus/context_menu_legacy.ts@@ -127,8 +127,6 @@ class ContextMenu {this.addItems(this.$widget, options.items);keyboardActionService.updateDisplayedShortcuts(this.$widget);-- this.positionMenu();}/**@@ -149,62 +147,6 @@ class ContextMenu {}}- positionMenu() {- if (!this.options) {- return;- }-- // the code below tries to detect when dropdown would overflow from page- // in such case we'll position it above click coordinates, so it will fit into the client-- const CONTEXT_MENU_PADDING = 5; // How many pixels to pad the context menu from edge of screen- const CONTEXT_MENU_OFFSET = 0; // How many pixels to offset the context menu by relative to cursor, see #3157-- const clientHeight = document.documentElement.clientHeight;- const clientWidth = document.documentElement.clientWidth;- const contextMenuHeight = this.$widget.outerHeight();- const contextMenuWidth = this.$widget.outerWidth();- let top, left;-- if (contextMenuHeight && this.options.y + contextMenuHeight - CONTEXT_MENU_OFFSET > clientHeight - CONTEXT_MENU_PADDING) {- // Overflow: bottom- top = clientHeight - contextMenuHeight - CONTEXT_MENU_PADDING;- } else if (this.options.y - CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {- // Overflow: top- top = CONTEXT_MENU_PADDING;- } else {- top = this.options.y - CONTEXT_MENU_OFFSET;- }-- if (this.options.orientation === "left" && contextMenuWidth) {- if (this.options.x + CONTEXT_MENU_OFFSET > clientWidth - CONTEXT_MENU_PADDING) {- // Overflow: right- left = clientWidth - contextMenuWidth - CONTEXT_MENU_OFFSET;- } else if (this.options.x - contextMenuWidth + CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {- // Overflow: left- left = CONTEXT_MENU_PADDING;- } else {- left = this.options.x - contextMenuWidth + CONTEXT_MENU_OFFSET;- }- } else if (contextMenuWidth && this.options.x + contextMenuWidth - CONTEXT_MENU_OFFSET > clientWidth - CONTEXT_MENU_PADDING) {- // Overflow: right- left = clientWidth - contextMenuWidth - CONTEXT_MENU_PADDING;- } else if (this.options.x - CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {- // Overflow: left- left = CONTEXT_MENU_PADDING;- } else {- left = this.options.x - CONTEXT_MENU_OFFSET;- }-- this.$widget- .css({- display: "block",- top,- left- })- .addClass("show");- }-private repositionSubmenu(submenuEl: HTMLElement) {const CONTEXT_MENU_PADDING = 5;diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.cssindex f220fe488c..cadd562e0d 100644--- a/apps/client/src/widgets/react/Menu.css+++ b/apps/client/src/widgets/react/Menu.css@@ -1,8 +1,13 @@.tn-menu {position: fixed;+ top: 0;+ left: 0;/* Matches the z-index the context menu had, above dialogs and floating panels. */z-index: 2000;+ /* `placeMenu()` shows the menu once it has a position. */+ visibility: hidden;min-width: 10rem;+ overflow-y: auto;padding: var(--menu-padding-size);border: 1px solid var(--dropdown-border-color);border-radius: var(--dropdown-border-radius);diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex dade21447c..12c6efd0d2 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -1,39 +1,74 @@import "./Menu.css";-import { useLayoutEffect, useRef, useState } from "preact/hooks";+import { computePosition, flip, type Placement, shift, size, type VirtualElement } from "@floating-ui/dom";+import { useCallback, useLayoutEffect, useRef } from "preact/hooks";++import { useResizeObserver } from "./hooks";export interface MenuProps {/** Where the menu opens, in viewport coordinates. */x: number;y: number;+ /** Opens the menu towards the left of {@link x} instead of towards the right. */+ orientation?: "left";}/** How many pixels the menu keeps from the edges of the viewport. */const VIEWPORT_PADDING = 5;-export default function Menu({ x, y }: MenuProps) {+export default function Menu({ x, y, orientation }: MenuProps) {const menuRef = useRef<HTMLDivElement>(null);- const [ position, setPosition ] = useState({ left: x, top: y });-- useLayoutEffect(() => {- const menu = menuRef.current;- if (!menu) return;+ const place = useCallback(() => {+ if (!menuRef.current) return;+ void placeMenu(menuRef.current, pointAt(x, y), orientation === "left" ? "left-start" : "right-start");+ }, [ x, y, orientation ]);- const { width, height } = menu.getBoundingClientRect();- const { clientWidth, clientHeight } = document.documentElement;- setPosition({- left: clampToViewport(x, clientWidth - width),- top: clampToViewport(y, clientHeight - height)- });- }, [ x, y ]);+ useLayoutEffect(place, [ place ]);+ // The menu's size can change after it opens, e.g. once asynchronously loaded items arrive.+ useResizeObserver(menuRef, place);return (- <div ref={menuRef} className="tn-menu" role="menu" style={position}>+ <div ref={menuRef} className="tn-menu" role="menu">Hello world</div>);}-function clampToViewport(value: number, max: number) {- return Math.max(VIEWPORT_PADDING, Math.min(value, max - VIEWPORT_PADDING));+/**+ * Positions `menu` beside `anchor`, preferring `placement` and then the placements that mirror it,+ * the way a native menu opens above or to the left of a pointer that is near the viewport's edge.+ * The menu stays hidden until it is placed, so it never paints at a stale position.+ */+async function placeMenu(menu: HTMLElement, anchor: VirtualElement, placement: Placement) {+ const [ side ] = placement.split("-");+ const otherSide = side === "left" ? "right" : "left";+ const { x, y } = await computePosition(anchor, menu, {+ strategy: "fixed",+ placement,+ middleware: [+ flip({+ fallbackPlacements: [ `${otherSide}-start`, `${side}-end`, `${otherSide}-end` ] as Placement[],+ padding: VIEWPORT_PADDING+ }),+ // `crossAxis` also shifts a menu wider than the room on either side of its anchor.+ shift({ crossAxis: true, padding: VIEWPORT_PADDING }),+ size({+ padding: VIEWPORT_PADDING,+ apply({ availableHeight }) {+ menu.style.maxHeight = `${availableHeight}px`;+ }+ })+ ]+ });++ menu.style.left = `${x}px`;+ menu.style.top = `${y}px`;+ menu.style.visibility = "visible";+}++/** A zero-size anchor at a point in the viewport, such as where a right-click landed. */+function pointAt(x: number, y: number): VirtualElement {+ return {+ getBoundingClientRect: () => DOMRect.fromRect({ x, y, width: 0, height: 0 })+ };}diff --git a/apps/standalone/package.json b/apps/standalone/package.jsonindex 7a7ca7549c..4170f14fb3 100644--- a/apps/standalone/package.json+++ b/apps/standalone/package.json@@ -15,6 +15,7 @@},"dependencies": {"@excalidraw/excalidraw": "0.18.1",+ "@floating-ui/dom": "1.8.0","@popperjs/core": "2.11.8","@preact/signals": "2.11.2","@sqlite.org/sqlite-wasm": "3.51.1-build2",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3b0cccbc95..844b2a32ca 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -207,6 +207,9 @@ importers:'@excalidraw/excalidraw':specifier: 0.18.1version: 0.18.1(patch_hash=859531a8ff622291b895d36bcd33e07ced6fcb3bcc90631ccaf776789b03f0c2)([email protected]([email protected]))([email protected])+ '@floating-ui/dom':+ specifier: 1.8.0+ version: 1.8.0'@fullcalendar/rrule':specifier: 7.1.0version: 7.1.0([email protected])([email protected])@@ -851,6 +854,9 @@ importers:'@excalidraw/excalidraw':specifier: 0.18.1version: 0.18.1(patch_hash=859531a8ff622291b895d36bcd33e07ced6fcb3bcc90631ccaf776789b03f0c2)([email protected]([email protected]))([email protected])+ '@floating-ui/dom':+ specifier: 1.8.0+ version: 1.8.0'@popperjs/core':specifier: 2.11.8version: 2.11.8