Skip to content

Build your personal knowledge base with Trilium Notes

feat(menu): turn a submenu's arrow to the side its submenu opens on

Elian Doran1b30418d8a64
diff --git a/apps/client/src/stylesheets/theme-next/base.css b/apps/client/src/stylesheets/theme-next/base.css
index 28226bb9b0..4a45bc4645 100644
--- a/apps/client/src/stylesheets/theme-next/base.css
+++ b/apps/client/src/stylesheets/theme-next/base.css
@@ -243,8 +243,9 @@ body.desktop .dropdown-item.dropdown-submenu .dropdown-toggle,
}
}
-body.desktop .dropdown-menu:has(> .dropdown-submenu.dropstart) > .dropdown-item:not(.dropdown-submenu),
-body.desktop .dropdown-menu:has(> .dropdown-submenu.dropstart) > .dropdown-item.dropdown-submenu .dropdown-toggle {
+/* A level's rows are all in its `.tn-menu-scroll`, and its submenus' layers outside it. */
+body.desktop .tn-menu-scroll:has(.dropdown-submenu.dropstart) .dropdown-item:not(.dropdown-submenu),
+body.desktop .tn-menu-scroll:has(.dropdown-submenu.dropstart) .dropdown-item.dropdown-submenu .dropdown-toggle {
padding-inline-end: var(--menu-item-start-padding) !important;
padding-inline-start: var(--menu-item-end-padding) !important;
}
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index c3e5288f8c..f8f0aed568 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -13,7 +13,7 @@ import FormToggle from "./FormToggle";
import HelpTooltipButton from "./HelpTooltipButton";
import { useStaticTooltip, useSyncedRef, useUniqueName } from "./hooks";
import Icon from "./Icon";
-import { MenuContext, type MenuContextValue, MenuLevelContext, type OpenSubmenu, pointerMoved } from "./menu_context";
+import { isRightToLeft, MenuContext, type MenuContextValue, MenuLevelContext, type OpenSubmenu, pointerMoved, shouldDropStart, useMenu } from "./menu_context";
import { placeFloating } from "./Popup";
import { joinElements } from "./react_utils";
import { renderShortcutKbds } from "./shortcut_kbd";
@@ -399,7 +399,7 @@ function MenuSubmenu({ menu, icon, title, children, onDropdownToggleClicked, col
menu.registerRow(id, element ? { level, element, custom: false, disabled: !!disabled, hasSubmenu: true, select } : undefined);
}}
className={clsx("dropdown-item dropdown-submenu", open && "submenu-open", isActive && "tn-menu-active",
- disabled && "disabled", className)}
+ menu.dropStart[level] && "dropstart", disabled && "disabled", className)}
role="menuitem"
aria-disabled={disabled || undefined}
aria-haspopup="menu"
@@ -466,14 +466,18 @@ function SubmenuLayer({ level, submenu, columns, children }: {
}) {
const layerRef = useRef<HTMLDivElement>(null);
const columnCount = (columns ?? 1) > 1 ? columns : undefined;
+ const { dropStart: dropStartLevels, setDropStart } = useMenu();
+ const dropStart = !!dropStartLevels[level - 1];
useLayoutEffect(() => {
const layer = layerRef.current;
if (!layer) return;
- const placement = handleRightToLeftPlacement("right") === "right" ? "right-start" : "left-start";
+ const rtl = isRightToLeft();
+ const startSide = rtl ? "right" : "left";
+ const endSide = rtl ? "left" : "right";
const options = {
- placement,
+ placement: `${dropStart ? startSide : endSide}-start`,
// Overlaps its row by 2px, so the pointer crosses no gap on its way over, and lines its
// first row up with that row.
offset: ({ elements }: { elements: { floating: HTMLElement } }) => {
@@ -483,8 +487,17 @@ function SubmenuLayer({ level, submenu, columns, children }: {
},
shiftAcross: true, capHeight: true, hideWithAnchor: true
} as const;
- return autoUpdate(submenu.anchor, layer, () => void placeFloating(layer, submenu.anchor, options));
- }, [ submenu.anchor ]);
+ return autoUpdate(submenu.anchor, layer, () => void placeFloating(layer, submenu.anchor, options).then((placed) => {
+ // Flipped for want of room, it turns the arrows of its parent level's rows with it.
+ const placedDropStart = placed.startsWith(startSide);
+ if (placedDropStart !== dropStart) {
+ setDropStart(level - 1, placedDropStart);
+ return;
+ }
+ setDropStart(level, shouldDropStart(layer.getBoundingClientRect(),
+ document.documentElement.clientWidth, rtl, dropStart));
+ }));
+ }, [ submenu.anchor, dropStart, level, setDropStart ]);
// In a `.dropdown-submenu`, so the theme's submenu rules apply.
return (
diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsx
index 3751dea108..542d6de8bc 100644
--- a/apps/client/src/widgets/react/Menu.spec.tsx
+++ b/apps/client/src/widgets/react/Menu.spec.tsx
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem } from "./FormList";
import Menu, { rowInNextColumn } from "./Menu";
+import { shouldDropStart } from "./menu_context";
/** A row 20px tall, `left` into the menu and `top` down it. */
function row(left: number, top: number) {
@@ -39,6 +40,28 @@ describe("rowInNextColumn", () => {
});
});
+describe("shouldDropStart", () => {
+ /** A level 200px wide, standing at `left` in a viewport 1000px wide. */
+ const at = (left: number) => ({ left, right: left + 200, width: 200 });
+
+ it("opens towards the end while there is room there, and turns only for more room at the start", () => {
+ expect(shouldDropStart(at(100), 1000, false, false)).toBe(false);
+ expect(shouldDropStart(at(750), 1000, false, false)).toBe(true);
+ // Cramped on both sides, it keeps to the end unless the start has more.
+ expect(shouldDropStart(at(50), 300, false, false)).toBe(false);
+ });
+
+ it("keeps to the start once its level opened that way, until the room there runs out", () => {
+ expect(shouldDropStart(at(400), 1000, false, true)).toBe(true);
+ expect(shouldDropStart(at(100), 1000, false, true)).toBe(false);
+ });
+
+ it("measures the end on the left when the page reads right to left", () => {
+ expect(shouldDropStart(at(750), 1000, true, false)).toBe(false);
+ expect(shouldDropStart(at(50), 1000, true, false)).toBe(true);
+ });
+});
+
describe("Menu with declared rows", () => {
const host = document.createElement("div");
document.body.append(host);
@@ -151,4 +174,31 @@ describe("Menu with declared rows", () => {
key(menu, "Enter");
expect(calls).toEqual([ "log", "close" ]);
});
+
+ it("turns its submenus and their arrows towards the start where the end has no room", async () => {
+ // The menus and their rows stand 120px wide against the right edge of a 1024px viewport.
+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1024);
+ vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(768);
+ const measure = HTMLElement.prototype.getBoundingClientRect;
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
+ return this.matches(".tn-menu, .dropdown-item")
+ ? DOMRect.fromRect({ x: 900, y: 10, width: 120, height: 20 })
+ : measure.call(this);
+ });
+ try {
+ const { menu } = renderMenu();
+ const advanced = rowTitled("Advanced");
+ await vi.waitFor(() => expect(advanced.classList).toContain("dropstart"));
+
+ advanced.dispatchEvent(new PointerEvent("pointerenter"));
+ await vi.waitFor(() => expect(layers(menu)).toHaveLength(1));
+ const layer = menu.querySelector<HTMLElement>(":scope > div.dropdown-submenu > .dropdown-menu");
+ // By the row's left edge, at 900px, rather than its right edge, at 1020px. happy-dom lays
+ // the layer out 0px wide.
+ await vi.waitFor(() => expect(parseFloat(layer?.style.left ?? "")).toBeLessThan(910));
+ expect(advanced.classList).toContain("dropstart");
+ } finally {
+ vi.restoreAllMocks();
+ }
+ });
});
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index a051fe0ec9..2d46746a41 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -5,9 +5,9 @@ import type { ComponentChildren } from "preact";
import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";
import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
-import { handleRightToLeftPlacement, isMobile } from "../../services/utils";
+import { isMobile } from "../../services/utils";
import { FormDropdownDivider, FormDropdownSubmenu, FormListCustomItem, FormListHeader, FormListItem } from "./FormList";
-import { type ActiveRow, MenuContext, type MenuContextValue, type OpenSubmenu, pointerMoved, type RowEntry } from "./menu_context";
+import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart } from "./menu_context";
import Popup, { type PopupProps } from "./Popup";
/**
@@ -74,6 +74,15 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
return rowId && anchor ? [ ...kept, { id: rowId, anchor, immediate } ] : kept;
});
}, []);
+ const [ dropStart, setDropStartLevels ] = useState<boolean[]>([]);
+ const setDropStart = useCallback((level: number, value: boolean) => {
+ setDropStartLevels((current) => {
+ if (current[level] === value) return current;
+ const next = [ ...current ];
+ next[level] = value;
+ return next;
+ });
+ }, []);
const [ active, setActiveRow ] = useState<ActiveRow>();
const rows = useRef(new Map<string, RowEntry>()).current;
/** The level whose first row becomes active once it has rendered, for a submenu a key opened. */
@@ -108,7 +117,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
});
}, [ rows ]);
const context: MenuContextValue = {
- open, openSubmenu, active, setActive, rows, registerRow, keyboardDriven, close, layerHost
+ open, openSubmenu, active, setActive, rows, registerRow, keyboardDriven, dropStart, setDropStart, close, layerHost
};
/** The ids of the rows the keys can stand on at `level`, in the order they stand in. */
@@ -196,7 +205,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
openSubmenu(closing - 1);
setActive(closing - 1, parent.id);
};
- const rtl = handleRightToLeftPlacement("right") !== "right";
+ const rtl = isRightToLeft();
/** Moves to the row beside the active one in a menu laid out in columns, if there is one. */
const moveAcross = (towards: "left" | "right") => {
const boxes = levelRows.map((rowId) => rows.get(rowId)?.element.getBoundingClientRect());
@@ -276,7 +285,14 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
anchor={anchor}
placement={placement ?? (anchor instanceof HTMLElement ? "bottom-start" : "right-start")}
placedByStylesheet={bottomSheet}
- onPlaced={takeFocus}
+ onPlaced={() => {
+ const menu = menuRef.current;
+ if (menu) {
+ setDropStart(0, shouldDropStart(menu.getBoundingClientRect(),
+ document.documentElement.clientWidth, isRightToLeft(), false));
+ }
+ takeFocus();
+ }}
onDismiss={onDismiss && (() => onDismiss())}
escapeDismisses={false}
elementRef={setMenuElement} id={id} role="menu" tabIndex={-1}
diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsx
index 50cbe7a01f..75573c972f 100644
--- a/apps/client/src/widgets/react/Popup.tsx
+++ b/apps/client/src/widgets/react/Popup.tsx
@@ -206,9 +206,10 @@ export interface FloatingPlacement {
* Positions `element` beside `anchor`, preferring its placement, then the side opposite, then the
* other alignment on either side, the way a native menu opens above or to the left of a pointer
* near the viewport's edge. It stays hidden until placed, so it never paints at a stale position.
+ * Resolves to the placement it took.
*/
export async function placeFloating(element: HTMLElement, anchor: ReferenceElement, { placement, offset: gap, shiftAcross, capHeight, hideWithAnchor }: FloatingPlacement) {
- const { x, y, middlewareData } = await computePosition(anchor, element, {
+ const { x, y, placement: placed, middlewareData } = await computePosition(anchor, element, {
strategy: "fixed",
placement,
middleware: [
@@ -228,6 +229,7 @@ export async function placeFloating(element: HTMLElement, anchor: ReferenceEleme
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.visibility = middlewareData.hide?.referenceHidden ? "hidden" : "visible";
+ return placed;
}
const OPPOSITE_SIDES = { top: "bottom", bottom: "top", left: "right", right: "left" } as const;
diff --git a/apps/client/src/widgets/react/menu_context.ts b/apps/client/src/widgets/react/menu_context.ts
index 9a21d24e61..6c888bc756 100644
--- a/apps/client/src/widgets/react/menu_context.ts
+++ b/apps/client/src/widgets/react/menu_context.ts
@@ -1,6 +1,8 @@
import { createContext } from "preact";
import { useContext } from "preact/hooks";
+import { handleRightToLeftPlacement } from "../../services/utils";
+
/*
* What a `Menu` shares with its rows, apart from the menu itself so the rows `FormList` draws can
* join one without `FormList` and `Menu` importing each other.
@@ -53,6 +55,13 @@ export interface MenuContextValue {
registerRow(id: string, row: RowEntry | undefined): void;
/** Whether the keys moved the menu since the pointer last did. */
keyboardDriven: boolean;
+ /**
+ * Whether the submenus of each level's rows open towards the start, the top level's first. The
+ * rows show it as `.dropstart`, which turns their arrow that way.
+ */
+ dropStart: boolean[];
+ /** Records the side the submenus of `level`'s rows open on. */
+ setDropStart(level: number, dropStart: boolean): void;
close(): void;
/**
* Where a row renders its submenu's layer: the top level's element, so the rules scoped to the
@@ -73,6 +82,23 @@ export function useMenu() {
return menu;
}
+/**
+ * Whether the submenus of a level's rows open towards the start, from where the level's menu or
+ * layer stands. They keep to `preferStart`, the side the level itself opened towards, unless that
+ * side has less room than the level is wide and the other side has more.
+ */
+export function shouldDropStart(frame: Pick<DOMRect, "left" | "right" | "width">, viewportWidth: number, rtl: boolean, preferStart: boolean) {
+ const roomAtEnd = rtl ? frame.left : viewportWidth - frame.right;
+ const roomAtStart = rtl ? viewportWidth - frame.right : frame.left;
+ const [ preferred, other ] = preferStart ? [ roomAtStart, roomAtEnd ] : [ roomAtEnd, roomAtStart ];
+ return preferred < frame.width && other > preferred ? !preferStart : preferStart;
+}
+
+/** Whether the page reads right to left, so a menu's end side is its left. */
+export function isRightToLeft() {
+ return handleRightToLeftPlacement("right") !== "right";
+}
+
/**
* Whether the pointer really moved. A menu appearing under a pointer at rest has the browser enter
* the row there, and Chromium follow with a `pointermove` that goes nowhere; neither is the user