Skip to content

Build your personal knowledge base with Trilium Notes

feat(menu): open the context menu's submenus as layers that scroll

Elian Dorane2e85bf3735a
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index 802ce0627d..5511cbbb51 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -6,6 +6,11 @@ vi.mock("../services/keyboard_actions", () => ({
effectiveShortcuts: name === "copyNotesToClipboard" ? [ "Ctrl+C", "Ctrl+Insert" ] : []
})
}));
+const layout = vi.hoisted(() => ({ onMobile: false }));
+vi.mock("../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../services/utils")>()),
+ isMobile: () => layout.onMobile
+}));
// Key names are translated; the formatting has specs of its own.
vi.mock("../services/keyboard_shortcut_display", () => ({
formatShortcut: (shortcut: string) => shortcut.split("+"),
@@ -307,6 +312,165 @@ describe("contextMenu", () => {
});
});
+ describe("submenus", () => {
+ const noteTypes = [ { title: "Text" }, { title: "Code" } ];
+ const templates = [ { title: "Meeting", items: [ { title: "Weekly" } ] } ];
+ const submenuItems = [
+ { title: "Copy" },
+ { title: "Insert child note", command: "insertChildNote", items: noteTypes },
+ { title: "Templates", items: templates }
+ ];
+
+ async function openMenu(onSelect: (title: string) => void = () => {}) {
+ buildPage();
+ const contextMenu = await buildContextMenu();
+ await contextMenu.show({
+ x: 10, y: 10, items: submenuItems,
+ selectMenuItemHandler: (item) => onSelect(String(item.title))
+ });
+ return contextMenu;
+ }
+
+ /** The row titled `title`, read off its own line: a row's text also holds its submenu's. */
+ function row(title: string) {
+ const found = [ ...document.querySelectorAll<HTMLElement>("li.dropdown-item") ]
+ .find((item) => item.querySelector(":scope > span")?.textContent === title);
+ if (!found) throw new Error(`expected a row titled ${title}`);
+ return found;
+ }
+
+ /** The submenu layers standing open, each as the titles of its rows. */
+ function layers() {
+ return [ ...menuElement()?.querySelectorAll(":scope > div.dropdown-submenu > ul.dropdown-menu") ?? [] ]
+ .map((layer) => [ ...layer.querySelectorAll(":scope > li") ].map((item) => item.textContent));
+ }
+
+ const hover = (element: HTMLElement) => element.dispatchEvent(new PointerEvent("pointerenter"));
+ const press = (element: HTMLElement) =>
+ element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
+
+ afterEach(() => {
+ layout.onMobile = false;
+ vi.restoreAllMocks();
+ });
+
+ it("opens a layer of its own for each level, beside the row it opens from", async () => {
+ await openMenu();
+ const parent = row("Templates");
+ // The arrow the theme draws, and the markup its submenu rules expect.
+ expect(parent.classList.contains("dropdown-submenu")).toBe(true);
+ expect(parent.querySelector(":scope > span")?.classList.contains("dropdown-toggle")).toBe(true);
+ expect(layers()).toEqual([]);
+
+ hover(parent);
+ await vi.waitFor(() => expect(layers()).toEqual([ [ "Meeting" ] ]));
+ expect(parent.classList.contains("submenu-open")).toBe(true);
+
+ hover(row("Meeting"));
+ // Each level stands beside the others, none nested in another's scrolling box.
+ await vi.waitFor(() => expect(layers()).toEqual([ [ "Meeting" ], [ "Weekly" ] ]));
+
+ // Pointing at another row of the root closes both.
+ hover(row("Copy"));
+ await vi.waitFor(() => expect(layers()).toEqual([]));
+ expect(parent.classList.contains("submenu-open")).toBe(false);
+ });
+
+ it("places a layer beside its row, flipped where it does not fit, and hides it while its row is scrolled away", async () => {
+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);
+ vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);
+ // Only the layer: a size unlike its rect would read to Floating UI as a CSS scale.
+ vi.spyOn(HTMLUListElement.prototype, "offsetWidth", "get").mockReturnValue(150);
+ vi.spyOn(HTMLUListElement.prototype, "offsetHeight", "get").mockReturnValue(100);
+ await openMenu();
+ const root = menuElement();
+ if (!root) throw new Error("expected the menu to render");
+ // happy-dom loads no stylesheet, so the menu is made to scroll as `Menu.css` makes it.
+ root.style.overflowY = "auto";
+ vi.spyOn(root, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: 0, y: 0, width: 1000, height: 300 }));
+ // Floating UI clips to a scrolling ancestor's client box, which happy-dom leaves at 0.
+ vi.spyOn(root, "clientWidth", "get").mockReturnValue(1000);
+ vi.spyOn(root, "clientHeight", "get").mockReturnValue(300);
+ const parent = row("Templates");
+ let rowRect = DOMRect.fromRect({ x: 10, y: 100, width: 200, height: 24 });
+ vi.spyOn(parent, "getBoundingClientRect").mockImplementation(() => rowRect);
+
+ hover(parent);
+ const layer = () => menuElement()?.querySelector<HTMLElement>("div.dropdown-submenu > ul");
+ // Overlapping the row by 2px, its top at the row's.
+ await vi.waitFor(() => expect([ layer()?.style.left, layer()?.style.top ]).toEqual([ "208px", "100px" ]));
+ expect(layer()?.style.visibility).toBe("visible");
+
+ // Scrolled out of the menu's view, the row takes its submenu out of sight with it.
+ rowRect = DOMRect.fromRect({ x: 10, y: 400, width: 200, height: 24 });
+ root.dispatchEvent(new Event("scroll"));
+ await vi.waitFor(() => expect(layer()?.style.visibility).toBe("hidden"));
+
+ // Near the right edge, it opens to the row's left.
+ rowRect = DOMRect.fromRect({ x: 850, y: 100, width: 100, height: 24 });
+ root.dispatchEvent(new Event("scroll"));
+ await vi.waitFor(() => expect([ layer()?.style.left, layer()?.style.visibility ]).toEqual([ "702px", "visible" ]));
+ });
+
+ it("runs a submenu's row and closes everything, and keeps a submenu's row that only opens it", async () => {
+ const picked: string[] = [];
+ const contextMenu = await openMenu((title) => picked.push(title));
+
+ // Nothing to run, so the menu stays up with its submenu open.
+ press(row("Templates"));
+ await vi.waitFor(() => expect(layers()).toEqual([ [ "Meeting" ] ]));
+ expect(contextMenu.isShown()).toBe(true);
+
+ press(row("Meeting"));
+ await vi.waitFor(() => expect(layers()).toEqual([ [ "Meeting" ], [ "Weekly" ] ]));
+ press(row("Weekly"));
+ expect(picked).toEqual([ "Templates", "Meeting", "Weekly" ]);
+ expect(contextMenu.isShown()).toBe(false);
+
+ // A row with a command of its own runs it, like any other.
+ await openMenu((title) => picked.push(title));
+ press(row("Insert child note"));
+ expect(picked.at(-1)).toBe("Insert child note");
+ });
+
+ it("lays a submenu with columns out on an element of its own, so a capped layer scrolls them", async () => {
+ buildPage();
+ const contextMenu = await buildContextMenu();
+ await contextMenu.show({
+ x: 10, y: 10, selectMenuItemHandler: () => {},
+ items: [ { title: "Insert child note", items: noteTypes, columns: 2 } ]
+ });
+
+ hover(row("Insert child note"));
+ await vi.waitFor(() => expect(menuElement()?.querySelector("div.dropdown-submenu > ul > .tn-menu-columns")).not.toBeNull());
+ const columns = menuElement()?.querySelector<HTMLElement>(".tn-menu-columns");
+ expect(columns?.style.columnCount).toBe("2");
+ expect(columns?.textContent).toBe("TextCode");
+ });
+
+ it("unfolds a submenu under its row on a phone", async () => {
+ layout.onMobile = true;
+ const picked: string[] = [];
+ await openMenu((title) => picked.push(title));
+ const parent = row("Templates");
+
+ hover(parent);
+ expect(layers()).toEqual([]);
+
+ press(parent);
+ await vi.waitFor(() => expect(parent.classList.contains("submenu-open")).toBe(true));
+ const nested = parent.querySelector(":scope > ul.dropdown-menu");
+ expect(nested?.classList.contains("show")).toBe(true);
+ expect(nested?.textContent).toBe("Meeting");
+ // Unfolding runs nothing.
+ expect(picked).toEqual([]);
+ expect(layers()).toEqual([]);
+
+ press(parent);
+ await vi.waitFor(() => expect(parent.classList.contains("submenu-open")).toBe(false));
+ });
+ });
+
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" }) {
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 2b2c993c91..ef07c273d5 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -120,7 +120,8 @@ class ContextMenu {
orientation: options.orientation,
items: options.items,
onSelect: (item, e) => {
- void this.hide();
+ // A submenu's row stays up to be opened, unless it runs something of its own.
+ if (!item.items || item.handler || item.command) void this.hide();
item.handler?.(item, e);
options.selectMenuItemHandler(item, e);
},
diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.ts
index 34f662fa97..c94c3034bb 100644
--- a/apps/client/src/menus/context_menu_legacy.ts
+++ b/apps/client/src/menus/context_menu_legacy.ts
@@ -85,12 +85,9 @@ 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.home = this.$widget[0]?.parentElement ?? null;
this.isMobile = utils.isMobile();
if (this.isMobile) {
@@ -113,8 +110,6 @@ 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");
@@ -124,55 +119,6 @@ class ContextMenu {
this.addItems(this.$widget, options.items);
}
- /**
- * 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);
- }
- }
-
- private repositionSubmenu(submenuEl: HTMLElement) {
- const CONTEXT_MENU_PADDING = 5;
-
- // Reset so the natural (downward, trailing) placement is measured on every hover.
- submenuEl.classList.remove("submenu-flip-up");
- submenuEl.classList.remove("submenu-flip-start");
-
- const rect = submenuEl.getBoundingClientRect();
- const clientHeight = document.documentElement.clientHeight;
- const clientWidth = document.documentElement.clientWidth;
- const overflowsBottom = rect.bottom > clientHeight - CONTEXT_MENU_PADDING;
- // Only flip up if there is actually more room above the parent than below, otherwise flipping
- // would just clip the other end.
- const fitsWhenFlippedUp = rect.top - rect.height >= CONTEXT_MENU_PADDING;
-
- if (overflowsBottom && fitsWhenFlippedUp) {
- submenuEl.classList.add("submenu-flip-up");
- }
-
- // The same for the side it opens on, which is the trailing one by default and the leading
- // one in a right-to-left page. Whichever edge it runs past, the flip puts it on the other
- // side of its parent, and only where the whole submenu fits there.
- const fitsWhenFlippedToStart = rect.left - rect.width >= CONTEXT_MENU_PADDING;
- const fitsWhenFlippedToEnd = rect.right + rect.width <= clientWidth - CONTEXT_MENU_PADDING;
-
- if ((rect.right > clientWidth - CONTEXT_MENU_PADDING && fitsWhenFlippedToStart)
- || (rect.left < CONTEXT_MENU_PADDING && fitsWhenFlippedToEnd)) {
- submenuEl.classList.add("submenu-flip-start");
- }
- }
-
addItems($parent: JQuery<HTMLElement>, items: MenuItem<any>[], multicolumn = false) {
let $group = $parent; // The current group or parent element to which items are being appended
let shouldStartNewGroup = false; // If true, the next item will start a new group
@@ -242,50 +188,8 @@ class ContextMenu {
const $item = $("<li>")
.addClass("dropdown-item")
.append($link)
- .on("contextmenu", (e) => false)
- .on("mousedown", (e) => {
- if (this.isMobile && "items" in item && item.items) {
- const $item = $(e.target).closest(".dropdown-item");
-
- $item.toggleClass("submenu-open");
- $item.find("ul.dropdown-menu").toggleClass("show");
- return false;
- }
-
- // A submenu's parent stays open so that it can still be expanded. One carrying a
- // command or handler of its own is dismissed like any other item once it has run.
- const opensSubmenu = "items" in item && !!item.items;
- const acts = ("handler" in item && !!item.handler)
- || ("command" in item && !!item.command);
- if (!opensSubmenu || acts) {
- this.hide();
- }
-
- // it's important to stop the propagation especially for sub-menus, otherwise the event
- // might be handled again by top-level menu
- return false;
- });
-
- if ("items" in item && item.items) {
- $item.addClass("dropdown-submenu");
- $link.addClass("dropdown-toggle");
+ .on("contextmenu", (e) => false);
- const $subMenu = $("<ul>").addClass("dropdown-menu");
- const hasColumns = !!item.columns && item.columns > 1;
- if (!this.isMobile && hasColumns) {
- $subMenu.css("column-count", item.columns!);
- }
-
- this.addItems($subMenu, item.items, hasColumns);
-
- $item.append($subMenu);
-
- // Submenus open downward by default (CSS `:hover`); flip them up when the parent item sits
- // near the bottom of the viewport, otherwise the submenu would be clipped off-screen.
- if (!this.isMobile) {
- $item.on("mouseenter", () => this.repositionSubmenu($subMenu[0]));
- }
- }
return $item;
}
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index 3048258e22..cea2493b25 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -7,3 +7,19 @@
visibility: hidden;
overflow-y: auto;
}
+
+/* A submenu is placed by `placeMenu()`, not beside a parent it is nested in. */
+.dropdown-submenu > .dropdown-menu.tn-menu {
+ inset: 0 auto auto 0;
+ margin: 0;
+}
+
+/* The pointer leaves the row for its submenu, so the row stays marked while the submenu is open. */
+body.desktop .dropdown-item.dropdown-submenu.submenu-open {
+ color: var(--hover-item-text-color);
+ background-color: var(--hover-item-background-color);
+}
+
+.tn-menu-columns {
+ column-rule: inherit;
+}
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 5d982e779b..fefbbe3411 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -1,11 +1,12 @@
import "./Menu.css";
-import { autoUpdate, computePosition, flip, type Placement, shift, size, type VirtualElement } from "@floating-ui/dom";
+import { autoUpdate, computePosition, flip, hide, offset, type Placement, type ReferenceElement, shift, size, type VirtualElement } from "@floating-ui/dom";
import clsx from "clsx";
-import { useLayoutEffect, useRef } from "preact/hooks";
+import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";
import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
import { getActionSync } from "../../services/keyboard_actions";
+import { handleRightToLeftPlacement, isMobile } from "../../services/utils";
import { joinElements } from "./react_utils";
import { renderShortcutKbds } from "./shortcut_kbd";
@@ -32,8 +33,40 @@ export interface MenuProps<T> {
/** How many pixels the menu keeps from the edges of the viewport. */
const VIEWPORT_PADDING = 5;
+/** A submenu standing open, and the row it opened from. */
+interface OpenSubmenu<T> {
+ item: MenuCommandItem<T>;
+ anchor: HTMLElement;
+ /** Remounts the layer when another submenu replaces it at the same level. */
+ key: number;
+}
+
+/** What every level of the menu shares. */
+interface MenuState<T> {
+ onSelect: MenuProps<T>["onSelect"];
+ onClose: MenuProps<T>["onClose"];
+ /**
+ * Opens `item`'s submenu at `level`, closing whatever stood open at that level and deeper, or
+ * without an item only closes them.
+ */
+ openSubmenu(level: number, item?: MenuCommandItem<T>, anchor?: HTMLElement): void;
+ /** The item whose submenu stands open at each level. */
+ openItems: MenuCommandItem<T>[];
+}
+
export default function Menu<T>({ id, className, x, y, orientation, items, onSelect, onClose }: MenuProps<T>) {
const menuRef = useRef<HTMLDivElement>(null);
+ const [ submenus, setSubmenus ] = useState<OpenSubmenu<T>[]>([]);
+ const nextKey = useRef(0);
+
+ const openSubmenu = useCallback((level: number, item?: MenuCommandItem<T>, anchor?: HTMLElement) => {
+ setSubmenus((open) => {
+ if (item ? open[level]?.item === item : open.length <= level) return open;
+ const kept = open.slice(0, level);
+ return item && anchor ? [ ...kept, { item, anchor, key: nextKey.current++ } ] : kept;
+ });
+ }, []);
+ const state: MenuState<T> = { onSelect, onClose, openSubmenu, openItems: submenus.map((submenu) => submenu.item) };
useLayoutEffect(() => {
const menu = menuRef.current;
@@ -47,37 +80,103 @@ export default function Menu<T>({ id, className, x, y, orientation, items, onSel
return (
<div ref={menuRef} id={id} className={clsx("dropdown-menu show tn-menu", className)} role="menu">
- {menuRows(items).map((row, index) => {
- if (!("kind" in row)) return <MenuRow key={index} item={row} onSelect={onSelect} />;
- if (row.kind === "separator") return <div key={index} className="dropdown-divider" role="separator" />;
- if (row.kind === "header") return <h6 key={index} className="dropdown-header">{row.title}</h6>;
- return (
- <li key={index} className="dropdown-custom-item" onClick={onClose}>
- <row.componentFn />
- </li>
- );
- })}
+ <MenuList level={0} items={items} state={state} />
+ {/* Inside the menu, so the rules scoped to it apply, but none inside another: a fixed
+ layer escapes a scrolling menu only while no ancestor carries a filter. */}
+ {submenus.map((submenu, index) => (
+ <SubmenuLayer key={submenu.key} level={index + 1} submenu={submenu} state={state} />
+ ))}
</div>
);
}
-function MenuRow<T>({ item, onSelect }: { item: MenuCommandItem<T>, onSelect: MenuProps<T>["onSelect"] }) {
+/**
+ * A submenu opened on the desktop, placed beside the row it opened from rather than nested in it,
+ * so a scrolling menu neither clips it nor scrolls it away.
+ */
+function SubmenuLayer<T>({ level, submenu, state }: { level: number, submenu: OpenSubmenu<T>, state: MenuState<T> }) {
+ const layerRef = useRef<HTMLUListElement>(null);
+ const columns = (submenu.item.columns ?? 1) > 1 ? submenu.item.columns : undefined;
+ const items = submenu.item.items ?? [];
+
+ useLayoutEffect(() => {
+ const layer = layerRef.current;
+ if (!layer) return;
+
+ const placement = handleRightToLeftPlacement("right") === "right" ? "right-start" : "left-start";
+ return autoUpdate(submenu.anchor, layer, () => void placeMenu(layer, submenu.anchor, placement, true));
+ }, [ submenu.anchor ]);
+
+ // In a `.dropdown-submenu`, so the theme's submenu rules apply.
+ return (
+ <div className="dropdown-submenu">
+ <ul ref={layerRef} className="dropdown-menu show tn-menu" role="menu">
+ {columns
+ // The columns go on an inner element of their full height, so a capped menu
+ // scrolls them rather than growing more columns to the side.
+ ? (
+ <div className="tn-menu-columns" style={{ columnCount: columns }}>
+ <MenuList level={level} items={items} state={state} />
+ </div>
+ )
+ : <MenuList level={level} items={items} state={state} />}
+ </ul>
+ </div>
+ );
+}
+
+function MenuList<T>({ level, items, state }: { level: number, items: MenuItem<T>[], state: MenuState<T> }) {
+ return <>
+ {menuRows(items).map((row, index) => {
+ if (!("kind" in row)) return <MenuRow key={index} level={level} item={row} state={state} />;
+ if (row.kind === "separator") return <div key={index} className="dropdown-divider" role="separator" />;
+ if (row.kind === "header") return <h6 key={index} className="dropdown-header">{row.title}</h6>;
+ return (
+ <li key={index} className="dropdown-custom-item" onClick={state.onClose}>
+ <row.componentFn />
+ </li>
+ );
+ })}
+ </>;
+}
+
+function MenuRow<T>({ level, item, state }: { level: number, item: MenuCommandItem<T>, state: MenuState<T> }) {
const disabled = item.enabled === false;
+ const hasSubmenu = !!item.items;
+ // A phone has no room beside the menu, so a submenu unfolds under its row instead.
+ const [ unfolded, setUnfolded ] = useState(false);
+ const open = isMobile() ? unfolded : state.openItems[level] === item;
return (
<li
- className={clsx("dropdown-item", disabled && "disabled", item.className)}
+ className={clsx("dropdown-item", hasSubmenu && "dropdown-submenu", open && "submenu-open",
+ disabled && "disabled", item.className)}
role="menuitem"
aria-disabled={disabled || undefined}
+ aria-haspopup={hasSubmenu ? "menu" : undefined}
+ aria-expanded={hasSubmenu ? open : undefined}
+ onPointerEnter={(e) => {
+ if (isMobile()) return;
+ state.openSubmenu(level, hasSubmenu && !disabled ? item : undefined, e.currentTarget);
+ }}
// `mousedown` rather than `click`, and its default prevented, so the press does not move
// focus: a text editor keeps the selection that commands such as a spelling fix act on.
onMouseDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
- if (!disabled) onSelect(item, e);
+ // An unfolded row holds its submenu's rows, whose presses would reach it too.
+ e.stopPropagation();
+ if (disabled) return;
+
+ if (hasSubmenu && isMobile()) {
+ setUnfolded(!unfolded);
+ return;
+ }
+ if (hasSubmenu) state.openSubmenu(level, item, e.currentTarget);
+ state.onSelect(item, e);
}}
>
- <span>
+ <span className={hasSubmenu ? "dropdown-toggle" : undefined}>
<MenuIconSlot item={item} />
<span className="tn-menu-gap" />
{/* Callers pass HTML: titles escaped with `escapeHtml()` or boxed by `menuName()`. */}
@@ -88,6 +187,11 @@ function MenuRow<T>({ item, onSelect }: { item: MenuCommandItem<T>, onSelect: Me
<MenuShortcut item={item} />
{item.trailingIcon && <span className={clsx(item.trailingIcon, "tn-icon", "menu-trailing-icon")} />}
</span>
+ {hasSubmenu && isMobile() && (
+ <ul className={clsx("dropdown-menu", unfolded && "show")} role="menu">
+ {unfolded && <MenuList level={level + 1} items={item.items ?? []} state={state} />}
+ </ul>
+ )}
</li>
);
}
@@ -142,14 +246,22 @@ function isSeparator<T>(item: MenuItem<T>) {
* 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.
+ *
+ * A submenu overlaps its row by 2px, so the pointer crosses no gap on its way over, and lines its
+ * first row up with that row. It is hidden while its row is scrolled out of its menu's view.
*/
-async function placeMenu(menu: HTMLElement, anchor: VirtualElement, placement: Placement) {
+async function placeMenu(menu: HTMLElement, anchor: ReferenceElement, placement: Placement, isSubmenu = false) {
const [ side ] = placement.split("-");
const otherSide = side === "left" ? "right" : "left";
- const { x, y } = await computePosition(anchor, menu, {
+ const { x, y, middlewareData } = await computePosition(anchor, menu, {
strategy: "fixed",
placement,
middleware: [
+ isSubmenu && offset(({ elements }) => {
+ const style = getComputedStyle(elements.floating);
+ const inset = (parseFloat(style.paddingTop) || 0) + (parseFloat(style.borderTopWidth) || 0);
+ return { mainAxis: -2, crossAxis: -inset };
+ }),
flip({
fallbackPlacements: [ `${otherSide}-start`, `${side}-end`, `${otherSide}-end` ] as Placement[],
padding: VIEWPORT_PADDING
@@ -161,13 +273,14 @@ async function placeMenu(menu: HTMLElement, anchor: VirtualElement, placement: P
apply({ availableHeight }) {
menu.style.maxHeight = `${availableHeight}px`;
}
- })
+ }),
+ isSubmenu && hide({ strategy: "referenceHidden" })
]
});
menu.style.left = `${x}px`;
menu.style.top = `${y}px`;
- menu.style.visibility = "visible";
+ menu.style.visibility = middlewareData.hide?.referenceHidden ? "hidden" : "visible";
}
/** A zero-size anchor at a point in the viewport, such as where a right-click landed. */