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: allow header rows to be defined using the context menu
Adorian Dorande55c8991b6d
diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.tsindex ecec48059b..3d7062d3f2 100644--- a/apps/client/src/menus/table_context_menu.spec.ts+++ b/apps/client/src/menus/table_context_menu.spec.ts@@ -21,6 +21,8 @@ const MAIN_TITLES = ["table_context_menu.insert_columns_left","table_context_menu.insert_columns_right","---",+ "table_context_menu.set_header_row",+ "---","table_context_menu.merge_cells","table_context_menu.split_cells","table_context_menu.distribute_columns"@@ -102,6 +104,7 @@ describe("buildTableMenuSections", () => {"triliumInsertTableRowsBelow","triliumInsertTableColumnsLeft","triliumInsertTableColumnsRight",+ "triliumSetTableHeaderRow","mergeTableCells","triliumDistributeTableColumns","removeTableRow",@@ -134,6 +137,36 @@ describe("buildTableMenuSections", () => {expect(findItem(items, "table_context_menu.insert_rows_above")?.enabled).toBe(true);});+ it("shows only the header item that applies, with a trailing check while it is on", () => {+ const FIRST_ROWS = "triliumSetTableHeaderRow";+ const LATER_ROW = "triliumSetTableHeaderUpToRow";+ const FIRST_ROWS_TITLE = "table_context_menu.set_header_row";+ const LATER_ROW_TITLE = "table_context_menu.set_header_up_to_row";+ const build = (disabled: string[], checkedCommands: string[] = []) => {+ const stub = stubEditor(disabled, { checkedCommands });+ const main = buildTableMenuSections(stub.editor, cellElement())?.main ?? [];+ return { ...stub, main };+ };++ const firstRows = build([LATER_ROW]);+ expect(titles(firstRows.main)).toEqual(MAIN_TITLES);+ expect(findItem(firstRows.main, FIRST_ROWS_TITLE))+ .toMatchObject({ uiIcon: "bx bx-dock-top", trailingIcon: undefined });++ const laterRow = build([FIRST_ROWS], [LATER_ROW]);+ expect(titles(laterRow.main)).toEqual(MAIN_TITLES+ .map((title) => (title === FIRST_ROWS_TITLE ? LATER_ROW_TITLE : title)));+ expect(findItem(laterRow.main, LATER_ROW_TITLE))+ .toMatchObject({ uiIcon: "bx bx-arrow-to-top", trailingIcon: "bx bx-check" });+ run(laterRow.main, LATER_ROW_TITLE);+ expect(laterRow.executed).toEqual([LATER_ROW]);++ // Several rows below the first take neither item, nor the separator that follows it.+ const index = MAIN_TITLES.indexOf(FIRST_ROWS_TITLE);+ expect(titles(build([FIRST_ROWS, LATER_ROW]).main))+ .toEqual([...MAIN_TITLES.slice(0, index), ...MAIN_TITLES.slice(index + 2)]);+ });+it("enables the split submenu while any of its rows is enabled", () => {const SPLIT_COMMANDS = ["splitTableCellVertically",@@ -268,10 +301,14 @@ describe("hasTableCellSelection", () => {});/**- * A minimal editor double: `TableContextMenu` is present unless `hasPlugin` says otherwise, and- * every command is enabled except the ones in `disabledCommands`.+ * A minimal editor double: `TableContextMenu` is present unless `hasPlugin` says otherwise, every+ * command is enabled except the ones in `disabledCommands`, and only the ones in+ * `checkedCommands` have a `true` value.*/-function stubEditor(disabledCommands: string[] = [], { hasPlugin = true, syncResult = true } = {}) {+function stubEditor(+ disabledCommands: string[] = [],+ { hasPlugin = true, syncResult = true, checkedCommands = [] as string[] } = {}+) {const executed: string[] = [];const focus = vi.fn();const syncSelectionToDomTarget = vi.fn(() => syncResult);@@ -281,7 +318,10 @@ function stubEditor(disabledCommands: string[] = [], { hasPlugin = true, syncResget: () => ({ syncSelectionToDomTarget })},commands: {- get: (name: string) => ({ isEnabled: !disabledCommands.includes(name) })+ get: (name: string) => ({+ isEnabled: !disabledCommands.includes(name),+ value: checkedCommands.includes(name)+ })},execute: (name: string) => {executed.push(name);diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.tsindex 5d28d3ebec..efae01adfc 100644--- a/apps/client/src/menus/table_context_menu.ts+++ b/apps/client/src/menus/table_context_menu.ts@@ -44,7 +44,22 @@ export function buildTableMenuSections(editor.editing.view.focus();}});+ const toggleItem = (title: string, uiIcon: string, commandName: string) => ({+ ...commandItem(title, uiIcon, commandName),+ trailingIcon: editor.commands.get(commandName)?.value === true ? "bx bx-check" : undefined+ });+ // The header items are one toggle under two labels, so only the one enabled for the+ // selection is shown.+ const headerItem = [+ toggleItem(t("table_context_menu.set_header_row"), "bx bx-dock-top",+ "triliumSetTableHeaderRow"),+ toggleItem(t("table_context_menu.set_header_up_to_row"), "bx bx-arrow-to-top",+ "triliumSetTableHeaderUpToRow")+ ].find((item) => item.enabled);+ const headerGroup: MenuItem<CommandNames>[] = headerItem+ ? [headerItem, { kind: "separator" }]+ : [];const splitItems = [commandItem(t("table_context_menu.split_vertically"), "bx bx-reflect-vertical","splitTableCellVertically"),@@ -78,6 +93,7 @@ export function buildTableMenuSections(commandItem(t("table_context_menu.insert_columns_right"),"bx bx-horizontal-right", "triliumInsertTableColumnsRight"),{ kind: "separator" },+ ...headerGroup,commandItem(t("table_context_menu.merge_cells"), "bx bx-border-outer","mergeTableCells"),{@@ -113,8 +129,8 @@ export function buildTableMenuSections(/** 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,- * and equal widths for the spanned columns. Shown above the clipboard.+ * Row and column insertion sized by the selection, the header rows, merging or splitting of+ * the selected cells, and equal widths for the spanned columns. Shown above the clipboard.*/main: MenuItem<CommandNames>[];/** Sorting of the rows by the column of the selection. Shown above the deletion rows. */diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex cbe34ecd2a..8b454a9b34 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3522,7 +3522,9 @@"select": "Select","select_row": "Row","select_column": "Column",- "select_table": "Table"+ "select_table": "Table",+ "set_header_row": "Set as header row",+ "set_header_up_to_row": "Set header up to this row"},"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 0bd8150e2e..87f65ac8bb 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@@ -32,6 +32,21 @@ src="3_Tables_image.png" width="384" height="100">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> workthe same way for columns.</li>+ <li>Since v0.107.0, <em>Set as header row</em> or <em>Set header up to this row</em>,+ depending on the selection, turns rows into header rows, which always start+ at the top of the table:+ <ul>+ <li><em>Set as header row</em> shows when the selection starts at the first+ row, and makes every selected row a header row.</li>+ <li><em>Set header up to this row</em> shows when the selection is in a single+ row below the first, and makes that row and every row above it header rows.</li>+ <li>Neither shows when the selection spans several rows below the first.</li>+ <li>A check mark shows that the rows are already header rows. Choosing the+ item again turns them, and every header row below them, back into regular+ rows. For example, in a table with five header rows, choosing <em>Set header up to this row</em> on+ the third row leaves only the first two as header rows.</li>+ </ul>+ </li><li><em>Merge cells</em> merges the selected cells into one. The selected cellsmust form a rectangle.</li><li><em>Split cell</em> splits each selected cell in two, either <em>Vertically</em> or <em>Horizontally</em>. <em>Unmerge cells</em>,diff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex cdb9c7c5d8..fd0deabf0e 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -25,6 +25,11 @@ Since v0.106.0, right-clicking anywhere inside a table opens a context menu with* _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.+* Since v0.107.0, _Set as header row_ or _Set header up to this row_, depending on the selection, turns rows into header rows, which always start at the top of the table:+ * _Set as header row_ shows when the selection starts at the first row, and makes every selected row a header row.+ * _Set header up to this row_ shows when the selection is in a single row below the first, and makes that row and every row above it header rows.+ * Neither shows when the selection spans several rows below the first.+ * A check mark shows that the rows are already header rows. Choosing the item again turns them, and every header row below them, back into regular rows. For example, in a table with five header rows, choosing _Set header up to this row_ on the third row leaves only the first two as header rows.* _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.diff --git a/packages/ckeditor5/src/plugins/table_context_menu.spec.ts b/packages/ckeditor5/src/plugins/table_context_menu.spec.tsindex 3c84f766e5..0996114d80 100644--- a/packages/ckeditor5/src/plugins/table_context_menu.spec.ts+++ b/packages/ckeditor5/src/plugins/table_context_menu.spec.ts@@ -214,6 +214,84 @@ describe("TableContextMenu", () => {});});+ describe("header rows", () => {+ const FIRST_ROWS = "triliumSetTableHeaderRow";+ const LATER_ROW = "triliumSetTableHeaderUpToRow";+ const isEnabled = (name: string) => editor.commands.get(name)?.isEnabled;+ const value = (name: string) => editor.commands.get(name)?.value;++ it("enables one command for rows from the first, the other for a single later row", () => {+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");+ expect([isEnabled(FIRST_ROWS), isEnabled(LATER_ROW)]).toEqual([false, false]);++ setModelData(editor.model, modelTable([["1[]1", "12"], ["21", "22"], ["31", "32"]]));+ expect([isEnabled(FIRST_ROWS), isEnabled(LATER_ROW)]).toEqual([true, false]);++ selectCells(editor, [0, 0], [1, 1]);+ expect([isEnabled(FIRST_ROWS), isEnabled(LATER_ROW)]).toEqual([true, false]);++ selectCells(editor, [1, 0], [1, 1]);+ expect([isEnabled(FIRST_ROWS), isEnabled(LATER_ROW)]).toEqual([false, true]);++ selectCells(editor, [1, 0], [2, 0]);+ expect([isEnabled(FIRST_ROWS), isEnabled(LATER_ROW)]).toEqual([false, false]);++ setModelData(editor.model, modelTable([["11"], ["2[]1"]]));+ expect([isEnabled(FIRST_ROWS), isEnabled(LATER_ROW)]).toEqual([false, true]);++ editor.enableReadOnlyMode("spec");+ expect([isEnabled(FIRST_ROWS), isEnabled(LATER_ROW)]).toEqual([false, false]);+ });++ it("holds true while every selected row is a header row", () => {+ setModelData(editor.model, modelTable([["1[]1"], ["21"], ["31"]], 'headingRows="2"'));+ expect(value(FIRST_ROWS)).toBe(true);++ selectCells(editor, [0, 0], [1, 0]);+ expect(value(FIRST_ROWS)).toBe(true);++ selectCells(editor, [0, 0], [2, 0]);+ expect(value(FIRST_ROWS)).toBe(false);++ selectCells(editor, [1, 0], [1, 0]);+ expect(value(LATER_ROW)).toBe(true);++ selectCells(editor, [2, 0], [2, 0]);+ expect(value(LATER_ROW)).toBe(false);+ });++ it("extends the header rows down to the selected rows", () => {+ setModelData(editor.model, modelTable([["11"], ["21"], ["31"]]));+ selectCells(editor, [0, 0], [1, 0]);+ editor.execute(FIRST_ROWS);+ expect(tableData(editor))+ .toBe(modelTable([["11"], ["21"], ["31"]], 'headingRows="2"'));++ setModelData(editor.model,+ modelTable([["11"], ["21"], ["31"], ["4[]1"]], 'headingRows="1"'));+ editor.execute(LATER_ROW);+ expect(tableData(editor))+ .toBe(modelTable([["11"], ["21"], ["31"], ["41"]], 'headingRows="4"'));+ });++ it("turns the selected row and every header row below it into body rows", () => {+ const rows = [["11"], ["21"], ["31"], ["41"], ["51"]];++ setModelData(editor.model, modelTable([["11"], ["2[]1"], ["31"], ["41"], ["51"]],+ 'headingRows="5"'));+ editor.execute(LATER_ROW);+ expect(tableData(editor)).toBe(modelTable(rows, 'headingRows="1"'));++ setModelData(editor.model, modelTable([["1[]1"], ["21"], ["31"], ["41"], ["51"]],+ 'headingRows="5"'));+ editor.execute(FIRST_ROWS);+ expect(tableData(editor)).toBe(modelTable(rows));++ editor.execute("undo");+ expect(tableData(editor)).toBe(modelTable(rows, 'headingRows="5"'));+ });+ });+describe("select table", () => {const COMMAND = "triliumSelectTable";diff --git a/packages/ckeditor5/src/plugins/table_context_menu.ts b/packages/ckeditor5/src/plugins/table_context_menu.tsindex 9d223eda0e..e954ae05d3 100644--- a/packages/ckeditor5/src/plugins/table_context_menu.ts+++ b/packages/ckeditor5/src/plugins/table_context_menu.ts@@ -18,10 +18,12 @@ import { DistributeTableColumnsCommand } from "./table_distribute_columns.js";* Registers insert commands that honor the size of the current selection (the upstream* `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.+ * upstream `selectTableRow` / `selectTableColumn`, and the two header-row commands over the+ * upstream `setTableRowHeader`, which differ in the selections they accept. 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 {@@ -49,6 +51,10 @@ export default class TableContextMenu extends Plugin {editor.commands.add("triliumDeleteTable", new DeleteTableCommand(editor));editor.commands.add("triliumResetTableCellSpans", new ResetTableCellSpansCommand(editor));editor.commands.add("triliumSelectTable", new SelectTableCommand(editor));+ editor.commands.add("triliumSetTableHeaderRow",+ new TableHeaderRowsCommand(editor, "firstRows"));+ editor.commands.add("triliumSetTableHeaderUpToRow",+ new TableHeaderRowsCommand(editor, "laterRow"));const view = editor.editing.view;view.addObserver(MouseObserver);@@ -179,6 +185,51 @@ export class DeleteTableCommand extends Command {}+/**+ * The selections a {@link TableHeaderRowsCommand} acts on: rows starting at the first row of the+ * table, or a single row below it.+ */+export type TableHeaderRowsScope = "firstRows" | "laterRow";++/**+ * Toggles the heading rows through the upstream `setTableRowHeader`, enabled only for the+ * selections its scope covers. `value` is `true` while every selected row is a heading row;+ * executing then turns the selected rows and the heading rows below them into body rows.+ * Otherwise, it extends the heading rows down to the last selected row.+ */+export class TableHeaderRowsCommand extends Command {++ private readonly scope: TableHeaderRowsScope;++ constructor(editor: Editor, scope: TableHeaderRowsScope) {+ super(editor);+ this.scope = scope;+ }++ refresh() {+ 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");+ if (!table) {+ this.isEnabled = false;+ this.value = false;+ return;+ }++ const { first, last } = tableUtils.getRowIndexes(cells);+ this.isEnabled = this.scope === "firstRows"+ ? first === 0+ : first === last && first > 0;+ this.value = this.isEnabled && last < Number(table.getAttribute("headingRows") ?? 0);+ }++ execute() {+ this.editor.execute("setTableRowHeader", { forceValue: !this.value });+ }++}+/*** 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.@@ -300,5 +351,7 @@ declare module "ckeditor5" {triliumDeleteTable: DeleteTableCommand;triliumResetTableCellSpans: ResetTableCellSpansCommand;triliumSelectTable: SelectTableCommand;+ triliumSetTableHeaderRow: TableHeaderRowsCommand;+ triliumSetTableHeaderUpToRow: TableHeaderRowsCommand;}}