Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tabs: add keyboard support for manipulating tabs

Adorian Dorand4bf1a5dddd9
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index b977d5a2d9..97b09bfa3b 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4536,7 +4536,18 @@
"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"
+ "add-a-column-before-the-current-one": "Add a column before the current one",
+ "keystrokes-that-can-be-used-in-a-tabs-block": "Keystrokes that can be used in a tabs block",
+ "move-the-selected-content-to-the-tab-on-the-left": "Move the selected content to the tab on the left",
+ "move-the-selected-content-to-the-tab-on-the-right": "Move the selected content to the tab on the right",
+ "move-the-selected-content-to-the-first-tab": "Move the selected content to the first tab",
+ "move-the-selected-content-to-the-last-tab": "Move the selected content to the last tab",
+ "move-the-tab-to-the-left": "Move the tab to the left",
+ "move-the-tab-to-the-right": "Move the tab to the right",
+ "make-the-tab-the-first-one": "Make the tab the first one",
+ "make-the-tab-the-last-one": "Make the tab the last one",
+ "add-a-tab-after-the-current-one": "Add a tab after the current one",
+ "add-a-tab-before-the-current-one": "Add a tab 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/Content tabs.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content tabs.html
index 98c026f94f..812c856a93 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content tabs.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Content tabs.html
@@ -44,6 +44,48 @@
</ul>
<p>The tab that is showing is not saved with the note: every tabs block opens
on its first tab.</p>
+<h3>Adding tabs</h3>
+<p>While the cursor is in a tab, either in its title or in its panel, you
+ can use these key combinations:</p>
+<ul>
+ <li><kbd>Ctrl</kbd> + <kbd>Enter</kbd>: Add a tab after the current one.</li>
+ <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>: Add a tab before the
+ current one.</li>
+</ul>
+<p>The new tab is shown and its title is selected, so typing replaces it.</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 tabs</h3>
+<p>While the cursor is in a tab, either in its title or in its panel, you
+ can use these key combinations:</p>
+<ul>
+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Right</kbd>: Move the tab to the right.</li>
+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Left</kbd>: Move the tab to the left.</li>
+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Home</kbd>: Make it the first tab.</li>
+ <li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>End</kbd>: Make it the last tab.</li>
+</ul>
+<h2>Moving content between tabs</h2>
+<p>To move content to another tab, select it in the panel, and then use these
+ key combinations:</p>
+<ul>
+ <li><kbd>Ctrl</kbd> + <kbd>Right</kbd>: Move to the tab on the right.</li>
+ <li><kbd>Ctrl</kbd> + <kbd>Left</kbd>: Move to the tab on the left.</li>
+ <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>End</kbd>: Move to the last tab.</li>
+ <li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Home</kbd>: Move to the first tab.</li>
+</ul>
+<p>The tab that receives the content is shown, with the content still selected,
+ so pressing the key again moves it on to the next tab. Paragraphs, list
+ items, tables and other blocks move whole, even when only part of them
+ is selected. Content moved to a tab on the left goes to the end of that
+ tab, and content moved to a tab on the right goes to its start, so it keeps
+ its place in the reading order.</p>
+<p>Without a selection, or with a selection in a tab title, these keys keep
+ their usual function: moving the cursor by word, or selecting up to the
+ start or end of the tab.</p>
+<p>When a tabs block and a <a class="reference-link" href="#root/_help_wYDzQ1fBFgfT">Multicolumn layout</a> are
+ nested in one another, the key combinations act on the one closest to the
+ cursor.</p>
<h2>Reading tabs</h2>
<p>In&nbsp;<a class="reference-link" href="#root/_help_CoFPLs3dRlXc">Read-Only Notes</a>&nbsp;and
on&nbsp;<a class="reference-link" href="#root/_help_R9pX4DGra2Vt">Sharing</a>,
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.html
index 23cad3053c..097b482a74 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
@@ -96,6 +96,22 @@
<td>Ctrl+Enter, Ctrl+Shift+Enter</td>
<td>⌘+Enter, ⌘+⇧+Enter</td>
</tr>
+ <tr>
+ <td>Move the selected content to another tab in <a class="reference-link" href="#root/_help_EK2ckIZ74tbT">Content tabs</a>
+ </td>
+ <td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td>
+ <td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td>
+ </tr>
+ <tr>
+ <td>Move the current tab of a tabs block</td>
+ <td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td>
+ <td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td>
+ </tr>
+ <tr>
+ <td>Add a tab after or before the current one in a tabs block</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.html
index 4f1d230357..78869767ea 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
@@ -84,6 +84,9 @@
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>
+<p>When a layout and <a class="reference-link" href="#root/_help_EK2ckIZ74tbT">Content tabs</a> are
+ nested in one another, the key combinations act on the one closest to the
+ cursor.</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> button
diff --git a/docs/User Guide/User Guide/Note Types/Text/Content tabs.md b/docs/User Guide/User Guide/Note Types/Text/Content tabs.md
index 508bf4afe3..74c7aa5d01 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Content tabs.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Content tabs.md
@@ -29,6 +29,41 @@ While the cursor is inside a tabs block, a toolbar appears above it with the fol
The tab that is showing is not saved with the note: every tabs block opens on its first tab.
+### Adding tabs
+
+While the cursor is in a tab, either in its title or in its panel, you can use these key combinations:
+
+* <kbd>Ctrl</kbd> + <kbd>Enter</kbd>: Add a tab after the current one.
+* <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>: Add a tab before the current one.
+
+The new tab is shown and its title is selected, so typing replaces it.
+
+<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 tabs
+
+While the cursor is in a tab, either in its title or in its panel, you can use these key combinations:
+
+* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Right</kbd>: Move the tab to the right.
+* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Left</kbd>: Move the tab to the left.
+* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Home</kbd>: Make it the first tab.
+* <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>End</kbd>: Make it the last tab.
+
+## Moving content between tabs
+
+To move content to another tab, select it in the panel, and then use these key combinations:
+
+* <kbd>Ctrl</kbd> + <kbd>Right</kbd>: Move to the tab on the right.
+* <kbd>Ctrl</kbd> + <kbd>Left</kbd>: Move to the tab on the left.
+* <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>End</kbd>: Move to the last tab.
+* <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Home</kbd>: Move to the first tab.
+
+The tab that receives the content is shown, with the content still selected, so pressing the key again moves it on to the next tab. Paragraphs, list items, tables and other blocks move whole, even when only part of them is selected. Content moved to a tab on the left goes to the end of that tab, and content moved to a tab on the right goes to its start, so it keeps its place in the reading order.
+
+Without a selection, or with a selection in a tab title, these keys keep their usual function: moving the cursor by word, or selecting up to the start or end of the tab.
+
+When a tabs block and a <a class="reference-link" href="Multicolumn%20layout.md">Multicolumn layout</a> are nested in one another, the key combinations act on the one closest to the cursor.
+
## Reading tabs
In <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md">Read-Only Notes</a> and on <a class="reference-link" href="../../Advanced%20Usage/Sharing.md">Sharing</a>, tabs blocks work as tabs as well:
diff --git a/docs/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.md b/docs/User Guide/User Guide/Note Types/Text/Keyboard shortcuts.md
index 741b6dbfdd..1095a204df 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
@@ -19,6 +19,9 @@
| 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 |
+| Move the selected content to another tab in <a class="reference-link" href="Content%20tabs.md">Content tabs</a> | Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End | ⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End |
+| Move the current tab of a tabs block | Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End | ⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End |
+| Add a tab after or before the current one in a tabs block | Ctrl+Enter, Ctrl+Shift+Enter | ⌘+Enter, ⌘+⇧+Enter |
## Common shortcuts
diff --git a/docs/User Guide/User Guide/Note Types/Text/Multicolumn layout.md b/docs/User Guide/User Guide/Note Types/Text/Multicolumn layout.md
index a4aa409ec2..47c5cf369f 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
@@ -58,6 +58,8 @@ Paragraphs, list items, tables and other blocks move whole, even when only part
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.
+When a layout and <a class="reference-link" href="Content%20tabs.md">Content tabs</a> are nested in one another, the key combinations act on the one closest to the cursor.
+
## 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/containers/container_content.ts b/packages/ckeditor5/src/plugins/containers/container_content.ts
new file mode 100644
index 0000000000..dec35eaa27
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/containers/container_content.ts
@@ -0,0 +1,121 @@
+import {
+ type Editor, type ModelElement, ModelLivePosition, type ModelNode, type ModelPosition,
+ type ModelWriter
+} from "ckeditor5";
+
+/**
+ * Where content or a container goes, relative to the current container among its siblings, such
+ * as the columns of a layout or the tabs of a tabs block.
+ */
+export type SiblingTarget = "previous" | "next" | "first" | "last";
+
+/** The children of `parent` that a selection touches, from `first` to `last`. */
+export interface SelectedChildren {
+ parent: ModelElement;
+ first: ModelNode;
+ last: ModelNode;
+}
+
+/**
+ * Returns the sibling of `element` that `target` names, or `null` when that is `element` itself or
+ * there is no such sibling.
+ */
+export function getSibling(element: ModelElement, target: SiblingTarget): ModelElement | null {
+ const siblings = [...(element.parent as ModelElement).getChildren()] as ModelElement[];
+ const index = siblings.indexOf(element);
+ const last = siblings.length - 1;
+ const found = siblings[{ previous: index - 1, next: index + 1, first: 0, last }[target]];
+ return found && found !== element ? found : null;
+}
+
+/** Moves `element` to the place of its sibling `sibling`, which shifts toward the old place. */
+export function moveToSibling(writer: ModelWriter, element: ModelElement, sibling: ModelElement) {
+ writer.move(writer.createRangeOn(element), sibling.isAfter(element)
+ ? writer.createPositionAfter(sibling)
+ : writer.createPositionBefore(sibling));
+}
+
+/**
+ * Returns the innermost `name` element around a non-collapsed selection, with the first and last
+ * of its children that the selection touches, or `null` when the selection ends outside it. A
+ * selection that ends at the start of a child leaves that child out.
+ */
+export function getSelectedChildren(editor: Editor, name: string): SelectedChildren | null {
+ const model = editor.model;
+ const selection = model.document.selection;
+ const start = selection.getFirstPosition();
+ const end = selection.getLastPosition();
+ const parent = start?.findAncestor(name);
+ if (selection.isCollapsed || !start || !end || !parent || end.findAncestor(name) !== parent) {
+ return null;
+ }
+
+ const first = getChildAt(parent, start, "after");
+ let last = getChildAt(parent, end, "before");
+ if (last && end.parent !== parent && end.isTouching(model.createPositionAt(last, 0))) {
+ last = last.previousSibling;
+ }
+ /* v8 ignore next 3 -- a selection that is not collapsed touches a child of its parent */
+ if (!first || !last) {
+ return null;
+ }
+ return { parent, first, last };
+}
+
+/**
+ * Moves the children from `first` to `last` into `destination`, and the selection with them. They
+ * go to the end of a destination before `parent` and to the start of one after it, so they keep
+ * their place in the reading order. A destination without content loses its empty paragraph.
+ */
+export function moveSelectedChildren(
+ editor: Editor, { parent, first, last }: SelectedChildren, destination: ModelElement
+) {
+ // The ends stick to the moved children; one in the child after `last` moves into `last`.
+ const model = 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(parent) ? 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();
+ }
+}
+
+/** Whether `element` holds more than the empty paragraph that a new column or tab starts with. */
+export function hasContent(element: ModelElement) {
+ const first = element.getChild(0);
+ if (!first) {
+ return false;
+ }
+ return element.childCount > 1
+ || !first.is("element", "paragraph")
+ || !first.isEmpty
+ || first.hasAttribute("listItemId");
+}
+
+/**
+ * Returns the child of `parent` that holds `position`, or the node on `side` of `position` when it
+ * is directly in `parent`.
+ */
+function getChildAt(parent: ModelElement, position: ModelPosition, side: "before" | "after") {
+ if (position.parent === parent) {
+ return side === "after" ? position.nodeAfter : position.nodeBefore;
+ }
+ return position.getAncestors().find((ancestor): ancestor is ModelElement =>
+ ancestor.is("element") && ancestor.parent === parent);
+}
diff --git a/packages/ckeditor5/src/plugins/containers/container_keyboard.spec.ts b/packages/ckeditor5/src/plugins/containers/container_keyboard.spec.ts
new file mode 100644
index 0000000000..ef37015469
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/containers/container_keyboard.spec.ts
@@ -0,0 +1,75 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ type ClassicEditor,
+ Essentials,
+ Paragraph
+} from "ckeditor5";
+import { describe, expect, it } from "vitest";
+
+import { createTestEditor, pressKey as press } from "../../../test/editor-kit.js";
+import Multicolumn from "../multicolumn/multicolumn.js";
+import Tabs from "../tabs/tabs.js";
+
+describe("container keyboard shortcuts", () => {
+
+ it("act in the innermost column or tab around the selection", async () => {
+ const editor = await createEditor();
+
+ setModelData(editor.model, columns(block(tab("A", p("a[]")), tab("B", p("b"))), p("C")));
+ expect(press(editor, "ArrowRight", { ctrlKey: true, altKey: true })).toBe(true);
+ expect(model(editor)).toBe(columns(block(tab("B", p("b")), tab("A", p("a[]"))), p("C")));
+
+ setModelData(editor.model, block(tab("A", columns(p("x[]"), p("y"))), tab("B", p("b"))));
+ expect(press(editor, "ArrowRight", { ctrlKey: true, altKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("A", columns(p("y"), p("x[]"))), tab("B", p("b"))));
+
+ setModelData(editor.model, block(tab("A", columns(p("[x]"), p("y"))), tab("B", p("b"))));
+ expect(press(editor, "ArrowRight", { ctrlKey: true })).toBe(true);
+ expect(model(editor))
+ .toBe(block(tab("A", columns(p(""), p("[x]", "y"))), tab("B", p("b"))));
+ });
+
+ it("leave a title to the editor, and move a tabs block selected as a whole", async () => {
+ const editor = await createEditor();
+ const data = columns(block(tab("[A]", p("a")), tab("B", p("b"))), p("C"));
+ setModelData(editor.model, data);
+ expect(press(editor, "ArrowRight", { ctrlKey: true })).toBe(false);
+ expect(model(editor)).toBe(data);
+
+ const tabs = block(tab("A", p("a")), tab("B", p("b")));
+ setModelData(editor.model, columns(`[${tabs}]`, p("C")));
+ expect(press(editor, "ArrowRight", { ctrlKey: true })).toBe(true);
+ expect(model(editor)).toBe(columns(p(""), `[${tabs}]${p("C")}`));
+ });
+});
+
+async function createEditor() {
+ return createTestEditor([Essentials, Paragraph, Multicolumn, Tabs]);
+}
+
+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 of equal columns that hold the given model content. */
+function columns(...contents: string[]) {
+ const content = contents.map(inner => `<multicolumnColumn>${inner}</multicolumnColumn>`);
+ const ratios = contents.map(() => "1").join("-");
+ return `<multicolumnLayout columnRatios="${ratios}">${content.join("")}</multicolumnLayout>`;
+}
+
+/** A tabs block in model notation that holds `tabs`. */
+function block(...tabs: string[]) {
+ return `<tabs>${tabs.join("")}</tabs>`;
+}
+
+/** A tab in model notation with the given title and panel content. */
+function tab(title: string, panel: string) {
+ return `<tab><tabTitle>${title}</tabTitle><tabPanel>${panel}</tabPanel></tab>`;
+}
diff --git a/packages/ckeditor5/src/plugins/containers/container_keyboard.ts b/packages/ckeditor5/src/plugins/containers/container_keyboard.ts
new file mode 100644
index 0000000000..b200155331
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/containers/container_keyboard.ts
@@ -0,0 +1,146 @@
+import { type Editor, env, Plugin } from "ckeditor5";
+
+import { addEditingKeydownCapture } from "../move_block_updown.js";
+import type { SiblingTarget } from "./container_content.js";
+
+/** The commands that the keyboard runs in one kind of container, such as a layout column. */
+export interface ContainerCommands {
+ /**
+ * Moves the selected content to another container and takes `{ target }`. Its keys act only
+ * while it is enabled, so a caret keeps word jumps and select-to-edge.
+ */
+ moveContent: string;
+ /** Moves the current container and takes `{ target }`. */
+ moveContainer: string;
+ /** Adds a container next to the current one and takes `{ position }`. */
+ insert: string;
+}
+
+/**
+ * Keyboard shortcuts of containers that sit side by side, such as layout columns and tabs. In the
+ * innermost registered container around the selection, Ctrl+Left/Right and Ctrl+Shift+Home/End
+ * move the selected content to another container, Ctrl+Alt+Left/Right/Home/End move the
+ * container, and Ctrl+Enter and Ctrl+Shift+Enter add a container after or before it. Ctrl is Cmd
+ * on macOS.
+ */
+export default class ContainerKeyboard extends Plugin {
+
+ public static get pluginName() {
+ return "ContainerKeyboard" as const;
+ }
+
+ /** The commands of each registered container, keyed by its model element name. */
+ private readonly containers = new Map<string, ContainerCommands>();
+
+ /** Lets the shortcuts act in `element` containers, through `commands`. */
+ public register(element: string, commands: ContainerCommands): void {
+ this.containers.set(element, commands);
+ }
+
+ public init(): void {
+ const editor = this.editor;
+
+ // 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);
+ const commands = shortcut && this.getInnermostCommands();
+ if (!shortcut || !commands || !appliesAtSelection(editor, shortcut, commands)) {
+ return;
+ }
+
+ // At either end, or where no container can be added, the key does nothing.
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ const command = commands[shortcut.action];
+ if (!editor.commands.get(command)?.isEnabled) {
+ return;
+ }
+ const version = editor.model.document.version;
+ if (shortcut.action === "insert") {
+ editor.execute(command, { position: shortcut.position });
+ } else {
+ editor.execute(command, { target: shortcut.target });
+ }
+ if (editor.model.document.version !== version) {
+ editor.editing.view.scrollToTheSelection();
+ }
+ });
+ }
+
+ /** Returns the commands of the innermost registered container around the selection. */
+ private getInnermostCommands(): ContainerCommands | null {
+ const position = this.editor.model.document.selection.getFirstPosition();
+ /* v8 ignore next -- the document selection always has a position */
+ for (const ancestor of position?.getAncestors().reverse() ?? []) {
+ const commands = ancestor.is("element") && this.containers.get(ancestor.name);
+ if (commands) {
+ return commands;
+ }
+ }
+ return null;
+ }
+
+}
+
+type Shortcut =
+ | { action: "moveContent" | "moveContainer"; target: SiblingTarget }
+ | { action: "insert"; 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 container.
+ */
+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 action = alt ? "moveContainer" : "moveContent";
+ switch (event.key) {
+ case "ArrowLeft":
+ case "ArrowRight": {
+ const target = (event.key === "ArrowRight") !== isRtl ? "next" : "previous";
+ return shift ? null : { action, target };
+ }
+ case "Home":
+ case "End": {
+ const target = event.key === "Home" ? "first" : "last";
+ return alt === shift ? null : { action, target };
+ }
+ case "Enter":
+ return alt ? null : { action: "insert", position: shift ? "before" : "after" };
+ default:
+ return null;
+ }
+}
+
+/**
+ * Whether `shortcut` acts on the selection in a container. 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, commands: ContainerCommands) {
+ const selection = editor.model.document.selection;
+ switch (shortcut.action) {
+ case "moveContent":
+ return !!editor.commands.get(commands.moveContent)?.isEnabled;
+ case "moveContainer":
+ return true;
+ case "insert":
+ 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");
+ }
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [ContainerKeyboard.pluginName]: ContainerKeyboard;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.ts
index 7435fe2c87..23ba7ebe0c 100644
--- a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.ts
+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_commands.ts
@@ -1,15 +1,14 @@
-import {
- Command, type Editor, type ModelElement, ModelLivePosition, type ModelPosition, type ModelWriter
-} from "ckeditor5";
+import { Command, type Editor, type ModelElement, type ModelWriter } from "ckeditor5";
+import {
+ getSelectedChildren, getSibling, hasContent, moveSelectedChildren, moveToSibling,
+ type SiblingTarget
+} from "../containers/container_content.js";
import {
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.
@@ -111,45 +110,18 @@ export class RemoveMulticolumnLayoutCommand extends Command {
export class MoveToLayoutColumnCommand extends Command {
public override refresh(): void {
- this.isEnabled = !!getSelectedColumnContent(this.editor);
+ this.isEnabled = !!getSelectedChildren(this.editor, ELEMENTS.column);
}
- public override execute({ target }: { target: ColumnTarget }): void {
- const content = getSelectedColumnContent(this.editor);
+ public override execute({ target }: { target: SiblingTarget }): void {
+ const content = getSelectedChildren(this.editor, ELEMENTS.column);
/* 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();
+ const destination = getSibling(content.parent, target);
+ if (destination) {
+ moveSelectedChildren(this.editor, content, destination);
}
}
}
@@ -164,13 +136,13 @@ export class MoveLayoutColumnCommand extends Command {
this.isEnabled = !!getSelectedColumn(this.editor);
}
- public override execute({ target }: { target: ColumnTarget }): void {
+ public override execute({ target }: { target: SiblingTarget }): 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);
+ const sibling = getSibling(column, target);
if (!sibling) {
return;
}
@@ -180,9 +152,7 @@ export class MoveLayoutColumnCommand extends Command {
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));
+ moveToSibling(writer, column, sibling);
const weights = String(layout.getAttribute(RATIOS_ATTRIBUTE)).split("-");
weights.splice(to, 0, ...weights.splice(from, 1));
@@ -240,57 +210,6 @@ export function getSelectedColumn(editor: Editor): ModelElement | null {
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.
@@ -325,15 +244,3 @@ function mergeColumn(writer: ModelWriter, from: ModelElement, to: ModelElement)
}
writer.remove(from);
}
-
-/** Whether `column` holds more than the empty paragraph that a new column starts with. */
-function hasContent(column: ModelElement) {
- const first = column.getChild(0);
- if (!first) {
- return false;
- }
- return column.childCount > 1
- || !first.is("element", "paragraph")
- || !first.isEmpty
- || first.hasAttribute("listItemId");
-}
diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.spec.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.spec.ts
index 644b74777d..8922feebce 100644
--- a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.spec.ts
+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.spec.ts
@@ -13,7 +13,7 @@ import {
} from "ckeditor5";
import { describe, expect, it, onTestFinished } from "vitest";
-import { createTestEditor } from "../../../test/editor-kit.js";
+import { createTestEditor, pressKey as press } from "../../../test/editor-kit.js";
import Multicolumn from "./multicolumn.js";
describe("multicolumn keyboard shortcuts", () => {
@@ -174,19 +174,6 @@ function StandIns(editor: Editor) {
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);
}
diff --git a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.ts b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.ts
index b1e7a6a621..5395b0aa68 100644
--- a/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.ts
+++ b/packages/ckeditor5/src/plugins/multicolumn/multicolumn_keyboard.ts
@@ -1,13 +1,13 @@
-import { type Editor, env, Plugin } from "ckeditor5";
+import { Plugin } from "ckeditor5";
-import { addEditingKeydownCapture } from "../move_block_updown.js";
-import { type ColumnTarget, getSelectedColumn } from "./multicolumn_commands.js";
+import ContainerKeyboard from "../containers/container_keyboard.js";
+import { ELEMENTS } from "./constants.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.
+ * Keyboard shortcuts of multicolumn layouts, run by `ContainerKeyboard`. 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.
*/
export default class MulticolumnKeyboard extends Plugin {
@@ -16,32 +16,17 @@ export default class MulticolumnKeyboard extends Plugin {
}
public static get requires() {
- return [MulticolumnEditing] as const;
+ return [MulticolumnEditing, ContainerKeyboard] 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.plugins.get(ContainerKeyboard).register(ELEMENTS.column, {
+ moveContent: "moveToLayoutColumn",
+ moveContainer: "moveLayoutColumn",
+ insert: "insertLayoutColumn"
});
editor.accessibility.addKeystrokeInfoGroup({
@@ -75,66 +60,3 @@ export default class MulticolumnKeyboard extends Plugin {
}
}
-
-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");
- }
-}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs.ts b/packages/ckeditor5/src/plugins/tabs/tabs.ts
index e985052383..81cd728954 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs.ts
@@ -3,20 +3,22 @@ import { Plugin } from "ckeditor5";
import "../../theme/tabs.css";
import type {
AssignTabReferenceCommand, InsertTabCommand, InsertTabsCommand, MoveTabCommand,
- RemoveTabCommand, TabAlignmentCommand
+ MoveToTabCommand, RemoveTabCommand, TabAlignmentCommand
} from "./tabs_commands.js";
import TabsEditing from "./tabs_editing.js";
+import TabsKeyboard from "./tabs_keyboard.js";
import TabsUI from "./tabs_ui.js";
/**
* The tabs block: titled panels of block content, one of which shows at a time.
*
- * This is a "glue" plugin which loads {@link TabsEditing} and {@link TabsUI}.
+ * This is a "glue" plugin which loads {@link TabsEditing}, {@link TabsKeyboard} and
+ * {@link TabsUI}.
*/
export default class Tabs extends Plugin {
public static get requires() {
- return [TabsEditing, TabsUI] as const;
+ return [TabsEditing, TabsKeyboard, TabsUI] as const;
}
public static get pluginName() {
@@ -29,6 +31,7 @@ declare module "ckeditor5" {
interface PluginsMap {
[Tabs.pluginName]: Tabs;
[TabsEditing.pluginName]: TabsEditing;
+ [TabsKeyboard.pluginName]: TabsKeyboard;
[TabsUI.pluginName]: TabsUI;
}
@@ -38,6 +41,8 @@ declare module "ckeditor5" {
removeTab: RemoveTabCommand;
moveTabLeft: MoveTabCommand;
moveTabRight: MoveTabCommand;
+ moveTab: MoveTabCommand;
+ moveToTab: MoveToTabCommand;
assignTabReference: AssignTabReferenceCommand;
tabAlignment: TabAlignmentCommand;
}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts
index ffb984022e..1f1e5df1aa 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_commands.spec.ts
@@ -1,5 +1,6 @@
import {
_getModelData as getModelData,
+ _setModelData as setModelData,
ClassicEditor,
Essentials,
type ModelElement,
@@ -40,6 +41,16 @@ describe("tabs commands", () => {
});
}
+ function modelWithSelection() {
+ return getModelData(editor.model);
+ }
+
+ function activeTitles() {
+ const root = editor.editing.view.getDomRoot();
+ return [...root?.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ?? []]
+ .map(title => title.textContent);
+ }
+
it("adds a tab at the end of a block selected as a whole, including a nested one", () => {
editor.setData(
`<div class="trilium-tabs">${tab("A")}<section class="trilium-tab">` +
@@ -125,4 +136,120 @@ describe("tabs commands", () => {
expect(editor.commands.get("moveTabLeft")?.isEnabled).toBe(false);
expect(editor.commands.get("moveTabRight")?.isEnabled).toBe(true);
});
+
+ describe("moveToTab", () => {
+ it("moves the touched blocks to a later tab's start or an earlier tab's end, and shows it", () => {
+ setModelData(editor.model, block(
+ modelTab("A", "a"), modelTab("B", "b[1", "b]2", "b3"), modelTab("C", "c")));
+ const before = editor.getData();
+
+ editor.execute("moveToTab", { target: "next" });
+ expect(modelWithSelection()).toBe(block(
+ modelTab("A", "a"), modelTab("B", "b3"), modelTab("C", "b[1", "b]2", "c")));
+ expect(activeTitles()).toEqual(["C"]);
+
+ editor.execute("moveToTab", { target: "first" });
+ expect(modelWithSelection()).toBe(block(
+ modelTab("A", "a", "b[1", "b]2"), modelTab("B", "b3"), modelTab("C", "c")));
+ expect(activeTitles()).toEqual(["A"]);
+
+ 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, block(modelTab("A", "[a]"), modelTab("B", "")));
+
+ editor.execute("moveToTab", { target: "last" });
+ expect(modelWithSelection()).toBe(block(modelTab("A", ""), modelTab("B", "[a]")));
+
+ editor.execute("moveToTab", { target: "next" });
+ editor.execute("moveToTab", { target: "last" });
+ expect(modelWithSelection()).toBe(block(modelTab("A", ""), modelTab("B", "[a]")));
+
+ editor.execute("moveToTab", { target: "previous" });
+ expect(modelWithSelection()).toBe(block(modelTab("A", "[a]"), modelTab("B", "")));
+ });
+
+ it("moves a nested tabs block selected as a whole", () => {
+ const inner = block(modelTab("X", "x"), modelTab("Y", "y"));
+ setModelData(editor.model, block(rawTab("A", `[${inner}]`), modelTab("B", "b")));
+
+ editor.execute("moveToTab", { target: "next" });
+
+ expect(modelWithSelection()).toBe(block(
+ modelTab("A", ""), rawTab("B", `[${inner}]<paragraph>b</paragraph>`)));
+ });
+
+ it("is enabled only for a selection inside one panel", () => {
+ const nested = block(modelTab("[X]", "x"), modelTab("Y", "y"));
+ const cases: Array<[string, boolean]> = [
+ [block(modelTab("A", "[a]"), modelTab("B", "b")), true],
+ [block(modelTab("A", "a[]"), modelTab("B", "b")), false],
+ [block(modelTab("[A]", "a"), modelTab("B", "b")), false],
+ [block(rawTab("A", nested), modelTab("B", "b")), false],
+ [`[${block(modelTab("A", "a"), modelTab("B", "b"))}]`, false],
+ ["<paragraph>[a]</paragraph>", false]
+ ];
+ for (const [data, isEnabled] of cases) {
+ setModelData(editor.model, data);
+ expect(editor.commands.get("moveToTab")?.isEnabled, data).toBe(isEnabled);
+ }
+ });
+ });
+
+ describe("moveTab", () => {
+ it("moves the current tab to any place, and the side commands only next to it", () => {
+ const [a, b, c] = [modelTab("A", "a"), modelTab("B", "b[]"), modelTab("C", "c")];
+ setModelData(editor.model, block(a, b, c));
+
+ editor.execute("moveTab", { target: "last" });
+ expect(modelWithSelection()).toBe(block(a, c, b));
+ expect(editor.commands.get("moveTabRight")?.isEnabled).toBe(false);
+ expect(editor.commands.get("moveTab")?.isEnabled).toBe(true);
+
+ editor.execute("moveTab", { target: "next" });
+ editor.execute("moveTab");
+ expect(modelWithSelection()).toBe(block(a, c, b));
+
+ editor.execute("moveTab", { target: "first" });
+ expect(modelWithSelection()).toBe(block(b, a, c));
+ expect(activeTitles()).toEqual(["B"]);
+ });
+ });
+
+ describe("insertTab", () => {
+ it("adds a tab before or after the current one, numbered by its place", () => {
+ const [a, b] = [modelTab("A", "a"), modelTab("B", "b")];
+ setModelData(editor.model, block(modelTab("A", "a[]"), b));
+
+ editor.execute("insertTab", { position: "before" });
+ expect(modelWithSelection()).toBe(block(modelTab("[Tab 1]", ""), a, b));
+ expect(activeTitles()).toEqual(["Tab 1"]);
+
+ editor.execute("insertTab", { position: "after" });
+ expect(modelWithSelection())
+ .toBe(block(modelTab("Tab 1", ""), modelTab("[Tab 2]", ""), a, b));
+
+ setModelData(editor.model, `[${block(a, b)}]`);
+ editor.execute("insertTab", { position: "before" });
+ expect(modelWithSelection()).toBe(block(modelTab("[Tab 1]", ""), a, b));
+ });
+ });
});
+
+/** A tabs block in model notation that holds `tabs`. */
+function block(...tabs: string[]) {
+ return `<tabs>${tabs.join("")}</tabs>`;
+}
+
+/** A tab in model notation with the given title and a paragraph for each of `texts`. */
+function modelTab(title: string, ...texts: string[]) {
+ return rawTab(title, texts.map(text => `<paragraph>${text}</paragraph>`).join(""));
+}
+
+/** A tab in model notation with the given title and panel content. */
+function rawTab(title: string, panel: string) {
+ return `<tab><tabTitle>${title}</tabTitle><tabPanel>${panel}</tabPanel></tab>`;
+}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts b/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
index e045bc510f..6d0d5ea036 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_commands.ts
@@ -1,6 +1,9 @@
import { Command, type Editor, type ModelElement, type ModelWriter } from "ckeditor5";
import { BLOCK_ID, type BlockReferenceTarget, generateBlockId } from "../block_reference/block_reference_editing.js";
+import {
+ getSelectedChildren, getSibling, moveSelectedChildren, moveToSibling, type SiblingTarget
+} from "../containers/container_content.js";
import {
ALIGNMENT_ATTRIBUTE, DEFAULT_TAB_ALIGNMENT, ELEMENTS, parseTabAlignment, type TabAlignment
} from "./constants.js";
@@ -37,8 +40,8 @@ export class InsertTabsCommand extends Command {
}
/**
- * Adds a tab after the one holding the selection, numbered by its position, and selects its
- * title. With the whole block selected, the tab goes at the end.
+ * Adds a tab after or before the one holding the selection, numbered by its position, and selects
+ * its title. With the whole block selected, the tab goes at the end or at the start.
*/
export class InsertTabCommand extends Command {
@@ -46,24 +49,23 @@ export class InsertTabCommand extends Command {
this.isEnabled = !!getSelectedTabs(this.editor);
}
- public override execute(): void {
+ public override execute({ position = "after" }: { position?: "before" | "after" } = {}): void {
const editor = this.editor;
+ const model = editor.model;
const tabs = getSelectedTabs(editor);
/* v8 ignore next 3 -- execute() runs only while refresh() keeps the command enabled */
if (!tabs) {
return;
}
const currentTab = getSelectedTab(editor);
- // A tabs block holds only elements, so the offset after a tab is its index plus one.
- const index = currentTab ? editor.model.createPositionAfter(currentTab).offset : tabs.childCount;
+ // A tabs block holds only elements, so the offset of the new tab is its index.
+ const at = currentTab
+ ? model.createPositionAt(currentTab, position)
+ : model.createPositionAt(tabs, position === "after" ? "end" : 0);
- editor.model.change(writer => {
- const tab = createTab(writer, getDefaultTitle(editor, index));
- if (currentTab) {
- writer.insert(tab, currentTab, "after");
- } else {
- writer.insert(tab, tabs, "end");
- }
+ model.change(writer => {
+ const tab = createTab(writer, getDefaultTitle(editor, at.offset));
+ writer.insert(tab, at);
selectTitle(writer, tab);
});
}
@@ -104,41 +106,60 @@ export class RemoveTabCommand extends Command {
}
}
-/** Swaps the tab holding the selection with its left or right neighbor. */
+/**
+ * Moves the blocks of the current tab's panel that the selection touches to the panel of another
+ * tab, which then shows. Content moved toward the first tab goes to the end of the target panel,
+ * and content moved toward the last tab goes to its start, so it keeps its place in the reading
+ * order.
+ */
+export class MoveToTabCommand extends Command {
+
+ public override refresh(): void {
+ this.isEnabled = !!getSelectedTabContent(this.editor);
+ }
+
+ public override execute({ target }: { target: SiblingTarget }): void {
+ const content = getSelectedTabContent(this.editor);
+ /* v8 ignore next 3 -- execute() runs only while refresh() keeps the command enabled */
+ if (!content) {
+ return;
+ }
+ const tab = getSibling(content.parent.parent as ModelElement, target);
+ if (tab) {
+ moveSelectedChildren(this.editor, content, getPanel(tab));
+ }
+ }
+}
+
+/**
+ * Moves the tab holding the selection to the place of another tab. A command made with a
+ * `target`, such as `moveTabLeft`, is disabled when there is no such tab; one made without takes
+ * the target in `execute()`.
+ */
export class MoveTabCommand extends Command {
- private readonly direction: "left" | "right";
+ private readonly target: SiblingTarget | undefined;
- public constructor(editor: Editor, direction: "left" | "right") {
+ public constructor(editor: Editor, target?: SiblingTarget) {
super(editor);
- this.direction = direction;
+ this.target = target;
}
public override refresh(): void {
const tab = getSelectedTab(this.editor);
- this.isEnabled = !!this.getNeighbor(tab);
+ this.isEnabled = !!tab && (!this.target || !!getSibling(tab, this.target));
}
- public override execute(): void {
- const editor = this.editor;
- const tab = getSelectedTab(editor);
- const neighbor = this.getNeighbor(tab);
+ public override execute({ target = this.target }: { target?: SiblingTarget } = {}): void {
+ const tab = getSelectedTab(this.editor);
/* v8 ignore next 3 -- execute() runs only while refresh() keeps the command enabled */
- if (!tab || !neighbor) {
+ if (!tab) {
return;
}
-
- editor.model.change(writer => {
- const target = this.direction === "left"
- ? writer.createPositionBefore(neighbor)
- : writer.createPositionAfter(neighbor);
- writer.move(writer.createRangeOn(tab), target);
- });
- }
-
- private getNeighbor(tab: ModelElement | null) {
- const neighbor = this.direction === "left" ? tab?.previousSibling : tab?.nextSibling;
- return neighbor?.is("element", ELEMENTS.tab) ? neighbor : null;
+ const sibling = target && getSibling(tab, target);
+ if (sibling) {
+ this.editor.model.change(writer => moveToSibling(writer, tab, sibling));
+ }
}
}
@@ -242,6 +263,16 @@ export function getSelectedTabs(editor: Editor): ModelElement | null {
return (position?.findAncestor(ELEMENTS.tabs) as ModelElement | null) ?? null;
}
+/**
+ * Returns the panel that holds a non-collapsed selection, with the first and last of its blocks
+ * that the selection touches, or `null` for a selection in a title.
+ */
+function getSelectedTabContent(editor: Editor) {
+ const content = getSelectedChildren(editor, ELEMENTS.tabPanel);
+ const tab = editor.model.document.selection.getFirstPosition()?.findAncestor(ELEMENTS.tab);
+ return content && content.parent.parent === tab ? content : null;
+}
+
/** Returns the title of `tab`, which the post-fixer keeps as its first child. */
function getTitle(tab: ModelElement): ModelElement {
return tab.getChild(0) as ModelElement;
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
index a635593ad0..7022594f9e 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
@@ -22,7 +22,7 @@ import {
} from "./constants.js";
import {
AssignTabReferenceCommand, InsertTabCommand, InsertTabsCommand, MoveTabCommand,
- RemoveTabCommand, TabAlignmentCommand
+ MoveToTabCommand, RemoveTabCommand, TabAlignmentCommand
} from "./tabs_commands.js";
/**
@@ -50,8 +50,10 @@ export default class TabsEditing extends Plugin {
editor.commands.add("tabs", new InsertTabsCommand(editor));
editor.commands.add("insertTab", new InsertTabCommand(editor));
editor.commands.add("removeTab", new RemoveTabCommand(editor));
- editor.commands.add("moveTabLeft", new MoveTabCommand(editor, "left"));
- editor.commands.add("moveTabRight", new MoveTabCommand(editor, "right"));
+ editor.commands.add("moveTabLeft", new MoveTabCommand(editor, "previous"));
+ editor.commands.add("moveTabRight", new MoveTabCommand(editor, "next"));
+ editor.commands.add("moveTab", new MoveTabCommand(editor));
+ editor.commands.add("moveToTab", new MoveToTabCommand(editor));
editor.commands.add("assignTabReference", new AssignTabReferenceCommand(editor));
editor.commands.add("tabAlignment", new TabAlignmentCommand(editor));
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.spec.ts
new file mode 100644
index 0000000000..eb4a05c0a3
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.spec.ts
@@ -0,0 +1,115 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ type ClassicEditor,
+ Essentials,
+ Paragraph
+} from "ckeditor5";
+import { describe, expect, it, vi } from "vitest";
+
+import { createTestEditor, pressKey as press } from "../../../test/editor-kit.js";
+import Tabs from "./tabs.js";
+
+describe("tabs keyboard shortcuts", () => {
+
+ it("lists the shortcuts in the accessibility help", async () => {
+ const editor = await createEditor();
+ const group = editor.accessibility.keystrokeInfos.get("contentEditing")?.groups.get("tabs");
+
+ expect(group?.label).toBe("Keystrokes that can be used in a tabs block");
+ 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 to another tab, shows that tab and scrolls to it", async () => {
+ const editor = await createEditor();
+ const scroll = vi.spyOn(editor.editing.view, "scrollToTheSelection");
+ setModelData(editor.model, block(tab("A", "a"), tab("B", "[b]"), tab("C", "c")));
+
+ expect(press(editor, "ArrowRight", { ctrlKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("A", "a"), tab("B", ""), tab("C", "[b]", "c")));
+ expect(activeTitles(editor)).toEqual(["C"]);
+ expect(scroll).toHaveBeenCalledOnce();
+
+ expect(press(editor, "Home", { ctrlKey: true, shiftKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("A", "a", "[b]"), tab("B", ""), tab("C", "c")));
+ expect(activeTitles(editor)).toEqual(["A"]);
+
+ expect(press(editor, "ArrowLeft", { ctrlKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("A", "a", "[b]"), tab("B", ""), tab("C", "c")));
+ expect(scroll).toHaveBeenCalledTimes(2);
+ });
+
+ it("leaves the keys to the editor for a caret and for a selection in a title", async () => {
+ const editor = await createEditor();
+ for (const data of [
+ block(tab("A", "a[]"), tab("B", "b")),
+ block(tab("[A]", "a"), tab("B", "b"))
+ ]) {
+ setModelData(editor.model, data);
+ expect(press(editor, "ArrowRight", { ctrlKey: true }), data).toBe(false);
+ expect(press(editor, "End", { ctrlKey: true, shiftKey: true }), data).toBe(false);
+ expect(model(editor)).toBe(data);
+ }
+ });
+
+ it("moves the current tab, from its title or its panel", async () => {
+ const editor = await createEditor();
+ setModelData(editor.model, block(tab("A[]", "a"), tab("B", "b"), tab("C", "c")));
+
+ expect(press(editor, "ArrowRight", { ctrlKey: true, altKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("B", "b"), tab("A[]", "a"), tab("C", "c")));
+
+ expect(press(editor, "End", { ctrlKey: true, altKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("B", "b"), tab("C", "c"), tab("A[]", "a")));
+
+ setModelData(editor.model, block(tab("A", "a"), tab("B", "b"), tab("C", "c[]")));
+ expect(press(editor, "Home", { ctrlKey: true, altKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("C", "c[]"), tab("A", "a"), tab("B", "b")));
+
+ expect(press(editor, "ArrowLeft", { ctrlKey: true, altKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("C", "c[]"), tab("A", "a"), tab("B", "b")));
+ expect(activeTitles(editor)).toEqual(["C"]);
+ });
+
+ it("adds a tab after or before the current one and selects its title", async () => {
+ const editor = await createEditor();
+ setModelData(editor.model, block(tab("A", "a"), tab("B", "b[]")));
+
+ expect(press(editor, "Enter", { ctrlKey: true, shiftKey: true })).toBe(true);
+ expect(model(editor)).toBe(block(tab("A", "a"), tab("[Tab 2]", ""), tab("B", "b")));
+
+ expect(press(editor, "Enter", { ctrlKey: true })).toBe(true);
+ expect(model(editor))
+ .toBe(block(tab("A", "a"), tab("Tab 2", ""), tab("[Tab 3]", ""), tab("B", "b")));
+ expect(activeTitles(editor)).toEqual(["Tab 3"]);
+ });
+});
+
+async function createEditor() {
+ return createTestEditor([Essentials, Paragraph, Tabs]);
+}
+
+function model(editor: ClassicEditor) {
+ return getModelData(editor.model);
+}
+
+function activeTitles(editor: ClassicEditor) {
+ const root = editor.editing.view.getDomRoot();
+ return [...root?.querySelectorAll(".trilium-tab--active > .trilium-tab-title") ?? []]
+ .map(title => title.textContent);
+}
+
+/** A tabs block in model notation that holds `tabs`. */
+function block(...tabs: string[]) {
+ return `<tabs>${tabs.join("")}</tabs>`;
+}
+
+/** A tab in model notation with the given title and a paragraph for each of `texts`. */
+function tab(title: string, ...texts: string[]) {
+ const panel = texts.map(text => `<paragraph>${text}</paragraph>`).join("");
+ return `<tab><tabTitle>${title}</tabTitle><tabPanel>${panel}</tabPanel></tab>`;
+}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.ts b/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.ts
new file mode 100644
index 0000000000..cf99a82b79
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_keyboard.ts
@@ -0,0 +1,63 @@
+import { Plugin } from "ckeditor5";
+
+import ContainerKeyboard from "../containers/container_keyboard.js";
+import { ELEMENTS } from "./constants.js";
+import TabsEditing from "./tabs_editing.js";
+
+/**
+ * Keyboard shortcuts of tabs blocks, run by `ContainerKeyboard`. Ctrl+Left/Right and
+ * Ctrl+Shift+Home/End move the selected content to another tab and show it,
+ * Ctrl+Alt+Left/Right/Home/End move the current tab, and Ctrl+Enter and Ctrl+Shift+Enter add a tab
+ * after or before it.
+ */
+export default class TabsKeyboard extends Plugin {
+
+ public static get pluginName() {
+ return "TabsKeyboard" as const;
+ }
+
+ public static get requires() {
+ return [TabsEditing, ContainerKeyboard] as const;
+ }
+
+ public init(): void {
+ const editor = this.editor;
+ const t = editor.t;
+
+ editor.plugins.get(ContainerKeyboard).register(ELEMENTS.tab, {
+ moveContent: "moveToTab",
+ moveContainer: "moveTab",
+ insert: "insertTab"
+ });
+
+ editor.accessibility.addKeystrokeInfoGroup({
+ id: "tabs",
+ label: t("Keystrokes that can be used in a tabs block"),
+ keystrokes: [
+ {
+ label: t("Move the selected content to the tab on the left"),
+ keystroke: "Ctrl+ArrowLeft"
+ },
+ {
+ label: t("Move the selected content to the tab on the right"),
+ keystroke: "Ctrl+ArrowRight"
+ },
+ {
+ label: t("Move the selected content to the first tab"),
+ keystroke: "Ctrl+Shift+Home"
+ },
+ {
+ label: t("Move the selected content to the last tab"),
+ keystroke: "Ctrl+Shift+End"
+ },
+ { label: t("Move the tab to the left"), keystroke: "Ctrl+Alt+ArrowLeft" },
+ { label: t("Move the tab to the right"), keystroke: "Ctrl+Alt+ArrowRight" },
+ { label: t("Make the tab the first one"), keystroke: "Ctrl+Alt+Home" },
+ { label: t("Make the tab the last one"), keystroke: "Ctrl+Alt+End" },
+ { label: t("Add a tab after the current one"), keystroke: "Ctrl+Enter" },
+ { label: t("Add a tab before the current one"), keystroke: "Ctrl+Shift+Enter" }
+ ]
+ });
+ }
+
+}
diff --git a/packages/ckeditor5/test/editor-kit.ts b/packages/ckeditor5/test/editor-kit.ts
index 59c4173552..a1287c0b68 100644
--- a/packages/ckeditor5/test/editor-kit.ts
+++ b/packages/ckeditor5/test/editor-kit.ts
@@ -76,6 +76,21 @@ export function getEditorElement(editor: Editor): HTMLDivElement {
return tracked.editorElement;
}
+/**
+ * Press `key` with `modifiers` in the editing root of `editor`, and return whether a listener
+ * prevented its default action. CKEditor's own key handlers read `keyCode`, which stays 0 here, so
+ * only listeners that read `key` act on the press.
+ */
+export function pressKey(editor: Editor, key: string, modifiers: KeyboardEventInit = {}): boolean {
+ 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;
+}
+
/**
* Destroy every editor created via {@link createTestEditor} and remove its host element.
* Called from the global `afterEach` in `setup.ts`; safe to call when nothing is tracked.