Skip to content

Build your personal knowledge base with Trilium Notes

feat(menu): open FormDropdownSubmenu as a layer of the menu it stands in

Elian Doran4ed9093a2a71
diff --git a/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsx b/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsx
index 4e2b4f3403..de10fcf977 100644
--- a/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsx
+++ b/apps/client/src/widgets/react/Dropdown.tooltip.spec.tsx
@@ -90,12 +90,13 @@ describe("Dropdown with a disabled toggle", () => {
it("closes an open menu when the toggle becomes disabled", () => {
act(() => render(<Dropdown>item</Dropdown>, container));
const toggle = container.querySelector("button");
- const menu = container.querySelector(".dropdown-menu");
+ // The menu stands in the page's body, and only while it is open.
+ const menu = () => document.querySelector(".tn-popup.dropdown-menu");
act(() => toggle?.click());
- expect(menu?.classList.contains("show"), "opened by the click").toBe(true);
+ expect(menu(), "opened by the click").not.toBeNull();
act(() => render(<Dropdown disabled>item</Dropdown>, container));
- expect(menu?.classList.contains("show"), "closed by the disable").toBe(false);
+ expect(menu(), "closed by the disable").toBeNull();
expect(toggle?.disabled).toBe(true);
expect(toggle?.getAttribute("aria-expanded")).toBe("false");
});
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 4f1c2e5d9c..8c8a36220f 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -1,10 +1,11 @@
import "./FormList.css";
+import { autoUpdate } from "@floating-ui/dom";
import type { KeyboardActionNames } from "@triliumnext/commons";
import { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";
import clsx from "clsx";
import { ComponentChildren, RefObject } from "preact";
-import { type CSSProperties, useContext, useEffect, useId, useMemo, useRef, useState } from "preact/compat";
+import { createPortal, type CSSProperties, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "preact/compat";
import { CommandNames } from "../../components/app_context";
import { getActionSync } from "../../services/keyboard_actions";
@@ -13,7 +14,7 @@ import FormToggle from "./FormToggle";
import HelpTooltipButton from "./HelpTooltipButton";
import { useStaticTooltip, useSyncedRef } from "./hooks";
import Icon from "./Icon";
-import { MenuContext, MenuLevelContext, pointerMoved } from "./menu_context";
+import { MenuContext, type MenuContextValue, MenuLevelContext, type OpenSubmenu, placeMenu, pointerMoved } from "./menu_context";
import { joinElements } from "./react_utils";
import { renderShortcutKbds } from "./shortcut_kbd";
@@ -343,17 +344,112 @@ export function FormDropdownDivider() {
return <li className="dropdown-divider" role="separator" onClick={(e) => e.stopPropagation()} />;
}
-export function FormDropdownSubmenu({ icon, title, children, dropStart, onDropdownToggleClicked }: {
- icon: string,
- title: ComponentChildren,
- children: ComponentChildren,
- onDropdownToggleClicked?: (e: MouseEvent) => void,
- dropStart?: boolean
-}) {
+export interface FormDropdownSubmenuProps {
+ icon: string;
+ title: ComponentChildren;
+ children: ComponentChildren;
+ /** Called when the row is clicked, or run from the keyboard, on the desktop. */
+ onDropdownToggleClicked?: (e: MouseEvent) => void;
+ /** Opens the nested list towards the start. Inside a menu, its layer flips on its own. */
+ dropStart?: boolean;
+ /** Inside a menu, lays the submenu's rows out in this many columns. */
+ columns?: number;
+ disabled?: boolean;
+ className?: string;
+}
+
+/**
+ * A row that opens its children as a submenu. Inside a `Menu` the submenu is a layer of its own
+ * beside the row, which a scrolling menu neither clips nor scrolls away; elsewhere, as in a
+ * dropdown, it is a list nested in the row, shown on hover.
+ */
+export function FormDropdownSubmenu(props: FormDropdownSubmenuProps) {
+ const menu = useContext(MenuContext);
+ return menu ? <MenuSubmenu {...props} menu={menu} /> : <NestedSubmenu {...props} />;
+}
+
+function MenuSubmenu({ menu, icon, title, children, onDropdownToggleClicked, columns, disabled, className }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {
+ const level = useContext(MenuLevelContext);
+ const id = useId();
+ const openSubmenu = menu.open[level];
+ const open = openSubmenu?.id === id;
+ const isActive = menu.active?.id === id;
+
+ /** Runs the row's own action for the keys, with the modifiers of the key that ran it. */
+ function select(e: MouseEvent | KeyboardEvent) {
+ onDropdownToggleClicked?.(new MouseEvent("click", { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey, altKey: e.altKey, metaKey: e.metaKey }));
+ }
+
+ function onPointed(e: { currentTarget: HTMLLIElement }) {
+ 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);
+ }
+
+ return (
+ <li
+ id={id}
+ ref={(element) => {
+ 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)}
+ role="menuitem"
+ aria-disabled={disabled || undefined}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ // 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={(e) => {
+ if (!menu.keyboardDriven) onPointed(e);
+ }}
+ // 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={(e) => {
+ if (!isActive && pointerMoved(e)) onPointed(e);
+ }}
+ // As any row: the press keeps focus where it was, and the release acts. An unfolded
+ // row holds its submenu's rows, whose presses and clicks reach it too; those are theirs.
+ onMouseDown={(e) => {
+ if (e.button === 0 && !inUnfoldedRows(e)) e.preventDefault();
+ }}
+ onClick={(e) => {
+ if (disabled || inUnfoldedRows(e)) return;
+ // Clicked again, an unfolded row folds its submenu back.
+ if (isMobile()) {
+ menu.openSubmenu(level, open ? undefined : id, e.currentTarget, true);
+ return;
+ }
+ menu.openSubmenu(level, id, e.currentTarget, true);
+ onDropdownToggleClicked?.(e);
+ }}
+ >
+ <span className="dropdown-toggle">
+ <Icon icon={icon} />
+ <span className="tn-menu-gap" />
+ <span id={titleId(id)}>{title}</span>
+ </span>
+ {isMobile()
+ // A phone has no room beside the menu, so an open submenu unfolds under its row.
+ ? (
+ <ul className={clsx("dropdown-menu", open && "show")} role="menu" aria-labelledby={titleId(id)}>
+ <MenuLevelContext.Provider value={level + 1}>{open && children}</MenuLevelContext.Provider>
+ </ul>
+ )
+ : open && openSubmenu && menu.layerHost && createPortal((
+ <SubmenuLayer level={level + 1} submenu={openSubmenu} columns={columns}>{children}</SubmenuLayer>
+ ), menu.layerHost)}
+ </li>
+ );
+}
+
+function NestedSubmenu({ icon, title, children, dropStart, onDropdownToggleClicked, disabled, className }: FormDropdownSubmenuProps) {
const [ openOnMobile, setOpenOnMobile ] = useState(false);
return (
- <li className={clsx("dropdown-item dropdown-submenu", { "submenu-open": openOnMobile, "dropstart": dropStart })}>
+ <li className={clsx("dropdown-item dropdown-submenu", { "submenu-open": openOnMobile, "dropstart": dropStart },
+ disabled && "disabled", className)}>
<span
className="dropdown-toggle"
onClick={(e) => {
@@ -367,7 +463,7 @@ export function FormDropdownSubmenu({ icon, title, children, dropStart, onDropdo
}}
>
<Icon icon={icon} />
- &nbsp;
+ <span className="tn-menu-gap" />
{title}
</span>
@@ -378,6 +474,63 @@ export function FormDropdownSubmenu({ icon, title, children, dropStart, onDropdo
);
}
+/**
+ * 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({ level, submenu, columns, children }: {
+ level: number,
+ submenu: OpenSubmenu,
+ columns?: number,
+ children: ComponentChildren
+}) {
+ const layerRef = useRef<HTMLDivElement>(null);
+ const columnCount = (columns ?? 1) > 1 ? columns : undefined;
+
+ 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 (
+ <MenuLevelContext.Provider value={level}>
+ <div className="dropdown-submenu">
+ <div
+ ref={layerRef} role="menu" aria-labelledby={titleId(submenu.anchor.id)}
+ className={clsx("dropdown-menu show tn-menu", submenu.immediate && "tn-menu-immediate")}
+ >
+ {/* Like the top level, so the blur on the layer's `::before` stays behind its rows. */}
+ {columnCount
+ // The columns go on an inner list of their full height, so a capped menu
+ // scrolls them rather than growing more columns to the side.
+ ? (
+ <div className="tn-menu-scroll">
+ <menu className="tn-menu-columns" role="none" style={{ columnCount }}>
+ {children}
+ </menu>
+ </div>
+ )
+ : <menu className="tn-menu-scroll" role="none">{children}</menu>}
+ </div>
+ </div>
+ </MenuLevelContext.Provider>
+ );
+}
+
+/** Whether an event on a submenu's row came from the rows its submenu unfolds inside it, on a phone. */
+function inUnfoldedRows(e: Event & { currentTarget: HTMLElement }) {
+ return e.target instanceof Element && e.target.closest(".dropdown-menu") !== e.currentTarget.closest(".dropdown-menu");
+}
+
+/** The id of a row's title, which names the submenu it opens. */
+function titleId(rowId: string) {
+ return `${rowId}-title`;
+}
+
/**
* A row holding a control of its own, such as the color picker. The keys stand on it when its
* content marks a way in with `tabindex="0"`, and a click on something in it that acts closes the
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 2ac8871840..2d77c69bd2 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -1,6 +1,6 @@
import "./Menu.css";
-import { autoUpdate, computePosition, flip, hide, offset, type Placement, type ReferenceElement, shift, size, type VirtualElement } from "@floating-ui/dom";
+import { autoUpdate, type VirtualElement } from "@floating-ui/dom";
import clsx from "clsx";
import type { ComponentChildren } from "preact";
import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";
@@ -8,7 +8,7 @@ import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";
import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
import { handleRightToLeftPlacement, 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, MenuContext, type MenuContextValue, type OpenSubmenu, placeMenu, pointerMoved, type RowEntry } from "./menu_context";
/**
* A menu of commands, drawn with the markup Bootstrap's dropdowns use (`.dropdown-menu`,
@@ -41,8 +41,6 @@ export interface MenuProps<T> {
onClose(): void;
}
-/** How many pixels the menu keeps from the edges of the viewport. */
-const VIEWPORT_PADDING = 5;
/** The keys the menu keeps while focus is inside a custom row: those that leave it. */
const KEYS_LEAVING_CUSTOM_ROW = new Set([ "ArrowUp", "ArrowDown", "Escape", "Tab" ]);
@@ -344,7 +342,10 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
if (items) {
return (
- <FormDropdownSubmenu icon={uiIcon ?? "bx bx-empty"} title={label} onDropdownToggleClicked={select}>
+ <FormDropdownSubmenu
+ icon={uiIcon ?? "bx bx-empty"} title={label} columns={row.columns} disabled={enabled === false}
+ className={className} onDropdownToggleClicked={select}
+ >
{/* A phone unfolds a submenu in a single column. */}
<MenuItems items={items} onSelect={onSelect} columns={(row.columns ?? 1) > 1 && !isMobile()} />
</FormDropdownSubmenu>
@@ -446,47 +447,6 @@ function isHeader<T>(item: MenuItem<T>) {
return "kind" in item && item.kind === "header";
}
-/**
- * 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.
- */
-export async function placeMenu(menu: HTMLElement, anchor: ReferenceElement, placement: Placement, isSubmenu = false) {
- const [ side ] = placement.split("-");
- const otherSide = side === "left" ? "right" : "left";
- 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
- }),
- // `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`;
- }
- }),
- isSubmenu && hide({ strategy: "referenceHidden" })
- ]
- });
-
- menu.style.left = `${x}px`;
- menu.style.top = `${y}px`;
- 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. */
function pointAt(x: number, y: number): VirtualElement {
return {
diff --git a/apps/client/src/widgets/react/Menu_legacy.tsx b/apps/client/src/widgets/react/Menu_legacy.tsx
deleted file mode 100644
index 51f3ada07e..0000000000
--- a/apps/client/src/widgets/react/Menu_legacy.tsx
+++ /dev/null
@@ -1,172 +0,0 @@
-// Reference copy of `MenuCommand`, the row `Menu` drew before its data adapter switched to
-// `FormListItem` and `FormDropdownSubmenu`. Nothing imports it. Delete a piece once those rows
-// cover it, and the file once they reach parity.
-
-import { autoUpdate } from "@floating-ui/dom";
-import clsx from "clsx";
-import type { ComponentChildren } from "preact";
-import { createPortal } from "preact/compat";
-import { useContext, useId, useLayoutEffect, useRef } from "preact/hooks";
-
-import type { MenuCommandItem } from "../../menus/context_menu";
-import { handleRightToLeftPlacement, isMobile } from "../../services/utils";
-import { placeMenu } from "./Menu";
-import { MenuLevelContext, type OpenSubmenu, useMenu } from "./menu_context";
-
-export interface MenuCommandProps extends Pick<MenuCommandItem<unknown>, "title" | "uiIcon" | "iconColorClass" | "checked"
- | "enabled" | "shortcut" | "keyboardShortcut" | "badges" | "trailingIcon" | "className" | "columns"> {
- /** Called when the row is pressed with the primary button, or run from the keyboard. */
- onSelect?(e: MouseEvent | KeyboardEvent): void;
- /** Whether running the row closes the menu. A row does, and one that opens a submenu does not. */
- closeOnSelect?: boolean;
- /** The rows of the submenu this row opens. */
- children?: ComponentChildren;
-}
-
-/**
- * A row that runs a command, or with children, opens them as its submenu. As with
- * {@link MenuCommandItem}, a row given `uiIcon` or `checked`, even as nothing, keeps a slot for
- * the icon, and one given `checked` can be checked.
- */
-export function MenuCommand(props: MenuCommandProps) {
- const { title, enabled, className, columns, onSelect, closeOnSelect, children } = props;
- const menu = useMenu();
- const level = useContext(MenuLevelContext);
- const id = useId();
- const disabled = enabled === false;
- const hasSubmenu = children !== undefined && children !== null && children !== false;
- const openSubmenu = menu.open[level];
- const open = openSubmenu?.id === id;
- const active = menu.active?.id === id;
-
- function select(e: MouseEvent | KeyboardEvent) {
- if (closeOnSelect ?? !hasSubmenu) menu.close();
- onSelect?.(e);
- }
-
- function onPointed(e: { currentTarget: HTMLLIElement }) {
- if (isMobile()) return;
- // The keyboard goes on from the row the pointer last pointed at.
- if (!disabled) menu.setActive(level, id);
- menu.openSubmenu(level, hasSubmenu && !disabled ? id : undefined, e.currentTarget);
- }
-
- return (
- <li
- id={id}
- ref={(element) => {
- menu.registerRow(id, element ? { level, element, custom: false, disabled, hasSubmenu, select } : undefined);
- }}
- className={clsx("dropdown-item", hasSubmenu && "dropdown-submenu", open && "submenu-open",
- active && "tn-menu-active", disabled && "disabled", className)}
- role="menuitem"
- aria-disabled={disabled || undefined}
- aria-haspopup={hasSubmenu ? "menu" : undefined}
- aria-expanded={hasSubmenu ? open : undefined}
- // 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={(e) => {
- if (!menu.keyboardDriven) onPointed(e);
- }}
- // 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={(e) => {
- if (!active && pointerMoved(e)) onPointed(e);
- }}
- // `mousedown` rather than `click`, and its default prevented, so the press does not move
- // focus out of the menu: `contextMenu` hands it back to a text editor before the command
- // runs, with the selection that commands such as a spelling fix act on.
- onMouseDown={(e) => {
- if (e.button !== 0) return;
- e.preventDefault();
- // An unfolded row holds its submenu's rows, whose presses would reach it too.
- e.stopPropagation();
- if (disabled) return;
-
- // Pressed again, an unfolded row folds its submenu back.
- if (hasSubmenu && isMobile()) {
- menu.openSubmenu(level, open ? undefined : id, e.currentTarget, true);
- return;
- }
- if (hasSubmenu) menu.openSubmenu(level, id, e.currentTarget, true);
- select(e);
- }}
- >
- <span className={hasSubmenu ? "dropdown-toggle" : undefined}>
- {/* Callers pass HTML: titles escaped with `escapeHtml()` or boxed by `menuName()`. */}
- <span id={titleId(id)} dangerouslySetInnerHTML={{ __html: title }} />
- </span>
- {hasSubmenu && (isMobile()
- // A phone has no room beside the menu, so an open submenu unfolds under its row.
- ? (
- <ul className={clsx("dropdown-menu", open && "show")} role="menu" aria-labelledby={titleId(id)}>
- <MenuLevelContext.Provider value={level + 1}>{open && children}</MenuLevelContext.Provider>
- </ul>
- )
- : open && openSubmenu && menu.layerHost && createPortal((
- <SubmenuLayer level={level + 1} submenu={openSubmenu} columns={columns}>{children}</SubmenuLayer>
- ), menu.layerHost))}
- </li>
- );
-}
-
-/**
- * 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({ level, submenu, columns, children }: {
- level: number,
- submenu: OpenSubmenu,
- columns?: number,
- children: ComponentChildren
-}) {
- const layerRef = useRef<HTMLDivElement>(null);
- const columnCount = (columns ?? 1) > 1 ? columns : undefined;
-
- 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 (
- <MenuLevelContext.Provider value={level}>
- <div className="dropdown-submenu">
- <div
- ref={layerRef} role="menu" aria-labelledby={titleId(submenu.anchor.id)}
- className={clsx("dropdown-menu show tn-menu", submenu.immediate && "tn-menu-immediate")}
- >
- {/* Like the top level, so the blur on the layer's `::before` stays behind its rows. */}
- {columnCount
- // The columns go on an inner list of their full height, so a capped menu
- // scrolls them rather than growing more columns to the side.
- ? (
- <div className="tn-menu-scroll">
- <menu className="tn-menu-columns" role="none" style={{ columnCount }}>
- {children}
- </menu>
- </div>
- )
- : <menu className="tn-menu-scroll" role="none">{children}</menu>}
- </div>
- </div>
- </MenuLevelContext.Provider>
- );
-}
-
-/** The id of a row's title, which names the submenu it opens. */
-function titleId(rowId: string) {
- return `${rowId}-title`;
-}
-
-/**
- * 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
- * turning to the pointer.
- */
-function pointerMoved(e: PointerEvent) {
- return e.movementX !== 0 || e.movementY !== 0;
-}
diff --git a/apps/client/src/widgets/react/menu_context.ts b/apps/client/src/widgets/react/menu_context.ts
index 9a21d24e61..465fd577b8 100644
--- a/apps/client/src/widgets/react/menu_context.ts
+++ b/apps/client/src/widgets/react/menu_context.ts
@@ -1,3 +1,4 @@
+import { computePosition, flip, hide, offset, type Placement, type ReferenceElement, shift, size } from "@floating-ui/dom";
import { createContext } from "preact";
import { useContext } from "preact/hooks";
@@ -81,3 +82,47 @@ export function useMenu() {
export function pointerMoved(e: PointerEvent) {
return e.movementX !== 0 || e.movementY !== 0;
}
+
+/** How many pixels the menu keeps from the edges of the viewport. */
+const VIEWPORT_PADDING = 5;
+
+/**
+ * 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.
+ */
+export async function placeMenu(menu: HTMLElement, anchor: ReferenceElement, placement: Placement, isSubmenu = false) {
+ const [ side ] = placement.split("-");
+ const otherSide = side === "left" ? "right" : "left";
+ 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
+ }),
+ // `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`;
+ }
+ }),
+ isSubmenu && hide({ strategy: "referenceHidden" })
+ ]
+ });
+
+ menu.style.left = `${x}px`;
+ menu.style.top = `${y}px`;
+ menu.style.visibility = middlewareData.hide?.referenceHidden ? "hidden" : "visible";
+}