Skip to content

Build your personal knowledge base with Trilium Notes

refactor(menu): place every floating surface with one function, and the context menu in a Popup

Elian Doran1cbfd83475df
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 5c5e8146e8..9bc2367a21 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -148,12 +148,13 @@ class ContextMenu {
// The id and classes the stylesheets, themes and `floating_layers` know this menu by.
id: "context-menu-container",
className: "dropdown-menu-sm dropend",
- x: options.x,
- y: options.y,
- orientation: options.orientation,
+ anchor: { x: options.x, y: options.y },
+ placement: options.orientation === "left" ? "left-start" : "right-start",
+ // Already where the screen shows it: see the host above.
+ container: this.host,
bottomSheet: utils.isMobile() && !options.forcePositionOnMobile,
// As a native menu opened from the keyboard, it starts at its first row.
- startAtFirstRow: this.lastInputWasKey,
+ startAt: this.lastInputWasKey ? "first" : undefined,
items: options.items,
onSelect: (item, e) => {
// A submenu's row stays up to be opened, unless it runs something of its own.
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 8c8a36220f..8717d746b6 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -5,16 +5,17 @@ import type { KeyboardActionNames } from "@triliumnext/commons";
import { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";
import clsx from "clsx";
import { ComponentChildren, RefObject } from "preact";
-import { createPortal, type CSSProperties, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "preact/compat";
+import { createPortal, type CSSProperties, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/compat";
import { CommandNames } from "../../components/app_context";
import { getActionSync } from "../../services/keyboard_actions";
import { handleRightToLeftPlacement, isMobile, openInAppHelpFromUrl } from "../../services/utils";
import FormToggle from "./FormToggle";
import HelpTooltipButton from "./HelpTooltipButton";
-import { useStaticTooltip, useSyncedRef } from "./hooks";
+import { useStaticTooltip, useSyncedRef, useUniqueName } from "./hooks";
import Icon from "./Icon";
-import { MenuContext, type MenuContextValue, MenuLevelContext, type OpenSubmenu, placeMenu, pointerMoved } from "./menu_context";
+import { MenuContext, type MenuContextValue, MenuLevelContext, type OpenSubmenu, pointerMoved } from "./menu_context";
+import { placeFloating } from "./Popup";
import { joinElements } from "./react_utils";
import { renderShortcutKbds } from "./shortcut_kbd";
@@ -172,7 +173,8 @@ export function FormListItem({ className, icon, iconClassName, value, title, act
// Inside a `Menu` the row is one of its items; elsewhere, as in a dropdown, it stands alone.
const menu = useContext(MenuContext);
const level = useContext(MenuLevelContext);
- const id = useId();
+ // Unique across portals, where `useId()` numbers a menu's layers over again.
+ const id = useUniqueName("menu-row");
const isActive = menu?.active?.id === id;
/**
@@ -370,7 +372,7 @@ export function FormDropdownSubmenu(props: FormDropdownSubmenuProps) {
function MenuSubmenu({ menu, icon, title, children, onDropdownToggleClicked, columns, disabled, className }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {
const level = useContext(MenuLevelContext);
- const id = useId();
+ const id = useUniqueName("menu-row");
const openSubmenu = menu.open[level];
const open = openSubmenu?.id === id;
const isActive = menu.active?.id === id;
@@ -492,7 +494,18 @@ function SubmenuLayer({ level, submenu, columns, children }: {
if (!layer) return;
const placement = handleRightToLeftPlacement("right") === "right" ? "right-start" : "left-start";
- return autoUpdate(submenu.anchor, layer, () => void placeMenu(layer, submenu.anchor, placement, true));
+ const options = {
+ placement,
+ // 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 } }) => {
+ const style = getComputedStyle(elements.floating);
+ const inset = (parseFloat(style.paddingTop) || 0) + (parseFloat(style.borderTopWidth) || 0);
+ return { mainAxis: -2, crossAxis: -inset };
+ },
+ shiftAcross: true, capHeight: true, hideWithAnchor: true
+ } as const;
+ return autoUpdate(submenu.anchor, layer, () => void placeFloating(layer, submenu.anchor, options));
}, [ submenu.anchor ]);
// In a `.dropdown-submenu`, so the theme's submenu rules apply.
@@ -540,7 +553,7 @@ export function FormListCustomItem({ children }: { children: ComponentChildren }
// Outside a `Menu`, as in a dropdown's plain list, there is none to join.
const menu = useContext(MenuContext);
const level = useContext(MenuLevelContext);
- const id = useId();
+ const id = useUniqueName("menu-row");
return (
<li
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index f3ff5e1bca..23bb0333dd 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -3,13 +3,13 @@
position: fixed;
top: 0;
left: 0;
- /* `placeMenu()` shows the menu once it has a position. */
+ /* `placeFloating()` shows the menu once it has a position. */
visibility: hidden;
}
/*
* The top level does not scroll, so the blur the theme puts on its `::before` covers it whatever
- * its rows scroll to. Its rows scroll inside, in the height `placeMenu()` caps it to.
+ * its rows scroll to. Its rows scroll inside, in the height `placeFloating()` caps it to.
*/
.dropdown-menu.tn-menu:has(> .tn-menu-scroll) {
display: flex;
@@ -41,7 +41,7 @@
overflow-y: auto;
}
-/* A submenu is placed by `placeMenu()`, not beside a parent it is nested in. */
+/* A submenu is placed by `placeFloating()`, not beside a parent it is nested in. */
.dropdown-submenu > .dropdown-menu.tn-menu {
inset: 0 auto auto 0;
margin: 0;
diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsx
index 508b552cc3..699d53b36e 100644
--- a/apps/client/src/widgets/react/Menu.spec.tsx
+++ b/apps/client/src/widgets/react/Menu.spec.tsx
@@ -60,7 +60,7 @@ describe("Menu with declared rows", () => {
);
}
render((
- <Menu x={10} y={10} onClose={onClose}>
+ <Menu anchor={{ x: 10, y: 10 }} onClose={onClose}>
<FormListHeader text="Note" />
<FormListItem onClick={() => calls.push("copy")}>Copy</FormListItem>
<FormListItem disabled onClick={() => calls.push("delete")}>Delete</FormListItem>
@@ -69,7 +69,7 @@ describe("Menu with declared rows", () => {
</Menu>
), host);
- const menu = host.querySelector<HTMLElement>(".tn-menu");
+ const menu = document.querySelector<HTMLElement>(".tn-popup.tn-menu");
if (!menu) throw new Error("expected the menu to render");
return { menu, calls, onClose };
}
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 2d77c69bd2..4bceec3f41 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -1,6 +1,5 @@
import "./Menu.css";
-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,31 +7,33 @@ 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, placeMenu, pointerMoved, type RowEntry } from "./menu_context";
+import { type ActiveRow, MenuContext, type MenuContextValue, type OpenSubmenu, pointerMoved, type RowEntry } from "./menu_context";
+import Popup, { type PopupProps } from "./Popup";
/**
* A menu of commands, drawn with the markup Bootstrap's dropdowns use (`.dropdown-menu`,
* `.dropdown-item`, `.dropdown-divider`), so the stylesheets and themes that style those style
- * this too. Only the placement is its own.
+ * this too. It stands in a `Popup`, which places it; the menu is what is inside: its rows, the
+ * layers of their submenus, and the keys.
*
* The rows come as data in {@link items}, or as components in {@link children}: `FormListItem`,
* `FormDropdownSubmenu`, `FormDropdownDivider`, `FormListHeader` and `FormListCustomItem`.
*/
-export interface MenuProps<T> {
+export interface MenuProps<T> extends Pick<PopupProps, "anchor" | "offset" | "container" | "portalClassName"
+ | "backdropClassName" | "style" | "aria-labelledby"> {
id?: string;
className?: string;
- /** 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";
+ /** The side of its anchor it prefers: beside a point towards the right, or below an element. */
+ placement?: PopupProps["placement"];
/**
- * Shows the menu as a sheet along the bottom of a phone's screen instead of at {@link x} and
- * {@link y}. The `.mobile-bottom-menu` rules place and cap it.
+ * Shows the menu as a sheet along the bottom of a phone's screen instead of beside its anchor.
+ * The `.mobile-bottom-menu` rules place and cap it.
*/
bottomSheet?: boolean;
- /** Makes the first row the active one as the menu takes focus, for a menu a key opened. */
- startAtFirstRow?: boolean;
+ /** Makes the first or the last row the active one as the menu takes focus, for a menu a key opened. */
+ startAt?: "first" | "last";
+ /** Called on a press outside the menu and its anchor. It answers Escape itself, with {@link onClose}. */
+ onDismiss?(): void;
items?: MenuItem<T>[];
/** Called when one of {@link items} is pressed with the primary button, or run from the keyboard. */
onSelect?(item: MenuCommandItem<T>, e: MouseEvent | KeyboardEvent): void;
@@ -48,7 +49,7 @@ const KEYS_LEAVING_CUSTOM_ROW = new Set([ "ArrowUp", "ArrowDown", "Escape", "Tab
/** How long typed letters keep adding to the text a row is looked up by. */
const TYPEAHEAD_TIMEOUT = 500;
-export default function Menu<T>({ id, className, x, y, orientation, bottomSheet, startAtFirstRow, items, onSelect, children, onClose }: MenuProps<T>) {
+export default function Menu<T>({ id, className, anchor, placement, bottomSheet, startAt, items, onSelect, children, onClose, onDismiss, ...popupProps }: MenuProps<T>) {
const menuRef = useRef<HTMLDivElement | null>(null);
// The submenus' layers render into the menu element, which rows reach through the context.
const [ layerHost, setLayerHost ] = useState<HTMLElement | null>(null);
@@ -241,41 +242,29 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,
e.stopPropagation();
}
- useLayoutEffect(() => {
- const menu = menuRef.current;
- if (!menu) return;
- // The keys go to the menu while it is up; `contextMenu` gives focus back once it is hidden.
- // A browser does not focus an element under `visibility: hidden`, so the menu takes focus
- // only once it is shown.
- const takeFocus = () => {
- menu.focus({ preventScroll: true });
- if (!startAtFirstRow) return;
- const first = navigableRows(0)[0];
- if (first) setActive(0, first);
- setKeyboardDriven(true);
- };
- if (bottomSheet) {
- // An inline `max-height` would override the sheet's own, which is not `!important`.
- menu.style.visibility = "visible";
- takeFocus();
- return;
- }
-
- const anchor = pointAt(x, y);
- const placement = orientation === "left" ? "left-start" : "right-start";
- let placed = false;
- // Places the menu now, and again whenever the viewport or the menu itself changes size.
- return autoUpdate(anchor, menu, () => void placeMenu(menu, anchor, placement).then(() => {
- if (placed) return;
- placed = true;
- takeFocus();
- }));
- }, [ x, y, orientation, bottomSheet ]);
+ // The keys go to the menu while it is up; `contextMenu` gives focus back once it is hidden. A
+ // browser does not focus an element under `visibility: hidden`, so the menu takes focus only
+ // once it is shown.
+ function takeFocus() {
+ menuRef.current?.focus({ preventScroll: true });
+ if (!startAt) return;
+ const rowIds = navigableRows(0);
+ const first = startAt === "first" ? rowIds[0] : rowIds.at(-1);
+ if (first) setActive(0, first);
+ setKeyboardDriven(true);
+ }
return (
<MenuContext.Provider value={context}>
- <div
- ref={setMenuElement} id={id} role="menu" tabIndex={-1}
+ <Popup
+ {...popupProps}
+ anchor={anchor}
+ placement={placement ?? (anchor instanceof HTMLElement ? "bottom-start" : "right-start")}
+ placedByStylesheet={bottomSheet}
+ onPlaced={takeFocus}
+ onDismiss={onDismiss && (() => onDismiss())}
+ escapeDismisses={false}
+ elementRef={setMenuElement} id={id} role="menu" tabIndex={-1}
className={clsx("dropdown-menu show tn-menu", bottomSheet && "mobile-bottom-menu",
keyboardDriven && "tn-menu-keyboard", className)}
onPointerMove={(e) => {
@@ -295,7 +284,7 @@ export default function Menu<T>({ id, className, x, y, orientation, bottomSheet,
{items ? <MenuItems items={items} onSelect={onSelect} /> : children}
</menu>
{/* The submenus' layers follow the scroller in here, portaled by their rows. */}
- </div>
+ </Popup>
</MenuContext.Provider>
);
}
@@ -446,10 +435,3 @@ function isSeparator<T>(item: MenuItem<T>) {
function isHeader<T>(item: MenuItem<T>) {
return "kind" in item && item.kind === "header";
}
-
-/** 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/client/src/widgets/react/Popup.css b/apps/client/src/widgets/react/Popup.css
index 4e0f8d019e..725e573510 100644
--- a/apps/client/src/widgets/react/Popup.css
+++ b/apps/client/src/widgets/react/Popup.css
@@ -1,6 +1,6 @@
/*
* `body` outranks the position a class it is given sets, such as Bootstrap's `.dropdown-menu`.
- * `placePopup()` shows it once it has a position.
+ * `placeFloating()` shows it once it has a position.
*/
body .tn-popup {
position: fixed;
diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsx
index 7beeb414be..915dcbae77 100644
--- a/apps/client/src/widgets/react/Popup.tsx
+++ b/apps/client/src/widgets/react/Popup.tsx
@@ -1,17 +1,18 @@
import "./Popup.css";
-import { autoUpdate, computePosition, flip, offset, type Placement, type ReferenceElement, shift, size } from "@floating-ui/dom";
+import { autoUpdate, computePosition, flip, hide, offset, type OffsetOptions, type Placement, type ReferenceElement, shift, size } from "@floating-ui/dom";
import clsx from "clsx";
-import type { ComponentChildren, HTMLAttributes } from "preact";
+import type { ComponentChildren, HTMLAttributes, Ref } from "preact";
import { createPortal } from "preact/compat";
-import { type MutableRef, useLayoutEffect, useRef } from "preact/hooks";
+import { useCallback, useLayoutEffect, useRef } from "preact/hooks";
/**
* A surface that stands beside something rather than in the page's flow: a dropdown's menu, and
* anything else that pops up from a control or at a point. It knows nothing of what it holds; it
* places itself, keeps inside the viewport, and says when it is dismissed.
*/
-export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" | "className" | "role" | "style" | "onClick" | "aria-labelledby"> {
+export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" | "className" | "role" | "style" | "tabIndex"
+ | "onClick" | "onPointerMove" | "onContextMenu" | "aria-labelledby"> {
/** What it stands beside: an element, or a point in the viewport such as where a right-click landed. */
anchor: HTMLElement | { x: number, y: number };
/**
@@ -38,22 +39,35 @@ export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" |
placedByStylesheet?: boolean;
/** Classes for an element drawn just before it, which dims the page under it. */
backdropClassName?: string;
- elementRef?: MutableRef<HTMLDivElement | null>;
+ elementRef?: Ref<HTMLDivElement>;
+ /**
+ * Where it renders, for a caller that has placed that itself. By default the element showing
+ * the screen fullscreen, or else the page's body.
+ */
+ container?: HTMLElement;
/** Called once it is first placed and shown: a browser focuses nothing inside it before. */
onPlaced?(): void;
/**
* Called on a press outside it and its anchor, and on Escape. A press on the anchor is left to
- * the anchor, as a dropdown's toggle closes its own popup.
+ * the anchor, as a dropdown's toggle closes its own popup. Without it, nothing dismisses it.
*/
- onDismiss(reason: "outside" | "escape"): void;
+ onDismiss?(reason: "outside" | "escape"): void;
+ /** Whether Escape dismisses it, as it does unless its content answers Escape itself, as a menu does. */
+ escapeDismisses?: boolean;
children?: ComponentChildren;
}
/** How many pixels it keeps from the edges of the viewport. */
const VIEWPORT_PADDING = 5;
-export default function Popup({ anchor, placement = "bottom-start", offset: gap = 0, capHeight = true, portalClassName, placedByStylesheet, backdropClassName, elementRef, onPlaced, onDismiss, className, children, ...elementProps }: PopupProps) {
+export default function Popup({ anchor, placement = "bottom-start", offset: gap = 0, capHeight = true, portalClassName, placedByStylesheet, backdropClassName, elementRef, container, onPlaced, onDismiss, escapeDismisses = true, className, children, ...elementProps }: PopupProps) {
const popupRef = useRef<HTMLDivElement | null>(null);
+ // Stable, so the element is handed on once rather than taken back and given again each render.
+ const setElement = useCallback((element: HTMLDivElement | null) => {
+ popupRef.current = element;
+ if (typeof elementRef === "function") elementRef(element);
+ else if (elementRef) elementRef.current = element;
+ }, [ elementRef ]);
const placed = useRef(onPlaced);
placed.current = onPlaced;
const anchorX = "x" in anchor ? anchor.x : undefined;
@@ -70,7 +84,8 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
const reference = anchor instanceof HTMLElement ? anchor : pointAt(anchor.x, anchor.y);
let shown = false;
// Places it now, and again whenever its anchor moves or the viewport or it changes size.
- return autoUpdate(reference, popup, () => void placePopup(popup, reference, placement, gap, capHeight).then(() => {
+ const options = { placement, offset: gap, capHeight, shiftAcross: !(anchor instanceof HTMLElement) };
+ return autoUpdate(reference, popup, () => void placeFloating(popup, reference, options).then(() => {
if (shown) return;
shown = true;
placed.current?.();
@@ -79,7 +94,10 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
+ const escapes = useRef(escapeDismisses);
+ escapes.current = escapeDismisses;
useLayoutEffect(() => {
+ if (!dismiss.current) return;
// Captured at the window, so a host that stops its own presses, as the note tree does,
// cannot keep them from here, and so Escape arrives before Bootstrap's handler for keys in
// a `.dropdown-menu`, which looks for a toggle beside the popup and crashes without one.
@@ -87,13 +105,13 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
const target = e.target as Node;
if (popupRef.current?.contains(target)) return;
if (anchor instanceof HTMLElement && anchor.contains(target)) return;
- dismiss.current("outside");
+ dismiss.current?.("outside");
};
const onKeyDown = (e: KeyboardEvent) => {
- if (e.key !== "Escape") return;
+ if (e.key !== "Escape" || !escapes.current) return;
// A dialog under it stays open.
e.stopPropagation();
- dismiss.current("escape");
+ dismiss.current?.("escape");
};
window.addEventListener("pointerdown", onPointerDown, true);
window.addEventListener("keydown", onKeyDown, true);
@@ -108,10 +126,7 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
const popup = (
<div
{...elementProps}
- ref={(element) => {
- popupRef.current = element;
- if (elementRef) elementRef.current = element;
- }}
+ ref={setElement}
className={clsx("tn-popup", className)}
>
{children}
@@ -122,40 +137,68 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
{popup}
</>;
return createPortal(portalClassName ? <div className={portalClassName}>{drawn}</div> : drawn,
- document.fullscreenElement ?? document.body);
+ container ?? document.fullscreenElement ?? document.body);
+}
+
+/** How it is placed beside its anchor. See {@link placeFloating}. */
+export interface FloatingPlacement {
+ /** The side of the anchor it prefers, and its alignment along that side. */
+ placement: Placement;
+ /** Its gap from the anchor, or how far it overlaps it, as Floating UI's `offset()` takes it. */
+ offset?: OffsetOptions;
+ /**
+ * Lets it also move across the side it stands on, over its anchor, as a menu wider than the
+ * room on either side of a point must. A popup under a toggle leaves this off, so it never
+ * covers the toggle.
+ */
+ shiftAcross?: boolean;
+ /** Caps its height to the room on the side it takes, for content that scrolls in it. */
+ capHeight?: boolean;
+ /** Hides it while its anchor is scrolled out of view, as a submenu whose row scrolled away. */
+ hideWithAnchor?: boolean;
}
/**
- * Positions `popup` beside `anchor`, preferring `placement` and flipping to the other side where
- * that has no room, and with `capHeight` caps its height to the room on the side it takes. It
- * stays hidden until placed, so it never paints at a stale position.
+ * 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.
*/
-async function placePopup(popup: HTMLElement, anchor: ReferenceElement, placement: Placement, gap: number, capHeight: boolean) {
- const { x, y } = await computePosition(anchor, popup, {
+export async function placeFloating(element: HTMLElement, anchor: ReferenceElement, { placement, offset: gap, shiftAcross, capHeight, hideWithAnchor }: FloatingPlacement) {
+ const { x, y, middlewareData } = await computePosition(anchor, element, {
strategy: "fixed",
placement,
middleware: [
- offset(gap),
- flip({ padding: VIEWPORT_PADDING }),
- // Over a point it can also move across the side it stands on, as a popup wider than
- // the room on either side of the point must; an element it must not cover.
- shift({ crossAxis: !(anchor instanceof HTMLElement), padding: VIEWPORT_PADDING }),
+ gap !== undefined && offset(gap),
+ flip({ fallbackPlacements: mirroredPlacements(placement), padding: VIEWPORT_PADDING }),
+ shift({ crossAxis: !!shiftAcross, padding: VIEWPORT_PADDING }),
capHeight && size({
padding: VIEWPORT_PADDING,
apply({ availableHeight }) {
- popup.style.maxHeight = `${availableHeight}px`;
+ element.style.maxHeight = `${availableHeight}px`;
}
- })
+ }),
+ hideWithAnchor && hide({ strategy: "referenceHidden" })
]
});
- popup.style.left = `${x}px`;
- popup.style.top = `${y}px`;
- popup.style.visibility = "visible";
+ element.style.left = `${x}px`;
+ element.style.top = `${y}px`;
+ element.style.visibility = middlewareData.hide?.referenceHidden ? "hidden" : "visible";
+}
+
+const OPPOSITE_SIDES = { top: "bottom", bottom: "top", left: "right", right: "left" } as const;
+
+/** The placements to fall back on from `placement`: the opposite side, then the other alignment on each. */
+function mirroredPlacements(placement: Placement): Placement[] {
+ const [ side, alignment ] = placement.split("-") as [ keyof typeof OPPOSITE_SIDES, "start" | "end" | undefined ];
+ const opposite = OPPOSITE_SIDES[side];
+ if (!alignment) return [ opposite ];
+ const other = alignment === "start" ? "end" : "start";
+ return [ `${opposite}-${alignment}`, `${side}-${other}`, `${opposite}-${other}` ];
}
/** A zero-size anchor at a point in the viewport. */
-function pointAt(x: number, y: number): ReferenceElement {
+export function pointAt(x: number, y: number): ReferenceElement {
return {
getBoundingClientRect: () => DOMRect.fromRect({ x, y, width: 0, height: 0 })
};
diff --git a/apps/client/src/widgets/react/menu_context.ts b/apps/client/src/widgets/react/menu_context.ts
index 465fd577b8..9a21d24e61 100644
--- a/apps/client/src/widgets/react/menu_context.ts
+++ b/apps/client/src/widgets/react/menu_context.ts
@@ -1,4 +1,3 @@
-import { computePosition, flip, hide, offset, type Placement, type ReferenceElement, shift, size } from "@floating-ui/dom";
import { createContext } from "preact";
import { useContext } from "preact/hooks";
@@ -82,47 +81,3 @@ 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";
-}