Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: allow rearranging rows and columns by keyboard

Adorian Doranadc2912e62c8
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 93930c2a48..534c83d826 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4359,7 +4359,11 @@
"rotate-270": "Rotate 270°",
"flip-horizontally": "Flip horizontally",
"flip-vertically": "Flip vertically",
- "change-icon": "Change icon"
+ "change-icon": "Change icon",
+ "move-row-up": "Move row up",
+ "move-row-down": "Move row down",
+ "move-column-left": "Move column left",
+ "move-column-right": "Move column right"
},
"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 320905f9a5..5256d59c6e 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
@@ -82,6 +82,23 @@ src="3_Tables_image.png" width="384" height="100">
<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>Moving rows and columns</h2>
+<p>Since v0.106.0, rows and columns can be reordered with the keyboard:</p>
+<ul>
+ <li><kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> move the
+ rows touched by the selection up or down.</li>
+ <li><kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> move the
+ columns touched by the selection left or right.</li>
+</ul>
+<p>Merged cells are never split by a move. The rows or columns held together
+ by a merged cell travel as one block, and moving toward such a block jumps
+ over it entirely.</p>
+<p>When the table has a header row, a header row moved below the header area
+ becomes a regular row, and a regular row moved into the header area becomes
+ a header row. Header columns behave the same way.</p>
+<p>Outside of tables, <kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> keep
+ navigating the note history, and <kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> keep
+ moving the current paragraph.</p>
<h2>Merging cells</h2>
<p>To merge two or more cells together, simply select them via drag &amp;
drop and press the&nbsp;<span class="tn-icon cke cke-table-merge-cell"></span> button
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 96527cdcb9..252c8e7da6 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md
@@ -51,6 +51,19 @@ Right-clicking a cell that is not part of the current selection moves the cursor
* 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.
+## Moving rows and columns
+
+Since v0.106.0, rows and columns can be reordered with the keyboard:
+
+* <kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> move the rows touched by the selection up or down.
+* <kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> move the columns touched by the selection left or right.
+
+Merged cells are never split by a move. The rows or columns held together by a merged cell travel as one block, and moving toward such a block jumps over it entirely.
+
+When the table has a header row, a header row moved below the header area becomes a regular row, and a regular row moved into the header area becomes a header row. Header columns behave the same way.
+
+Outside of tables, <kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> keep navigating the note history, and <kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> keep moving the current paragraph.
+
## Merging cells
To merge two or more cells together, simply select them via drag & drop and press the <span class="tn-icon cke cke-table-merge-cell"></span> button from the formatting toolbar.
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 4ce982ee0c..f3f2aef893 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -58,6 +58,7 @@ import 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";
+import TableMove from "./plugins/table_move/table_move.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.
@@ -94,6 +95,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
CollapsibleListItems,
TableIndent,
TableContextMenu,
+ TableMove,
CopyAnchorLinkButton,
CopyLinkUrlButton,
ImageActions,
diff --git a/packages/ckeditor5/src/plugins/move_block_updown.spec.ts b/packages/ckeditor5/src/plugins/move_block_updown.spec.ts
index d64a08769b..a93516e9d4 100644
--- a/packages/ckeditor5/src/plugins/move_block_updown.spec.ts
+++ b/packages/ckeditor5/src/plugins/move_block_updown.spec.ts
@@ -5,6 +5,7 @@ import {
Essentials,
Paragraph,
Plugin,
+ Table,
} from "ckeditor5";
import type { ModelElement, ModelText } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -12,6 +13,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import { TestBoxPlugin } from "../../test/fixture-plugins.js";
import MoveBlockUpDownPlugin from "./move_block_updown.js";
+import TableMove from "./table_move/table_move.js";
/** Returns the text data of the Nth block in the editor root (0-indexed). */
function getBlockText(editor: ClassicEditor, index: number): string {
@@ -518,3 +520,105 @@ describe("MoveBlockUpDownPlugin with collapsible summary element", () => {
expect(c0?.is("element") && (c0 as ModelElement).name).toBe("details");
});
});
+
+describe("MoveBlockUpDownPlugin inside tables", () => {
+ async function fireAltArrow(editor: ClassicEditor, key: "ArrowUp" | "ArrowDown") {
+ await new Promise<void>((resolve) => {
+ editor.editing.view.once("render", () => resolve());
+ editor.editing.view.forceRender();
+ });
+ const domRoot = editor.editing.view.getDomRoot();
+ if (!domRoot) { throw new Error("No editing DOM root"); }
+
+ const event = new KeyboardEvent("keydown", {
+ key,
+ altKey: true,
+ bubbles: true,
+ cancelable: true
+ });
+ domRoot.dispatchEvent(event);
+ return event;
+ }
+
+ const twoRowTable =
+ "<table>" +
+ "<tableRow><tableCell><paragraph>a[]</paragraph></tableCell></tableRow>" +
+ "<tableRow><tableCell><paragraph>b</paragraph></tableCell></tableRow>" +
+ "</table>";
+
+ describe("with the TableMove plugin", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor(
+ [Essentials, Paragraph, Table, MoveBlockUpDownPlugin, TableMove]
+ );
+ });
+
+ it("moves the table row instead of the block", async () => {
+ setModelData(editor.model, twoRowTable);
+
+ await fireAltArrow(editor, "ArrowDown");
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ "<table>" +
+ "<tableRow><tableCell><paragraph>b</paragraph></tableCell></tableRow>" +
+ "<tableRow><tableCell><paragraph>a</paragraph></tableCell></tableRow>" +
+ "</table>"
+ );
+ });
+
+ it("does not fall back to a block move at the table edge", async () => {
+ // The cell holds two paragraphs; a block-move fallback would swap them.
+ setModelData(editor.model,
+ "<table><tableRow><tableCell>" +
+ "<paragraph>x</paragraph><paragraph>y[]</paragraph>" +
+ "</tableCell></tableRow></table>"
+ );
+
+ const event = await fireAltArrow(editor, "ArrowUp");
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ "<table><tableRow><tableCell>" +
+ "<paragraph>x</paragraph><paragraph>y</paragraph>" +
+ "</tableCell></tableRow></table>"
+ );
+ });
+
+ it("still moves a selected table widget as a block", async () => {
+ setModelData(editor.model,
+ "<paragraph>First</paragraph>" +
+ "[<table><tableRow><tableCell><paragraph>a</paragraph></tableCell></tableRow></table>]"
+ );
+
+ await fireAltArrow(editor, "ArrowUp");
+
+ const root = editor.model.document.getRoot();
+ if (!root) { throw new Error("No root"); }
+ const c0 = root.getChild(0);
+ expect(c0?.is("element") && (c0 as ModelElement).name).toBe("table");
+ });
+ });
+
+ describe("without the TableMove plugin", () => {
+ it("keeps moving blocks inside a table cell", async () => {
+ const editor = await createTestEditor(
+ [Essentials, Paragraph, Table, MoveBlockUpDownPlugin]
+ );
+ setModelData(editor.model,
+ "<table><tableRow><tableCell>" +
+ "<paragraph>x</paragraph><paragraph>y[]</paragraph>" +
+ "</tableCell></tableRow></table>"
+ );
+
+ await fireAltArrow(editor, "ArrowUp");
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ "<table><tableRow><tableCell>" +
+ "<paragraph>y</paragraph><paragraph>x</paragraph>" +
+ "</tableCell></tableRow></table>"
+ );
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/move_block_updown.ts b/packages/ckeditor5/src/plugins/move_block_updown.ts
index df72cddf93..8871415011 100644
--- a/packages/ckeditor5/src/plugins/move_block_updown.ts
+++ b/packages/ckeditor5/src/plugins/move_block_updown.ts
@@ -4,10 +4,17 @@
import { Command, ModelDocumentSelection, ModelElement, ModelLiveRange, ModelNode, Plugin, _isMac, Editor } from 'ckeditor5';
-const keyMap = {
- ArrowUp: 'moveBlockUp',
- ArrowDown: 'moveBlockDown'
-};
+import { isSelectionInTable } from "./table_move/table_move_commands.js";
+
+interface MoveKeyCommands {
+ table: "moveTableRowUp" | "moveTableRowDown";
+ block: "moveBlockUp" | "moveBlockDown";
+}
+
+const keyMap = new Map<string, MoveKeyCommands>([
+ ["ArrowUp", { table: "moveTableRowUp", block: "moveBlockUp" }],
+ ["ArrowDown", { table: "moveTableRowDown", block: "moveBlockDown" }]
+]);
export default class MoveBlockUpDownPlugin extends Plugin {
init() {
@@ -22,40 +29,63 @@ export default class MoveBlockUpDownPlugin extends Plugin {
}
bindMoveBlockShortcuts(editor: Editor) {
- editor.editing.view.once('render', () => {
- const domRoot = editor.editing.view.getDomRoot();
- /* v8 ignore next 1 -- domRoot is always set while the editor is alive; only null after destroy */
- if (!domRoot) return;
-
- const isMac = _isMac(navigator.userAgent.toLowerCase());
- const handleKeydown = (e: KeyboardEvent) => {
- const command = keyMap[e.key];
- if (!command) return;
- const isOnlyMeta = (!e.ctrlKey && !e.altKey && e.metaKey);
- const isOnlyAlt = (!e.ctrlKey && e.altKey && !e.metaKey);
-
- if ((!isMac && isOnlyMeta) || isOnlyAlt) {
- e.preventDefault();
- e.stopImmediatePropagation();
- editor.execute(command);
+ addEditingKeydownCapture(this, (e) => {
+ const commands = keyMap.get(e.key);
+ if (!commands || !hasMoveModifier(e)) {
+ return;
+ }
+ e.preventDefault();
+ e.stopImmediatePropagation();
+
+ // Inside a table the whole row moves; the block commands would only shuffle
+ // paragraphs inside one cell. The guard keeps block moves working in editor
+ // builds without the TableMove plugin.
+ const tableCommand = editor.commands.get(commands.table);
+ if (tableCommand && isSelectionInTable(editor.model.document.selection)) {
+ if (tableCommand.isEnabled) {
+ editor.execute(commands.table);
}
- };
-
- domRoot.addEventListener('keydown', handleKeydown, { capture: true });
-
- // Remove the native listener when the editor is destroyed. The editing root is
- // reused across editor recreations (e.g. switching the content language rebuilds
- // the editor in the same container — see #10095). Without this cleanup the orphaned
- // listener stays attached, captures the keystroke first and runs editor.execute()
- // against the destroyed editor — silently swallowing the shortcut until a reload.
- this.listenTo(editor, 'destroy', () => {
- domRoot.removeEventListener('keydown', handleKeydown, { capture: true });
- });
+ return;
+ }
+ editor.execute(commands.block);
});
}
}
+/** True when the keydown carries the move-shortcut modifier: plain Alt, or plain Meta off macOS. */
+export function hasMoveModifier(e: KeyboardEvent): boolean {
+ const isMac = _isMac(navigator.userAgent.toLowerCase());
+ const isOnlyMeta = (!e.ctrlKey && !e.altKey && e.metaKey);
+ const isOnlyAlt = (!e.ctrlKey && e.altKey && !e.metaKey);
+ return (!isMac && isOnlyMeta) || isOnlyAlt;
+}
+
+/**
+ * Adds a capture-phase keydown listener on the editing DOM root once it renders. Native
+ * capturing intercepts the keystroke before plugin-level keystroke handling, which can fail
+ * when the selection is near an object, and before window-scoped application shortcuts.
+ *
+ * The listener is removed when the editor is destroyed. The editing root is reused across
+ * editor recreations (e.g. switching the content language rebuilds the editor in the same
+ * container — see #10095). Without this cleanup the orphaned listener stays attached, captures
+ * the keystroke first and runs editor.execute() against the destroyed editor — silently
+ * swallowing the shortcut until a reload.
+ */
+export function addEditingKeydownCapture(plugin: Plugin, handleKeydown: (e: KeyboardEvent) => void) {
+ const editor = plugin.editor;
+ editor.editing.view.once('render', () => {
+ const domRoot = editor.editing.view.getDomRoot();
+ /* v8 ignore next 1 -- domRoot is always set while the editor is alive; only null after destroy */
+ if (!domRoot) return;
+
+ domRoot.addEventListener('keydown', handleKeydown, { capture: true });
+ plugin.listenTo(editor, 'destroy', () => {
+ domRoot.removeEventListener('keydown', handleKeydown, { capture: true });
+ });
+ });
+}
+
abstract class MoveBlockUpDownCommand extends Command {
abstract getSibling(selectedBlock: ModelElement): ModelNode | null;
diff --git a/packages/ckeditor5/src/plugins/table_move/table_move.spec.ts b/packages/ckeditor5/src/plugins/table_move/table_move.spec.ts
new file mode 100644
index 0000000000..c7ab221336
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_move/table_move.spec.ts
@@ -0,0 +1,129 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ Essentials,
+ Paragraph,
+ Table
+} from "ckeditor5";
+import type { ClassicEditor } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { modelTable } from "../../../test/table-kit.js";
+import TableMove from "./table_move.js";
+
+describe("TableMove", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Table, TableMove]);
+ });
+
+ async function getRenderedDomRoot(): Promise<HTMLElement> {
+ await new Promise<void>((resolve) => {
+ editor.editing.view.once("render", () => resolve());
+ editor.editing.view.forceRender();
+ });
+ const domRoot = editor.editing.view.getDomRoot();
+ if (!domRoot) {
+ throw new Error("No editing DOM root.");
+ }
+ return domRoot;
+ }
+
+ function keydown(domRoot: HTMLElement, key: string, modifiers: Partial<KeyboardEventInit> = {}) {
+ const event = new KeyboardEvent("keydown", {
+ key,
+ altKey: true,
+ bubbles: true,
+ cancelable: true,
+ ...modifiers
+ });
+ domRoot.dispatchEvent(event);
+ return event;
+ }
+
+ it("registers the plugin and the four move commands", () => {
+ expect(editor.plugins.get(TableMove)).toBeInstanceOf(TableMove);
+ expect(editor.commands.get("moveTableRowUp")).toBeDefined();
+ expect(editor.commands.get("moveTableRowDown")).toBeDefined();
+ expect(editor.commands.get("moveTableColumnLeft")).toBeDefined();
+ expect(editor.commands.get("moveTableColumnRight")).toBeDefined();
+ });
+
+ it("registers accessibility info for the four keystrokes", () => {
+ const contentEditing = editor.accessibility.keystrokeInfos.get("contentEditing");
+ const keystrokes = [...(contentEditing?.groups.get("common")?.keystrokes ?? [])];
+ const labels = keystrokes.map((definition) => definition.label);
+ expect(labels).toContain("Move row up");
+ expect(labels).toContain("Move row down");
+ expect(labels).toContain("Move column left");
+ expect(labels).toContain("Move column right");
+ });
+
+ it("moves the column on Alt+ArrowRight inside a table", async () => {
+ setModelData(editor.model, modelTable([["a[]", "b"]]));
+ const domRoot = await getRenderedDomRoot();
+
+ const event = keydown(domRoot, "ArrowRight");
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(modelTable([["b", "a"]]));
+ });
+
+ it("moves the column on Alt+ArrowLeft inside a table", async () => {
+ setModelData(editor.model, modelTable([["a", "b[]"]]));
+ const domRoot = await getRenderedDomRoot();
+
+ const event = keydown(domRoot, "ArrowLeft");
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(modelTable([["b", "a"]]));
+ });
+
+ it("lets Alt+ArrowLeft through outside a table so the app shortcut keeps working", async () => {
+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");
+ const domRoot = await getRenderedDomRoot();
+ const spy = vi.spyOn(editor, "execute");
+
+ const event = keydown(domRoot, "ArrowLeft");
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it("swallows an edge press inside a table without executing or navigating", async () => {
+ setModelData(editor.model, modelTable([["a[]", "b"]]));
+ const domRoot = await getRenderedDomRoot();
+ const spy = vi.spyOn(editor, "execute");
+
+ const event = keydown(domRoot, "ArrowLeft");
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(spy).not.toHaveBeenCalled();
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(modelTable([["a", "b"]]));
+ });
+
+ it("ignores the keys without the move modifier or with extra modifiers", async () => {
+ setModelData(editor.model, modelTable([["a[]", "b"]]));
+ const domRoot = await getRenderedDomRoot();
+ const spy = vi.spyOn(editor, "execute");
+
+ expect(keydown(domRoot, "ArrowRight", { ctrlKey: true }).defaultPrevented).toBe(false);
+ expect(keydown(domRoot, "a").defaultPrevented).toBe(false);
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it("removes the native keydown listener when the editor is destroyed", async () => {
+ setModelData(editor.model, modelTable([["a[]"]]));
+ const domRoot = await getRenderedDomRoot();
+ const removeSpy = vi.spyOn(domRoot, "removeEventListener");
+
+ await editor.destroy();
+
+ expect(removeSpy).toHaveBeenCalledWith("keydown", expect.any(Function), { capture: true });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/table_move/table_move.ts b/packages/ckeditor5/src/plugins/table_move/table_move.ts
new file mode 100644
index 0000000000..76b720208e
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_move/table_move.ts
@@ -0,0 +1,77 @@
+import { Plugin, Table, TableUtils } from "ckeditor5";
+
+import { addEditingKeydownCapture, hasMoveModifier } from "../move_block_updown.js";
+import { isSelectionInTable, MoveTableColumnCommand, MoveTableRowCommand } from "./table_move_commands.js";
+
+/**
+ * Moves table rows and columns with Alt+Arrow keys. The rows or columns touched by the
+ * selection move as one block over the adjacent one; merged cells extend both blocks so the
+ * grid is never torn apart. Alt+ArrowUp/Down is dispatched by `MoveBlockUpDownPlugin`, which
+ * runs the row commands when the selection is in a table.
+ */
+export default class TableMove extends Plugin {
+
+ static get requires() {
+ return [Table, TableUtils] as const;
+ }
+
+ static get pluginName() {
+ return "TableMove" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+ const t = editor.t;
+
+ editor.commands.add("moveTableRowUp", new MoveTableRowCommand(editor, "up"));
+ editor.commands.add("moveTableRowDown", new MoveTableRowCommand(editor, "down"));
+ editor.commands.add("moveTableColumnLeft", new MoveTableColumnCommand(editor, "left"));
+ editor.commands.add("moveTableColumnRight", new MoveTableColumnCommand(editor, "right"));
+
+ // Alt+Left/Right keeps its application meaning (note history) outside tables, so the
+ // event is only swallowed when the selection is in a table. That includes presses at
+ // the table edge, where the command is a no-op, so they do not navigate away mid-edit.
+ addEditingKeydownCapture(this, (e) => {
+ const command = columnKeyCommands.get(e.key);
+ if (!command || !hasMoveModifier(e)) {
+ return;
+ }
+ if (!isSelectionInTable(editor.model.document.selection)) {
+ return;
+ }
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ if (editor.commands.get(command)?.isEnabled) {
+ editor.execute(command);
+ }
+ });
+
+ editor.accessibility.addKeystrokeInfos({
+ keystrokes: [
+ { label: t("Move row up"), keystroke: "Alt+ArrowUp" },
+ { label: t("Move row down"), keystroke: "Alt+ArrowDown" },
+ { label: t("Move column left"), keystroke: "Alt+ArrowLeft" },
+ { label: t("Move column right"), keystroke: "Alt+ArrowRight" }
+ ]
+ });
+ }
+
+}
+
+const columnKeyCommands = new Map<string, "moveTableColumnLeft" | "moveTableColumnRight">([
+ ["ArrowLeft", "moveTableColumnLeft"],
+ ["ArrowRight", "moveTableColumnRight"]
+]);
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [TableMove.pluginName]: TableMove;
+ }
+
+ interface CommandsMap {
+ moveTableRowUp: MoveTableRowCommand;
+ moveTableRowDown: MoveTableRowCommand;
+ moveTableColumnLeft: MoveTableColumnCommand;
+ moveTableColumnRight: MoveTableColumnCommand;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/table_move/table_move_commands.spec.ts b/packages/ckeditor5/src/plugins/table_move/table_move_commands.spec.ts
new file mode 100644
index 0000000000..7495c17949
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_move/table_move_commands.spec.ts
@@ -0,0 +1,282 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ Essentials,
+ Paragraph,
+ Table,
+ TableColumnResize,
+ TableUtils
+} from "ckeditor5";
+import type { ClassicEditor } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { cellAt, modelTable, selectCells } from "../../../test/table-kit.js";
+import TableMove from "./table_move.js";
+
+const MOVE_COMMANDS = [
+ "moveTableRowUp",
+ "moveTableRowDown",
+ "moveTableColumnLeft",
+ "moveTableColumnRight"
+] as const;
+
+describe("table move commands", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Table, TableColumnResize, TableMove]);
+ });
+
+ function tableData(): string {
+ return getModelData(editor.model, { withoutSelection: true });
+ }
+
+ describe("isEnabled", () => {
+ it("is disabled outside a table", () => {
+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");
+ for (const name of MOVE_COMMANDS) {
+ expect(editor.commands.get(name)?.isEnabled, name).toBe(false);
+ }
+ });
+
+ it("is disabled when the move would leave the table", () => {
+ setModelData(editor.model, modelTable([["a[]"]]));
+ for (const name of MOVE_COMMANDS) {
+ expect(editor.commands.get(name)?.isEnabled, name).toBe(false);
+ }
+
+ setModelData(editor.model, modelTable([["a[]", "b"], ["c", "d"]]));
+ expect(editor.commands.get("moveTableRowUp")?.isEnabled).toBe(false);
+ expect(editor.commands.get("moveTableRowDown")?.isEnabled).toBe(true);
+ expect(editor.commands.get("moveTableColumnLeft")?.isEnabled).toBe(false);
+ expect(editor.commands.get("moveTableColumnRight")?.isEnabled).toBe(true);
+ });
+
+ it("is disabled when merged cells bind the whole table into one group", () => {
+ setModelData(editor.model, modelTable([
+ [{ contents: "a[]", rowspan: 2 }, "b"],
+ ["c"]
+ ]));
+ expect(editor.commands.get("moveTableRowUp")?.isEnabled).toBe(false);
+ expect(editor.commands.get("moveTableRowDown")?.isEnabled).toBe(false);
+ });
+
+ it("execute is a no-op when the plan is gone despite the enabled state", () => {
+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");
+ const command = editor.commands.get("moveTableRowDown");
+ if (!command) {
+ throw new Error("Command not registered.");
+ }
+ command.isEnabled = true;
+ expect(() => command.execute()).not.toThrow();
+ expect(tableData()).toBe("<paragraph>foo</paragraph>");
+ });
+ });
+
+ describe("row moves", () => {
+ it("moves the caret row and keeps the caret in its cell", () => {
+ setModelData(editor.model, modelTable([["a[]", "b"], ["c", "d"], ["e", "f"]]));
+ editor.execute("moveTableRowDown");
+ expect(getModelData(editor.model)).toBe(modelTable([["c", "d"], ["a[]", "b"], ["e", "f"]]));
+
+ editor.execute("moveTableRowUp");
+ expect(getModelData(editor.model)).toBe(modelTable([["a[]", "b"], ["c", "d"], ["e", "f"]]));
+ });
+
+ it("moves a rowspan group as one block", () => {
+ const original = modelTable([
+ ["a", "b"],
+ [{ contents: "c", rowspan: 2 }, "d[]"],
+ ["e"],
+ ["f", "g"]
+ ]);
+ setModelData(editor.model, original);
+
+ editor.execute("moveTableRowDown");
+ expect(tableData()).toBe(modelTable([
+ ["a", "b"],
+ ["f", "g"],
+ [{ contents: "c", rowspan: 2 }, "d"],
+ ["e"]
+ ]));
+
+ editor.execute("moveTableRowUp");
+ expect(getModelData(editor.model)).toBe(original);
+ });
+
+ it("jumps over a rowspan group instead of entering it", () => {
+ setModelData(editor.model, modelTable([
+ ["a[]", "b"],
+ [{ contents: "c", rowspan: 2 }, "d"],
+ ["e"],
+ ["f", "g"]
+ ]));
+
+ editor.execute("moveTableRowDown");
+ expect(tableData()).toBe(modelTable([
+ [{ contents: "c", rowspan: 2 }, "d"],
+ ["e"],
+ ["a", "b"],
+ ["f", "g"]
+ ]));
+ });
+
+ it("moves every row a multi-cell selection touches and keeps the selection", () => {
+ setModelData(editor.model, modelTable([["a"], ["b"], ["c"], ["d"]]));
+ const selected = [cellAt(editor, 0, 0), cellAt(editor, 1, 0)];
+ selectCells(editor, [0, 0], [1, 0]);
+
+ editor.execute("moveTableRowDown");
+ expect(tableData()).toBe(modelTable([["c"], ["a"], ["b"], ["d"]]));
+
+ const tableUtils = editor.plugins.get(TableUtils);
+ const cells = tableUtils.getSelectionAffectedTableCells(editor.model.document.selection);
+ expect(cells).toHaveLength(2);
+ for (const cell of selected) {
+ expect(cells).toContain(cell);
+ }
+ });
+
+ it("reverts order and heading in a single undo step", () => {
+ const original = modelTable([["h[]"], ["b1"], ["b2"]], 'headingRows="1"');
+ setModelData(editor.model, original);
+
+ editor.execute("moveTableRowDown");
+ editor.execute("undo");
+ expect(getModelData(editor.model)).toBe(original);
+ });
+ });
+
+ describe("headingRows", () => {
+ it("drops heading status from a header row moved below the band", () => {
+ setModelData(editor.model, modelTable([["h[]"], ["b1"], ["b2"]], 'headingRows="1"'));
+ editor.execute("moveTableRowDown");
+ expect(tableData()).toBe(modelTable([["b1"], ["h"], ["b2"]]));
+ });
+
+ it("grants heading status to a body row moved into the band", () => {
+ setModelData(editor.model, modelTable([["h"], ["b1[]"], ["b2"]], 'headingRows="1"'));
+ editor.execute("moveTableRowUp");
+ expect(tableData()).toBe(modelTable([["b1"], ["h"], ["b2"]], 'headingRows="2"'));
+ });
+
+ it("keeps the count when the move stays inside the band or inside the body", () => {
+ setModelData(editor.model, modelTable([["h1[]"], ["h2"], ["b1"]], 'headingRows="2"'));
+ editor.execute("moveTableRowDown");
+ expect(tableData()).toBe(modelTable([["h2"], ["h1"], ["b1"]], 'headingRows="2"'));
+
+ setModelData(editor.model, modelTable([["h"], ["b1[]"], ["b2"]], 'headingRows="1"'));
+ editor.execute("moveTableRowDown");
+ expect(tableData()).toBe(modelTable([["h"], ["b2"], ["b1"]], 'headingRows="1"'));
+ });
+ });
+
+ describe("column moves", () => {
+ it("moves the caret column and keeps the caret in its cell", () => {
+ setModelData(editor.model, modelTable([["a[]", "b"], ["c", "d"]]));
+ editor.execute("moveTableColumnRight");
+ expect(getModelData(editor.model)).toBe(modelTable([["b", "a[]"], ["d", "c"]]));
+
+ editor.execute("moveTableColumnLeft");
+ expect(getModelData(editor.model)).toBe(modelTable([["a[]", "b"], ["c", "d"]]));
+ });
+
+ it("moves a colspan group as one block", () => {
+ setModelData(editor.model, modelTable([
+ ["a", { contents: "b", colspan: 2 }, "d"],
+ ["e", "f[]", "g", "h"]
+ ]));
+
+ editor.execute("moveTableColumnRight");
+ expect(tableData()).toBe(modelTable([
+ ["a", "d", { contents: "b", colspan: 2 }],
+ ["e", "h", "f", "g"]
+ ]));
+ });
+
+ it("keeps the child order of rows covered by a rowspan", () => {
+ setModelData(editor.model, modelTable([
+ [{ contents: "a", rowspan: 2 }, "b[]", "c"],
+ ["d", "e"]
+ ]));
+
+ editor.execute("moveTableColumnLeft");
+ expect(tableData()).toBe(modelTable([
+ ["b", { contents: "a", rowspan: 2 }, "c"],
+ ["d", "e"]
+ ]));
+ });
+
+ it("moves every column a multi-cell selection touches", () => {
+ setModelData(editor.model, modelTable([["a", "b", "c"], ["d", "e", "f"]]));
+ selectCells(editor, [0, 1], [0, 2]);
+
+ editor.execute("moveTableColumnLeft");
+ expect(tableData()).toBe(modelTable([["b", "c", "a"], ["e", "f", "d"]]));
+ });
+ });
+
+ describe("headingColumns", () => {
+ it("follows the band boundary like headingRows", () => {
+ setModelData(editor.model, modelTable([["h[]", "b1", "b2"]], 'headingColumns="1"'));
+ editor.execute("moveTableColumnRight");
+ expect(tableData()).toBe(modelTable([["b1", "h", "b2"]]));
+
+ setModelData(editor.model, modelTable([["h", "b1[]", "b2"]], 'headingColumns="1"'));
+ editor.execute("moveTableColumnLeft");
+ expect(tableData()).toBe(modelTable([["b1", "h", "b2"]], 'headingColumns="2"'));
+ });
+ });
+
+ describe("column widths", () => {
+ function tableWithWidths(cells: string[], columns: string): string {
+ return modelTable([cells]).replace(
+ "</table>",
+ `<tableColumnGroup>${columns}</tableColumnGroup></table>`
+ );
+ }
+
+ it("moves the width along with the column", () => {
+ setModelData(editor.model, tableWithWidths(
+ ["a[]", "b", "c"],
+ '<tableColumn columnWidth="20%"></tableColumn>' +
+ '<tableColumn columnWidth="30%"></tableColumn>' +
+ '<tableColumn columnWidth="50%"></tableColumn>'
+ ));
+
+ editor.execute("moveTableColumnRight");
+ expect(tableData()).toBe(tableWithWidths(
+ ["b", "a", "c"],
+ '<tableColumn columnWidth="30%"></tableColumn>' +
+ '<tableColumn columnWidth="20%"></tableColumn>' +
+ '<tableColumn columnWidth="50%"></tableColumn>'
+ ));
+
+ editor.execute("undo");
+ expect(tableData()).toBe(tableWithWidths(
+ ["a", "b", "c"],
+ '<tableColumn columnWidth="20%"></tableColumn>' +
+ '<tableColumn columnWidth="30%"></tableColumn>' +
+ '<tableColumn columnWidth="50%"></tableColumn>'
+ ));
+ });
+
+ it("expands a colSpan width entry into per-column entries", () => {
+ setModelData(editor.model, tableWithWidths(
+ ["a", "b", "c[]"],
+ '<tableColumn columnWidth="25%" colSpan="2"></tableColumn>' +
+ '<tableColumn columnWidth="50%"></tableColumn>'
+ ));
+
+ editor.execute("moveTableColumnLeft");
+ expect(tableData()).toBe(tableWithWidths(
+ ["a", "c", "b"],
+ '<tableColumn columnWidth="25%"></tableColumn>' +
+ '<tableColumn columnWidth="50%"></tableColumn>' +
+ '<tableColumn columnWidth="25%"></tableColumn>'
+ ));
+ });
+
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/table_move/table_move_commands.ts b/packages/ckeditor5/src/plugins/table_move/table_move_commands.ts
new file mode 100644
index 0000000000..b1c44bd8ca
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_move/table_move_commands.ts
@@ -0,0 +1,213 @@
+import { Command, ModelLiveRange, TableUtils, TableWalker } from "ckeditor5";
+import type { Editor, ModelDocumentSelection, ModelElement, ModelPosition, ModelWriter } from "ckeditor5";
+
+import { adjustedHeadingCount, planGroupMove } from "./table_move_groups.js";
+import type { GroupMovePlan, IndexRange, TableAxis } from "./table_move_groups.js";
+
+interface PlannedMove {
+ table: ModelElement;
+ plan: GroupMovePlan;
+}
+
+/**
+ * Moves the span group of rows or columns touched by the selection over the adjacent group
+ * (see `planGroupMove`). Enabled only when the selection is in a table and such a target exists,
+ * so the commands can back menu items directly.
+ */
+abstract class MoveTableGroupCommand extends Command {
+
+ protected readonly isForward: boolean;
+ protected abstract readonly axis: TableAxis;
+
+ constructor(editor: Editor, isForward: boolean) {
+ super(editor);
+ this.isForward = isForward;
+ }
+
+ override refresh() {
+ this.isEnabled = this.planMove() !== null;
+ }
+
+ override execute() {
+ const planned = this.planMove();
+ if (!planned) {
+ return;
+ }
+
+ const model = this.editor.model;
+ const selectionRanges = [...model.document.selection.getRanges()]
+ .map((range) => ModelLiveRange.fromRange(range));
+
+ model.change((writer) => {
+ this.applyMove(writer, planned.table, planned.plan);
+ writer.setSelection(selectionRanges.map((range) => range.toRange()));
+ });
+
+ for (const range of selectionRanges) {
+ range.detach();
+ }
+
+ this.editor.editing.view.focus();
+ this.editor.editing.view.scrollToTheSelection();
+ }
+
+ protected abstract applyMove(writer: ModelWriter, table: ModelElement, plan: GroupMovePlan): void;
+
+ protected updateHeadingCount(
+ writer: ModelWriter,
+ table: ModelElement,
+ attribute: "headingRows" | "headingColumns",
+ plan: GroupMovePlan
+ ) {
+ const heading = Number(table.getAttribute(attribute) ?? 0);
+ const adjusted = adjustedHeadingCount(heading, plan, this.isForward);
+ if (adjusted === heading) {
+ return;
+ }
+
+ if (adjusted > 0) {
+ writer.setAttribute(attribute, adjusted, table);
+ } else {
+ writer.removeAttribute(attribute, table);
+ }
+ }
+
+ private planMove(): PlannedMove | null {
+ const tableUtils = this.editor.plugins.get(TableUtils);
+ const cells = tableUtils.getSelectionAffectedTableCells(this.editor.model.document.selection);
+ const table = cells[0]?.findAncestor("table");
+ if (!table) {
+ return null;
+ }
+
+ const selected = this.axis === "row"
+ ? tableUtils.getRowIndexes(cells)
+ : tableUtils.getColumnIndexes(cells);
+ const plan = planGroupMove(table, this.axis, selected, this.isForward);
+ return plan && { table, plan };
+ }
+
+}
+
+export class MoveTableRowCommand extends MoveTableGroupCommand {
+
+ protected readonly axis = "row";
+
+ constructor(editor: Editor, direction: "up" | "down") {
+ super(editor, direction === "down");
+ }
+
+ protected applyMove(writer: ModelWriter, table: ModelElement, plan: GroupMovePlan) {
+ const rows = [...table.getChildren()]
+ .filter((child): child is ModelElement => child.is("element", "tableRow"));
+
+ const movedRows = writer.createRange(
+ writer.createPositionBefore(rows[plan.source.first]),
+ writer.createPositionAfter(rows[plan.source.last])
+ );
+ const insertAt = this.isForward
+ ? writer.createPositionAfter(rows[plan.target.last])
+ : writer.createPositionBefore(rows[plan.target.first]);
+
+ writer.move(movedRows, insertAt);
+ this.updateHeadingCount(writer, table, "headingRows", plan);
+ }
+
+}
+
+export class MoveTableColumnCommand extends MoveTableGroupCommand {
+
+ protected readonly axis = "column";
+
+ constructor(editor: Editor, direction: "left" | "right") {
+ super(editor, direction === "right");
+ }
+
+ protected applyMove(writer: ModelWriter, table: ModelElement, plan: GroupMovePlan) {
+ const left = this.isForward ? plan.source : plan.target;
+ const right = this.isForward ? plan.target : plan.source;
+
+ // Swapping the adjacent groups is one operation per row: the right group's anchored
+ // cells land where the left group starts. Positions are collected before any move so
+ // the walker never iterates a half-changed table.
+ const insertPositions = new Map<number, ModelPosition>();
+ const movedCells = new Map<number, ModelElement[]>();
+ const walker = new TableWalker(table, {
+ startColumn: left.first,
+ endColumn: right.last,
+ includeAllSlots: true
+ });
+ for (const slot of walker) {
+ if (slot.column === left.first) {
+ insertPositions.set(slot.row, slot.getPositionBefore());
+ }
+ if (slot.isAnchor && slot.column >= right.first) {
+ const cells = movedCells.get(slot.row) ?? [];
+ cells.push(slot.cell);
+ movedCells.set(slot.row, cells);
+ }
+ }
+
+ for (const [row, cells] of movedCells) {
+ const insertAt = insertPositions.get(row);
+ const movedFrom = writer.createPositionBefore(cells[0]);
+ /* v8 ignore next 3 -- includeAllSlots yields a slot at every column, so the position always exists */
+ if (!insertAt) {
+ continue;
+ }
+ // A row whose left-group slots are all covered by rowspans from earlier rows keeps
+ // its child order; the covering cells move within their own anchor rows.
+ if (insertAt.isEqual(movedFrom)) {
+ continue;
+ }
+ writer.move(
+ writer.createRange(movedFrom, writer.createPositionAfter(cells[cells.length - 1])),
+ insertAt
+ );
+ }
+
+ moveColumnWidths(writer, table, left, right);
+ this.updateHeadingCount(writer, table, "headingColumns", plan);
+ }
+
+}
+
+/** Whether the document selection is inside a table. */
+export function isSelectionInTable(selection: ModelDocumentSelection): boolean {
+ return !!selection.getFirstPosition()?.findAncestor("table");
+}
+
+/**
+ * Mirrors a column-group swap on the `tableColumn` elements kept by `TableColumnResize`, so
+ * every column keeps its width. Tables that were never resized have no `tableColumnGroup`.
+ */
+function moveColumnWidths(writer: ModelWriter, table: ModelElement, left: IndexRange, right: IndexRange) {
+ const columnGroup = [...table.getChildren()]
+ .find((child): child is ModelElement => child.is("element", "tableColumnGroup"));
+ if (!columnGroup) {
+ return;
+ }
+
+ const widths: string[] = [];
+ for (const column of columnGroup.getChildren()) {
+ const span = Number(column.getAttribute("colSpan") ?? 1);
+ for (let i = 0; i < span; i++) {
+ widths.push(String(column.getAttribute("columnWidth")));
+ }
+ }
+ /* v8 ignore next 3 -- defensive: TableColumnResize's post-fixer keeps one entry per column whenever the group exists */
+ if (widths.length <= right.last) {
+ return;
+ }
+
+ const reordered = [
+ ...widths.slice(0, left.first),
+ ...widths.slice(right.first, right.last + 1),
+ ...widths.slice(left.first, right.first),
+ ...widths.slice(right.last + 1)
+ ];
+ writer.remove(writer.createRangeIn(columnGroup));
+ for (const width of reordered) {
+ writer.insertElement("tableColumn", { columnWidth: width }, columnGroup, "end");
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/table_move/table_move_groups.spec.ts b/packages/ckeditor5/src/plugins/table_move/table_move_groups.spec.ts
new file mode 100644
index 0000000000..f375fb2de9
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_move/table_move_groups.spec.ts
@@ -0,0 +1,143 @@
+import { _setModelData as setModelData, Essentials, Paragraph, Table } from "ckeditor5";
+import type { ClassicEditor, ModelElement } from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { modelTable } from "../../../test/table-kit.js";
+import { adjustedHeadingCount, planGroupMove } from "./table_move_groups.js";
+
+describe("planGroupMove", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Table]);
+ });
+
+ function getTable(markup: string): ModelElement {
+ setModelData(editor.model, markup);
+ const table = editor.model.document.getRoot()?.getChild(0);
+ if (!table?.is("element", "table")) {
+ throw new Error("Fixture did not produce a table.");
+ }
+ return table;
+ }
+
+ it("plans single-row moves in a table without merged cells", () => {
+ const table = getTable(modelTable([["a"], ["b"], ["c"]]));
+
+ expect(planGroupMove(table, "row", { first: 1, last: 1 }, true))
+ .toEqual({ source: { first: 1, last: 1 }, target: { first: 2, last: 2 } });
+ expect(planGroupMove(table, "row", { first: 1, last: 1 }, false))
+ .toEqual({ source: { first: 1, last: 1 }, target: { first: 0, last: 0 } });
+ });
+
+ it("returns null at the table edges", () => {
+ const table = getTable(modelTable([["a"], ["b"]]));
+
+ expect(planGroupMove(table, "row", { first: 0, last: 0 }, false)).toBeNull();
+ expect(planGroupMove(table, "row", { first: 1, last: 1 }, true)).toBeNull();
+ });
+
+ it("expands the source over the rows a merged cell binds together", () => {
+ const table = getTable(modelTable([
+ ["a", "b"],
+ [{ contents: "c", rowspan: 2 }, "d"],
+ ["e"],
+ ["f", "g"]
+ ]));
+
+ expect(planGroupMove(table, "row", { first: 1, last: 1 }, true))
+ .toEqual({ source: { first: 1, last: 2 }, target: { first: 3, last: 3 } });
+ expect(planGroupMove(table, "row", { first: 2, last: 2 }, false))
+ .toEqual({ source: { first: 1, last: 2 }, target: { first: 0, last: 0 } });
+ });
+
+ it("expands the target over the rows a merged cell binds together", () => {
+ const table = getTable(modelTable([
+ ["a", "b"],
+ [{ contents: "c", rowspan: 2 }, "d"],
+ ["e"],
+ ["f", "g"]
+ ]));
+
+ expect(planGroupMove(table, "row", { first: 0, last: 0 }, true))
+ .toEqual({ source: { first: 0, last: 0 }, target: { first: 1, last: 2 } });
+ expect(planGroupMove(table, "row", { first: 3, last: 3 }, false))
+ .toEqual({ source: { first: 3, last: 3 }, target: { first: 1, last: 2 } });
+ });
+
+ it("returns null when a merged cell spans the whole table", () => {
+ const table = getTable(modelTable([
+ [{ contents: "a", rowspan: 2 }, "b"],
+ ["c"]
+ ]));
+
+ expect(planGroupMove(table, "row", { first: 0, last: 0 }, true)).toBeNull();
+ expect(planGroupMove(table, "row", { first: 1, last: 1 }, false)).toBeNull();
+ });
+
+ it("plans column moves around a colspan group", () => {
+ const table = getTable(modelTable([
+ ["a", { contents: "b", colspan: 2 }, "d"],
+ ["e", "f", "g", "h"]
+ ]));
+
+ expect(planGroupMove(table, "column", { first: 1, last: 1 }, true))
+ .toEqual({ source: { first: 1, last: 2 }, target: { first: 3, last: 3 } });
+ expect(planGroupMove(table, "column", { first: 0, last: 0 }, true))
+ .toEqual({ source: { first: 0, last: 0 }, target: { first: 1, last: 2 } });
+ expect(planGroupMove(table, "column", { first: 0, last: 0 }, false)).toBeNull();
+ expect(planGroupMove(table, "column", { first: 3, last: 3 }, true)).toBeNull();
+ });
+
+ it("expands a multi-group selection to cover every touched group", () => {
+ const table = getTable(modelTable([
+ ["a", "b"],
+ [{ contents: "c", rowspan: 2 }, "d"],
+ ["e"],
+ ["f", "g"]
+ ]));
+
+ expect(planGroupMove(table, "row", { first: 0, last: 1 }, true))
+ .toEqual({ source: { first: 0, last: 2 }, target: { first: 3, last: 3 } });
+ });
+});
+
+describe("adjustedHeadingCount", () => {
+ it("keeps a zero heading count", () => {
+ const plan = { source: { first: 0, last: 0 }, target: { first: 1, last: 1 } };
+ expect(adjustedHeadingCount(0, plan, true)).toBe(0);
+ });
+
+ it("drops heading status from rows moved below the heading band", () => {
+ const plan = { source: { first: 0, last: 0 }, target: { first: 1, last: 1 } };
+ expect(adjustedHeadingCount(1, plan, true)).toBe(0);
+ });
+
+ it("grants heading status to rows moved into the heading band", () => {
+ const plan = { source: { first: 1, last: 1 }, target: { first: 0, last: 0 } };
+ expect(adjustedHeadingCount(1, plan, false)).toBe(2);
+ });
+
+ it("keeps the count for moves inside the heading band", () => {
+ const plan = { source: { first: 0, last: 0 }, target: { first: 1, last: 1 } };
+ expect(adjustedHeadingCount(2, plan, true)).toBe(2);
+ });
+
+ it("keeps the count for moves inside the body", () => {
+ expect(adjustedHeadingCount(
+ 1, { source: { first: 1, last: 1 }, target: { first: 2, last: 2 } }, true
+ )).toBe(1);
+ expect(adjustedHeadingCount(
+ 1, { source: { first: 2, last: 2 }, target: { first: 1, last: 1 } }, false
+ )).toBe(1);
+ });
+
+ it("counts only the heading part of a source that straddles the band boundary", () => {
+ const down = { source: { first: 1, last: 2 }, target: { first: 3, last: 3 } };
+ expect(adjustedHeadingCount(2, down, true)).toBe(1);
+
+ const up = { source: { first: 1, last: 2 }, target: { first: 0, last: 0 } };
+ expect(adjustedHeadingCount(1, up, false)).toBe(3);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/table_move/table_move_groups.ts b/packages/ckeditor5/src/plugins/table_move/table_move_groups.ts
new file mode 100644
index 0000000000..85438c96ab
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_move/table_move_groups.ts
@@ -0,0 +1,95 @@
+import { TableWalker } from "ckeditor5";
+import type { ModelElement } from "ckeditor5";
+
+export type TableAxis = "row" | "column";
+
+/** An inclusive range of row or column indexes. */
+export interface IndexRange {
+ first: number;
+ last: number;
+}
+
+export interface GroupMovePlan {
+ source: IndexRange;
+ target: IndexRange;
+}
+
+/**
+ * Plans moving the selected rows or columns one span group forward (down/right) or backward
+ * (up/left). Both ranges are expanded so that no merged cell sticks out of them, which makes
+ * swapping the two blocks always grid-safe. Returns `null` when the move would leave the table.
+ */
+export function planGroupMove(
+ table: ModelElement,
+ axis: TableAxis,
+ selected: IndexRange,
+ isForward: boolean
+): GroupMovePlan | null {
+ const { crossed, count } = scanSpannedBoundaries(table, axis);
+ const source = expandToGroup(selected, crossed, count);
+
+ if (isForward) {
+ if (source.last + 1 >= count) {
+ return null;
+ }
+ const next = { first: source.last + 1, last: source.last + 1 };
+ return { source, target: expandToGroup(next, crossed, count) };
+ }
+
+ if (source.first <= 0) {
+ return null;
+ }
+ const previous = { first: source.first - 1, last: source.first - 1 };
+ return { source, target: expandToGroup(previous, crossed, count) };
+}
+
+/**
+ * Returns the `headingRows`/`headingColumns` value after applying `plan`. The heading band is
+ * positional: entries moved out of the leading band lose heading status and entries moved into
+ * it gain heading status, while the entries that did not move keep their role.
+ */
+export function adjustedHeadingCount(heading: number, plan: GroupMovePlan, isForward: boolean): number {
+ if (heading <= 0) {
+ return heading;
+ }
+
+ const { source, target } = plan;
+ if (isForward && target.last >= heading) {
+ return heading - Math.max(0, Math.min(source.last + 1, heading) - source.first);
+ }
+ if (!isForward && target.first < heading) {
+ return heading + Math.max(0, source.last + 1 - Math.max(source.first, heading));
+ }
+ return heading;
+}
+
+/** Boundary `i` is crossed when a cell spans from before `i` to `i` or beyond. */
+function scanSpannedBoundaries(table: ModelElement, axis: TableAxis) {
+ const crossed: boolean[] = [];
+ let count = 0;
+
+ for (const slot of new TableWalker(table)) {
+ const start = axis === "row" ? slot.row : slot.column;
+ const span = axis === "row" ? slot.cellHeight : slot.cellWidth;
+ for (let boundary = start + 1; boundary < start + span; boundary++) {
+ crossed[boundary] = true;
+ }
+ count = Math.max(count, start + span);
+ }
+
+ return { crossed, count };
+}
+
+function expandToGroup(range: IndexRange, crossed: boolean[], count: number): IndexRange {
+ let first = range.first;
+ while (first > 0 && crossed[first]) {
+ first--;
+ }
+
+ let last = range.last;
+ while (last + 1 < count && crossed[last + 1]) {
+ last++;
+ }
+
+ return { first, last };
+}
diff --git a/packages/ckeditor5/test/table-kit.ts b/packages/ckeditor5/test/table-kit.ts
new file mode 100644
index 0000000000..fb5db4737f
--- /dev/null
+++ b/packages/ckeditor5/test/table-kit.ts
@@ -0,0 +1,68 @@
+import { TableSelection } from "ckeditor5";
+import type { ClassicEditor, ModelElement } from "ckeditor5";
+
+/**
+ * Table fixtures for the spec suite. `modelTable` builds table model markup the way the
+ * upstream test helper does (that helper is not exported from the `ckeditor5` bundle),
+ * including merged cells and table attributes:
+ *
+ * ```ts
+ * modelTable([
+ * [{ contents: "a", rowspan: 2 }, "b"],
+ * ["c"]
+ * ], 'headingRows="1"');
+ * ```
+ */
+
+export type CellSpec = string | {
+ contents: string;
+ colspan?: number;
+ rowspan?: number;
+};
+
+export function modelTable(rows: CellSpec[][], attributes = ""): string {
+ const rowsMarkup = rows
+ .map((cells) => `<tableRow>${cells.map(cellMarkup).join("")}</tableRow>`)
+ .join("");
+ return `<table${attributes ? ` ${attributes}` : ""}>${rowsMarkup}</table>`;
+}
+
+/**
+ * Returns the model cell at the given child indexes of the table (the first table in the
+ * root). With merged cells these are child positions, not grid coordinates.
+ */
+export function cellAt(editor: ClassicEditor, rowIndex: number, cellIndex: number): ModelElement {
+ const table = editor.model.document.getRoot()?.getChild(0);
+ if (!table?.is("element", "table")) {
+ throw new Error("The first root child is not a table.");
+ }
+ const row = table.getChild(rowIndex);
+ if (!row?.is("element", "tableRow")) {
+ throw new Error(`No table row at index ${rowIndex}.`);
+ }
+ const cell = row.getChild(cellIndex);
+ if (!cell?.is("element", "tableCell")) {
+ throw new Error(`No table cell at row ${rowIndex}, child ${cellIndex}.`);
+ }
+ return cell;
+}
+
+/** Selects the rectangle of cells between two child-index positions (see `cellAt`). */
+export function selectCells(
+ editor: ClassicEditor,
+ anchor: [number, number],
+ target: [number, number]
+) {
+ editor.plugins.get(TableSelection).setCellSelection(
+ cellAt(editor, anchor[0], anchor[1]),
+ cellAt(editor, target[0], target[1])
+ );
+}
+
+function cellMarkup(cell: CellSpec): string {
+ const spec = typeof cell === "string" ? { contents: cell } : cell;
+ const attributes =
+ (spec.colspan ? ` colspan="${spec.colspan}"` : "") +
+ (spec.rowspan ? ` rowspan="${spec.rowspan}"` : "");
+ return `<tableCell${attributes}><paragraph>${spec.contents}</paragraph></tableCell>`;
+}