Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(menu): keep a column submenu's headers and separators with their rows
Elian Doran12b3fe552d30
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex 5511cbbb51..4b88057a7f 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -448,6 +448,42 @@ describe("contextMenu", () => {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.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 > ul"))).toEqual([+ "Text", "Code", "---", "Templates", "Meeting", "Weekly"+ ]);+ });+it("unfolds a submenu under its row on a phone", async () => {layout.onMobile = true;const picked: string[] = [];diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.tsindex c94c3034bb..5731e9680d 100644--- a/apps/client/src/menus/context_menu_legacy.ts+++ b/apps/client/src/menus/context_menu_legacy.ts@@ -119,66 +119,9 @@ class ContextMenu {this.addItems(this.$widget, options.items);}- 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- let shouldResetGroup = false; // If true, the next item will be the last one from the group- let prevItemKind: string = "";-- for (let index = 0; index < items.length; index++) {- const item = items[index];- const itemKind = ("kind" in item) ? item.kind : "";-- if (!item) {- continue;- }-- // If the current item is a header, start a new group. This group will contain the- // header and the next item that follows the header.- if (itemKind === "header") {- if (multicolumn && !shouldResetGroup) {- shouldStartNewGroup = true;- }- }-- // If the next item is a separator, start a new group. This group will contain the- // current item, the separator, and the next item after the separator.- const nextItem = (index < items.length - 1) ? items[index + 1] : null;- if (multicolumn && nextItem && "kind" in nextItem && nextItem.kind === "separator") {- if (!shouldResetGroup) {- shouldStartNewGroup = true;- } else {- shouldResetGroup = true; // Continue the current group- }- }-- // Create a new group to avoid column breaks before and after the seaparator / header.- // This is a workaround for Firefox not supporting break-before / break-after: avoid- // for columns.- if (shouldStartNewGroup) {- $group = $("<div class='dropdown-no-break'>");- $parent.append($group);- shouldStartNewGroup = false;- }-- if (itemKind === "separator") {- $group.append($("<div>").addClass("dropdown-divider"));- shouldResetGroup = true; // End the group after the next item- } else if (itemKind === "header") {- shouldResetGroup = true;- } else {- $group.append(this.createMenuItem(item as MenuCommandItem<any>));-- // After adding a menu item, if the previous item was a separator or header,- // reset the group so that the next item will be appended directly to the parent.- if (shouldResetGroup) {- $group = $parent;- shouldResetGroup = false;- };- }-- prevItemKind = itemKind;-+ addItems($parent: JQuery<HTMLElement>, items: MenuItem<any>[]) {+ for (const item of items) {+ if (!("kind" in item)) $parent.append(this.createMenuItem(item));}}diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex fefbbe3411..2ada6933d5 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -116,7 +116,7 @@ function SubmenuLayer<T>({ level, submenu, state }: { level: number, submenu: Op// 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} />+ <MenuList level={level} items={items} state={state} columns /></div>): <MenuList level={level} items={items} state={state} />}@@ -125,21 +125,39 @@ function SubmenuLayer<T>({ level, submenu, state }: { level: number, submenu: Op);}-function MenuList<T>({ level, items, state }: { level: number, items: MenuItem<T>[], state: MenuState<T> }) {+function MenuList<T>({ level, items, state, columns }: {+ level: number,+ items: MenuItem<T>[],+ state: MenuState<T>,+ /** Wraps the rows a column must not break between in `.dropdown-no-break`. */+ columns?: boolean+}) {+ const rows = menuRows(items);+ if (!columns) return <>{rows.map((row, index) => <MenuListRow key={index} level={level} row={row} state={state} />)}</>;+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>- );- })}+ {unbreakableGroups(rows).map((group, groupIndex) => (group.length > 1+ ? (+ <div key={groupIndex} className="dropdown-no-break">+ {group.map((row, index) => <MenuListRow key={index} level={level} row={row} state={state} />)}+ </div>+ )+ : <MenuListRow key={groupIndex} level={level} row={group[0]} state={state} />+ ))}</>;}+function MenuListRow<T>({ level, row, state }: { level: number, row: MenuItem<T>, state: MenuState<T> }) {+ if (!("kind" in row)) return <MenuRow level={level} item={row} state={state} />;+ if (row.kind === "separator") return <div className="dropdown-divider" role="separator" />;+ if (row.kind === "header") return <h6 className="dropdown-header">{row.title}</h6>;+ return (+ <li 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;@@ -238,10 +256,33 @@ 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";+}+/*** 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.