Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: update the table toolbar

Adorian Doranfae0aedc940a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f8863d3907..f9b38630e8 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4370,7 +4370,10 @@
"enter-a-whole-number-between-1-and-0": "Enter a whole number between 1 and %0.",
"the-table-is-too-large-max-0-cells": "The table is too large (max %0 cells).",
"math": "Math",
- "date-time": "Date/time"
+ "date-time": "Date/time",
+ "distribute-columns-evenly": "Distribute columns evenly",
+ "merge-selected-cells": "Merge selected cells",
+ "reset-merged-cells": "Reset merged cells"
},
"task-state-dropped-title": "Invalid task states",
"task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
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.html
index f8f0a5f13c..bed30ccbb4 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
@@ -100,7 +100,8 @@ src="3_Tables_image.png" width="384" height="100">
<li>Columns can be resized by hovering the mouse over the border of two adjacent
cells and dragging it.</li>
<li>To give several columns the same width, select cells across them and choose <em>Distribute columns evenly</em> from
- the <a href="#context-menu">context menu</a>.</li>
+ the <span class="tn-icon cke cke-table-column"></span> button of the formatting
+ toolbar or from the <a href="#context-menu">context menu</a>.</li>
<li>By default, the row height is not adjustable using the mouse, but it can
be configured from the cell settings (see below).</li>
<li>To adjust exactly the width (in pixels or percentages) of a cell, select
@@ -147,12 +148,18 @@ src="3_Tables_image.png" width="384" height="100">
<ul>
<li>Click on a single cell and select Merge cell up/down/right/left to merge
with an adjacent cell.</li>
+ <li>Select <em>Merge selected cells</em> to merge the selected cells, the same
+ as pressing the button itself.</li>
<li>Select <em>Split cell vertically</em> or <em>horizontally</em>, to split
a cell into multiple cells (can also be used to undo a merge).</li>
+ <li>Select <em>Reset merged cells</em> to turn each merged cell in the selection
+ back into the single cells it covers, keeping its content in the top-left
+ one.</li>
</ul>
-<p>Merging and splitting are also available by right-clicking the selected
- cells, via the <a href="#context-menu">context menu</a>. To undo merges
- entirely, use <em>Split cells</em> → <em>Reset</em> from the same menu.</p>
+<p><em>Merge selected cells</em> and <em>Reset merged cells</em> are available
+ since v0.107.0. Merging and splitting are also available by right-clicking
+ the selected cells, via the <a href="#context-menu">context menu</a>, where <em>Split cells</em> → <em>Reset</em> does
+ the same as <em>Reset merged cells</em>.</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.md
index 8543992592..b1d949bdcf 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md
@@ -54,7 +54,7 @@ Right-clicking a cell that is not part of the current selection moves the cursor
## Resizing cells
* Columns can be resized by hovering the mouse over the border of two adjacent cells and dragging it.
-* To give several columns the same width, select cells across them and choose _Distribute columns evenly_ from the [context menu](#context-menu).
+* To give several columns the same width, select cells across them and choose _Distribute columns evenly_ from the <span class="tn-icon cke cke-table-column"></span> button of the formatting toolbar or from the [context menu](#context-menu).
* By default, the row height is not adjustable using the mouse, but it can be configured from the cell settings (see below).
* To adjust exactly the width (in pixels or percentages) of a cell, select the <span class="tn-icon cke cke-table-cell-properties"></span> button.
@@ -85,9 +85,11 @@ To merge two or more cells together, simply select them via drag & drop and pres
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 _Merge selected cells_ to merge the selected cells, the same as pressing the button itself.
* Select _Split cell vertically_ or _horizontally_, to split a cell into multiple cells (can also be used to undo a merge).
+* Select _Reset merged cells_ to turn each merged cell in the selection back into the single cells it covers, keeping its content in the top-left one.
-Merging and splitting are also available by right-clicking the selected cells, via the [context menu](#context-menu). To undo merges entirely, use _Split cells_ → _Reset_ from the same menu.
+_Merge selected cells_ and _Reset merged cells_ are available since v0.107.0. Merging and splitting are also available by right-clicking the selected cells, via the [context menu](#context-menu), where _Split cells_ → _Reset_ does the same as _Reset merged cells_.
## Table properties
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index f19d83a5d4..f5d35f4f7f 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -60,6 +60,7 @@ import TableIndent from "./plugins/table_indent.js";
import TableContextMenu from "./plugins/table_context_menu.js";
import TableMove from "./plugins/table_move/table_move.js";
import TableInsertUI from "./plugins/table_insert/table_insert_ui.js";
+import TableToolbarDropdowns from "./plugins/table_toolbar_dropdowns.js";
import ToolbarGroupMenu from "./plugins/toolbar_group_menu.js";
/**
@@ -99,6 +100,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
TableContextMenu,
TableMove,
TableInsertUI,
+ TableToolbarDropdowns,
ToolbarGroupMenu,
CopyAnchorLinkButton,
CopyLinkUrlButton,
diff --git a/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.spec.ts b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.spec.ts
new file mode 100644
index 0000000000..77685f60eb
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.spec.ts
@@ -0,0 +1,208 @@
+import {
+ _setModelData as setModelData,
+ ButtonView,
+ Essentials,
+ ListItemView,
+ ListSeparatorView,
+ Paragraph,
+ SplitButtonView,
+ SwitchButtonView,
+ Table
+} from "ckeditor5";
+import type { ClassicEditor, DropdownView } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { modelTable, selectCells } from "../../test/table-kit.js";
+import TableToolbarDropdowns from "./table_toolbar_dropdowns.js";
+
+const TOOLBAR = ["tableColumn", "mergeTableCells"] as const;
+
+type ToolbarItem = typeof TOOLBAR[number];
+
+describe("TableToolbarDropdowns", () => {
+ describe("compared with the upstream dropdowns", () => {
+ for (const content of ["en", "ar"]) {
+ it(`keeps every upstream item and adds the Trilium ones (${content})`, async () => {
+ const config = { toolbar: [...TOOLBAR], language: { content } };
+ const upstream = await createTestEditor([Essentials, Paragraph, Table], config);
+ const editor = await createTestEditor(
+ [Essentials, Paragraph, Table, TableToolbarDropdowns], config);
+
+ for (const name of TOOLBAR) {
+ const upstreamButton = getDropdown(upstream, name).buttonView;
+ const button = getDropdown(editor, name).buttonView;
+ expect(button.constructor, name).toBe(upstreamButton.constructor);
+ expect(button.label, name).toBe(upstreamButton.label);
+ expect(button.icon, name).toBe(upstreamButton.icon);
+ }
+
+ expect(getItems(getDropdown(editor, "tableColumn"))).toEqual([
+ ...getItems(getDropdown(upstream, "tableColumn")),
+ "|",
+ "triliumDistributeTableColumns: Distribute columns evenly"
+ ]);
+
+ const upstreamMergeItems = getItems(getDropdown(upstream, "mergeTableCells"));
+ const splitIndex = upstreamMergeItems.indexOf("|");
+ expect(splitIndex).toBeGreaterThan(0);
+ expect(getItems(getDropdown(editor, "mergeTableCells"))).toEqual([
+ ...upstreamMergeItems.slice(0, splitIndex),
+ "mergeTableCells: Merge selected cells",
+ ...upstreamMergeItems.slice(splitIndex),
+ "triliumResetTableCellSpans: Reset merged cells"
+ ]);
+ });
+ }
+ });
+
+ describe("in the editor", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Table, TableToolbarDropdowns], {
+ toolbar: [...TOOLBAR]
+ });
+ setModelData(editor.model, modelTable([["1[]1", "12"], ["21", "22"]]));
+ });
+
+ it("enables the dropdowns inside a table only", () => {
+ for (const name of TOOLBAR) {
+ expect(getDropdown(editor, name).isEnabled, name).toBe(true);
+ }
+
+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");
+ for (const name of TOOLBAR) {
+ expect(getDropdown(editor, name).isEnabled, name).toBe(false);
+ }
+ });
+
+ it("enables the added items with their commands", () => {
+ const columnDropdown = getDropdown(editor, "tableColumn");
+ const mergeDropdown = getDropdown(editor, "mergeTableCells");
+ expect(getItem(columnDropdown, "Distribute columns evenly").isEnabled).toBe(false);
+ expect(getItem(mergeDropdown, "Merge selected cells").isEnabled).toBe(false);
+ expect(getItem(mergeDropdown, "Reset merged cells").isEnabled).toBe(false);
+
+ selectCells(editor, [0, 0], [0, 1]);
+ expect(getItem(columnDropdown, "Distribute columns evenly").isEnabled).toBe(true);
+ expect(getItem(mergeDropdown, "Merge selected cells").isEnabled).toBe(true);
+ expect(getItem(mergeDropdown, "Reset merged cells").isEnabled).toBe(false);
+
+ editor.execute("mergeTableCells");
+ expect(getItem(mergeDropdown, "Reset merged cells").isEnabled).toBe(true);
+ });
+
+ it("runs the command of a clicked item and focuses the editing view", () => {
+ const execute = vi.spyOn(editor, "execute");
+ const focus = vi.spyOn(editor.editing.view, "focus");
+ selectCells(editor, [0, 0], [0, 1]);
+
+ const columnDropdown = getDropdown(editor, "tableColumn");
+ clickItem(columnDropdown, "Distribute columns evenly");
+ expect(execute).toHaveBeenLastCalledWith("triliumDistributeTableColumns");
+ expect(columnDropdown.isOpen).toBe(false);
+ expect(focus).toHaveBeenCalledTimes(1);
+
+ const mergeDropdown = getDropdown(editor, "mergeTableCells");
+ clickItem(mergeDropdown, "Merge selected cells");
+ expect(execute).toHaveBeenLastCalledWith("mergeTableCells");
+ clickItem(mergeDropdown, "Reset merged cells");
+ expect(execute).toHaveBeenLastCalledWith("triliumResetTableCellSpans");
+ expect(mergeDropdown.isOpen).toBe(false);
+ expect(focus).toHaveBeenCalledTimes(3);
+ });
+
+ it("toggles a switch without closing the dropdown or moving the focus", () => {
+ const focus = vi.spyOn(editor.editing.view, "focus");
+ const dropdown = getDropdown(editor, "tableColumn");
+
+ clickItem(dropdown, "Header column");
+ expect(editor.commands.get("setTableColumnHeader")?.value).toBe(true);
+ expect(getItem(dropdown, "Header column").isOn).toBe(true);
+ expect(dropdown.isOpen).toBe(true);
+ expect(focus).not.toHaveBeenCalled();
+ });
+
+ it("merges the selected cells from the main part of the split button", () => {
+ const execute = vi.spyOn(editor, "execute");
+ const dropdown = getDropdown(editor, "mergeTableCells");
+ selectCells(editor, [0, 0], [0, 1]);
+
+ const splitButton = dropdown.buttonView as SplitButtonView;
+ getElement(splitButton.actionView).click();
+ expect(execute).toHaveBeenCalledWith("mergeTableCells");
+ expect(dropdown.isOpen).toBe(false);
+ expect(getItem(dropdown, "Reset merged cells").isEnabled).toBe(true);
+ });
+
+ it("leaves out an item whose command is not registered", () => {
+ const getCommand = editor.commands.get.bind(editor.commands);
+ vi.spyOn(editor.commands, "get").mockImplementation(((name: string) =>
+ name === "selectTableColumn" ? undefined : getCommand(name)
+ ) as typeof editor.commands.get);
+
+ const dropdown = editor.ui.componentFactory.create("tableColumn") as DropdownView;
+ dropdown.render();
+ document.body.appendChild(getElement(dropdown));
+
+ const items = getItems(dropdown);
+ expect(items).not.toContain("selectTableColumn: Select column");
+ expect(items).toContain("removeTableColumn: Delete column");
+
+ getElement(dropdown).remove();
+ dropdown.destroy();
+ });
+ });
+});
+
+function getElement(view: { element: HTMLElement | null }): HTMLElement {
+ if (!view.element) {
+ throw new Error("The view is not rendered.");
+ }
+ return view.element;
+}
+
+function getDropdown(editor: ClassicEditor, name: ToolbarItem): DropdownView {
+ return editor.ui.view.toolbar.items.get(TOOLBAR.indexOf(name)) as DropdownView;
+}
+
+/** The list buttons of `dropdown`, which is opened to build them. */
+function getButtons(dropdown: DropdownView): (ButtonView & { commandName: string } | null)[] {
+ dropdown.isOpen = true;
+ const items = dropdown.listView?.items;
+ if (!items) {
+ throw new Error("The dropdown has no list.");
+ }
+
+ return Array.from(items, (item) => {
+ if (item instanceof ListSeparatorView) {
+ return null;
+ }
+ expect(item).toBeInstanceOf(ListItemView);
+ return (item as ListItemView).children.first as ButtonView & { commandName: string };
+ });
+}
+
+/** The items of `dropdown` as `commandName: label` strings, with `|` for a separator. */
+function getItems(dropdown: DropdownView): string[] {
+ return getButtons(dropdown).map((button) => {
+ if (!button) {
+ return "|";
+ }
+ const suffix = button instanceof SwitchButtonView ? " (switch)" : "";
+ return `${button.commandName}: ${button.label}${suffix}`;
+ });
+}
+
+function getItem(dropdown: DropdownView, label: string): ButtonView {
+ const button = getButtons(dropdown).find((candidate) => candidate?.label === label);
+ if (!button) {
+ throw new Error(`The dropdown has no "${label}" item.`);
+ }
+ return button;
+}
+
+function clickItem(dropdown: DropdownView, label: string) {
+ getElement(getItem(dropdown, label)).click();
+}
diff --git a/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.ts b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.ts
new file mode 100644
index 0000000000..472ceb21e9
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_toolbar_dropdowns.ts
@@ -0,0 +1,176 @@
+import {
+ addListToDropdown,
+ Collection,
+ createDropdown,
+ IconTableColumn,
+ IconTableMergeCell,
+ Plugin,
+ SplitButtonView,
+ SwitchButtonView,
+ Table,
+ UIModel
+} from "ckeditor5";
+import type {
+ ButtonExecuteEvent,
+ Command,
+ DropdownView,
+ ListDropdownItemDefinition,
+ Locale
+} from "ckeditor5";
+
+import TableContextMenu from "./table_context_menu.js";
+
+/**
+ * Replaces the `tableColumn` and `mergeTableCells` dropdowns of `TableUI` with copies that add
+ * commands of the table context menu: "Distribute columns evenly", "Merge selected cells" and
+ * "Reset merged cells".
+ *
+ * `TableUI` builds its item lists in private methods, so the dropdowns are rebuilt from public
+ * helpers and command names instead of patched. The spec compares them with the upstream
+ * dropdowns to catch upstream changes on a CKEditor upgrade.
+ */
+export default class TableToolbarDropdowns extends Plugin {
+
+ static get requires() {
+ return [Table, TableContextMenu] as const;
+ }
+
+ static get pluginName() {
+ return "TableToolbarDropdowns" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+ const factory = editor.ui.componentFactory;
+ const t = editor.t;
+ const isContentLtr = editor.locale.contentLanguageDirection === "ltr";
+
+ // Replaces the dropdowns of `TableUI`, which `Table` initializes before this plugin.
+ factory.add("tableColumn", (locale) => this.createDropdown(locale, {
+ label: t("Column"),
+ icon: IconTableColumn,
+ items: [
+ switchItem("setTableColumnHeader", t("Header column")),
+ SEPARATOR_ITEM,
+ buttonItem(isContentLtr ? "insertTableColumnLeft" : "insertTableColumnRight",
+ t("Insert column left")),
+ buttonItem(isContentLtr ? "insertTableColumnRight" : "insertTableColumnLeft",
+ t("Insert column right")),
+ buttonItem("removeTableColumn", t("Delete column")),
+ buttonItem("selectTableColumn", t("Select column")),
+ SEPARATOR_ITEM,
+ buttonItem("triliumDistributeTableColumns", t("Distribute columns evenly"))
+ ]
+ }));
+
+ factory.add("mergeTableCells", (locale) => this.createDropdown(locale, {
+ label: t("Merge cells"),
+ icon: IconTableMergeCell,
+ splitButtonCommandName: "mergeTableCells",
+ items: [
+ buttonItem("mergeTableCellUp", t("Merge cell up")),
+ buttonItem(isContentLtr ? "mergeTableCellRight" : "mergeTableCellLeft",
+ t("Merge cell right")),
+ buttonItem("mergeTableCellDown", t("Merge cell down")),
+ buttonItem(isContentLtr ? "mergeTableCellLeft" : "mergeTableCellRight",
+ t("Merge cell left")),
+ buttonItem("mergeTableCells", t("Merge selected cells")),
+ SEPARATOR_ITEM,
+ buttonItem("splitTableCellVertically", t("Split cell vertically")),
+ buttonItem("splitTableCellHorizontally", t("Split cell horizontally")),
+ buttonItem("triliumResetTableCellSpans", t("Reset merged cells"))
+ ]
+ }));
+ }
+
+ /**
+ * Creates a dropdown listing `items`, enabled while one of their commands is. With
+ * `splitButtonCommandName`, the main part of a split button runs that command.
+ */
+ private createDropdown(locale: Locale, options: TableDropdownOptions): DropdownView {
+ const editor = this.editor;
+ const { label, icon, items, splitButtonCommandName } = options;
+
+ const dropdownView = splitButtonCommandName
+ ? createDropdown(locale, SplitButtonView)
+ : createDropdown(locale);
+ dropdownView.buttonView.set({ label, icon, tooltip: true });
+
+ const commands: Command[] = [];
+ const definitions = new Collection<ListDropdownItemDefinition>();
+ for (const item of items) {
+ if (item.type === "separator") {
+ // A new object each time: `Collection#add()` gives it an `id`.
+ definitions.add({ type: "separator" });
+ continue;
+ }
+
+ // Skips an item whose command is not registered, e.g. after an upstream rename.
+ const command = editor.commands.get(item.commandName);
+ if (!command) {
+ continue;
+ }
+ commands.push(command);
+
+ const model = new UIModel({
+ commandName: item.commandName,
+ label: item.label,
+ withText: true
+ });
+ model.bind("isEnabled").to(command);
+ if (item.type === "switchbutton") {
+ model.bind("isOn").to(command, "value");
+ }
+ definitions.add({ type: item.type, model });
+ }
+ addListToDropdown(dropdownView, definitions);
+
+ dropdownView.bind("isEnabled").toMany(commands, "isEnabled",
+ (...areEnabled) => areEnabled.some((isEnabled) => isEnabled));
+
+ if (splitButtonCommandName) {
+ this.listenTo(dropdownView.buttonView, "execute", () => {
+ editor.execute(splitButtonCommandName);
+ editor.editing.view.focus();
+ });
+ }
+ this.listenTo<ButtonExecuteEvent>(dropdownView, "execute", (evt) => {
+ const source = evt.source as { commandName: string };
+ editor.execute(source.commandName);
+ // A switch keeps the dropdown open, so the focus stays in the list.
+ if (!(source instanceof SwitchButtonView)) {
+ editor.editing.view.focus();
+ }
+ });
+
+ return dropdownView;
+ }
+
+}
+
+type TableDropdownItem =
+ | { type: "button" | "switchbutton"; commandName: string; label: string }
+ | { type: "separator" };
+
+interface TableDropdownOptions {
+ label: string;
+ icon: string;
+ items: TableDropdownItem[];
+ splitButtonCommandName?: string;
+}
+
+const SEPARATOR_ITEM: TableDropdownItem = { type: "separator" };
+
+function buttonItem(commandName: string, label: string): TableDropdownItem {
+ return { type: "button", commandName, label };
+}
+
+function switchItem(commandName: string, label: string): TableDropdownItem {
+ return { type: "switchbutton", commandName, label };
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [TableToolbarDropdowns.pluginName]: TableToolbarDropdowns;
+ }
+}