Skip to content

Build your personal knowledge base with Trilium Notes

refactor(client): lay every menu out in a single column

Elian Dorandef31da0539c
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index 5546763c8b..a00b7a4575 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -370,7 +370,7 @@ describe("contextMenu", () => {
{ kind: "header", title: "Colour" },
{ kind: "custom", componentFn: () => null },
{ kind: "separator" },
- { title: "Insert child note", columns: 2, items: [
+ { title: "Insert child note", items: [
{ title: "Text" }, { kind: "separator" }, { title: "Code" }, { title: "Weekly" }
] }
]
@@ -385,13 +385,10 @@ describe("contextMenu", () => {
const parent = menuRows().at(-1);
parent?.dispatchEvent(new PointerEvent("pointerenter"));
- await vi.waitFor(() => expect(menuElement()?.querySelector(".tn-menu-columns")).not.toBeNull());
- const columns = menuElement()?.querySelector(".tn-menu-columns");
- expect([ columns?.tagName, columns?.getAttribute("role") ]).toEqual([ "MENU", "none" ]);
- // A group a column must not break is a list item holding a list of its own.
- const group = columns?.querySelector(":scope > .dropdown-no-break");
- expect([ group?.tagName, group?.getAttribute("role") ]).toEqual([ "LI", "none" ]);
- expect(group?.querySelector(":scope > menu")?.getAttribute("role")).toBe("none");
+ const submenuList = () => menuElement()?.querySelector("div.dropdown-submenu .tn-menu-scroll");
+ await vi.waitFor(() => expect(submenuList()).not.toBeNull());
+ expect([ submenuList()?.tagName, submenuList()?.getAttribute("role") ]).toEqual([ "MENU", "none" ]);
+ expect(submenuList()?.children).toHaveLength(4);
for (const element of menuElement()?.querySelectorAll("menu") ?? []) {
expect([ ...element.children ].every((child) => child.tagName === "LI")).toBe(true);
}
@@ -654,57 +651,6 @@ describe("contextMenu", () => {
expect(again.isShown).toBe(false);
});
- 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 > .dropdown-menu > .tn-menu-scroll > .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("keeps a header with the row after it, and a separator with the rows around it, in one column", async () => {
- buildPage();
- const contextMenu = await buildContextMenu();
- const columnItems = [
- { title: "Text" }, { title: "Code" },
- { kind: "separator" as const },
- { title: "Templates", kind: "header" as const },
- { title: "Meeting" }, { title: "Weekly" }
- ];
- await contextMenu.show({
- x: 10, y: 10, selectMenuItemHandler: () => {},
- items: [
- { title: "Insert child note", items: columnItems, columns: 2 },
- { title: "Insert note after", items: columnItems }
- ]
- });
- /** The layer's rows, a group of rows that must not break as the list of its rows. */
- const layout = (list: Element | null | undefined) => [ ...list?.children ?? [] ].map((child) =>
- child.classList.contains("dropdown-no-break")
- ? [ ...child.querySelector(":scope > menu")?.children ?? [] ].map((grouped) => grouped.textContent || "---")
- : child.textContent || "---");
-
- hover(row("Insert child note"));
- await vi.waitFor(() => expect(menuElement()?.querySelector(".tn-menu-columns")).not.toBeNull());
- expect(layout(menuElement()?.querySelector(".tn-menu-columns"))).toEqual([
- "Text", [ "Code", "---", "Templates", "Meeting" ], "Weekly"
- ]);
-
- // A single column has no breaks to avoid, so nothing is grouped.
- hover(row("Insert note after"));
- await vi.waitFor(() => expect(menuElement()?.querySelector(".tn-menu-columns")).toBeNull());
- expect(layout(menuElement()?.querySelector("div.dropdown-submenu > .dropdown-menu > .tn-menu-scroll"))).toEqual([
- "Text", "Code", "---", "Templates", "Meeting", "Weekly"
- ]);
- });
-
it("unfolds a submenu under its row on a phone", async () => {
layout.onMobile = true;
const picked: string[] = [];
@@ -980,44 +926,6 @@ describe("contextMenu", () => {
expect(contextMenu.isShown).toBe(false);
});
- it("moves across a submenu's columns, and leaves it from its first", async () => {
- buildPage();
- const contextMenu = await buildContextMenu();
- await contextMenu.show({
- x: 10, y: 10, selectMenuItemHandler: () => {},
- items: [ {
- title: "Insert child note", columns: 2,
- items: [ { title: "Text" }, { title: "Code" }, { title: "Meeting" }, { title: "Weekly" } ]
- } ]
- });
- await vi.waitFor(() => expect(document.activeElement).toBe(menuElement()));
-
- key("ArrowDown");
- await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));
- key("ArrowRight");
- await vi.waitFor(() => expect(activeRow()).toBe("Text"));
- // Where the browser broke the columns: happy-dom lays out nothing.
- const boxes: Record<string, [number, number]> = { Text: [ 0, 0 ], Code: [ 0, 24 ], Meeting: [ 150, 0 ], Weekly: [ 150, 24 ] };
- for (const layerRow of menuElement()?.querySelectorAll<HTMLElement>("div.dropdown-submenu li") ?? []) {
- const [ left, top ] = boxes[layerRow.textContent ?? ""] ?? [ 0, 0 ];
- vi.spyOn(layerRow, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: left, y: top, width: 140, height: 24 }));
- }
-
- key("ArrowDown");
- await vi.waitFor(() => expect(activeRow()).toBe("Code"));
- key("ArrowRight");
- await vi.waitFor(() => expect(activeRow()).toBe("Weekly"));
- // Nothing further right, so it stays.
- key("ArrowRight");
- key("ArrowLeft");
- await vi.waitFor(() => expect(activeRow()).toBe("Code"));
- // From the first column, Left closes the submenu as before.
- key("ArrowLeft");
- await vi.waitFor(() => expect(activeRow()).toBe("Insert child note"));
- expect(menuElement()?.querySelector("div.dropdown-submenu")).toBeNull();
- vi.restoreAllMocks();
- });
-
it("steps into a custom row that has something to focus, and leaves it the keys it answers", async () => {
buildPage();
const contextMenu = await buildContextMenu();
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 82435b3e47..5dda99bc19 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -73,7 +73,6 @@ export interface MenuCommandItem<T> {
* icon standing — for a list where that icon is what tells one entry from another.
*/
trailingIcon?: string;
- columns?: number;
}
export type MenuItem<T> = MenuCommandItem<T> | CustomMenuItem | MenuSeparatorItem | MenuHeader;
diff --git a/apps/client/src/menus/tree_context_menu.ts b/apps/client/src/menus/tree_context_menu.ts
index 2872696ec5..6efde7d98c 100644
--- a/apps/client/src/menus/tree_context_menu.ts
+++ b/apps/client/src/menus/tree_context_menu.ts
@@ -166,8 +166,7 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Pr
keyboardShortcut: "createNoteAfter",
uiIcon: "bx bx-plus",
items: insertNoteAfterItems,
- enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp,
- columns: 2
+ enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp
},
{
@@ -176,8 +175,7 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Pr
keyboardShortcut: "createNoteInto",
uiIcon: "bx bx-subdirectory-right",
items: insertChildNoteItems,
- enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted,
- columns: 2
+ enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted
},
{ kind: "separator" },
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index c024331686..bb45c523c5 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -478,7 +478,6 @@ body.desktop .tabulator-popup-container,
:root .excalidraw .dropdown-menu .dropdown-menu-container,
:root .excalidraw .popover {
border: 1px solid var(--dropdown-border-color);
- column-rule: 1px solid var(--dropdown-border-color);
box-shadow: 0px 10px 20px rgba(0, 0, 0, var(--dropdown-shadow-opacity));
animation: dropdown-menu-opening 100ms ease-in;
}
@@ -582,12 +581,6 @@ body.mobile .dropdown-menu .dropdown-submenu {
border: 1px solid transparent !important;
}
-/* This is a workaround for Firefox not supporting break-before / break-after: avoid on columns.
- * It usually wraps a menu item followed by a separator / header and another menu item. */
-.dropdown-no-break {
- break-inside: avoid;
-}
-
.dropdown-item.disabled,
.dropdown-item.disabled kbd {
color: #aaa !important;
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 9823e189fc..1d324f17b8 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -379,8 +379,6 @@ export interface FormDropdownSubmenuProps {
children: ComponentChildren;
/** Called when the row is clicked, or run from the keyboard, on the desktop. */
onDropdownToggleClicked?: (e: MouseEvent) => void;
- /** Inside a menu, lays the submenu's rows out in this many columns. */
- columns?: number;
disabled?: boolean;
className?: string;
}
@@ -396,7 +394,7 @@ export function FormDropdownSubmenu(props: FormDropdownSubmenuProps) {
return <MenuSubmenu {...props} menu={menu} />;
}
-function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleClicked, columns, disabled, className }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {
+function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleClicked, disabled, className }: FormDropdownSubmenuProps & { menu: MenuContextValue }) {
const level = useContext(MenuLevelContext);
const id = useUniqueName("menu-row");
const openSubmenu = menu.open[level];
@@ -471,7 +469,7 @@ function MenuSubmenu({ menu, icon, iconSvg, title, children, onDropdownToggleCli
</ul>
)
: open && openSubmenu && menu.layerHost && createPortal((
- <SubmenuLayer level={level + 1} submenu={openSubmenu} columns={columns}>{children}</SubmenuLayer>
+ <SubmenuLayer level={level + 1} submenu={openSubmenu}>{children}</SubmenuLayer>
), menu.layerHost)}
</li>
);
@@ -481,14 +479,12 @@ 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.
*/
-function SubmenuLayer({ level, submenu, columns, children }: {
+function SubmenuLayer({ level, submenu, children }: {
level: number,
submenu: OpenSubmenu,
- columns?: number,
children: ComponentChildren
}) {
const layerRef = useRef<HTMLDivElement>(null);
- const columnCount = (columns ?? 1) > 1 ? columns : undefined;
const { dropStart: dropStartLevels, setDropStart } = useMenu();
const dropStart = !!dropStartLevels[level - 1];
@@ -531,17 +527,7 @@ function SubmenuLayer({ level, submenu, columns, children }: {
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>}
+ <menu className="tn-menu-scroll" role="none">{children}</menu>
</div>
</div>
</MenuLevelContext.Provider>
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index 6acccaa6f0..c0c8c9b052 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -78,12 +78,3 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,
background-color: transparent !important;
border-color: transparent !important;
}
-
-/*
- * The theme draws the line between columns with the menu's `column-rule`, which is not inherited,
- * so the scroller hands it on to the columns inside it.
- */
-.tn-menu-scroll,
-.tn-menu-columns {
- column-rule: inherit;
-}
diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsx
index 2071b17277..ce5f206d39 100644
--- a/apps/client/src/widgets/react/Menu.spec.tsx
+++ b/apps/client/src/widgets/react/Menu.spec.tsx
@@ -2,44 +2,9 @@ import { render } from "preact";
import { afterEach, describe, expect, it, vi } from "vitest";
import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem } from "./FormList";
-import Menu, { type MenuProps, rowInNextColumn } from "./Menu";
+import Menu, { type MenuProps } from "./Menu";
import { shouldDropStart } from "./menu_context";
-/** A row 20px tall, `left` into the menu and `top` down it. */
-function row(left: number, top: number) {
- return { left, top, bottom: top + 20 };
-}
-
-describe("rowInNextColumn", () => {
- // Three rows in the first column, two in the second, one in the third.
- const columns = [
- row(0, 0), row(0, 20), row(0, 40),
- row(100, 0), row(100, 20),
- row(200, 0)
- ];
-
- it("goes to the row at the same height in the column beside", () => {
- expect(rowInNextColumn(columns, 1, "right")).toBe(4);
- expect(rowInNextColumn(columns, 4, "left")).toBe(1);
- // The nearest column, not the one after it.
- expect(rowInNextColumn(columns, 0, "right")).toBe(3);
- });
-
- it("goes to the nearest row where the column beside is shorter", () => {
- expect(rowInNextColumn(columns, 2, "right")).toBe(4);
- expect(rowInNextColumn(columns, 4, "right")).toBe(5);
- });
-
- it("finds nothing past the outermost column, in a single column, or for a row it cannot place", () => {
- expect(rowInNextColumn(columns, 0, "left")).toBeUndefined();
- expect(rowInNextColumn(columns, 5, "right")).toBeUndefined();
- expect(rowInNextColumn([ row(0, 0), row(0, 20) ], 0, "right")).toBeUndefined();
- expect(rowInNextColumn(columns, -1, "right")).toBeUndefined();
- // A row not laid out yet is passed over.
- expect(rowInNextColumn([ row(0, 0), undefined, row(100, 0) ], 0, "right")).toBe(2);
- });
-});
-
describe("shouldDropStart", () => {
/** A level 200px wide at `left`, in a viewport 1000px wide. */
const at = (left: number) => ({ left, right: left + 200, width: 200 });
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 1911ffe77f..4a616f2923 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -5,7 +5,6 @@ import type { ComponentChildren } from "preact";
import { useCallback, useLayoutEffect, useRef, useState } from "preact/hooks";
import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
-import { isMobile } from "../../services/utils";
import { FormDropdownDivider, FormDropdownSubmenu, FormListCustomItem, FormListHeader, FormListItem } from "./FormList";
import { type ActiveRow, isRightToLeft, MenuContext, type MenuContextValue, type OpenSubmenu, pointerMoved, type RowEntry, shouldDropStart } from "./menu_context";
import Popup, { type PopupProps } from "./Popup";
@@ -206,28 +205,19 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
setActive(closing - 1, parent.id);
};
const rtl = isRightToLeft();
- /** Moves to the row beside the active one in a menu laid out in columns, if there is one. */
- const moveAcross = (towards: "left" | "right") => {
- const boxes = levelRows.map((rowId) => rows.get(rowId)?.element.getBoundingClientRect());
- const target = rowInNextColumn(boxes, index, towards);
- const rowId = target !== undefined ? levelRows[target] : undefined;
- if (rowId) moveTo(rowId);
- return !!rowId;
- };
switch (e.key) {
case "ArrowDown": goTo(index + 1); break;
case "ArrowUp": goTo(index < 0 ? -1 : index - 1); break;
case "Home": goTo(0); break;
case "End": goTo(-1); break;
- // Into the active row's submenu, or else across to the next column.
+ // Into the active row's submenu.
case rtl ? "ArrowLeft" : "ArrowRight":
- if (activeRow && !activeRow.custom && activeRow.hasSubmenu) openActive();
- else moveAcross(e.key === "ArrowRight" ? "right" : "left");
+ openActive();
break;
- // Back across a column, or else out of the submenu.
+ // Out of the submenu.
case rtl ? "ArrowRight" : "ArrowLeft":
- if (!moveAcross(e.key === "ArrowRight" ? "right" : "left") && level > 0) closeLevel(level);
+ if (level > 0) closeLevel(level);
break;
case "Enter":
case " ":
@@ -320,30 +310,12 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
);
}
-/**
- * `items` drawn as the rows that stand for them, with a run of separators reduced to one. In
- * `columns`, the rows a column must not break between are wrapped in `.dropdown-no-break`.
- */
-function MenuItems<T>({ items, onSelect, columns }: {
+/** `items` drawn as the rows that stand for them, with a run of separators reduced to one. */
+function MenuItems<T>({ items, onSelect }: {
items: MenuItem<T>[],
- onSelect: MenuProps<T>["onSelect"],
- columns?: boolean
+ onSelect: MenuProps<T>["onSelect"]
}) {
- const rows = menuRows(items);
- if (!columns) return <>{rows.map((row, index) => <MenuItemRow key={index} row={row} onSelect={onSelect} />)}</>;
-
- return <>
- {unbreakableGroups(rows).map((group, groupIndex) => (group.length > 1
- ? (
- <li key={groupIndex} className="dropdown-no-break" role="none">
- <menu role="none">
- {group.map((row, index) => <MenuItemRow key={index} row={row} onSelect={onSelect} />)}
- </menu>
- </li>
- )
- : <MenuItemRow key={groupIndex} row={group[0]} onSelect={onSelect} />
- ))}
- </>;
+ return <>{menuRows(items).map((row, index) => <MenuItemRow key={index} row={row} onSelect={onSelect} />)}</>;
}
function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuProps<T>["onSelect"] }) {
@@ -363,11 +335,10 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
if (items) {
return (
<FormDropdownSubmenu
- icon={uiIcon ?? "bx bx-empty"} title={label} columns={row.columns} disabled={enabled === false}
+ icon={uiIcon ?? "bx bx-empty"} title={label} 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()} />
+ <MenuItems items={items} onSelect={onSelect} />
</FormDropdownSubmenu>
);
}
@@ -386,44 +357,6 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
);
}
-/** How far apart, in pixels, two rows' left edges can be and still stand in one column. */
-const COLUMN_TOLERANCE = 1;
-
-/**
- * In a menu laid out in columns, the index of the row beside `boxes[index]` in the nearest column
- * towards `towards`: the one whose middle is nearest its middle. The browser decides where CSS
- * columns break, so the rows' boxes are all there is to go by. Rows without a box are passed over.
- */
-export function rowInNextColumn(
- boxes: (Pick<DOMRect, "left" | "top" | "bottom"> | undefined)[],
- index: number,
- towards: "left" | "right"
-): number | undefined {
- const from = boxes[index];
- if (!from) return undefined;
-
- const middle = (box: Pick<DOMRect, "top" | "bottom">) => (box.top + box.bottom) / 2;
- const beyond: { box: Pick<DOMRect, "left" | "top" | "bottom">, index: number }[] = [];
- for (const [ candidateIndex, box ] of boxes.entries()) {
- if (!box) continue;
- const offset = box.left - from.left;
- if (towards === "right" ? offset > COLUMN_TOLERANCE : offset < -COLUMN_TOLERANCE) {
- beyond.push({ box, index: candidateIndex });
- }
- }
- if (!beyond.length) return undefined;
-
- const lefts = beyond.map(({ box }) => box.left);
- const columnLeft = towards === "right" ? Math.min(...lefts) : Math.max(...lefts);
- let nearest: { box: Pick<DOMRect, "left" | "top" | "bottom">, index: number } | undefined;
- for (const candidate of beyond) {
- if (Math.abs(candidate.box.left - columnLeft) > COLUMN_TOLERANCE) continue;
- const distance = Math.abs(middle(candidate.box) - middle(from));
- if (!nearest || distance < Math.abs(middle(nearest.box) - middle(from))) nearest = candidate;
- }
- return nearest?.index;
-}
-
/** Where a custom row takes focus: the element its content marks as its way in with `tabindex="0"`. */
function focusTarget(row: HTMLElement | undefined) {
return row?.querySelector<HTMLElement>("[tabindex='0']") ?? null;
@@ -440,29 +373,6 @@ function menuRows<T>(items: MenuItem<T>[]) {
return rows;
}
-/**
- * The rows split where a column can break: a row stays with the one before it when that one is a
- * header or a separator, or when it is a separator itself. Firefox ignores `break-before` and
- * `break-after: avoid` in columns, so a group is kept whole with `break-inside: avoid` instead.
- */
-function unbreakableGroups<T>(rows: MenuItem<T>[]) {
- const groups: MenuItem<T>[][] = [];
- for (const [ index, row ] of rows.entries()) {
- const previous = rows[index - 1];
- const lastGroup = groups.at(-1);
- if (previous && lastGroup && (isHeader(previous) || isSeparator(previous) || isSeparator(row))) {
- lastGroup.push(row);
- } else {
- groups.push([ row ]);
- }
- }
- return groups;
-}
-
function isSeparator<T>(item: MenuItem<T>) {
return "kind" in item && item.kind === "separator";
}
-
-function isHeader<T>(item: MenuItem<T>) {
- return "kind" in item && item.kind === "header";
-}