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/tables: add a context menu with improved editing commands
Adorian Doran95728363f310
diff --git a/apps/client/src/menus/electron_context_menu.ts b/apps/client/src/menus/electron_context_menu.tsindex 4cb9626b6a..b4a00aafbf 100644--- a/apps/client/src/menus/electron_context_menu.ts+++ b/apps/client/src/menus/electron_context_menu.ts@@ -16,20 +16,23 @@ function setupContextMenu() {const api = eApi.contextMenu;api.onContextMenu(async (params) => {+ // The IPC params carry window coordinates only, so the element under the pointer is read+ // back from the page; the zoom factor maps them onto CSS pixels.+ const zoomLevel = zoomService.getCurrentZoom();+const items = await buildNoteContextMenuItems({linkURL: params.linkURL,linkText: params.linkText,isMedia: params.mediaType !== "none",isEditable: params.isEditable,- selectionText: params.selectionText+ selectionText: params.selectionText,+ element: document.elementFromPoint(params.x / zoomLevel, params.y / zoomLevel)}, electronHost(eApi, params));if (items.length === 0) {return;}- const zoomLevel = zoomService.getCurrentZoom();-contextMenu.show({x: params.x / zoomLevel,y: params.y / zoomLevel,diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex aa4df9c271..7be66c61b7 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -27,10 +27,14 @@ vi.mock("../services/utils.js", () => ({default: { escapeHtml: (s: string) => s, isMac: () => false }}));vi.mock("./context_menu.js", () => ({ default: { show: vi.fn() } }));+vi.mock("./table_context_menu.js", () => ({+ buildTableContextMenuItems: vi.fn(async () => null)+}));import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";import server from "../services/server.js";import contextMenu, { type MenuCommandItem, type MenuItem } from "./context_menu.js";+import { buildTableContextMenuItems } from "./table_context_menu.js";import {buildNoteContextMenuItems,type ContextMenuHost,@@ -204,6 +208,37 @@ describe("buildNoteContextMenuItems", () => {});});+ it("puts the table section ahead of the clipboard rows and hands it the element", async () => {+ const cell = document.createElement("td");+ vi.mocked(buildTableContextMenuItems).mockResolvedValueOnce([+ { title: "T1" },+ { kind: "separator" },+ { title: "T2" }+ ] as MenuItem<any>[]);++ const items = await build({ isEditable: true, element: cell });++ expect(buildTableContextMenuItems).toHaveBeenCalledWith(cell);+ expect(titles(items)).toEqual([+ "T1",+ "---",+ "T2",+ "---",+ "electron_context_menu.cut",+ "electron_context_menu.copy",+ "electron_context_menu.copy-as-markdown",+ "---",+ "electron_context_menu.search_online",+ "electron_context_menu.search_in_trilium"+ ]);+ });++ it("skips the table section for a non-editable target", async () => {+ await build({ element: document.createElement("td") });++ expect(buildTableContextMenuItems).not.toHaveBeenCalled();+ });+it("converts the selection through the to-markdown route", async () => {vi.mocked(server.post).mockResolvedValue({ markdownContent: "# Hi" });setSelection(document.createElement("span"), "<h1>Hi</h1>");@@ -274,6 +309,63 @@ describe("setupContextMenu (browser)", () => {return vi.mocked(contextMenu.show).mock.calls[0][0].items;}+ /** A table cell inside an editable, the target a table-section click lands on. */+ function editableTableCell(readOnly = false) {+ const content = codeEditable(readOnly);+ const table = document.createElement("table");+ const row = document.createElement("tr");+ const cell = document.createElement("td");+ cell.textContent = "cell";+ row.appendChild(cell);+ table.appendChild(row);+ content.appendChild(table);+ return cell;+ }++ it("claims a bare-caret right-click on an editable table cell", async () => {+ const cell = editableTableCell();+ setSelection(null, "", "");+ vi.mocked(buildTableContextMenuItems).mockResolvedValueOnce([+ { title: "table_context_menu.merge_cells" }+ ] as MenuItem<any>[]);++ const event = rightClick(cell);++ expect(event.defaultPrevented).toBe(true);+ await vi.waitFor(() => expect(contextMenu.show).toHaveBeenCalled());+ const shown = vi.mocked(contextMenu.show).mock.calls[0][0];+ expect(titles(shown.items)).toContain("table_context_menu.merge_cells");+ expect(buildTableContextMenuItems).toHaveBeenCalledWith(cell);+ });++ it("leaves a table cell to the browser when read-only, non-editable, or Shift is held", async () => {+ setSelection(null, "", "");++ expect(rightClick(editableTableCell(true)).defaultPrevented).toBe(false);++ const bareCell = document.createElement("td");+ document.body.appendChild(bareCell);+ expect(rightClick(bareCell).defaultPrevented).toBe(false);++ expect(rightClick(editableTableCell(), { shiftKey: true }).defaultPrevented).toBe(false);++ await settle();+ expect(contextMenu.show).not.toHaveBeenCalled();+ });++ it("still claims the cell when the table section resolves empty", async () => {+ const cell = editableTableCell();+ setSelection(null, "", "");++ const event = rightClick(cell);++ expect(event.defaultPrevented).toBe(true);+ await vi.waitFor(() => expect(contextMenu.show).toHaveBeenCalled());+ const shown = titles(vi.mocked(contextMenu.show).mock.calls[0][0].items);+ expect(shown).not.toContain("table_context_menu.merge_cells");+ expect(shown).toContain("electron_context_menu.copy");+ });+it("leaves the browser's own menu up when nothing is selected", async () => {const div = document.createElement("div");document.body.appendChild(div);diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex c2ba4438a5..00c03f67fa 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 { buildTableContextMenuItems } from "./table_context_menu.js";import { buildAiActionsMenuItem, getTextEditorAtSelection } from "./text_editor_context_menu.js";/** What the pointer was over when the menu was summoned. */@@ -21,6 +22,8 @@ export interface ContextMenuTarget {isEditable: boolean;/** The selected text, or an empty string. */selectionText: string;+ /** The element under the pointer, when the host can resolve one. */+ element?: Element | null;}/**@@ -66,32 +69,39 @@ export function setupContextMenu() {return;}+ const element = event.target instanceof HTMLElement ? event.target : null;+ const isEditable = acceptsTyping(element);+// `window.getSelection()` does not report a selection inside an `<input>` or `<textarea>`,// so those keep the browser's menu, which is the better one for a plain text field.+ // The clipboard and search rows act on the selection, so the pointer has to be on it: a+ // right-click on the surrounding UI, which takes no selection of its own, leaves an+ // earlier one standing.const selection = window.getSelection();const selectionText = selection?.toString() ?? "";- if (!selection || !selectionText.trim()) {- return;- }+ const isOnSelection = !!selection && !!selectionText.trim()+ && isPointInSelection(selection, event.clientX, event.clientY);- // The rows act on the selection, so the pointer has to be on it. A right-click on the- // surrounding UI, which takes no selection of its own, leaves an earlier one standing.- if (!isPointInSelection(selection, event.clientX, event.clientY)) {+ // A table cell in the text editor is claimed even at a bare caret, for the table section.+ const isOnEditableTableCell = isEditable && !!element?.closest("td, th");++ if (!isOnSelection && !isOnEditableTableCell) {return;}// Claimed before the items are built: after an await the default action has already run.event.preventDefault();- const element = event.target instanceof HTMLElement ? event.target : null;const link = element?.closest("a[href]");void showBrowserContextMenu(event.pageX, event.pageY, {linkURL: link instanceof HTMLAnchorElement ? link.href : "",linkText: link?.textContent ?? "",isMedia: !!element?.closest("img, video, audio"),- isEditable: acceptsTyping(element),- selectionText+ isEditable,+ // Claimed off the selection (a bare caret in a table cell), those rows get none.+ selectionText: isOnSelection ? selectionText : "",+ element});});}@@ -115,6 +125,7 @@ export async function buildNoteContextMenuItems(// depend on how the editor answers, and `isEditable` keeps the lookup off every click that// lands somewhere a completion could not be committed anyway (a read-only note, the tree).const aiActions = target.isEditable ? await buildAiActionsMenuItem() : null;+ const tableItems = target.isEditable ? await buildTableContextMenuItems(target.element) : null;if (host.spelling?.misspelledWord) {const { misspelledWord, suggestions, addToDictionary } = host.spelling;@@ -141,6 +152,10 @@ export async function buildNoteContextMenuItems(items.push(aiActions, { kind: "separator" });}+ if (tableItems) {+ items.push(...tableItems, { kind: "separator" });+ }+if (target.isEditable) {items.push({enabled: host.canCut && hasText,diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.tsnew file mode 100644index 0000000000..47fa44501d--- /dev/null+++ b/apps/client/src/menus/table_context_menu.spec.ts@@ -0,0 +1,169 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));+vi.mock("./text_editor_context_menu.js", () => ({ getTextEditorContaining: vi.fn() }));++import type { CKTextEditor } from "@triliumnext/ckeditor5";++import type { MenuCommandItem, MenuItem } from "./context_menu.js";+import { buildTableContextMenuItems, buildTableMenuItems } from "./table_context_menu.js";+import { getTextEditorContaining } from "./text_editor_context_menu.js";++const SECTION_TITLES = [+ "table_context_menu.insert_rows_above",+ "table_context_menu.insert_rows_below",+ "---",+ "table_context_menu.insert_columns_left",+ "table_context_menu.insert_columns_right",+ "---",+ "table_context_menu.delete_rows",+ "table_context_menu.delete_columns",+ "---",+ "table_context_menu.merge_cells",+ "table_context_menu.split_cells"+];++describe("buildTableMenuItems", () => {+ it("returns the section in order, with a split submenu", () => {+ const { editor, syncSelectionToDomTarget } = stubEditor();+ const element = cellElement();++ const items = buildTableMenuItems(editor, element) ?? [];++ expect(syncSelectionToDomTarget).toHaveBeenCalledWith(element);+ expect(titles(items)).toEqual(SECTION_TITLES);++ const submenu = findItem(items, "table_context_menu.split_cells")?.items ?? [];+ expect(titles(submenu)).toEqual([+ "table_context_menu.split_vertically",+ "table_context_menu.split_horizontally"+ ]);+ });++ it("executes the mapped command and refocuses the editor", () => {+ const { editor, executed, focus } = stubEditor();+ const items = buildTableMenuItems(editor, cellElement()) ?? [];+ const submenu = findItem(items, "table_context_menu.split_cells")?.items ?? [];++ for (const title of titles(items).filter((t) => t !== "---")) {+ run(items, title);+ }+ run(submenu, "table_context_menu.split_vertically");+ run(submenu, "table_context_menu.split_horizontally");++ expect(executed).toEqual([+ "triliumInsertTableRowsAbove",+ "triliumInsertTableRowsBelow",+ "triliumInsertTableColumnsLeft",+ "triliumInsertTableColumnsRight",+ "removeTableRow",+ "removeTableColumn",+ "mergeTableCells",+ "splitTableCellVertically",+ "splitTableCellHorizontally"+ ]);+ expect(focus).toHaveBeenCalledTimes(executed.length);+ });++ it("snapshots each row's enablement from its command", () => {+ const { editor } = stubEditor([+ "mergeTableCells",+ "splitTableCellVertically",+ "removeTableRow"+ ]);+ const items = buildTableMenuItems(editor, cellElement()) ?? [];++ expect(findItem(items, "table_context_menu.merge_cells")?.enabled).toBe(false);+ expect(findItem(items, "table_context_menu.split_cells")?.enabled).toBe(false);+ expect(findItem(items, "table_context_menu.delete_rows")?.enabled).toBe(false);+ expect(findItem(items, "table_context_menu.delete_columns")?.enabled).toBe(true);+ expect(findItem(items, "table_context_menu.insert_rows_above")?.enabled).toBe(true);+ });++ it("returns null without the plugin or a table cell at the target", () => {+ const { editor: withoutPlugin } = stubEditor([], { hasPlugin: false });+ expect(buildTableMenuItems(withoutPlugin, cellElement())).toBeNull();++ const { editor } = stubEditor([], { syncResult: false });+ expect(buildTableMenuItems(editor, cellElement())).toBeNull();+ });+});++describe("buildTableContextMenuItems", () => {+ const resolveEditor = vi.mocked(getTextEditorContaining);++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("ignores targets outside a table cell without resolving the editor", async () => {+ expect(await buildTableContextMenuItems(null)).toBeNull();+ expect(await buildTableContextMenuItems(document.createElement("div"))).toBeNull();+ expect(resolveEditor).not.toHaveBeenCalled();+ });++ it("builds the section for a cell target inside the active text editor", async () => {+ const { editor } = stubEditor();+ resolveEditor.mockResolvedValue(editor);+ const element = cellElement();++ const items = (await buildTableContextMenuItems(element)) ?? [];++ expect(resolveEditor).toHaveBeenCalledWith(element);+ expect(titles(items)).toEqual(SECTION_TITLES);+ });++ it("returns null when no text editor contains the target", async () => {+ resolveEditor.mockResolvedValue(null);+ expect(await buildTableContextMenuItems(cellElement())).toBeNull();+ });+});++/**+ * A minimal editor double: `TableContextMenu` is present unless `hasPlugin` says otherwise, and+ * every command is enabled except the ones in `disabledCommands`.+ */+function stubEditor(disabledCommands: string[] = [], { hasPlugin = true, syncResult = true } = {}) {+ const executed: string[] = [];+ const focus = vi.fn();+ const syncSelectionToDomTarget = vi.fn(() => syncResult);+ const editor = {+ plugins: {+ has: (name: string) => hasPlugin && name === "TableContextMenu",+ get: () => ({ syncSelectionToDomTarget })+ },+ commands: {+ get: (name: string) => ({ isEnabled: !disabledCommands.includes(name) })+ },+ execute: (name: string) => {+ executed.push(name);+ },+ editing: { view: { focus } }+ };++ return { editor: editor as unknown as CKTextEditor, executed, focus, syncSelectionToDomTarget };+}++/** A node nested inside a detached `<td>`, standing in for the right-click target. */+function cellElement(): Element {+ const cell = document.createElement("td");+ const inner = document.createElement("span");+ cell.appendChild(inner);+ return inner;+}++/** The titles of `items`, with separators rendered as "---" so ordering stays readable. */+function titles(items: MenuItem<any>[]) {+ return items.map((item) => ("kind" in item && item.kind === "separator"+ ? "---"+ : (item as MenuCommandItem<any>).title));+}++function findItem(items: MenuItem<any>[], title: string) {+ const found = items.find((item) => !("kind" in item) && item.title === title);+ return found as MenuCommandItem<any> | undefined;+}++function run(items: MenuItem<any>[], title: string) {+ findItem(items, title)?.handler?.({} as never, {} as never);+}diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.tsnew file mode 100644index 0000000000..7a0f38ca2a--- /dev/null+++ b/apps/client/src/menus/table_context_menu.ts@@ -0,0 +1,77 @@+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 { getTextEditorContaining } from "./text_editor_context_menu.js";++/**+ * The table section of the text editor's right-click menu: row and column insertion sized by the+ * selection, deletion of every spanned row or column, and merging or splitting of the selected+ * cells.+ *+ * Returns `null` when the click is not on a table cell of the active text editor.+ */+export async function buildTableContextMenuItems(+ element: Element | null | undefined+): Promise<MenuItem<CommandNames>[] | null> {+ if (!element?.closest("td, th")) {+ return null;+ }++ const editor = await getTextEditorContaining(element);+ return editor && buildTableMenuItems(editor, element);+}++/**+ * Builds the section against a resolved editor. The selection is first moved into the clicked+ * cell (and kept when the cell is already part of it), so the enablement snapshots and the+ * executed commands agree with the cell the menu is opened on.+ */+export function buildTableMenuItems(+ editor: CKTextEditor,+ element: Element+): MenuItem<CommandNames>[] | null {+ if (!editor.plugins.has("TableContextMenu")+ || !editor.plugins.get("TableContextMenu").syncSelectionToDomTarget(element)) {+ return null;+ }++ const commandItem = (title: string, uiIcon: string, commandName: string) => ({+ title,+ uiIcon,+ enabled: editor.commands.get(commandName)?.isEnabled === true,+ handler: () => {+ editor.execute(commandName);+ editor.editing.view.focus();+ }+ });++ return [+ commandItem(t("table_context_menu.insert_rows_above"),+ "bx bx-horizontal-left bx-rotate-90", "triliumInsertTableRowsAbove"),+ commandItem(t("table_context_menu.insert_rows_below"),+ "bx bx-horizontal-left bx-rotate-270", "triliumInsertTableRowsBelow"),+ { kind: "separator" },+ commandItem(t("table_context_menu.insert_columns_left"),+ "bx bx-horizontal-left", "triliumInsertTableColumnsLeft"),+ commandItem(t("table_context_menu.insert_columns_right"),+ "bx bx-horizontal-right", "triliumInsertTableColumnsRight"),+ { kind: "separator" },+ commandItem(t("table_context_menu.delete_rows"), "bx bx-trash", "removeTableRow"),+ commandItem(t("table_context_menu.delete_columns"), "bx bx-trash", "removeTableColumn"),+ { kind: "separator" },+ 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: editor.commands.get("splitTableCellVertically")?.isEnabled === true,+ items: [+ commandItem(t("table_context_menu.split_vertically"), "bx bx-empty",+ "splitTableCellVertically"),+ commandItem(t("table_context_menu.split_horizontally"), "bx bx-empty",+ "splitTableCellHorizontally")+ ]+ }+ ];+}diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsindex 336066b63f..9e9f5df9b4 100644--- a/apps/client/src/menus/text_editor_context_menu.ts+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -139,16 +139,26 @@ function buildQuickActionItems(* happily report its own stale model selection for it.*/export async function getTextEditorAtSelection(): Promise<CKTextEditor | null> {- if (appContext.tabManager.getActiveContextNote()?.type !== "text") {+ return getTextEditorContaining(window.getSelection()?.anchorNode);+}++/**+ * The text editor whose editable contains `node`, or `null` when the node sits anywhere else.+ * Answers a pointer target rather than the DOM selection, which a right-click does not move in+ * every browser.+ */+export async function getTextEditorContaining(+ node: Node | null | undefined+): Promise<CKTextEditor | null> {+ if (!node || appContext.tabManager.getActiveContextNote()?.type !== "text") {return null;}try {const editor = await appContext.tabManager.getActiveContext()?.getTextEditor();const domRoot = editor?.editing.view.getDomRoot();- const anchorNode = window.getSelection()?.anchorNode;- if (editor && domRoot && anchorNode && domRoot.contains(anchorNode)) {+ if (editor && domRoot && domRoot.contains(node)) {return editor;}} catch (error) {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e65dd965d6..93930c2a48 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3502,7 +3502,17 @@"presentation-theme": "Theme"},"table_context_menu": {- "delete_row": "Delete row"+ "delete_row": "Delete row",+ "insert_rows_above": "Insert row above",+ "insert_rows_below": "Insert row below",+ "insert_columns_left": "Insert column to the left",+ "insert_columns_right": "Insert column to the right",+ "delete_rows": "Delete rows",+ "delete_columns": "Delete columns",+ "merge_cells": "Merge cells",+ "split_cells": "Split cells",+ "split_vertically": "Vertically",+ "split_horizontally": "Horizontally"},"board_view": {"delete-note": "Delete note...",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 c22122531c..320905f9a5 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@@ -10,6 +10,30 @@<p>When a table is selected, a special formatting toolbar will appear:</p><imgsrc="3_Tables_image.png" width="384" height="100">+<h2>Context menu</h2>+<p>Since v0.106.0, right-clicking anywhere inside a table opens a context+ menu with the most common table operations:</p>+<ul>+ <li><em>Insert row above</em> and <em>Insert row below</em> insert a blank row+ next to the row of the current cell. When the selection spans multiple+ rows, the same number of rows is inserted.</li>+ <li><em>Insert column to the left</em> and <em>Insert column to the right</em> work+ the same way for columns.</li>+ <li><em>Delete rows</em> and <em>Delete columns</em> remove every row or column+ the selection touches, even when only some of their cells are selected.</li>+ <li><em>Merge cells</em> merges the selected cells into one. The selected cells+ must form a rectangle.</li>+ <li><em>Split cells</em> splits each selected cell in two, either <em>Vertically</em> or <em>Horizontally</em>.</li>+</ul>+<p>Right-clicking a cell that is not part of the current selection moves+ the cursor there first, so the menu always applies to the cell under the+ pointer.</p>+<aside class="admonition note">+ <p>In the browser, Trilium's menu replaces the browser's own context menu+ inside tables. To reach the browser's menu (for example for its spell checking+ suggestions), hold <kbd>Shift</kbd> while right-clicking. The desktop application+ is unaffected, since its menu already includes the spelling suggestions.</p>+</aside><h2>Navigating a table</h2><ul><li>Using the mouse:@@ -55,6 +79,8 @@ src="3_Tables_image.png" width="384" height="100">is to press the <kbd>Tab</kbd> key.</li></ul></li>+ <li>Both operations are also available in the <a href="#context-menu">context menu</a>,+ which inserts as many rows or columns as the selection spans.</li></ul><h2>Merging cells</h2><p>To merge two or more cells together, simply select them via drag &@@ -67,6 +93,8 @@ src="3_Tables_image.png" width="384" height="100"><li>Select <em>Split cell vertically</em> or <em>horizontally</em>, to splita cell into multiple cells (can also be used to undo a merge).</li></ul>+<p>Merging and splitting are also available by right-clicking the selected+ cells, via the <a href="#context-menu">context menu</a>.</p><h2>Table properties</h2><figure class="image image-style-align-right"><img style="aspect-ratio:312/311;" src="Tables_image.png" width="312"diff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex 7b2e5712bf..96527cdcb9 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -11,6 +11,21 @@ When a table is selected, a special formatting toolbar will appear:<img src="3_Tables_image.png" width="384" height="100">+## Context menu++Since v0.106.0, right-clicking anywhere inside a table opens a context menu with the most common table operations:++* _Insert row above_ and _Insert row below_ insert a blank row next to the row of the current cell. When the selection spans multiple rows, the same number of rows is inserted.+* _Insert column to the left_ and _Insert column to the right_ work the same way for columns.+* _Delete rows_ and _Delete columns_ remove every row or column the selection touches, even when only some of their cells are selected.+* _Merge cells_ merges the selected cells into one. The selected cells must form a rectangle.+* _Split cells_ splits each selected cell in two, either _Vertically_ or _Horizontally_.++Right-clicking a cell that is not part of the current selection moves the cursor there first, so the menu always applies to the cell under the pointer.++> [!NOTE]+> In the browser, Trilium's menu replaces the browser's own context menu inside tables. To reach the browser's menu (for example for its spell checking suggestions), hold <kbd>Shift</kbd> while right-clicking. The desktop application is unaffected, since its menu already includes the spelling suggestions.+## Navigating a table* Using the mouse:@@ -34,6 +49,7 @@ When a table is selected, a special formatting toolbar will appear:* To insert a new column, click on a desired location, then press the <span class="tn-icon cke cke-table-column"></span> button from the formatting toolbar and select _Insert column left or right._* To insert a new row, click on a desired location, then press the <span class="tn-icon cke cke-table-row"></span> button and select _Insert row above_ or _below_.* A quicker alternative to creating a new row while at the end of the table is to press the <kbd>Tab</kbd> key.+* Both operations are also available in the [context menu](#context-menu), which inserts as many rows or columns as the selection spans.## Merging cells@@ -44,6 +60,8 @@ More options are available by pressing the arrow next to it:* Click on a single cell and select Merge cell up/down/right/left to merge with an adjacent cell.* Select _Split cell vertically_ or _horizontally_, to split a cell into multiple cells (can also be used to undo a merge).+Merging and splitting are also available by right-clicking the selected cells, via the [context menu](#context-menu).+## Table properties<figure class="image image-style-align-right"><img style="aspect-ratio:312/311;" src="Tables_image.png" width="312" height="311"></figure>diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 4d603a19dd..87f733fad6 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -25,6 +25,7 @@ export * from "./utils.js";// Import with sideffects to ensure that type augmentations are present.import "./plugins/math/math.js";import "./plugins/mermaid/mermaid.js";+import "./plugins/table_context_menu.js";window[Symbol.for("cke distribution")] = "trilium";diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 2fd43a575d..4ce982ee0c 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -57,6 +57,7 @@ import TodoListMultistate from "./plugins/todo_list_multistate/todo_list_multistimport TodoListUncheckOnEnter from "./plugins/todo_list_uncheck_on_enter.js";import CollapsibleListItems from "./plugins/collapsible_list_items.js";import TableIndent from "./plugins/table_indent.js";+import TableContextMenu from "./plugins/table_context_menu.js";/*** Plugins that are specific to Trilium and not part of the CKEditor 5 core, included in both text editors but not in the attribute editor.@@ -92,6 +93,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [TodoListMultistate,CollapsibleListItems,TableIndent,+ TableContextMenu,CopyAnchorLinkButton,CopyLinkUrlButton,ImageActions,diff --git a/packages/ckeditor5/src/plugins/table_context_menu.spec.ts b/packages/ckeditor5/src/plugins/table_context_menu.spec.tsnew file mode 100644index 0000000000..7a7b6bd256--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_context_menu.spec.ts@@ -0,0 +1,218 @@+import { _getModelData as getModelData, _setModelData as setModelData, Essentials, Paragraph, Table, TableSelection, TableUtils } from "ckeditor5";+import type { ClassicEditor, ModelElement } from "ckeditor5";+import { beforeEach, describe, expect, it } from "vitest";++import { createTestEditor } from "../../test/editor-kit.js";+import TableContextMenu from "./table_context_menu.js";++const INSERT_COMMANDS = [+ "triliumInsertTableRowsAbove",+ "triliumInsertTableRowsBelow",+ "triliumInsertTableColumnsLeft",+ "triliumInsertTableColumnsRight"+] as const;++describe("TableContextMenu", () => {+ let editor: ClassicEditor;++ beforeEach(async () => {+ editor = await createTestEditor([Essentials, Paragraph, Table, TableSelection, TableContextMenu]);+ });++ it("loads and registers the multi-insert commands", () => {+ expect(editor.plugins.get(TableContextMenu)).toBeInstanceOf(TableContextMenu);+ for (const name of INSERT_COMMANDS) {+ expect(editor.commands.get(name), name).toBeDefined();+ }+ });++ it("enables the insert commands only inside a table", () => {+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");+ for (const name of INSERT_COMMANDS) {+ expect(editor.commands.get(name)?.isEnabled, name).toBe(false);+ }++ setModelData(editor.model, modelTable([["1[]1"]]));+ for (const name of INSERT_COMMANDS) {+ expect(editor.commands.get(name)?.isEnabled, name).toBe(true);+ }+ });++ describe("insert rows", () => {+ it("inserts one row above or below the caret row", () => {+ setModelData(editor.model, modelTable([["1[]1", "12"], ["21", "22"]]));+ editor.execute("triliumInsertTableRowsAbove");+ expect(tableData(editor)).toBe(modelTable([["", ""], ["11", "12"], ["21", "22"]]));++ setModelData(editor.model, modelTable([["1[]1", "12"], ["21", "22"]]));+ editor.execute("triliumInsertTableRowsBelow");+ expect(tableData(editor)).toBe(modelTable([["11", "12"], ["", ""], ["21", "22"]]));+ });++ it("inserts as many rows as the selection spans", () => {+ setModelData(editor.model, modelTable([["11"], ["21"], ["31"]]));+ selectCells(editor, [0, 0], [1, 0]);+ editor.execute("triliumInsertTableRowsAbove");+ expect(tableData(editor)).toBe(modelTable([[""], [""], ["11"], ["21"], ["31"]]));++ setModelData(editor.model, modelTable([["11"], ["21"], ["31"]]));+ selectCells(editor, [1, 0], [2, 0]);+ editor.execute("triliumInsertTableRowsBelow");+ expect(tableData(editor)).toBe(modelTable([["11"], ["21"], ["31"], [""], [""]]));+ });++ it("extends headingRows only when inserting inside the heading band", () => {+ setModelData(editor.model, modelTable([["h[]1"], ["21"]], 'headingRows="1"'));+ editor.execute("triliumInsertTableRowsAbove");+ expect(tableData(editor)).toBe(modelTable([[""], ["h1"], ["21"]], 'headingRows="2"'));++ setModelData(editor.model, modelTable([["h[]1"], ["21"]], 'headingRows="1"'));+ editor.execute("triliumInsertTableRowsBelow");+ expect(tableData(editor)).toBe(modelTable([["h1"], [""], ["21"]], 'headingRows="1"'));+ });+ });++ describe("insert columns", () => {+ it("inserts one column left or right of the caret column", () => {+ setModelData(editor.model, modelTable([["1[]1", "12"]]));+ editor.execute("triliumInsertTableColumnsLeft");+ expect(tableData(editor)).toBe(modelTable([["", "11", "12"]]));++ setModelData(editor.model, modelTable([["1[]1", "12"]]));+ editor.execute("triliumInsertTableColumnsRight");+ expect(tableData(editor)).toBe(modelTable([["11", "", "12"]]));+ });++ it("inserts as many columns as the selection spans", () => {+ setModelData(editor.model, modelTable([["11", "12", "13"]]));+ selectCells(editor, [0, 0], [0, 1]);+ editor.execute("triliumInsertTableColumnsLeft");+ expect(tableData(editor)).toBe(modelTable([["", "", "11", "12", "13"]]));++ setModelData(editor.model, modelTable([["11", "12", "13"]]));+ selectCells(editor, [0, 0], [0, 1]);+ editor.execute("triliumInsertTableColumnsRight");+ expect(tableData(editor)).toBe(modelTable([["11", "12", "", "", "13"]]));+ });+ });++ describe("syncSelectionToDomTarget", () => {+ it("moves the selection into an unselected cell", () => {+ setModelData(editor.model, modelTable([["1[]1", "12"], ["21", "22"]]));+ const plugin = editor.plugins.get(TableContextMenu);++ expect(plugin.syncSelectionToDomTarget(domCell(editor, 1, 1))).toBe(true);+ expect(selectionCells(editor)).toHaveLength(1);+ expect(selectionCells(editor)[0]).toBe(getCell(editor, 1, 1));++ // A node nested inside the cell resolves to the cell.+ const nested = domCell(editor, 0, 1).firstChild;+ expect(nested && plugin.syncSelectionToDomTarget(nested)).toBe(true);+ expect(selectionCells(editor)[0]).toBe(getCell(editor, 0, 1));+ });++ it("keeps a multi-cell selection that contains the target", () => {+ setModelData(editor.model, modelTable([["11", "12"], ["21", "22"]]));+ const plugin = editor.plugins.get(TableContextMenu);+ selectCells(editor, [0, 0], [1, 1]);++ expect(plugin.syncSelectionToDomTarget(domCell(editor, 0, 1))).toBe(true);+ expect(selectionCells(editor)).toHaveLength(4);+ expect(selectionCells(editor)).toContain(getCell(editor, 0, 0));+ });++ it("rejects targets outside a table cell of this editor", () => {+ setModelData(editor.model, "<paragraph>foo</paragraph>");+ const plugin = editor.plugins.get(TableContextMenu);++ const paragraph = editor.editing.view.getDomRoot()?.querySelector("p");+ expect(paragraph && plugin.syncSelectionToDomTarget(paragraph)).toBe(false);+ expect(plugin.syncSelectionToDomTarget(document.body)).toBe(false);++ const strayCell = document.createElement("td");+ document.body.appendChild(strayCell);+ try {+ expect(plugin.syncSelectionToDomTarget(strayCell)).toBe(false);+ } finally {+ strayCell.remove();+ }+ });+ });++ describe("right-button mousedown", () => {+ it("keeps a cell selection alive under a right-click on it", () => {+ setModelData(editor.model, modelTable([["11", "12"], ["21", "22"]]));+ selectCells(editor, [0, 0], [1, 1]);++ const event = mouseDown(domCell(editor, 0, 1), 2);++ expect(event.defaultPrevented).toBe(true);+ expect(selectionCells(editor)).toHaveLength(4);+ });++ it("does not interfere with other clicks", () => {+ setModelData(editor.model, modelTable([["11", "12"], ["21", "22"]]));+ selectCells(editor, [0, 0], [1, 0]);++ // Left button on a selected cell.+ expect(mouseDown(domCell(editor, 0, 0), 0).defaultPrevented).toBe(false);++ // Right button outside the cell selection.+ expect(mouseDown(domCell(editor, 1, 1), 2).defaultPrevented).toBe(false);++ // Right button with a plain in-cell selection.+ setModelData(editor.model, modelTable([["1[]1"]]));+ expect(mouseDown(domCell(editor, 0, 0), 2).defaultPrevented).toBe(false);+ });+ });+});++function modelTable(rows: string[][], attributes = ""): string {+ const rowsMarkup = rows+ .map((cells) => {+ const cellsMarkup = cells+ .map((cell) => `<tableCell><paragraph>${cell}</paragraph></tableCell>`)+ .join("");+ return `<tableRow>${cellsMarkup}</tableRow>`;+ })+ .join("");+ return `<table${attributes ? ` ${attributes}` : ""}>${rowsMarkup}</table>`;+}++function tableData(editor: ClassicEditor): string {+ return getModelData(editor.model, { withoutSelection: true });+}++function getCell(editor: ClassicEditor, row: number, column: number): ModelElement {+ const cell = editor.model.document.getRoot()?.getNodeByPath([0, row, column]);+ if (!cell || !cell.is("element", "tableCell")) {+ throw new Error(`No table cell at row ${row}, column ${column}.`);+ }+ return cell;+}++function domCell(editor: ClassicEditor, row: number, column: number): HTMLElement {+ const viewCell = editor.editing.mapper.toViewElement(getCell(editor, row, column));+ const dom = viewCell && editor.editing.view.domConverter.mapViewToDom(viewCell);+ if (!(dom instanceof HTMLElement)) {+ throw new Error(`No DOM cell at row ${row}, column ${column}.`);+ }+ return dom;+}++function selectCells(editor: ClassicEditor, anchor: [number, number], target: [number, number]) {+ editor.plugins.get(TableSelection).setCellSelection(+ getCell(editor, anchor[0], anchor[1]),+ getCell(editor, target[0], target[1])+ );+}++function selectionCells(editor: ClassicEditor): ModelElement[] {+ return editor.plugins.get(TableUtils).getSelectionAffectedTableCells(editor.model.document.selection);+}++function mouseDown(target: HTMLElement, button: number): MouseEvent {+ const event = new MouseEvent("mousedown", { button, bubbles: true, cancelable: true });+ target.dispatchEvent(event);+ return event;+}diff --git a/packages/ckeditor5/src/plugins/table_context_menu.ts b/packages/ckeditor5/src/plugins/table_context_menu.tsnew file mode 100644index 0000000000..da5c26052f--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_context_menu.ts@@ -0,0 +1,165 @@+import { Command, MouseObserver, Plugin, Table, TableSelection, TableUtils } from "ckeditor5";+import type { Editor, ModelElement, ViewDocumentMouseDownEvent } from "ckeditor5";++/**+ * Editor-side support for the client's table context menu.+ *+ * Registers insert commands that honor the size of the current selection (the upstream+ * `insertTableRow*` / `insertTableColumn*` commands always insert one row or column), keeps a+ * multi-cell selection alive under a right-click, and moves the selection to the cell a context+ * menu is opened on. Merge, split and delete need no counterparts here: the upstream+ * `mergeTableCells`, `splitTableCell*` and `removeTableRow` / `removeTableColumn` commands already+ * act on the whole selection.+ */+export default class TableContextMenu extends Plugin {++ static get requires() {+ return [Table, TableSelection, TableUtils] as const;+ }++ static get pluginName() {+ return "TableContextMenu" as const;+ }++ init() {+ const editor = this.editor;++ editor.commands.add("triliumInsertTableRowsAbove",+ new TableMultiInsertCommand(editor, "above"));+ editor.commands.add("triliumInsertTableRowsBelow",+ new TableMultiInsertCommand(editor, "below"));+ editor.commands.add("triliumInsertTableColumnsLeft",+ new TableMultiInsertCommand(editor, "left"));+ editor.commands.add("triliumInsertTableColumnsRight",+ new TableMultiInsertCommand(editor, "right"));++ const view = editor.editing.view;+ view.addObserver(MouseObserver);+ this.listenTo<ViewDocumentMouseDownEvent>(view.document, "mousedown", (evt, data) => {+ // Stops the caret move that would collapse a multi-cell selection before the+ // `contextmenu` event fires.+ const isRightButton = data.domEvent.button === RIGHT_MOUSE_BUTTON;+ if (isRightButton && this.isInsideCellSelection(data.domTarget)) {+ data.preventDefault();+ }+ }, { priority: "high" });+ }++ /**+ * Moves the model selection into the table cell containing `domTarget`, so commands run+ * against the cell the context menu is opened on. A target inside the current selection keeps+ * that selection. Returns `false` when the target is not in a table cell of this editor.+ */+ syncSelectionToDomTarget(domTarget: Node): boolean {+ const editor = this.editor;+ const modelCell = resolveModelCell(editor, domTarget);+ if (!modelCell) {+ return false;+ }++ const tableUtils = editor.plugins.get(TableUtils);+ const selection = editor.model.document.selection;+ if (!tableUtils.getSelectionAffectedTableCells(selection).includes(modelCell)) {+ editor.model.change((writer) => {+ writer.setSelection(writer.createPositionAt(modelCell, 0));+ });+ }++ return true;+ }++ /** Whether `domTarget` sits in one of the cells the selection covers from the outside. */+ private isInsideCellSelection(domTarget: Node): boolean {+ const editor = this.editor;+ const modelCell = resolveModelCell(editor, domTarget);+ if (!modelCell) {+ return false;+ }++ const tableUtils = editor.plugins.get(TableUtils);+ return tableUtils.getSelectedTableCells(editor.model.document.selection).includes(modelCell);+ }++}++const RIGHT_MOUSE_BUTTON = 2;++/** Where {@link TableMultiInsertCommand} inserts, relative to the rows or columns it spans. */+export type TableMultiInsertDirection = "above" | "below" | "left" | "right";++/**+ * Inserts as many rows or columns as the selection spans, next to the spanned block.+ */+export class TableMultiInsertCommand extends Command {++ private readonly direction: TableMultiInsertDirection;++ constructor(editor: Editor, direction: TableMultiInsertDirection) {+ super(editor);+ this.direction = direction;+ }++ refresh() {+ const tableUtils = this.editor.plugins.get(TableUtils);+ const selection = this.editor.model.document.selection;+ this.isEnabled = tableUtils.getSelectionAffectedTableCells(selection).length > 0;+ }++ execute() {+ const tableUtils = this.editor.plugins.get(TableUtils);+ const selection = this.editor.model.document.selection;+ const cells = tableUtils.getSelectionAffectedTableCells(selection);+ const table = cells[0]?.findAncestor("table");+ /* v8 ignore next 3 -- defensive: disabled whenever the selection is outside a table */+ if (!table) {+ return;+ }++ if (this.direction === "above" || this.direction === "below") {+ const { first, last } = tableUtils.getRowIndexes(cells);+ const insertAbove = this.direction === "above";+ tableUtils.insertRows(table, {+ at: insertAbove ? first : last + 1,+ rows: last - first + 1,+ copyStructureFromAbove: !insertAbove+ });+ } else {+ const { first, last } = tableUtils.getColumnIndexes(cells);+ tableUtils.insertColumns(table, {+ at: this.direction === "left" ? first : last + 1,+ columns: last - first + 1+ });+ }+ }++}++/** The model `tableCell` whose rendered cell contains `domTarget`, or `null` when there is none. */+function resolveModelCell(editor: Editor, domTarget: Node): ModelElement | null {+ const domElement = domTarget instanceof Element ? domTarget : domTarget.parentElement;+ const domCell = domElement?.closest<HTMLTableCellElement>("td, th");+ if (!domCell) {+ return null;+ }++ const viewCell = editor.editing.view.domConverter.mapDomToView(domCell);+ if (!viewCell?.is("element")) {+ return null;+ }++ const modelCell = editor.editing.mapper.toModelElement(viewCell);+ return modelCell?.is("element", "tableCell") ? modelCell : null;+}++declare module "ckeditor5" {+ interface PluginsMap {+ [TableContextMenu.pluginName]: TableContextMenu;+ }++ interface CommandsMap {+ triliumInsertTableRowsAbove: TableMultiInsertCommand;+ triliumInsertTableRowsBelow: TableMultiInsertCommand;+ triliumInsertTableColumnsLeft: TableMultiInsertCommand;+ triliumInsertTableColumnsRight: TableMultiInsertCommand;+ }+}