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
client/text editor: regroup clipboard commands in the context menu
Adorian Doran994633ee4b64
diff --git a/apps/client/src/menus/context_menu_utils.spec.ts b/apps/client/src/menus/context_menu_utils.spec.tsnew file mode 100644index 0000000000..e0860fa434--- /dev/null+++ b/apps/client/src/menus/context_menu_utils.spec.ts@@ -0,0 +1,58 @@+import { describe, expect, it, vi } from "vitest";++import { splitMenuItem, submenuItem } from "./context_menu_utils";++describe("submenuItem", () => {+ it("opens its items, and is enabled while any of their commands is", () => {+ const on = { title: "On" };+ const off = { title: "Off", enabled: false };+ const separator = { kind: "separator" as const };++ expect(submenuItem({ title: "Group", uiIcon: "bx bx-folder" }, [off, separator, on]))+ .toEqual({+ title: "Group",+ uiIcon: "bx bx-folder",+ enabled: true,+ items: [off, separator, on]+ });+ expect(submenuItem({ title: "Group" }, [off, separator]).enabled).toBe(false);+ });+});++describe("splitMenuItem", () => {+ it("runs its primary item, showing its shortcut, and lists it first in the submenu", () => {+ const primary = {+ title: "Copy",+ uiIcon: "bx bx-copy",+ shortcut: "Ctrl+C",+ handler: vi.fn()+ };+ const variant = { title: "Copy as Markdown", handler: vi.fn() };++ const row = splitMenuItem(primary, [variant]);++ expect(row).toMatchObject({+ title: "Copy",+ uiIcon: "bx bx-copy",+ shortcut: "Ctrl+C",+ enabled: true+ });+ expect(row.items).toEqual([primary, variant]);+ expect(row.handler).toBe(primary.handler);++ const configurable = splitMenuItem(+ { title: "Copy", keyboardShortcut: "copyNotesToClipboard" }, [variant]);+ expect(configurable.keyboardShortcut).toBe("copyNotesToClipboard");+ });++ it("only opens its submenu while the primary item is disabled", () => {+ const primary = { title: "Copy", enabled: false, handler: vi.fn() };++ const row = splitMenuItem(primary, [{ title: "Copy as Markdown" }]);+ expect(row.enabled).toBe(true);+ expect(row.handler).toBeUndefined();++ expect(splitMenuItem(primary, [{ title: "Copy as Markdown", enabled: false }]).enabled)+ .toBe(false);+ });+});diff --git a/apps/client/src/menus/context_menu_utils.ts b/apps/client/src/menus/context_menu_utils.tsindex 9a8043888e..d6b86f718e 100644--- a/apps/client/src/menus/context_menu_utils.ts+++ b/apps/client/src/menus/context_menu_utils.ts@@ -1,5 +1,5 @@import type FNote from "../entities/fnote"-import type { MenuItem } from "./context_menu"+import type { MenuCommandItem, MenuItem } from "./context_menu"import { t } from "../services/i18n"import { setArchivedOnNotes, shared } from "../services/note_set"import { escapeHtml } from "../services/utils"@@ -38,3 +38,32 @@ export function getArchiveMenuItems<T>(notes: FNote[]): MenuItem<T>[] {export function menuName(name: string) {return `<span class="tn-menu-name">${escapeHtml(name)}</span>`}++/** A row that opens `items` as a submenu, enabled while any of their commands is. */+export function submenuItem<T>(+ row: Pick<MenuCommandItem<T>, "title" | "uiIcon">,+ items: MenuItem<T>[]+): MenuCommandItem<T> {+ return { ...row, enabled: items.some(isEnabledCommand), items }+}++/**+ * A row that runs `primary` when clicked and opens `primary` and its `variants` as a submenu. The+ * row shows the shortcut of `primary`. The submenu lists `primary` again because a tap on a touch+ * device only unfolds a submenu row. While `primary` is disabled, the row only opens the submenu.+ */+export function splitMenuItem<T>(+ primary: MenuCommandItem<T>,+ variants: MenuItem<T>[]+): MenuCommandItem<T> {+ return {+ ...submenuItem({ title: primary.title, uiIcon: primary.uiIcon }, [ primary, ...variants ]),+ shortcut: primary.shortcut,+ keyboardShortcut: primary.keyboardShortcut,+ handler: primary.enabled === false ? undefined : primary.handler+ }+}++function isEnabledCommand<T>(item: MenuItem<T>) {+ return !("kind" in item) && item.enabled !== false+}diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex dc516e5145..494410f6c5 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -139,6 +139,11 @@ function run(items: MenuItem<any>[], title: string): void | Promise<void> {return findItem(items, title)?.handler?.({} as never, {} as never);}+/** The rows of the submenu that the row titled `title` opens. */+function submenu(items: MenuItem<any>[], title: string): MenuItem<any>[] {+ return findItem(items, title)?.items ?? [];+}+describe("buildNoteContextMenuItems", () => {beforeEach(() => {vi.clearAllMocks();@@ -151,11 +156,46 @@ describe("buildNoteContextMenuItems", () => {expect(titles(items)).toEqual(["electron_context_menu.copy",- "electron_context_menu.copy-as-markdown","---","electron_context_menu.search_online","electron_context_menu.search_in_trilium"]);+ expect(titles(submenu(items, "electron_context_menu.copy"))).toEqual([+ "electron_context_menu.copy",+ "electron_context_menu.copy-as-markdown"+ ]);+ });++ it("groups the copy and paste variants under rows that copy or paste on a click", async () => {+ const host = browserLikeHost({+ paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn(), read: vi.fn() }+ });+ const items = await build({ isEditable: true }, host);++ expect(titles(items)).toEqual([+ "electron_context_menu.cut",+ "electron_context_menu.copy",+ "electron_context_menu.paste",+ "---",+ "electron_context_menu.search_online",+ "electron_context_menu.search_in_trilium"+ ]);+ expect(titles(submenu(items, "electron_context_menu.paste"))).toEqual([+ "electron_context_menu.paste",+ "electron_context_menu.paste-as-plain-text"+ ]);+ expect(findItem(items, "electron_context_menu.copy"))+ .toMatchObject({ uiIcon: "bx bx-copy", shortcut: "Ctrl+C" });+ expect(findItem(items, "electron_context_menu.paste"))+ .toMatchObject({ uiIcon: "bx bx-paste", shortcut: "Ctrl+V" });++ run(items, "electron_context_menu.copy");+ expect(host.copy).toHaveBeenCalledTimes(1);+ run(items, "electron_context_menu.paste");+ expect(host.paste?.run).toHaveBeenCalledTimes(1);+ run(submenu(items, "electron_context_menu.paste"),+ "electron_context_menu.paste-as-plain-text");+ expect(host.paste?.runAsPlainText).toHaveBeenCalledTimes(1);});it("omits the spelling and paste rows when the host does not supply them", async () => {@@ -184,7 +224,8 @@ describe("buildNoteContextMenuItems", () => {// The suggestions carry a command rather than a handler: only the host can commit one.expect(findItem(items, "the")?.command).toBe("replaceMisspelling");expect(findItem(items, "the")?.spellingSuggestion).toBe("the");- expect(titles(items)).toContain("electron_context_menu.paste-as-plain-text");+ expect(titles(submenu(items, "electron_context_menu.paste")))+ .toContain("electron_context_menu.paste-as-plain-text");run(items, "electron_context_menu.add-term-to-dictionary");expect(addToDictionary).toHaveBeenCalledWith("teh");@@ -241,11 +282,7 @@ describe("buildNoteContextMenuItems", () => {"---","electron_context_menu.cut","electron_context_menu.copy",- "electron_context_menu.copy-as-markdown","electron_context_menu.paste",- "electron_context_menu.paste-as-plain-text",- "PR1",- "PR2","---","S","---",@@ -257,6 +294,14 @@ describe("buildNoteContextMenuItems", () => {"electron_context_menu.search_online","electron_context_menu.search_in_trilium"]);+ // The table's paste rows join the paste variants, as a group of their own.+ expect(titles(submenu(items, "electron_context_menu.paste"))).toEqual([+ "electron_context_menu.paste",+ "electron_context_menu.paste-as-plain-text",+ "---",+ "PR1",+ "PR2"+ ]);});it("skips the table section for a non-editable target", async () => {@@ -270,7 +315,8 @@ describe("buildNoteContextMenuItems", () => {setSelection(document.createElement("span"), "<h1>Hi</h1>");const items = await build();- await run(items, "electron_context_menu.copy-as-markdown");+ await run(submenu(items, "electron_context_menu.copy"),+ "electron_context_menu.copy-as-markdown");expect(server.post).toHaveBeenCalledWith("other/to-markdown", {htmlContent: "<h1>Hi</h1>",@@ -290,16 +336,19 @@ describe("buildNoteContextMenuItems", () => {} as TableMenuSections);// No cell selection and no text: the rows show but stay disabled.+ const copyRows = (items: MenuItem<any>[]) => [+ findItem(items, "electron_context_menu.cut")?.enabled,+ findItem(items, "electron_context_menu.copy")?.enabled,+ ...submenu(items, "electron_context_menu.copy")+ .map((item) => (item as MenuCommandItem<any>).enabled)+ ];+const disabled = await build({ isEditable: true, element: cell, selectionText: "" });- expect(findItem(disabled, "electron_context_menu.cut")?.enabled).toBe(false);- expect(findItem(disabled, "electron_context_menu.copy")?.enabled).toBe(false);- expect(findItem(disabled, "electron_context_menu.copy-as-markdown")?.enabled).toBe(false);+ expect(copyRows(disabled)).toEqual([ false, false, false, false ]);vi.mocked(hasTableCellSelection).mockResolvedValue(true);const enabled = await build({ isEditable: true, element: cell, selectionText: "" });- expect(findItem(enabled, "electron_context_menu.cut")?.enabled).toBe(true);- expect(findItem(enabled, "electron_context_menu.copy")?.enabled).toBe(true);- expect(findItem(enabled, "electron_context_menu.copy-as-markdown")?.enabled).toBe(true);+ expect(copyRows(enabled)).toEqual([ true, true, true, true ]);vi.mocked(buildTableContextMenuSections).mockResolvedValue(null);vi.mocked(hasTableCellSelection).mockResolvedValue(false);@@ -591,7 +640,8 @@ describe("setupContextMenu (browser)", () => {expect(editor.pasteTarget.paste).toHaveBeenCalledWith("<b>hi</b>", "hi"));// Paste as plain text withholds the HTML flavor.- await run(rows, "electron_context_menu.paste-as-plain-text");+ await run(submenu(rows, "electron_context_menu.paste"),+ "electron_context_menu.paste-as-plain-text");await vi.waitFor(() =>expect(editor.pasteTarget.paste).toHaveBeenCalledWith("", "hi"));expect(editor.pasteTarget.release).toHaveBeenCalledTimes(2);@@ -682,11 +732,12 @@ describe("setupContextMenu (browser)", () => {tabManager.activeNote = { type: "code" };setSelection(content, "<span>code</span>", "code");- const shown = titles(await menuFor(content));+ const rows = await menuFor(content);- expect(shown).not.toContain("electron_context_menu.cut");- expect(shown).toContain("electron_context_menu.copy");- expect(shown).toContain("electron_context_menu.copy-as-markdown");+ expect(titles(rows)).not.toContain("electron_context_menu.cut");+ expect(titles(rows)).toContain("electron_context_menu.copy");+ expect(titles(submenu(rows, "electron_context_menu.copy")))+ .toContain("electron_context_menu.copy-as-markdown");});it("takes the menu over for a selection, and reads the link under the pointer", async () => {@@ -703,7 +754,6 @@ describe("setupContextMenu (browser)", () => {const shown = vi.mocked(contextMenu.show).mock.calls[0][0];expect(titles(shown.items)).toEqual(["electron_context_menu.copy",- "electron_context_menu.copy-as-markdown","electron_context_menu.copy-link","---","electron_context_menu.search_online",diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex e8cff7ff95..1a56b29fe4 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -7,6 +7,7 @@ import options from "../services/options.js";import server from "../services/server.js";import utils from "../services/utils.js";import contextMenu, { type MenuItem } from "./context_menu.js";+import { splitMenuItem } from "./context_menu_utils.js";import { buildTableContextMenuSections, hasTableCellSelection } from "./table_context_menu.js";import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";@@ -177,20 +178,22 @@ export async function buildNoteContextMenuItems(}if (target.isEditable || hasText) {- items.push({+ const copyVariants: MenuItem<CommandNames>[] = [+ {+ enabled: hasClipboardContent,+ title: t("electron_context_menu.copy-as-markdown"),+ uiIcon: "bx bx-copy-alt",+ handler: copySelectionAsMarkdown+ }+ ];++ items.push(splitMenuItem({enabled: host.canCopy && hasClipboardContent,title: t("electron_context_menu.copy"),shortcut: `${platformModifier}+C`,uiIcon: "bx bx-copy",handler: () => host.copy()- });-- items.push({- enabled: hasClipboardContent,- title: t("electron_context_menu.copy-as-markdown"),- uiIcon: "bx bx-copy-alt",- handler: copySelectionAsMarkdown- });+ }, copyVariants));}const unlinkable = [ "", "javascript:", "about:blank#blocked" ];@@ -208,26 +211,26 @@ export async function buildNoteContextMenuItems(if (host.paste && target.isEditable) {const { enabled, run, runAsPlainText } = host.paste;+ const pasteVariants: MenuItem<CommandNames>[] = [+ {+ enabled,+ title: t("electron_context_menu.paste-as-plain-text"),+ shortcut: `${platformModifier}+Shift+V`,+ uiIcon: "bx bx-paste",+ handler: runAsPlainText+ }+ ];+ if (tableSections?.pasteRows.length) {+ pasteVariants.push({ kind: "separator" }, ...tableSections.pasteRows);+ }- items.push({+ items.push(splitMenuItem({enabled,title: t("electron_context_menu.paste"),shortcut: `${platformModifier}+V`,uiIcon: "bx bx-paste",handler: run- });-- items.push({- enabled,- title: t("electron_context_menu.paste-as-plain-text"),- shortcut: `${platformModifier}+Shift+V`,- uiIcon: "bx bx-paste",- handler: runAsPlainText- });-- if (tableSections) {- items.push(...tableSections.pasteRows);- }+ }, pasteVariants));}if (tableSections) {diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.tsindex 98b0cf2ea8..d82c387bf7 100644--- a/apps/client/src/menus/table_context_menu.ts+++ b/apps/client/src/menus/table_context_menu.ts@@ -3,6 +3,7 @@ import type { CKTextEditor } from "@triliumnext/ckeditor5";import type { CommandNames } from "../components/app_context.js";import { t } from "../services/i18n.js";import type { MenuItem } from "./context_menu.js";+import { submenuItem } from "./context_menu_utils.js";import { getTextEditorContaining } from "./text_editor_context_menu.js";/**@@ -96,33 +97,27 @@ export function buildTableMenuSections(...(headerItem ? [headerItem] : []),commandItem(t("table_context_menu.merge_cells"), "bx bx-border-outer","mergeTableCells"),- {- title: t("table_context_menu.split_cells"),- uiIcon: "bx bx-border-inner",- enabled: [...splitItems, unmergeItem].some((item) => item.enabled),- items: [...splitItems, { kind: "separator" }, unmergeItem]- },+ submenuItem(+ { title: t("table_context_menu.split_cells"), uiIcon: "bx bx-border-inner" },+ [...splitItems, { kind: "separator" }, unmergeItem]+ ),commandItem(t("table_context_menu.distribute_columns"), "bx bx-move-horizontal","triliumDistributeTableColumns")],- sort: {- title: t("table_context_menu.sort"),- uiIcon: "bx bx-sort-alt-2",- enabled: sortItems.some((item) => item.enabled),- items: sortItems- },+ sort: submenuItem(+ { title: t("table_context_menu.sort"), uiIcon: "bx bx-sort-alt-2" },+ sortItems+ ),delete: [commandItem(t("table_context_menu.delete_rows"), "bx bx-trash", "removeTableRow"),commandItem(t("table_context_menu.delete_columns"), "bx bx-trash","removeTableColumn"),commandItem(t("table_context_menu.delete_table"), "bx bx-trash", "triliumDeleteTable")],- select: {- title: t("table_context_menu.select"),- uiIcon: "bx bx-select-multiple",- enabled: selectItems.some((item) => item.enabled),- items: selectItems- },+ select: submenuItem(+ { title: t("table_context_menu.select"), uiIcon: "bx bx-select-multiple" },+ selectItems+ ),pasteRows: buildPasteRowsItems(editor, clipboard)};}@@ -149,9 +144,9 @@ export interface TableMenuSections {/** Selection of the spanned rows or columns, or of the whole table. Shown below deletion. */select: MenuItem<CommandNames>;/**- * Pasting the clipboard as new rows above or below the row of the selection. Shown below the- * paste rows of the clipboard section; empty unless the selection is in one row and the host- * can read the clipboard.+ * Pasting the clipboard as new rows above or below the row of the selection. Shown in the+ * _Paste_ submenu; empty unless the selection is in one row and the host can read the+ * clipboard.*/pasteRows: MenuItem<CommandNames>[];}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.htmlindex bb2c076c47..e85b531f8f 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html@@ -58,7 +58,9 @@ src="3_Tables_image.png" width="384" height="100">of the table stay as they are. It needs a selection spanning at least twocolumns; a merged cell counts for every column it covers.</li><li><em>Cut</em>, <em>Copy</em> and <em>Copy as Markdown</em> act on the selected- cells:+ cells. Since v0.107.0, <em>Copy</em> and <em>Paste</em> open submenus with+ their variants, such as <em>Copy as Markdown</em> and <em>Paste as plain text</em>;+ clicking <em>Copy</em> or <em>Paste</em> itself still copies or pastes:<ul><li>Cutting or copying produces a smaller table holding just the selectedcells. Pasting it over a cell selection replaces those cells; pasting elsewhere@@ -70,9 +72,9 @@ src="3_Tables_image.png" width="384" height="100"></ul></li><li>Since v0.107.0, <em>Paste rows above</em> and <em>Paste rows below</em>,- after <em>Paste as plain text</em>, paste the clipboard as new rows next- to the row of the current cell, instead of over the cells from the cursor- on. They show only when the selection is in a single row, and, like <em>Paste</em>,+ in the <em>Paste</em> submenu, paste the clipboard as new rows next to the+ row of the current cell, instead of over the cells from the cursor on.+ They show only when the selection is in a single row, and, like <em>Paste</em>,only where the clipboard can be read:<ul><li>A copied table becomes one new row for each of its rows, filled from thediff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex b5759ea937..0fe8bd9903 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -33,10 +33,10 @@ Since v0.106.0, right-clicking anywhere inside a table opens a context menu with* _Merge cells_ merges the selected cells into one. The selected cells must form a rectangle.* _Split cell_ splits each selected cell in two, either _Vertically_ or _Horizontally_. _Unmerge cells_, in the same submenu, turns each merged cell in the selection back into the single cells it covers, keeping its content in the top-left one; cells that are not merged stay as they are.* _Distribute columns evenly_ splits the combined width of the columns the selection touches equally between them. The other columns and the width of the table stay as they are. It needs a selection spanning at least two columns; a merged cell counts for every column it covers.-* _Cut_, _Copy_ and _Copy as Markdown_ act on the selected cells:+* _Cut_, _Copy_ and _Copy as Markdown_ act on the selected cells. Since v0.107.0, _Copy_ and _Paste_ open submenus with their variants, such as _Copy as Markdown_ and _Paste as plain text_; clicking _Copy_ or _Paste_ itself still copies or pastes:* Cutting or copying produces a smaller table holding just the selected cells. Pasting it over a cell selection replaces those cells; pasting elsewhere inserts it as a table of its own. Cutting clears the cells without removing rows or columns.* _Copy as Markdown_ converts the selected cells to a Markdown table. A selected header row becomes the Markdown header; without one, an empty header row is emitted, since Markdown tables require one.-* Since v0.107.0, _Paste rows above_ and _Paste rows below_, after _Paste as plain text_, paste the clipboard as new rows next to the row of the current cell, instead of over the cells from the cursor on. They show only when the selection is in a single row, and, like _Paste_, only where the clipboard can be read:+* Since v0.107.0, _Paste rows above_ and _Paste rows below_, in the _Paste_ submenu, paste the clipboard as new rows next to the row of the current cell, instead of over the cells from the cursor on. They show only when the selection is in a single row, and, like _Paste_, only where the clipboard can be read:* A copied table becomes one new row for each of its rows, filled from the first column. When it has more columns than the table, the table gains columns, as with a regular paste. Other content goes in the first cell of a single new row.* The new rows are selected afterwards.* When merged cells join the row to others, the new rows go above or below that whole block of rows.