Skip to content

Build your personal knowledge base with Trilium Notes

fix(menu): keep a filtered submenu's top while its height changes

Elian Doran4252e24d2721
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index 09cce1c804..c96b32bffb 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -1033,6 +1033,49 @@ describe("contextMenu", () => {
expect(document.activeElement).toBe(menuElement());
});
+ it("keeps its top while filtered, as its height follows the matches", async () => {
+ // A browser's layout, which happy-dom has none of: a submenu taller than the room
+ // beside its row, low in the viewport, which moves it up to fit.
+ let height = 400;
+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);
+ vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(200);
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(() => height);
+ const submenuLayer = () => menuElement()?.querySelector<HTMLElement>("div.dropdown-submenu > .dropdown-menu");
+ /** Lets Floating UI place the layer again, as it does when the layer resizes. */
+ const relayout = () => new Promise((resolve) => {
+ window.dispatchEvent(new Event("resize"));
+ setTimeout(resolve, 20);
+ });
+ try {
+ await openFilterable();
+ const parent = [ ...menuElement()?.querySelectorAll<HTMLElement>("li.dropdown-submenu") ?? [] ]
+ .find((row) => row.textContent?.includes("Insert child note"));
+ if (!parent) throw new Error("no submenu row");
+ vi.spyOn(parent, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: 10, y: 600, width: 200, height: 30 }));
+ await openSubmenuByKeys();
+ await vi.waitFor(() => expect(submenuLayer()?.style.visibility).toBe("visible"));
+ const top = submenuLayer()?.style.top;
+ expect(parseFloat(top ?? "")).toBeLessThan(600);
+
+ type("p");
+ await vi.waitFor(() => expect(layer().rows).toHaveLength(3));
+ height = 100;
+ await relayout();
+ // Short enough to stand beside its row, it stays where the reader was looking.
+ expect(submenuLayer()?.style.top).toBe(top);
+ expect(submenuLayer()?.style.maxHeight).toBe(`${800 - parseFloat(top ?? "") - 5}px`);
+
+ // Emptied, it is placed as it opened, which is where it already stands.
+ edit("");
+ height = 400;
+ await relayout();
+ expect(submenuLayer()?.style.top).toBe(top);
+ } finally {
+ vi.restoreAllMocks();
+ }
+ });
+
it("scrolls back to the input when the keys come round to the first row", async () => {
await openFilterable();
await openSubmenuByKeys();
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 49c237164a..26d0623271 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -474,7 +474,7 @@ function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleCli
</ul>
)
: open && openSubmenu && menu.layerHost && createPortal((
- <SubmenuLayer level={level + 1} submenu={openSubmenu}>
+ <SubmenuLayer level={level + 1} submenu={openSubmenu} pinned={!!filter?.text}>
<MenuFilterContext.Provider value={filter}>{children}</MenuFilterContext.Provider>
</SubmenuLayer>
), menu.layerHost)}
@@ -484,16 +484,31 @@ function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleCli
/**
* 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.
+ * so a scrolling menu neither clips it nor scrolls it away. While {@link pinned}, as while it is
+ * filtered, it keeps the top it had when pinned, relative to its row, and only its height follows
+ * its content.
*/
-function SubmenuLayer({ level, submenu, children }: {
+function SubmenuLayer({ level, submenu, pinned, children }: {
level: number,
submenu: OpenSubmenu,
+ pinned?: boolean,
children: ComponentChildren
}) {
const layerRef = useRef<HTMLDivElement>(null);
const { dropStart: dropStartLevels, setDropStart } = useMenu();
const dropStart = !!dropStartLevels[level - 1];
+ /** How far below its row's top the layer stands while pinned. */
+ const pinnedOffset = useRef<number | undefined>(undefined);
+
+ // Taken as the content changes, before the layer is placed again for its new height.
+ useLayoutEffect(() => {
+ const layer = layerRef.current;
+ if (!pinned || !layer) {
+ pinnedOffset.current = undefined;
+ } else if (pinnedOffset.current === undefined) {
+ pinnedOffset.current = parseFloat(layer.style.top) - submenu.anchor.getBoundingClientRect().top;
+ }
+ }, [ pinned, submenu.anchor ]);
useLayoutEffect(() => {
const layer = layerRef.current;
@@ -513,7 +528,14 @@ function SubmenuLayer({ level, submenu, children }: {
},
shiftAcross: true, capHeight: true, hideWithAnchor: true
} as const;
- return autoUpdate(submenu.anchor, layer, () => void placeFloating(layer, submenu.anchor, options).then((placed) => {
+ const place = () => {
+ const offset = pinnedOffset.current;
+ const pinTop = offset === undefined || Number.isNaN(offset)
+ ? undefined
+ : submenu.anchor.getBoundingClientRect().top + offset;
+ return placeFloating(layer, submenu.anchor, { ...options, pinTop });
+ };
+ return autoUpdate(submenu.anchor, layer, () => void place().then((placed) => {
// After a flip, the parent level follows, so its rows' arrows match.
const placedDropStart = placed.startsWith(startSide);
if (placedDropStart !== dropStart) {
diff --git a/apps/client/src/widgets/react/Popup.spec.tsx b/apps/client/src/widgets/react/Popup.spec.tsx
index 41204eac17..6cca797d11 100644
--- a/apps/client/src/widgets/react/Popup.spec.tsx
+++ b/apps/client/src/widgets/react/Popup.spec.tsx
@@ -97,6 +97,23 @@ describe("Popup", () => {
expect(tall.style.maxHeight).toBe(`${800 - 330 - 5}px`);
});
+ it("keeps a top it is pinned to, whatever its height, and caps its height to the room below", async () => {
+ const layer = document.createElement("div");
+ document.body.append(layer);
+ anchorAt(100, 600);
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(400);
+ // Unpinned, too tall for the room beside its anchor, it moves up to fit.
+ await placeFloating(layer, anchor, { placement: "right-start", capHeight: true });
+ expect(parseFloat(layer.style.top)).toBeLessThan(600);
+
+ await placeFloating(layer, anchor, { placement: "right-start", capHeight: true, pinTop: 250 });
+ expect(layer.style.top).toBe("250px");
+ expect(layer.style.maxHeight).toBe(`${800 - 250 - 5}px`);
+ // Its side still follows the room it has.
+ expect(layer.style.left).toBe("180px");
+ layer.remove();
+ });
+
it("keeps to one side of a caret, never over the line typed, however long it is", async () => {
vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(1000);
const caret = { getBoundingClientRect: () => DOMRect.fromRect({ x: 100, y: 300, width: 1, height: 16 }) };
diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsx
index 38c77f8ac8..a2c1f7927f 100644
--- a/apps/client/src/widgets/react/Popup.tsx
+++ b/apps/client/src/widgets/react/Popup.tsx
@@ -249,6 +249,11 @@ export interface FloatingPlacement {
capHeight?: boolean;
/** Hides it while its anchor is scrolled out of view, as a submenu whose row scrolled away. */
hideWithAnchor?: boolean;
+ /**
+ * Keeps its top at this viewport y instead of where its height would place it, for a popup
+ * whose content changes while it is read. With {@link capHeight}, the cap is the room below it.
+ */
+ pinTop?: number;
/**
* An arrow element inside it. Its offset along the edge facing the anchor is set to point at
* the anchor, at least `padding` pixels from the corners.
@@ -262,7 +267,7 @@ export interface FloatingPlacement {
* near the viewport's edge. It stays hidden until placed, so it never paints at a stale position.
* Resolves to the placement Floating UI chose.
*/
-export async function placeFloating(element: HTMLElement, anchor: ReferenceElement, { placement, offset: gap, shiftAcross, capHeight, hideWithAnchor, arrow: pointer }: FloatingPlacement) {
+export async function placeFloating(element: HTMLElement, anchor: ReferenceElement, { placement, offset: gap, shiftAcross, capHeight, hideWithAnchor, pinTop, arrow: pointer }: FloatingPlacement) {
const padding = viewportPadding();
const { x, y, placement: placed, middlewareData } = await computePosition(anchor, element, {
strategy: "fixed",
@@ -283,7 +288,10 @@ export async function placeFloating(element: HTMLElement, anchor: ReferenceEleme
});
element.style.left = `${x}px`;
- element.style.top = `${y}px`;
+ element.style.top = `${pinTop ?? y}px`;
+ if (capHeight && pinTop !== undefined) {
+ element.style.maxHeight = `${document.documentElement.clientHeight - pinTop - padding.bottom}px`;
+ }
element.style.visibility = middlewareData.hide?.referenceHidden ? "hidden" : "visible";
if (pointer) {
// Only the offset along the facing edge; the stylesheet sets the other axis.