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/multicolumn layout: add keyboard support for manipulating columns
Adorian Doran084ce0ba0c8c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 22b3f6b1b4..b977d5a2d9 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4525,7 +4525,18 @@"type-the-content-of-the-third-column": "Type the content of the third column","type-the-content-of-the-fourth-column": "Type the content of the fourth column","table-columns": "Table columns",- "column-0-width-1": "Column %0 width: %1%"+ "column-0-width-1": "Column %0 width: %1%",+ "keystrokes-that-can-be-used-in-a-multicolumn-layout": "Keystrokes that can be used in a multicolumn layout",+ "move-the-selected-content-to-the-column-on-the-left": "Move the selected content to the column on the left",+ "move-the-selected-content-to-the-column-on-the-right": "Move the selected content to the column on the right",+ "move-the-selected-content-to-the-first-column": "Move the selected content to the first column",+ "move-the-selected-content-to-the-last-column": "Move the selected content to the last column",+ "move-the-column-to-the-left": "Move the column to the left",+ "move-the-column-to-the-right": "Move the column to the right",+ "make-the-column-the-first-one": "Make the column the first one",+ "make-the-column-the-last-one": "Make the column the last one",+ "add-a-column-after-the-current-one": "Add a column after the current one",+ "add-a-column-before-the-current-one": "Add a column before the current one"},"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/Keyboard shortcuts.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.htmlindex 5a36aabd3b..23cad3053c 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.html@@ -79,6 +79,23 @@<td>⌥+↓</td><td></td></tr>+ <tr>+ <td>Move the selected content to another column of a <a class="reference-link"+ href="#root/_help_wYDzQ1fBFgfT">Multicolumn layout</a>+ </td>+ <td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td>+ <td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td>+ </tr>+ <tr>+ <td>Move the current column of a multicolumn layout</td>+ <td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td>+ <td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td>+ </tr>+ <tr>+ <td>Add a column after or before the current one in a multicolumn layout</td>+ <td>Ctrl+Enter, Ctrl+Shift+Enter</td>+ <td>⌘+Enter, ⌘+⇧+Enter</td>+ </tr></tbody></table></figure>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Multicolumn layout.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Multicolumn layout.htmlindex ace3100656..4f1d230357 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Multicolumn layout.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Multicolumn layout.html@@ -11,6 +11,7 @@<p>The columns of a new layout have equal widths. If text is selected whenthe layout is inserted, the selection moves into the first column.</p><h2>Changing the columns</h2>+<h3>Changing the layout</h3><p>While the cursor is inside a layout, a toolbar appears above it with abutton that shows the current layout. Clicking it opens a row of figures,one for each available layout; hovering over a figure shows its number@@ -44,6 +45,45 @@<li>Choosing a layout with fewer columns removes the last columns and movestheir content to the end of the last remaining column.</li></ul>+<h3>Adding columns</h3>+<p>While the cursor is in a column, you can use these key combinations:</p>+<ul>+ <li><kbd>Ctrl</kbd> + <kbd>Enter</kbd>: Add a column after the current one.</li>+ <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>: Add a column before+ the current one.</li>+</ul>+<p>The new column is empty and the cursor moves into it. All the columns+ then have equal widths. A layout has at most four columns, so the keys+ do nothing in a layout that already has four.</p>+<p><kbd>Ctrl</kbd> + <kbd>Enter</kbd> keeps its usual function on a link, in+ a to-do item and in the title of a collapsible block, and <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd> in+ a to-do item.</p>+<h3>Reordering columns</h3>+<p>While the cursor is anywhere inside a column, you can use these key combinations:</p>+<ul>+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Right</kbd>: Move the column to the+ right.</li>+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Left</kbd>: Move the column to the+ left.</li>+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Home</kbd>: Make it the first column.</li>+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>End</kbd>: Make it the last column.</li>+</ul>+<p>In a layout with two columns of different widths, the column keeps its+ width.</p>+<h2>Moving content between columns</h2>+<p>To move content to another column, select it, and then use these key combinations:</p>+<ul>+ <li><kbd>Ctrl</kbd> + <kbd>Right</kbd>: Move to the column on the right.</li>+ <li><kbd>Ctrl</kbd> + <kbd>Left</kbd>: Move to the column on the left.</li>+ <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>End</kbd>: Move to the last column.</li>+ <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Home</kbd>: Move to the first column.</li>+</ul>+<p>Paragraphs, list items, tables and other blocks move whole, even when+ only part of them is selected. Content moved to a column on the left goes+ to the end of that column, and content moved to a column on the right goes+ to its start, so it keeps its place in the reading order.</p>+<p>Without a selection, these keys keep their usual function: moving the+ cursor by word, or selecting up to the start or end of the column.</p><h2>Removing a layout</h2><ul><li>To remove the layout but keep its content, click the <span class="tn-icon cke cke-remove"></span> <em>Remove layout</em> buttondiff --git a/docs/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.md b/docs/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.mdindex eddb2d9fe5..741b6dbfdd 100644--- a/docs/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.md+++ b/docs/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.md@@ -16,6 +16,9 @@| Alt+↑ | ⌥+↑ | || Move blocks (lists, paragraphs, etc.) down | Ctrl+↑ | ⌘+↑ || Alt+↓ | ⌥+↓ | |+| Move the selected content to another column of a <a class="reference-link" href="Multicolumn%20layout.md">Multicolumn layout</a> | Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End | ⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End |+| Move the current column of a multicolumn layout | Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End | ⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End |+| Add a column after or before the current one in a multicolumn layout | Ctrl+Enter, Ctrl+Shift+Enter | ⌘+Enter, ⌘+⇧+Enter |## Common shortcutsdiff --git a/docs/User Guide/User Guide/Note Types/Text/Multicolumn layout.md b/docs/User Guide/User Guide/Note Types/Text/Multicolumn layout.mdindex afa0ded10c..a4aa409ec2 100644--- a/docs/User Guide/User Guide/Note Types/Text/Multicolumn layout.md+++ b/docs/User Guide/User Guide/Note Types/Text/Multicolumn layout.md@@ -10,6 +10,8 @@ The columns of a new layout have equal widths. If text is selected when the layo## Changing the columns+### Changing the layout+While the cursor is inside a layout, a toolbar appears above it with a button that shows the current layout. Clicking it opens a row of figures, one for each available layout; hovering over a figure shows its number of columns and their widths:| Columns | Widths |@@ -21,6 +23,41 @@ While the cursor is inside a layout, a toolbar appears above it with a button th* Choosing a layout with more columns adds empty columns at the end.* Choosing a layout with fewer columns removes the last columns and moves their content to the end of the last remaining column.+### Adding columns++While the cursor is in a column, you can use these key combinations:++* <kbd>Ctrl</kbd> + <kbd>Enter</kbd>: Add a column after the current one.+* <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>: Add a column before the current one.++The new column is empty and the cursor moves into it. All the columns then have equal widths. A layout has at most four columns, so the keys do nothing in a layout that already has four.++<kbd>Ctrl</kbd> + <kbd>Enter</kbd> keeps its usual function on a link, in a to-do item and in the title of a collapsible block, and <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd> in a to-do item.++### Reordering columns++While the cursor is anywhere inside a column, you can use these key combinations:++* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Right</kbd>: Move the column to the right.+* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Left</kbd>: Move the column to the left.+* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Home</kbd>: Make it the first column.+* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>End</kbd>: Make it the last column.++In a layout with two columns of different widths, the column keeps its width.++## Moving content between columns++To move content to another column, select it, and then use these key combinations:++* <kbd>Ctrl</kbd> + <kbd>Right</kbd>: Move to the column on the right.+* <kbd>Ctrl</kbd> + <kbd>Left</kbd>: Move to the column on the left.+* <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>End</kbd>: Move to the last column.+* <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Home</kbd>: Move to the first column.++Paragraphs, list items, tables and other blocks move whole, even when only part of them is selected. Content moved to a column on the left goes to the end of that column, and content moved to a column on the right goes to its start, so it keeps its place in the reading order.++Without a selection, these keys keep their usual function: moving the cursor by word, or selecting up to the start or end of the column.+## Removing a layout* To remove the layout but keep its content, click the <span class="tn-icon cke cke-remove"></span> _Remove layout_ button in the layout's toolbar. The content of the columns is placed one after another where the layout was, and empty columns are left out.diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn.tsindex 363ee9be4a..c41e439fba 100644--- a/packages/ckeditor5/src/plugins/multicolumn/multicolumn.ts+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn.ts@@ -2,20 +2,23 @@ import { Plugin } from "ckeditor5";import "../../theme/multicolumn.css";import type {- ColumnLayoutCommand, InsertMulticolumnLayoutCommand, RemoveMulticolumnLayoutCommand+ ColumnLayoutCommand, InsertLayoutColumnCommand, InsertMulticolumnLayoutCommand,+ MoveLayoutColumnCommand, MoveToLayoutColumnCommand, RemoveMulticolumnLayoutCommand} from "./multicolumn_commands.js";import MulticolumnEditing from "./multicolumn_editing.js";+import MulticolumnKeyboard from "./multicolumn_keyboard.js";import MulticolumnUI from "./multicolumn_ui.js";/*** The multicolumn layout: two to four columns of block content, side by side.*- * This is a "glue" plugin which loads {@link MulticolumnEditing} and {@link MulticolumnUI}.+ * This is a "glue" plugin which loads {@link MulticolumnEditing}, {@link MulticolumnKeyboard} and+ * {@link MulticolumnUI}.*/export default class Multicolumn extends Plugin {public static get requires() {- return [MulticolumnEditing, MulticolumnUI] as const;+ return [MulticolumnEditing, MulticolumnKeyboard, MulticolumnUI] as const;}public static get pluginName() {@@ -28,6 +31,7 @@ declare module "ckeditor5" {interface PluginsMap {[Multicolumn.pluginName]: Multicolumn;[MulticolumnEditing.pluginName]: MulticolumnEditing;+ [MulticolumnKeyboard.pluginName]: MulticolumnKeyboard;[MulticolumnUI.pluginName]: MulticolumnUI;}@@ -35,5 +39,8 @@ declare module "ckeditor5" {multicolumnLayout: InsertMulticolumnLayoutCommand;columnLayout: ColumnLayoutCommand;removeMulticolumnLayout: RemoveMulticolumnLayoutCommand;+ insertLayoutColumn: InsertLayoutColumnCommand;+ moveLayoutColumn: MoveLayoutColumnCommand;+ moveToLayoutColumn: MoveToLayoutColumnCommand;}}diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.spec.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.spec.tsindex 5adf6222a0..19fb2623a5 100644--- a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.spec.ts@@ -20,6 +20,14 @@ function layout(ratios: string, ...columns: string[]) {return `<multicolumnLayout columnRatios="${ratios}">${content.join("")}</multicolumnLayout>`;}+/** A layout with the given weights whose columns hold the given model content. */+function columns(ratios: string, ...contents: string[]) {+ const content = contents.map(inner => `<multicolumnColumn>${inner}</multicolumnColumn>`);+ return `<multicolumnLayout columnRatios="${ratios}">${content.join("")}</multicolumnLayout>`;+}++const TABLE = "<table><tableRow><tableCell><paragraph>T</paragraph></tableCell></tableRow></table>";+/** An empty bulleted item and an empty checked to-do item, in model notation. */const EMPTY_BULLET = "<paragraph listIndent=\"0\" listItemId=\"a\" listType=\"bulleted\">" +"</paragraph>";@@ -383,4 +391,149 @@ describe("multicolumn commands", () => {expect(editor.getData()).toBe(before);});});++ describe("moveToLayoutColumn", () => {+ it("moves the touched blocks to a later column's start or an earlier column's end", () => {+ setModelData(editor.model, columns("1-1",+ "<paragraph>A</paragraph><paragraph>B[x</paragraph><paragraph>y]C</paragraph>" ++ "<paragraph>D</paragraph>",+ "<paragraph>E</paragraph>"));+ const before = editor.getData();++ editor.execute("moveToLayoutColumn", { target: "next" });+ expect(modelWithSelection()).toBe(columns("1-1",+ "<paragraph>A</paragraph><paragraph>D</paragraph>",+ "<paragraph>B[x</paragraph><paragraph>y]C</paragraph><paragraph>E</paragraph>"));++ editor.execute("moveToLayoutColumn", { target: "previous" });+ expect(modelWithSelection()).toBe(columns("1-1",+ "<paragraph>A</paragraph><paragraph>D</paragraph><paragraph>B[x</paragraph>" ++ "<paragraph>y]C</paragraph>",+ "<paragraph>E</paragraph>"));++ editor.execute("undo");+ editor.execute("undo");+ expect(editor.getData()).toBe(before);+ });++ it("fills an empty target, refills the source and ignores targets past an end", () => {+ setModelData(editor.model, layout("1-1-1-1", "A", "[B]", "C", "D"));++ editor.execute("moveToLayoutColumn", { target: "last" });+ expect(modelWithSelection()).toBe(columns("1-1-1-1",+ "<paragraph>A</paragraph>", "<paragraph></paragraph>", "<paragraph>C</paragraph>",+ "<paragraph>[B]</paragraph><paragraph>D</paragraph>"));++ const atLast = modelWithSelection();+ editor.execute("moveToLayoutColumn", { target: "next" });+ editor.execute("moveToLayoutColumn", { target: "last" });+ expect(modelWithSelection()).toBe(atLast);++ setModelData(editor.model, layout("1-1", "[A]", ""));+ editor.execute("moveToLayoutColumn", { target: "next" });+ expect(modelWithSelection()).toBe(layout("1-1", "", "[A]"));++ editor.execute("moveToLayoutColumn", { target: "first" });+ expect(modelWithSelection()).toBe(layout("1-1", "[A]", ""));+ });++ it("leaves out the block that the selection ends at the start of", () => {+ setModelData(editor.model, columns("1-1",+ "<paragraph>[A</paragraph><paragraph>]B</paragraph>", "<paragraph>C</paragraph>"));++ editor.execute("moveToLayoutColumn", { target: "next" });++ expect(modelWithSelection()).toBe(columns("1-1",+ "<paragraph>B</paragraph>", "<paragraph>[A]</paragraph><paragraph>C</paragraph>"));+ });++ it("moves a selected object", () => {+ setModelData(editor.model, columns("1-1",+ `<paragraph>A</paragraph>[${TABLE}]`, "<paragraph>C</paragraph>"));++ editor.execute("moveToLayoutColumn", { target: "next" });++ expect(modelWithSelection()).toBe(columns("1-1",+ "<paragraph>A</paragraph>", `[${TABLE}]<paragraph>C</paragraph>`));+ });++ it("is enabled only for a selection inside one column", () => {+ const command = editor.commands.get("moveToLayoutColumn");+ setModelData(editor.model, layout("1-1", "[A]", "B"));+ expect(command?.isEnabled).toBe(true);++ setModelData(editor.model, layout("1-1", "A[]", "B"));+ expect(command?.isEnabled).toBe(false);++ setModelData(editor.model, `[${layout("1-1", "A", "B")}]`);+ expect(command?.isEnabled).toBe(false);++ setModelData(editor.model, "<paragraph>[A]</paragraph>");+ expect(command?.isEnabled).toBe(false);+ editor.execute("moveToLayoutColumn", { target: "next" });+ expect(modelWithSelection()).toBe("<paragraph>[A]</paragraph>");+ });+ });++ describe("moveLayoutColumn", () => {+ it("moves the current column and its width where the layout has the new order", () => {+ setModelData(editor.model, layout("1-3", "A[]", "B"));++ editor.execute("moveLayoutColumn", { target: "next" });+ expect(modelWithSelection()).toBe(layout("3-1", "B", "A[]"));++ editor.execute("moveLayoutColumn", { target: "previous" });+ expect(modelWithSelection()).toBe(layout("1-3", "A[]", "B"));+ });++ it("keeps the widths where the layout lacks the new order, and ignores the ends", () => {+ setModelData(editor.model, layout("1-2-1", "A[]", "B", "C"));++ editor.execute("moveLayoutColumn", { target: "last" });+ expect(modelWithSelection()).toBe(layout("1-2-1", "B", "C", "A[]"));++ editor.execute("moveLayoutColumn", { target: "next" });+ editor.execute("moveLayoutColumn", { target: "last" });+ expect(modelWithSelection()).toBe(layout("1-2-1", "B", "C", "A[]"));++ editor.execute("moveLayoutColumn", { target: "first" });+ expect(modelWithSelection()).toBe(layout("1-2-1", "A[]", "B", "C"));+ });++ it("is enabled only inside a column", () => {+ const command = editor.commands.get("moveLayoutColumn");+ setModelData(editor.model, layout("1-1", "A[]", "B"));+ expect(command?.isEnabled).toBe(true);++ setModelData(editor.model, "<paragraph>A[]</paragraph>");+ expect(command?.isEnabled).toBe(false);+ editor.execute("moveLayoutColumn", { target: "next" });+ expect(modelWithSelection()).toBe("<paragraph>A[]</paragraph>");+ });+ });++ describe("insertLayoutColumn", () => {+ it("adds an empty column after or before the current one, with equal widths", () => {+ setModelData(editor.model, layout("1-3", "A[]", "B"));++ editor.execute("insertLayoutColumn", { position: "after" });+ expect(modelWithSelection()).toBe(layout("1-1-1", "A", "[]", "B"));++ editor.execute("insertLayoutColumn", { position: "before" });+ expect(modelWithSelection()).toBe(layout("1-1-1-1", "A", "[]", "", "B"));+ });++ it("is disabled with four columns and outside a column", () => {+ const command = editor.commands.get("insertLayoutColumn");+ setModelData(editor.model, layout("1-1-1-1", "A[]", "B", "C", "D"));+ expect(command?.isEnabled).toBe(false);+ editor.execute("insertLayoutColumn", { position: "after" });+ expect(modelWithSelection()).toBe(layout("1-1-1-1", "A[]", "B", "C", "D"));++ setModelData(editor.model, "<paragraph>A[]</paragraph>");+ expect(command?.isEnabled).toBe(false);+ editor.execute("insertLayoutColumn", { position: "after" });+ expect(modelWithSelection()).toBe("<paragraph>A[]</paragraph>");+ });+ });});diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.tsindex 99ecf851dc..7435fe2c87 100644--- a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.ts+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.ts@@ -1,9 +1,15 @@-import { Command, type Editor, type ModelElement, type ModelWriter } from "ckeditor5";+import {+ Command, type Editor, type ModelElement, ModelLivePosition, type ModelPosition, type ModelWriter+} from "ckeditor5";import {- COLUMN_RATIOS, ELEMENTS, getColumnCount, getDefaultRatios, MIN_COLUMNS, RATIOS_ATTRIBUTE+ COLUMN_RATIOS, ELEMENTS, getColumnCount, getDefaultRatios, MAX_COLUMNS, MIN_COLUMNS,+ RATIOS_ATTRIBUTE} from "./constants.js";+/** Where content or a column goes, relative to the current column. */+export type ColumnTarget = "previous" | "next" | "first" | "last";+/*** Inserts a layout with the column weights `value`, two equal columns by default, at the selection.* Selected content moves into the first column, and the caret goes to the end of that column.@@ -97,6 +103,125 @@ export class RemoveMulticolumnLayoutCommand extends Command {}}+/**+ * Moves the blocks of the current column that the selection touches to another column of the+ * layout. Content moved toward the first column goes to the end of the target column, and content+ * moved toward the last column goes to its start, so it keeps its place in the reading order.+ */+export class MoveToLayoutColumnCommand extends Command {++ public override refresh(): void {+ this.isEnabled = !!getSelectedColumnContent(this.editor);+ }++ public override execute({ target }: { target: ColumnTarget }): void {+ const content = getSelectedColumnContent(this.editor);+ /* v8 ignore next 3 -- execute() runs only while refresh() keeps the command enabled */+ if (!content) {+ return;+ }+ const { column, first, last } = content;+ const destination = getTargetColumn(column, target);+ if (!destination) {+ return;+ }++ // The ends stick to the moved blocks; one in the block after `last` moves into `last`.+ const model = this.editor.model;+ const after = model.createPositionAfter(last);+ /* v8 ignore next -- `last` holds a place for the selection, or is an object itself */+ const lastEnd = model.schema.getNearestSelectionRange(after, "backward")?.end ?? after;+ const ends = [...model.document.selection.getRanges()].map(range => [+ ModelLivePosition.fromPosition(range.start, "toNext"),+ ModelLivePosition.fromPosition(range.end.isAfter(after) ? lastEnd : range.end,+ "toPrevious")+ ] as const);++ model.change(writer => {+ if (!hasContent(destination)) {+ writer.remove(writer.createRangeIn(destination));+ }+ const moved = writer.createRange(+ writer.createPositionBefore(first), writer.createPositionAfter(last));+ const offset = destination.isAfter(column) ? 0 : "end";+ writer.move(moved, writer.createPositionAt(destination, offset));+ writer.setSelection(ends.map(([start, end]) => writer.createRange(start, end)));+ });++ for (const position of ends.flat()) {+ position.detach();+ }+ }+}++/**+ * Moves the current column to another place in its layout. The column keeps its width where the+ * layout has the widths in their new order, such as `3-1` from `1-3`.+ */+export class MoveLayoutColumnCommand extends Command {++ public override refresh(): void {+ this.isEnabled = !!getSelectedColumn(this.editor);+ }++ public override execute({ target }: { target: ColumnTarget }): void {+ const column = getSelectedColumn(this.editor);+ /* v8 ignore next 3 -- execute() runs only while refresh() keeps the command enabled */+ if (!column) {+ return;+ }+ const sibling = getTargetColumn(column, target);+ if (!sibling) {+ return;+ }++ const layout = column.parent as ModelElement;+ const columns = [...layout.getChildren()];+ const from = columns.indexOf(column);+ const to = columns.indexOf(sibling);+ this.editor.model.change(writer => {+ writer.move(writer.createRangeOn(column), to > from+ ? writer.createPositionAfter(sibling)+ : writer.createPositionBefore(sibling));++ const weights = String(layout.getAttribute(RATIOS_ATTRIBUTE)).split("-");+ weights.splice(to, 0, ...weights.splice(from, 1));+ const ratios = weights.join("-");+ if (COLUMN_RATIOS.includes(ratios)) {+ writer.setAttribute(RATIOS_ATTRIBUTE, ratios, layout);+ }+ });+ }+}++/**+ * Adds an empty column before or after the current one and puts the caret in it. The columns of+ * the layout then have equal widths.+ */+export class InsertLayoutColumnCommand extends Command {++ public override refresh(): void {+ const column = getSelectedColumn(this.editor);+ this.isEnabled = !!column && (column.parent as ModelElement).childCount < MAX_COLUMNS;+ }++ public override execute({ position }: { position: "before" | "after" }): void {+ const column = getSelectedColumn(this.editor);+ /* v8 ignore next 3 -- execute() runs only while refresh() keeps the command enabled */+ if (!column) {+ return;+ }++ const layout = column.parent as ModelElement;+ this.editor.model.change(writer => {+ const added = createColumn(writer);+ writer.insert(added, column, position);+ writer.setAttribute(RATIOS_ATTRIBUTE, getDefaultRatios(layout.childCount), layout);+ writer.setSelection(added, 0);+ });+ }+}+/*** Returns the selected layout, or the innermost layout that contains the selection.*/@@ -109,6 +234,63 @@ export function getSelectedLayout(editor: Editor): ModelElement | null {return selection.getFirstPosition()?.findAncestor(ELEMENTS.layout) ?? null;}+/** Returns the innermost column that contains the selection. */+export function getSelectedColumn(editor: Editor): ModelElement | null {+ const selection = editor.model.document.selection;+ return selection.getFirstPosition()?.findAncestor(ELEMENTS.column) ?? null;+}++/**+ * Returns the column of a non-collapsed selection and the first and last of its children that the+ * selection touches. A selection that ends at the start of a child leaves that child out.+ */+export function getSelectedColumnContent(editor: Editor) {+ const model = editor.model;+ const selection = model.document.selection;+ const start = selection.getFirstPosition();+ const end = selection.getLastPosition();+ const column = start?.findAncestor(ELEMENTS.column);+ if (selection.isCollapsed || !start || !end || !column+ || end.findAncestor(ELEMENTS.column) !== column) {+ return null;+ }++ const first = getChildAt(column, start, "after");+ let last = getChildAt(column, end, "before");+ if (last && end.parent !== column && end.isTouching(model.createPositionAt(last, 0))) {+ last = last.previousSibling;+ }+ /* v8 ignore next 3 -- a selection that is not collapsed touches a child of the column */+ if (!first || !last) {+ return null;+ }+ return { column, first, last };+}++/**+ * Returns the column of the layout of `column` that `target` names, or `null` when that is `column`+ * itself or there is no such column.+ */+function getTargetColumn(column: ModelElement, target: ColumnTarget): ModelElement | null {+ const columns = [...(column.parent as ModelElement).getChildren()] as ModelElement[];+ const index = columns.indexOf(column);+ const last = columns.length - 1;+ const found = columns[{ previous: index - 1, next: index + 1, first: 0, last }[target]];+ return found && found !== column ? found : null;+}++/**+ * Returns the child of `column` that holds `position`, or the node on `side` of `position` when it+ * is directly in `column`.+ */+function getChildAt(column: ModelElement, position: ModelPosition, side: "before" | "after") {+ if (position.parent === column) {+ return side === "after" ? position.nodeAfter : position.nodeBefore;+ }+ return position.getAncestors().find((ancestor): ancestor is ModelElement =>+ ancestor.is("element") && ancestor.parent === column);+}+/*** Appends empty columns to `layout`, or merges its last columns into the column before them, until* it has `count` columns.diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_editing.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_editing.tsindex dd2130ea76..ccc3305b1a 100644--- a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_editing.ts+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_editing.ts@@ -19,7 +19,8 @@ import {LAYOUT_WIDGET_PROPERTY, MAX_COLUMNS, MIN_COLUMNS, RATIOS_ATTRIBUTE, RATIOS_DATA_ATTRIBUTE} from "./constants.js";import {- ColumnLayoutCommand, InsertMulticolumnLayoutCommand, RemoveMulticolumnLayoutCommand,+ ColumnLayoutCommand, InsertLayoutColumnCommand, InsertMulticolumnLayoutCommand,+ MoveLayoutColumnCommand, MoveToLayoutColumnCommand, RemoveMulticolumnLayoutCommand,setColumnCount} from "./multicolumn_commands.js";@@ -42,6 +43,9 @@ export default class MulticolumnEditing extends Plugin {editor.commands.add("multicolumnLayout", new InsertMulticolumnLayoutCommand(editor));editor.commands.add("columnLayout", new ColumnLayoutCommand(editor));editor.commands.add("removeMulticolumnLayout", new RemoveMulticolumnLayoutCommand(editor));+ editor.commands.add("insertLayoutColumn", new InsertLayoutColumnCommand(editor));+ editor.commands.add("moveLayoutColumn", new MoveLayoutColumnCommand(editor));+ editor.commands.add("moveToLayoutColumn", new MoveToLayoutColumnCommand(editor));this.registerSchema();this.registerConversion();diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.spec.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.spec.tsnew file mode 100644index 0000000000..644b74777d--- /dev/null+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.spec.ts@@ -0,0 +1,203 @@+import {+ _getModelData as getModelData,+ _setModelData as setModelData,+ type ClassicEditor,+ Command,+ type Editor,+ env,+ Essentials,+ LinkEditing,+ List,+ Paragraph,+ TodoList+} from "ckeditor5";+import { describe, expect, it, onTestFinished } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import Multicolumn from "./multicolumn.js";++describe("multicolumn keyboard shortcuts", () => {++ it("lists the shortcuts in the accessibility help", async () => {+ const editor = await createEditor();+ const group = editor.accessibility.keystrokeInfos.get("contentEditing")+ ?.groups.get("multicolumnLayout");++ expect(group?.label).toBe("Keystrokes that can be used in a multicolumn layout");+ expect(group?.keystrokes.map(({ keystroke }) => keystroke)).toEqual([+ "Ctrl+ArrowLeft", "Ctrl+ArrowRight", "Ctrl+Shift+Home", "Ctrl+Shift+End",+ "Ctrl+Alt+ArrowLeft", "Ctrl+Alt+ArrowRight", "Ctrl+Alt+Home", "Ctrl+Alt+End",+ "Ctrl+Enter", "Ctrl+Shift+Enter"+ ]);+ });++ it("moves the selected content between columns, and leaves a caret to the editor", async () => {+ const editor = await createEditor();+ setModelData(editor.model, columns("1-1-1", p("A"), p("[B]"), p("C")));++ expect(press(editor, "ArrowRight", { ctrlKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("A"), p(""), p("[B]", "C")));++ expect(press(editor, "Home", { ctrlKey: true, shiftKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("A", "[B]"), p(""), p("C")));++ expect(press(editor, "ArrowLeft", { ctrlKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("A", "[B]"), p(""), p("C")));++ expect(press(editor, "End", { ctrlKey: true, shiftKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("A"), p(""), p("[B]", "C")));++ setModelData(editor.model, columns("1-1", p("A[]"), p("B")));+ expect(press(editor, "ArrowRight", { ctrlKey: true })).toBe(false);+ expect(press(editor, "End", { ctrlKey: true, shiftKey: true })).toBe(false);+ expect(model(editor)).toBe(columns("1-1", p("A[]"), p("B")));+ });++ it("moves the current column", async () => {+ const editor = await createEditor();+ setModelData(editor.model, columns("1-1-1", p("A[]"), p("B"), p("C")));++ expect(press(editor, "ArrowRight", { ctrlKey: true, altKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("B"), p("A[]"), p("C")));++ expect(press(editor, "End", { ctrlKey: true, altKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("B"), p("C"), p("A[]")));++ expect(press(editor, "ArrowRight", { ctrlKey: true, altKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("B"), p("C"), p("A[]")));++ expect(press(editor, "Home", { ctrlKey: true, altKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("A[]"), p("B"), p("C")));++ expect(press(editor, "ArrowLeft", { ctrlKey: true, altKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("A[]"), p("B"), p("C")));+ });++ it("follows the screen in right-to-left content", async () => {+ const editor = await createEditor({ language: { content: "ar" } });+ setModelData(editor.model, columns("1-1", p("A"), p("[B]")));++ press(editor, "ArrowRight", { ctrlKey: true });+ expect(model(editor)).toBe(columns("1-1", p("A", "[B]"), p("")));++ press(editor, "ArrowLeft", { ctrlKey: true, altKey: true });+ expect(model(editor)).toBe(columns("1-1", p(""), p("A", "[B]")));+ });++ it("adds a column after or before the current one, up to four columns", async () => {+ const editor = await createEditor();+ setModelData(editor.model, columns("1-3", p("A[]"), p("B")));++ expect(press(editor, "Enter", { ctrlKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1", p("A"), p("[]"), p("B")));++ expect(press(editor, "Enter", { ctrlKey: true, shiftKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1-1", p("A"), p("[]"), p(""), p("B")));++ expect(press(editor, "Enter", { ctrlKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1-1-1", p("A"), p("[]"), p(""), p("B")));+ });++ it("leaves Ctrl+Enter to links, to-do items, collapsible titles and references", async () => {+ const editor = await createEditor();+ const contents = [+ "<paragraph><$text linkHref=\"x\">Li[]nk</$text></paragraph>",+ "<paragraph listIndent=\"0\" listItemId=\"a\" listType=\"todo\">X[]</paragraph>",+ "<summary>Ti[]tle</summary>",+ "<paragraph>[<reference></reference>]</paragraph>"+ ];+ for (const content of contents) {+ setModelData(editor.model, columns("1-1", content, p("")));+ expect(press(editor, "Enter", { ctrlKey: true }), content).toBe(false);+ expect(model(editor).match(/<multicolumnColumn>/g), content).toHaveLength(2);+ }+ });++ it("leaves Ctrl+Shift+Enter to the states of to-do items", async () => {+ const editor = await createEditor();+ editor.commands.add("setTaskState", new Command(editor));+ setModelData(editor.model, columns("1-1", p("A[]"), p("B")));++ expect(press(editor, "Enter", { ctrlKey: true, shiftKey: true })).toBe(false);+ expect(model(editor)).toBe(columns("1-1", p("A[]"), p("B")));+ });++ it("leaves other keys and the keys outside a layout alone", async () => {+ const editor = await createEditor();+ setModelData(editor.model, columns("1-1", p("[A]"), p("B")));+ const presses: Array<[string, KeyboardEventInit]> = [+ ["ArrowRight", {}],+ ["ArrowRight", { ctrlKey: true, shiftKey: true }],+ ["ArrowRight", { ctrlKey: true, metaKey: true }],+ ["Home", { ctrlKey: true }],+ ["End", { ctrlKey: true, altKey: true, shiftKey: true }],+ ["Enter", { ctrlKey: true, altKey: true }],+ ["a", { ctrlKey: true }]+ ];+ for (const [key, modifiers] of presses) {+ expect(press(editor, key, modifiers), `${key} ${JSON.stringify(modifiers)}`)+ .toBe(false);+ }+ expect(model(editor)).toBe(columns("1-1", p("[A]"), p("B")));++ setModelData(editor.model, "<paragraph>[A]</paragraph>");+ expect(press(editor, "ArrowRight", { ctrlKey: true })).toBe(false);+ expect(press(editor, "Enter", { ctrlKey: true })).toBe(false);+ });++ it("uses Cmd instead of Ctrl on macOS", async () => {+ const isMac = env.isMac;+ env.isMac = true;+ onTestFinished(() => {+ env.isMac = isMac;+ });+ const editor = await createEditor();+ setModelData(editor.model, columns("1-1", p("A[]"), p("B")));++ expect(press(editor, "ArrowRight", { ctrlKey: true, altKey: true })).toBe(false);+ expect(press(editor, "ArrowRight", { metaKey: true, altKey: true })).toBe(true);+ expect(model(editor)).toBe(columns("1-1", p("B"), p("A[]")));+ });+});++async function createEditor(config: Parameters<typeof createTestEditor>[1] = {}) {+ return createTestEditor(+ [Essentials, Paragraph, List, TodoList, LinkEditing, StandIns, Multicolumn], config);+}++/** Stands in for the title of a collapsible block and for a note reference. */+function StandIns(editor: Editor) {+ const schema = editor.model.schema;+ schema.register("summary", { allowWhere: "$block", allowContentOf: "$block", isBlock: true });+ schema.register("reference", { inheritAllFrom: "$inlineObject" });+ editor.conversion.elementToElement({ model: "summary", view: "summary" });+ editor.conversion.elementToElement({ model: "reference", view: "span" });+}++/** Presses `key` in the editing root and returns whether the layout took the key. */+function press(editor: ClassicEditor, key: string, modifiers: KeyboardEventInit) {+ const root = editor.editing.view.getDomRoot();+ if (!root) {+ throw new Error("The editor has no editing root.");+ }+ const event = new KeyboardEvent("keydown", {+ key, bubbles: true, cancelable: true, ...modifiers+ });+ root.dispatchEvent(event);+ return event.defaultPrevented;+}++function model(editor: ClassicEditor) {+ return getModelData(editor.model);+}++/** A paragraph for each of `texts`, in model notation. */+function p(...texts: string[]) {+ return texts.map(text => `<paragraph>${text}</paragraph>`).join("");+}++/** A layout with the given weights whose columns hold the given model content. */+function columns(ratios: string, ...contents: string[]) {+ const content = contents.map(inner => `<multicolumnColumn>${inner}</multicolumnColumn>`);+ return `<multicolumnLayout columnRatios="${ratios}">${content.join("")}</multicolumnLayout>`;+}diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.tsnew file mode 100644index 0000000000..b1e7a6a621--- /dev/null+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.ts@@ -0,0 +1,140 @@+import { type Editor, env, Plugin } from "ckeditor5";++import { addEditingKeydownCapture } from "../move_block_updown.js";+import { type ColumnTarget, getSelectedColumn } from "./multicolumn_commands.js";+import MulticolumnEditing from "./multicolumn_editing.js";++/**+ * Keyboard shortcuts of multicolumn layouts. Ctrl+Left/Right and Ctrl+Shift+Home/End move the+ * selected content to another column, Ctrl+Alt+Left/Right/Home/End move the current column, and+ * Ctrl+Enter and Ctrl+Shift+Enter add a column after or before it. Ctrl is Cmd on macOS.+ */+export default class MulticolumnKeyboard extends Plugin {++ public static get pluginName() {+ return "MulticolumnKeyboard" as const;+ }++ public static get requires() {+ return [MulticolumnEditing] as const;+ }++ public init(): void {+ const editor = this.editor;+ const t = editor.t;++ // The capture phase runs before `TodoListEditing`, which stops every Ctrl+Enter.+ addEditingKeydownCapture(this, event => {+ const isRtl = editor.locale.contentLanguageDirection === "rtl";+ const shortcut = getShortcut(event, isRtl);+ if (!shortcut || !appliesAtSelection(editor, shortcut)) {+ return;+ }++ // At the first or last column, or with four columns, the key does nothing.+ event.preventDefault();+ event.stopImmediatePropagation();+ if (!editor.commands.get(shortcut.command)?.isEnabled) {+ return;+ }+ if (shortcut.command === "insertLayoutColumn") {+ editor.execute(shortcut.command, { position: shortcut.position });+ } else {+ editor.execute(shortcut.command, { target: shortcut.target });+ }+ });++ editor.accessibility.addKeystrokeInfoGroup({+ id: "multicolumnLayout",+ label: t("Keystrokes that can be used in a multicolumn layout"),+ keystrokes: [+ {+ label: t("Move the selected content to the column on the left"),+ keystroke: "Ctrl+ArrowLeft"+ },+ {+ label: t("Move the selected content to the column on the right"),+ keystroke: "Ctrl+ArrowRight"+ },+ {+ label: t("Move the selected content to the first column"),+ keystroke: "Ctrl+Shift+Home"+ },+ {+ label: t("Move the selected content to the last column"),+ keystroke: "Ctrl+Shift+End"+ },+ { label: t("Move the column to the left"), keystroke: "Ctrl+Alt+ArrowLeft" },+ { label: t("Move the column to the right"), keystroke: "Ctrl+Alt+ArrowRight" },+ { label: t("Make the column the first one"), keystroke: "Ctrl+Alt+Home" },+ { label: t("Make the column the last one"), keystroke: "Ctrl+Alt+End" },+ { label: t("Add a column after the current one"), keystroke: "Ctrl+Enter" },+ { label: t("Add a column before the current one"), keystroke: "Ctrl+Shift+Enter" }+ ]+ });+ }++}++type Shortcut =+ | { command: "moveToLayoutColumn" | "moveLayoutColumn"; target: ColumnTarget }+ | { command: "insertLayoutColumn"; position: "before" | "after" };++/**+ * Returns the shortcut that `event` presses. Left and Right follow the screen, so in right-to-left+ * content Right moves toward the first column.+ */+function getShortcut(event: KeyboardEvent, isRtl: boolean): Shortcut | null {+ const { altKey: alt, shiftKey: shift } = event;+ const ctrl = env.isMac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;+ if (!ctrl) {+ return null;+ }++ const command = alt ? "moveLayoutColumn" : "moveToLayoutColumn";+ switch (event.key) {+ case "ArrowLeft":+ case "ArrowRight": {+ const target = (event.key === "ArrowRight") !== isRtl ? "next" : "previous";+ return shift ? null : { command, target };+ }+ case "Home":+ case "End": {+ const target = event.key === "Home" ? "first" : "last";+ return alt === shift ? null : { command, target };+ }+ case "Enter":+ return alt+ ? null+ : { command: "insertLayoutColumn", position: shift ? "before" : "after" };+ default:+ return null;+ }+}++/**+ * Whether `shortcut` acts on the selection in a column. A caret keeps Ctrl+Left/Right and+ * Ctrl+Shift+Home/End for moving and selecting by word and to the edges. Ctrl+Enter stays with+ * links, to-do items and collapsible titles, and Ctrl+Shift+Enter with to-do items.+ */+function appliesAtSelection(editor: Editor, shortcut: Shortcut) {+ const selection = editor.model.document.selection;+ if (!getSelectedColumn(editor)) {+ return false;+ }++ switch (shortcut.command) {+ case "moveToLayoutColumn":+ return !selection.isCollapsed;+ case "moveLayoutColumn":+ return true;+ case "insertLayoutColumn":+ if (shortcut.position === "before") {+ return !editor.commands.get("setTaskState")?.isEnabled;+ }+ return !editor.commands.get("checkTodoList")?.isEnabled+ && !selection.hasAttribute("linkHref")+ && !selection.getSelectedElement()?.is("element", "reference")+ && !selection.getFirstPosition()?.findAncestor("summary");+ }+}