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/ui/menus: add a delay before automatically closing the submenus while hovering the sibling menu items
Adorian Doran2e47a3de580f
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsxindex b30dbd0147..5db30b8612 100644--- a/apps/client/src/widgets/react/FormList.tsx+++ b/apps/client/src/widgets/react/FormList.tsx@@ -232,11 +232,12 @@ export function FormListItem({run(new MouseEvent("click", { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey, altKey: e.altKey, metaKey: e.metaKey }));}- function onPointed(e: { currentTarget: HTMLLIElement }) {+ function onPointed() {if (!menu || isMobile()) return;+ // First, as it can make the row of the submenus it closes active.+ menu.hoverSubmenu(level);// The keyboard goes on from the row the pointer last pointed at.if (!disabled) menu.setActive(level, id);- menu.openSubmenu(level, undefined, e.currentTarget);}const hasOwnIcon = !!iconSvg || (!!icon && icon !== EMPTY_ICON);@@ -266,13 +267,13 @@ export function FormListItem({tabIndex={menu ? undefined : container ? -1 : 0}// While the keys drive the menu, a row entered by a pointer at rest, as when the menu// appears under it, keeps the keys' row. See `pointerMoved`.- onPointerEnter={menu ? (e) => {- if (!menu.keyboardDriven) onPointed(e);+ onPointerEnter={menu ? () => {+ if (!menu.keyboardDriven) onPointed();} : undefined}// The keys can move the active row from under a pointer at rest, whose `:hover` would// then mark a second row. The next move of the pointer makes its row the active one.onPointerMove={menu ? (e) => {- if (!isActive && pointerMoved(e)) onPointed(e);+ if (!isActive && pointerMoved(e)) onPointed();} : undefined}// A press keeps focus where it was, as in a native menu: a text editor keeps the// selection a command such as a spelling fix acts on, and a field beside a dropdown@@ -454,7 +455,7 @@ export function FormListHeader({ text, actions = [] }: FormListHeaderOpts) {className="tn-menu-header-actions"// As over a row, the pointer closes the submenu open at this level.onPointerMove={(e) => {- if (menu && pointerMoved(e)) menu.closeSubmenu(level);+ if (menu && pointerMoved(e)) menu.hoverSubmenu(level);}}// A press keeps focus where it was, as on a row.onMouseDown={(e) => e.preventDefault()}@@ -553,7 +554,7 @@ function MenuSubmenu({if (isMobile()) return;// The keyboard goes on from the row the pointer last pointed at.if (!disabled) menu.setActive(level, id);- menu.openSubmenu(level, disabled ? undefined : id, e.currentTarget);+ menu.hoverSubmenu(level, disabled ? undefined : id, e.currentTarget);}const layer = isMobile()@@ -587,7 +588,7 @@ function MenuSubmenu({// opens its own only on a press.onPointerMove={(e) => {if (!pointerMoved(e)) return;- if (!open) menu.closeSubmenu(level);+ menu.hoverSubmenu(level, open ? id : undefined, e.currentTarget);if (!disabled && !isActive) menu.setActive(level, id);}}// As any row: the press keeps focus where it was, and the release acts.@@ -684,7 +685,7 @@ function SubmenuLayer({ level, submenu, filter, children }: {children: ComponentChildren}) {const layerRef = useRef<HTMLDivElement>(null);- const { dropStart: dropStartLevels, setDropStart, submenuShown } = useMenu();+ const { dropStart: dropStartLevels, setDropStart, submenuShown, hoverSubmenu } = useMenu();const dropStart = !!dropStartLevels[level - 1];const pinned = !!filter?.text;/** How far below its row's top the layer stands while pinned. */@@ -748,6 +749,9 @@ function SubmenuLayer({ level, submenu, filter, children }: {onAnimationStart={(e) => {if (e.target === e.currentTarget) submenuShown(submenu);}}+ // Over the layer, the pointer keeps it open as over its row, whatever rows it+ // crossed on the way.+ onPointerEnter={() => hoverSubmenu(level - 1, submenu.id, submenu.anchor)}><MenuList filter={filter}>{children}</MenuList></div>diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsxindex 22cfb30434..a5f81cbfc8 100644--- a/apps/client/src/widgets/react/Menu.spec.tsx+++ b/apps/client/src/widgets/react/Menu.spec.tsx@@ -1,6 +1,7 @@import { Tooltip } from "bootstrap";import { render } from "preact";import { useState } from "preact/hooks";+import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { MenuHeaderAction, MenuHeaderActions, MenuItem } from "../../menus/context_menu";@@ -238,6 +239,79 @@ describe("Menu with declared rows", () => {expect(activeTitle(menu)).toBe("Copy");});+ it("keeps a submenu in view open for 750ms once the pointer moves onto another row", async () => {+ vi.useFakeTimers();+ try {+ render((+ <Menu anchor={{ x: 10, y: 10 }} onClose={vi.fn()}>+ <FormDropdownSubmenu title="Advanced" icon="bx bx-chip">+ <FormListItem>Reload</FormListItem>+ </FormDropdownSubmenu>+ <FormListItem>Copy</FormListItem>+ <FormDropdownSubmenu title="Export" icon="bx bx-export">+ <FormListItem>As PDF</FormListItem>+ </FormDropdownSubmenu>+ </Menu>+ ), host);+ const menu = document.querySelector<HTMLElement>(".tn-popup.tn-menu");+ if (!menu) throw new Error("expected the menu to render");+ const layer = () => menu.querySelector<HTMLElement>(":scope > div.dropdown-submenu > .dropdown-menu");+ const enter = (element: Element | null) => {+ if (!element) throw new Error("expected an element to point at");+ act(() => void element.dispatchEvent(new PointerEvent("pointerenter")));+ };+ const wait = (ms: number) => act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });++ // happy-dom runs no animation, so a submenu the pointer opened never leaves the+ // stylesheet's opening delay: unseen, it closes at once.+ enter(rowTitled("Advanced"));+ expect(layers(menu)).toEqual([ [ "Reload" ] ]);+ enter(rowTitled("Copy"));+ expect(layers(menu)).toEqual([]);++ // Opened by a press, it shows at once, and stays while the pointer crosses a row on its+ // way into the layer.+ act(() => press(rowTitled("Advanced")));+ enter(rowTitled("Copy"));+ await wait(749);+ expect(layers(menu)).toEqual([ [ "Reload" ] ]);+ expect(activeTitle(menu)).toBe("Copy");+ enter(layer());+ await wait(750);+ expect(layers(menu)).toEqual([ [ "Reload" ] ]);++ // The delay runs from the first row the pointer moves onto; the row it rests on then+ // opens its own submenu, at once, as it replaces one in view.+ enter(rowTitled("Copy"));+ await wait(400);+ enter(rowTitled("Export"));+ await wait(349);+ expect(layers(menu)).toEqual([ [ "Reload" ] ]);+ await wait(1);+ expect(layers(menu)).toEqual([ [ "As PDF" ] ]);+ expect(layer()?.classList).toContain("tn-menu-immediate");++ // Back on the submenu's row, off the menu, or with a key, the submenu stays.+ enter(rowTitled("Copy"));+ enter(rowTitled("Export"));+ await wait(750);+ expect(layers(menu)).toEqual([ [ "As PDF" ] ]);+ enter(rowTitled("Copy"));+ act(() => void menu.dispatchEvent(new PointerEvent("pointerleave")));+ await wait(750);+ expect(layers(menu)).toEqual([ [ "As PDF" ] ]);+ enter(rowTitled("Copy"));+ act(() => void key(menu, "ArrowDown"));+ await wait(750);+ expect(layers(menu)).toEqual([ [ "As PDF" ] ]);+ expect(activeTitle(menu)).toBe("Export");+ } finally {+ vi.useRealTimers();+ }+ });+it("starts at the last row when asked to, and takes no focus once it is no longer wanted", async () => {const { menu } = renderMenu({ startAt: "last" });await vi.waitFor(() => expect(activeTitle(menu)).toBe("Advanced"));diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex 7f371cd05e..a773f9a2ed 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -88,6 +88,17 @@ const ACTION_TOOLTIP = { placement: "top", animation: false } as const;/** How long typed letters keep adding to the text a row is looked up by. */const TYPEAHEAD_TIMEOUT = 500;+/** How long a submenu in view stays open once the pointer moves onto another row of its level. */+const SUBMENU_CLOSE_DELAY = 750;++/** A change to the submenus at `level` that the pointer asked for, held back by `SUBMENU_CLOSE_DELAY`. */+interface HeldChange {+ level: number;+ rowId?: string;+ anchor?: HTMLElement;+ timeout: number;+}+export default function Menu<T>({ id, className, anchor, placement, bottomSheet, inline, startAt, items, filterable, keepOrder, onSelect, children, onClose, onDismiss, isWanted, elementRef, ...popupProps }: MenuProps<T>) {const menuRef = useRef<HTMLDivElement | null>(null);// The submenus' layers render into the menu element, which rows reach through the context.@@ -102,16 +113,23 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,/** The submenus whose layer waited out the stylesheet's opening delay. */const shownSubmenus = useRef(new WeakSet<OpenSubmenu>()).current;+ const heldChange = useRef<HeldChange | undefined>(undefined);+ const dropHeldChange = useCallback(() => {+ window.clearTimeout(heldChange.current?.timeout);+ heldChange.current = undefined;+ }, []);+ useLayoutEffect(() => dropHeldChange, [ dropHeldChange ]);+const openSubmenu = useCallback((level: number, rowId?: string, anchor?: HTMLElement, chosen = false) => {+ dropHeldChange();setOpen((current) => {if (rowId ? current[level]?.id === rowId : current.length <= level) return current;const kept = current.slice(0, level);const replaced = current[level];- const immediate = chosen- || (!!replaced && (replaced.immediate || shownSubmenus.has(replaced)));+ const immediate = chosen || (!!replaced && isInView(replaced, shownSubmenus));return rowId && anchor ? [ ...kept, { id: rowId, anchor, immediate } ] : kept;});- }, [ shownSubmenus ]);+ }, [ shownSubmenus, dropHeldChange ]);const submenuShown = useCallback((submenu: OpenSubmenu) => {shownSubmenus.add(submenu);}, [ shownSubmenus ]);@@ -177,14 +195,46 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,activateFirstRowRef.current(row.level);});}, [ rows ]);+ /**+ * Closes the submenus open at `level` and deeper. If the active row is inside them, the row+ * that opened them becomes active, so the keys continue from there.+ */const closeSubmenu = (level: number) => {const opener = open[level];if (!opener) return;openSubmenu(level);if (active && active.level > level) setActive(level, opener.id);};+ const applyHover = (level: number, rowId?: string, anchor?: HTMLElement) => {+ if (rowId && anchor) openSubmenu(level, rowId, anchor);+ else closeSubmenu(level);+ };+ // The held change runs with the state of the render it runs after.+ const applyHoverRef = useRef(applyHover);+ applyHoverRef.current = applyHover;+ const hoverSubmenu = (level: number, rowId?: string, anchor?: HTMLElement) => {+ const standing = open[level];+ if (!standing || standing.id === rowId || !isInView(standing, shownSubmenus)) {+ dropHeldChange();+ applyHover(level, rowId, anchor);+ return;+ }+ // The delay runs from the first row the pointer moved onto; the last one decides.+ const held = heldChange.current;+ if (held?.level === level) {+ Object.assign(held, { rowId, anchor });+ return;+ }+ dropHeldChange();+ const change: HeldChange = { level, rowId, anchor, timeout: 0 };+ change.timeout = window.setTimeout(() => {+ heldChange.current = undefined;+ applyHoverRef.current(change.level, change.rowId, change.anchor);+ }, SUBMENU_CLOSE_DELAY);+ heldChange.current = change;+ };const context: MenuContextValue = {- open, openSubmenu, closeSubmenu, submenuShown, active, setActive, rows, registerRow,+ open, openSubmenu, hoverSubmenu, submenuShown, active, setActive, rows, registerRow,keyboardDriven, isReversed, dropStart, setDropStart, close, filter, setFilter, layerHost};@@ -284,6 +334,8 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,}, []);function onKeyDown(e: KeyboardEvent) {+ // The keys take over from the pointer, whose held change would undo where they go.+ dropHeldChange();// From a filter input, the keys act on the rows of the submenu it filters.const filterInput = e.target instanceof HTMLInputElement && e.target.matches(FILTER_INPUT) ? e.target : undefined;// On a phone, the deepest open submenu is the page on show, even before a row in it is active.@@ -464,9 +516,10 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,if (pointerMoved(e)) setKeyboardDriven(false);}}// Fires only when the pointer is off every level, as the submenu layers are children- // of this element. Unless the keys drive the menu, only the deepest open submenu's- // row stays active.+ // of this element. The open submenus stay, and unless the keys drive the menu, only+ // the deepest one's row stays active.onPointerLeave={() => {+ dropHeldChange();if (keyboardDriven) return;const deepest = open.at(-1);setActiveRow(deepest && { level: open.length - 1, id: deepest.id });@@ -682,7 +735,7 @@ export function MenuTile({ icon, iconSvg, iconBadge, title, tooltip, keyboardSho// goes on from the action it last pointed at.onPointerMove={(e) => {if (!menu || !pointerMoved(e)) return;- menu.closeSubmenu(level);+ menu.hoverSubmenu(level);if (!disabled && menu.active?.id !== id) menu.setActive(level, id);}}// A press keeps focus where it was, as on a row.@@ -799,6 +852,14 @@ function hasRowBefore(row: Element | undefined) {return false;}+/**+ * Whether the layer of `submenu` is in view: shown at once, past the stylesheet's opening delay as+ * `shown` records, or with motion off, which runs no delay.+ */+function isInView(submenu: OpenSubmenu, shown: WeakSet<OpenSubmenu>) {+ return submenu.immediate || shown.has(submenu) || document.body.classList.contains("motion-disabled");+}+/** The filter input of the submenu open in `menu`, if one is. */function filterInputIn(menu: HTMLElement | null) {return menu?.querySelector<HTMLInputElement>(FILTER_INPUT) ?? null;diff --git a/apps/client/src/widgets/react/menu_context.ts b/apps/client/src/widgets/react/menu_context.tsindex d7c7282939..20154ae06b 100644--- a/apps/client/src/widgets/react/menu_context.ts+++ b/apps/client/src/widgets/react/menu_context.ts@@ -64,10 +64,12 @@ export interface MenuContextValue {*/openSubmenu(level: number, id?: string, anchor?: HTMLElement, chosen?: boolean): void;/**- * Closes the submenus open at `level` and deeper. If the active row is inside them, the row- * that opened them becomes active, so the keys continue from there.+ * As {@link openSubmenu}, for the pointer moving onto a row at `level`, except that without a+ * row it also moves the active row out of the submenus it closes. A submenu in view at `level`+ * stays open until 750ms after the pointer moved onto the first other row, so the pointer can+ * cross rows on its way into it; the pointer back on its row or over its layer keeps it.*/- closeSubmenu(level: number): void;+ hoverSubmenu(level: number, id?: string, anchor?: HTMLElement): void;/** Records that the layer of `submenu` is past the stylesheet's opening delay, and in view. */submenuShown(submenu: OpenSubmenu): void;active?: ActiveRow;