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 selection commands in the context menu
Adorian Dorandb0ab8c0b9cc
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex 1f94f11490..7ee3da3586 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -223,7 +223,8 @@ describe("buildNoteContextMenuItems", () => {vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({main: [ { title: "T1" }, { kind: "separator" }, { title: "T2" } ],sort: { title: "S" },- delete: [ { title: "D1" }, { title: "D2" } ]+ delete: [ { title: "D1" }, { title: "D2" } ],+ select: { title: "SEL" }} as TableMenuSections);const host = browserLikeHost({paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn() }@@ -248,6 +249,8 @@ describe("buildNoteContextMenuItems", () => {"D1","D2","---",+ "SEL",+ "---","electron_context_menu.search_online","electron_context_menu.search_in_trilium"]);@@ -278,7 +281,8 @@ describe("buildNoteContextMenuItems", () => {vi.mocked(buildTableContextMenuSections).mockResolvedValue({main: [ { title: "T1" } ],sort: { title: "S" },- delete: []+ delete: [],+ select: { title: "SEL" }} as TableMenuSections);// No cell selection and no text: the rows show but stay disabled.@@ -302,7 +306,8 @@ describe("buildNoteContextMenuItems", () => {vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({main: [ { title: "T1" } ],sort: { title: "S" },- delete: []+ delete: [],+ select: { title: "SEL" }} as TableMenuSections);vi.mocked(hasTableCellSelection).mockResolvedValueOnce(true);@@ -393,7 +398,8 @@ describe("setupContextMenu (browser)", () => {vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({main: [ { title: "table_context_menu.merge_cells" } ],sort: { title: "S" },- delete: []+ delete: [],+ select: { title: "SEL" }} as TableMenuSections);const event = rightClick(cell);diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex 83eab2e9dc..f02528ef94 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -226,7 +226,7 @@ export async function buildNoteContextMenuItems(if (tableSections) {items.push({ kind: "separator" }, tableSections.sort, { kind: "separator" },- ...tableSections.delete);+ ...tableSections.delete, { kind: "separator" }, tableSections.select);}if (hasText) {diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.tsindex ae3b33d16c..ecec48059b 100644--- a/apps/client/src/menus/table_context_menu.spec.ts+++ b/apps/client/src/menus/table_context_menu.spec.ts@@ -37,6 +37,14 @@ const DELETE_TITLES = ["table_context_menu.delete_table"];+const SELECT_TITLES = [+ "table_context_menu.select_row",+ "table_context_menu.select_column",+ "table_context_menu.select_table"+];++const SELECT_COMMANDS = ["selectTableRow", "selectTableColumn", "triliumSelectTable"];+describe("buildTableMenuSections", () => {it("returns the sections in order, with a split submenu", () => {const { editor, syncSelectionToDomTarget } = stubEditor();@@ -53,6 +61,12 @@ describe("buildTableMenuSections", () => {expect(sortRow?.uiIcon).toBe("bx bx-sort-alt-2");expect(sortSubmenu(sections).map((item) => (item as MenuCommandItem<any>).uiIcon)).toEqual(["bx bx-sort-up", "bx bx-sort-down"]);+ expect(titles(sections ? [sections.select] : [])).toEqual(["table_context_menu.select"]);+ expect(titles(selectSubmenu(sections))).toEqual(SELECT_TITLES);+ const selectRow = sections?.select as MenuCommandItem<any> | undefined;+ expect(selectRow?.uiIcon).toBe("bx bx-select-multiple");+ expect(selectSubmenu(sections).map((item) => (item as MenuCommandItem<any>).uiIcon))+ .toEqual(["bx bx-grid-horizontal", "bx bx-grid-vertical", "bx bx-table"]);const splitRow = findItem(sections?.main ?? [], "table_context_menu.split_cells");const submenu = splitRow?.items ?? [];@@ -79,6 +93,9 @@ describe("buildTableMenuSections", () => {for (const title of SORT_TITLES) {run(sortSubmenu(sections), title);}+ for (const title of SELECT_TITLES) {+ run(selectSubmenu(sections), title);+ }expect(executed).toEqual(["triliumInsertTableRowsAbove",@@ -94,7 +111,8 @@ describe("buildTableMenuSections", () => {"splitTableCellHorizontally","triliumResetTableCellSpans","triliumSortTableRowsAscending",- "triliumSortTableRowsDescending"+ "triliumSortTableRowsDescending",+ ...SELECT_COMMANDS]);expect(focus).toHaveBeenCalledTimes(executed.length);});@@ -153,6 +171,25 @@ describe("buildTableMenuSections", () => {expect(findItem(submenu, SORT_TITLES[1])?.enabled).toBe(false);});+ it("enables the select submenu while any of its rows is enabled", () => {+ const selectSections = (disabled: string[]) => {+ const { editor } = stubEditor(disabled);+ return buildTableMenuSections(editor, cellElement());+ };+ const selectRowEnabled = (disabled: string[]) =>+ (selectSections(disabled)?.select as MenuCommandItem<any> | undefined)?.enabled;++ for (const enabled of SELECT_COMMANDS) {+ const disabled = SELECT_COMMANDS.filter((command) => command !== enabled);+ expect(selectRowEnabled(disabled), enabled).toBe(true);+ }+ expect(selectRowEnabled(SELECT_COMMANDS)).toBe(false);++ const submenu = selectSubmenu(selectSections([SELECT_COMMANDS[2]]));+ expect(submenu.map((item) => (item as MenuCommandItem<any>).enabled))+ .toEqual([true, true, false]);+ });+it("returns null without the plugin or a table cell at the target", () => {const { editor: withoutPlugin } = stubEditor([], { hasPlugin: false });expect(buildTableMenuSections(withoutPlugin, cellElement())).toBeNull();@@ -272,6 +309,10 @@ function sortSubmenu(sections: TableMenuSections | null): MenuItem<any>[] {return (sections?.sort as MenuCommandItem<any> | undefined)?.items ?? [];}+function selectSubmenu(sections: TableMenuSections | null): MenuItem<any>[] {+ return (sections?.select as MenuCommandItem<any> | undefined)?.items ?? [];+}+/** 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"diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.tsindex 1e5fabfe8a..5d28d3ebec 100644--- a/apps/client/src/menus/table_context_menu.ts+++ b/apps/client/src/menus/table_context_menu.ts@@ -59,6 +59,12 @@ export function buildTableMenuSections(commandItem(t("table_context_menu.sort_descending"), "bx bx-sort-down","triliumSortTableRowsDescending")];+ const selectItems = [+ commandItem(t("table_context_menu.select_row"), "bx bx-grid-horizontal", "selectTableRow"),+ commandItem(t("table_context_menu.select_column"), "bx bx-grid-vertical",+ "selectTableColumn"),+ commandItem(t("table_context_menu.select_table"), "bx bx-table", "triliumSelectTable")+ ];return {main: [@@ -94,11 +100,17 @@ export function buildTableMenuSections(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+ }};}-/** The table rows of the text editor's right-click menu, in two sections. */+/** The table rows of the text editor's right-click menu, in four sections. */export interface TableMenuSections {/*** Row and column insertion sized by the selection, merging or splitting of the selected cells,@@ -109,6 +121,8 @@ export interface TableMenuSections {sort: MenuItem<CommandNames>;/** Deletion of the spanned rows or columns, or of the table. Shown below the clipboard. */delete: MenuItem<CommandNames>[];+ /** Selection of the spanned rows or columns, or of the whole table. Shown below deletion. */+ select: MenuItem<CommandNames>;}/**diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 62e4c9755f..cbe34ecd2a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3518,7 +3518,11 @@"split_reset": "Unmerge cells","sort": "Sort","sort_ascending": "Ascending",- "sort_descending": "Descending"+ "sort_descending": "Descending",+ "select": "Select",+ "select_row": "Row",+ "select_column": "Column",+ "select_table": "Table"},"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 9f97b7ae8d..0bd8150e2e 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@@ -63,6 +63,13 @@ src="3_Tables_image.png" width="384" height="100"><li><em>Delete table</em> removes the whole table and leaves an empty paragraphin its place. In a table nested inside another, only the inner table isremoved.</li>+ <li>Since v0.107.0, <em>Select</em>, below <em>Delete table</em>, selects the+ cells of every row (<em>Row</em>) or column (<em>Column</em>) the selection+ touches, or every cell of the table (<em>Table</em>). Unlike the <span class="tn-icon cke cke-drag-handle"></span> button,+ which selects the table as a whole, <em>Table</em> selects its cells, so+ cell operations such as <em>Merge cells</em> apply to all of them. In a table+ nested inside another, <em>Table</em> selects only the cells of the inner+ table.</li></ul><p>Right-clicking a cell that is not part of the current selection movesthe cursor there first, so the menu always applies to the cell under thediff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex 40e101cac3..cdb9c7c5d8 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -34,6 +34,7 @@ Since v0.106.0, right-clicking anywhere inside a table opens a context menu with* _Sort_, below the clipboard section, sorts the rows by the column of the current cell, in _Ascending_ or _Descending_ order. See [Sorting rows](#sorting-rows).* _Delete row_ and _Delete column_, below _Sort_, remove every row or column the selection touches, even when only some of their cells are selected.* _Delete table_ removes the whole table and leaves an empty paragraph in its place. In a table nested inside another, only the inner table is removed.+* Since v0.107.0, _Select_, below _Delete table_, selects the cells of every row (_Row_) or column (_Column_) the selection touches, or every cell of the table (_Table_). Unlike the <span class="tn-icon cke cke-drag-handle"></span> button, which selects the table as a whole, _Table_ selects its cells, so cell operations such as _Merge cells_ apply to all of them. In a table nested inside another, _Table_ selects only the cells of the inner table.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.diff --git a/packages/ckeditor5/src/plugins/table_context_menu.spec.ts b/packages/ckeditor5/src/plugins/table_context_menu.spec.tsindex 5e25bad6ae..3c84f766e5 100644--- a/packages/ckeditor5/src/plugins/table_context_menu.spec.ts+++ b/packages/ckeditor5/src/plugins/table_context_menu.spec.ts@@ -214,6 +214,50 @@ describe("TableContextMenu", () => {});});+ describe("select table", () => {+ const COMMAND = "triliumSelectTable";++ it("is enabled inside a table, in read-only mode too", () => {+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");+ expect(editor.commands.get(COMMAND)?.isEnabled).toBe(false);++ setModelData(editor.model, modelTable([["1[]1"]]));+ expect(editor.commands.get(COMMAND)?.isEnabled).toBe(true);++ editor.enableReadOnlyMode("spec");+ expect(editor.commands.get(COMMAND)?.isEnabled).toBe(true);+ });++ it("selects every cell of the table, merged cells included", () => {+ const rows = [+ [{ contents: "a", colspan: 2 }, "b"],+ ["c", "d", { contents: "e", rowspan: 2 }],+ ["f", "g"]+ ];+ const columns = ["20%", "30%", "50%"]+ .map((width) => `<tableColumn columnWidth="${width}"></tableColumn>`)+ .join("");+ const table = spannedTable(rows)+ .replace(/<\/table>$/, `<tableColumnGroup>${columns}</tableColumnGroup></table>`);+ setModelData(editor.model, table.replace(">d<", ">d[]<"));++ editor.execute(COMMAND);++ expect(getModelData(editor.model)).toBe(withEveryCellSelected(table));+ });++ it("selects only the innermost table around the selection", () => {+ const inner = modelTable([["11", "12"]]);+ const outer = (content: string) => "<table><tableRow><tableCell><paragraph>outer"+ + `</paragraph></tableCell><tableCell>${content}</tableCell></tableRow></table>`;+ setModelData(editor.model, outer(inner.replace("11", "1[]1")));++ editor.execute(COMMAND);++ expect(getModelData(editor.model)).toBe(outer(withEveryCellSelected(inner)));+ });+ });+describe("syncSelectionToDomTarget", () => {it("moves the selection into an unselected cell", () => {setModelData(editor.model, modelTable([["1[]1", "12"], ["21", "22"]]));@@ -327,6 +371,11 @@ function tableData(editor: ClassicEditor): string {return getModelData(editor.model, { withoutSelection: true });}+/** Marks every cell of `markup` as selected, the way `getModelData` prints a cell selection. */+function withEveryCellSelected(markup: string): string {+ return markup.replace(/<tableCell[^>]*>.*?<\/tableCell>/g, "[$&]");+}+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")) {diff --git a/packages/ckeditor5/src/plugins/table_context_menu.ts b/packages/ckeditor5/src/plugins/table_context_menu.tsindex ab3ea788ff..9d223eda0e 100644--- a/packages/ckeditor5/src/plugins/table_context_menu.ts+++ b/packages/ckeditor5/src/plugins/table_context_menu.ts@@ -5,7 +5,8 @@ import {Table,TableColumnResize,TableSelection,- TableUtils+ TableUtils,+ TableWalker} from "ckeditor5";import type { Editor, ModelElement, ViewDocumentMouseDownEvent } from "ckeditor5";@@ -15,11 +16,12 @@ import { DistributeTableColumnsCommand } from "./table_distribute_columns.js";* 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) and- * `triliumDistributeTableColumns`, 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.+ * `insertTableRow*` / `insertTableColumn*` commands always insert one row or column),+ * `triliumDistributeTableColumns` and `triliumSelectTable`, the whole-table counterpart of the+ * upstream `selectTableRow` / `selectTableColumn`. 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 {@@ -46,6 +48,7 @@ export default class TableContextMenu extends Plugin {new DistributeTableColumnsCommand(editor));editor.commands.add("triliumDeleteTable", new DeleteTableCommand(editor));editor.commands.add("triliumResetTableCellSpans", new ResetTableCellSpansCommand(editor));+ editor.commands.add("triliumSelectTable", new SelectTableCommand(editor));const view = editor.editing.view;view.addObserver(MouseObserver);@@ -156,11 +159,11 @@ export class TableMultiInsertCommand extends Command {export class DeleteTableCommand extends Command {refresh() {- this.isEnabled = this.findTable() !== null;+ this.isEnabled = findSelectionTable(this.editor) !== null;}execute() {- const table = this.findTable();+ const table = findSelectionTable(this.editor);/* v8 ignore next 3 -- defensive: disabled whenever the selection is outside a table */if (!table) {return;@@ -174,10 +177,35 @@ export class DeleteTableCommand extends Command {});}- private findTable(): ModelElement | null {- const tableUtils = this.editor.plugins.get(TableUtils);- const selection = this.editor.model.document.selection;- return tableUtils.getSelectionAffectedTableCells(selection)[0]?.findAncestor("table") ?? null;+}++/**+ * Selects every cell of the table the selection is in, the innermost one when tables are nested.+ * Like `selectTableRow` and `selectTableColumn`, it stays enabled in read-only mode.+ */+export class SelectTableCommand extends Command {++ constructor(editor: Editor) {+ super(editor);+ this.affectsData = false;+ }++ refresh() {+ this.isEnabled = findSelectionTable(this.editor) !== null;+ }++ execute() {+ const table = findSelectionTable(this.editor);+ /* v8 ignore next 3 -- defensive: disabled whenever the selection is outside a table */+ if (!table) {+ return;+ }++ const model = this.editor.model;+ const ranges = Array.from(new TableWalker(table), ({ cell }) => model.createRangeOn(cell));+ model.change((writer) => {+ writer.setSelection(ranges);+ });}}@@ -230,6 +258,13 @@ export class ResetTableCellSpansCommand extends Command {}+/** The table the selection is in, the innermost one when tables are nested. */+function findSelectionTable(editor: Editor): ModelElement | null {+ const tableUtils = editor.plugins.get(TableUtils);+ const selection = editor.model.document.selection;+ return tableUtils.getSelectionAffectedTableCells(selection)[0]?.findAncestor("table") ?? null;+}+function getSpan(cell: ModelElement, attribute: "colspan" | "rowspan"): number {return Number(cell.getAttribute(attribute) ?? 1);}@@ -264,5 +299,6 @@ declare module "ckeditor5" {triliumDistributeTableColumns: DistributeTableColumnsCommand;triliumDeleteTable: DeleteTableCommand;triliumResetTableCellSpans: ResetTableCellSpansCommand;+ triliumSelectTable: SelectTableCommand;}}