Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: allow creating tables with more than 10 rows and 10 columns

Adorian Doranbae6e242c8d3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 6baed9fba4..d79fe2a8cd 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4366,7 +4366,11 @@
"move-row-up": "Move row up",
"move-row-down": "Move row down",
"move-column-left": "Move column left",
- "move-column-right": "Move column right"
+ "move-column-right": "Move column right",
+ "insert-table": "Insert table…",
+ "rows": "Rows",
+ "columns": "Columns",
+ "enter-a-whole-number-between-1-and-0": "Enter a whole number between 1 and %0."
},
"task-state-dropped-title": "Invalid task states",
"task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
index f9e4e95287..e92bf75c59 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
@@ -6,6 +6,18 @@
</figure>
<p>To create a table, simply press the table button and select with the mouse
the desired amount of columns and rows, as indicated in the adjacent figure.</p>
+<p>Since v0.107.0, the same menu starts with an <em>Insert table…</em> item,
+ for a table larger than the grid or to type its size instead:</p>
+<ol>
+ <li>Click the <span class="tn-icon cke cke-table"></span> button and select <em>Insert table…</em>.
+ A small form opens at the cursor.</li>
+ <li>Enter the number of <em>Rows</em> (up to 1000) and <em>Columns</em> (up to
+ 100).</li>
+ <li>Press <em>Insert</em> or <kbd>Enter</kbd>.</li>
+</ol>
+<p>To close the form without inserting a table, press <kbd>Esc</kbd> or click
+ outside it. From the keyboard, <kbd>Tab</kbd> moves between <em>Insert table…</em> and
+ the grid while the menu is open.</p>
<h2>Formatting toolbar</h2>
<p>When a table is selected, a special formatting toolbar will appear:</p>
<img
diff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.md
index 3f6ba9fa6c..93eb77390c 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md
@@ -5,6 +5,14 @@ Tables are a powerful feature for <a class="reference-link" href="../Text.md">T
To create a table, simply press the table button and select with the mouse the desired amount of columns and rows, as indicated in the adjacent figure.
+Since v0.107.0, the same menu starts with an _Insert table…_ item, for a table larger than the grid or to type its size instead:
+
+1. Click the <span class="tn-icon cke cke-table"></span> button and select _Insert table…_. A small form opens at the cursor.
+2. Enter the number of _Rows_ (up to 1000) and _Columns_ (up to 100).
+3. Press _Insert_ or <kbd>Enter</kbd>.
+
+To close the form without inserting a table, press <kbd>Esc</kbd> or click outside it. From the keyboard, <kbd>Tab</kbd> moves between _Insert table…_ and the grid while the menu is open.
+
## Formatting toolbar
When a table is selected, a special formatting toolbar will appear:
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index f3f2aef893..4d1c68533b 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -59,6 +59,7 @@ import CollapsibleListItems from "./plugins/collapsible_list_items.js";
import TableIndent from "./plugins/table_indent.js";
import TableContextMenu from "./plugins/table_context_menu.js";
import TableMove from "./plugins/table_move/table_move.js";
+import TableInsertUI from "./plugins/table_insert/table_insert_ui.js";
/**
* Plugins that are specific to Trilium and not part of the CKEditor 5 core, included in both text editors but not in the attribute editor.
@@ -96,6 +97,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
TableIndent,
TableContextMenu,
TableMove,
+ TableInsertUI,
CopyAnchorLinkButton,
CopyLinkUrlButton,
ImageActions,
diff --git a/packages/ckeditor5/src/plugins/table_insert/table_insert_form.spec.ts b/packages/ckeditor5/src/plugins/table_insert/table_insert_form.spec.ts
new file mode 100644
index 0000000000..bf48a2e1cb
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_insert/table_insert_form.spec.ts
@@ -0,0 +1,213 @@
+import { Locale } from "ckeditor5";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { userEvent } from "vitest/browser";
+
+import TableInsertFormView, {
+ DEFAULT_TABLE_SIZE,
+ MAX_TABLE_COLUMNS,
+ MAX_TABLE_ROWS,
+ parseTableSize,
+ type TableSizeFieldView
+} from "./table_insert_form.js";
+
+describe("parseTableSize", () => {
+ it("accepts a whole number from 1 to the maximum", () => {
+ expect(parseTableSize("1", 10)).toBe(1);
+ expect(parseTableSize("10", 10)).toBe(10);
+ expect(parseTableSize("007", 10)).toBe(7);
+ expect(parseTableSize(" 4 ", 10)).toBe(4);
+ });
+
+ it("rejects anything else", () => {
+ for (const value of ["", " ", "0", "00", "11", "-1", "+3", "1.5", "1e1", "abc", "3x"]) {
+ expect(parseTableSize(value, 10), value).toBeNull();
+ }
+ expect(parseTableSize("9".repeat(400), 10)).toBeNull();
+ });
+});
+
+describe("TableInsertFormView", () => {
+ let form: TableInsertFormView;
+
+ beforeEach(() => {
+ form = new TableInsertFormView(new Locale());
+ form.render();
+ document.body.appendChild(getElement(form));
+ form.reset();
+ });
+
+ afterEach(() => {
+ getElement(form).remove();
+ form.destroy();
+ });
+
+ it("renders the Rows and Columns fields and a submit button", () => {
+ const element = getElement(form);
+ expect(element.tagName).toBe("FORM");
+ expect(element.getAttribute("aria-label")).toBe("Insert table");
+
+ const [rowsLabel, columnsLabel] = Array.from(element.querySelectorAll("label"));
+ expect(rowsLabel.textContent).toBe("Rows");
+ expect(columnsLabel.textContent).toBe("Columns");
+ expect(rowsLabel.htmlFor).toBe(getInput(form.rowsField).id);
+ expect(columnsLabel.htmlFor).toBe(getInput(form.columnsField).id);
+ expect(getInput(form.rowsField).id).not.toBe(getInput(form.columnsField).id);
+
+ expect(getInput(form.rowsField)).toMatchObject({ type: "number", min: "1", step: "1" });
+ expect(getInput(form.rowsField).max).toBe(String(MAX_TABLE_ROWS));
+ expect(getInput(form.columnsField).max).toBe(String(MAX_TABLE_COLUMNS));
+ expect(getInput(form.rowsField).inputMode).toBe("numeric");
+
+ const button = getElement(form.insertButtonView);
+ expect(button.textContent).toBe("Insert");
+ expect(button.getAttribute("type")).toBe("submit");
+ expect(element.lastElementChild).toBe(button);
+ });
+
+ it("returns the entered size", () => {
+ getInput(form.rowsField).value = "12";
+ getInput(form.columnsField).value = "3";
+
+ expect(form.validate()).toEqual({ rows: 12, columns: 3 });
+ expect(form.rowsField.errorText).toBeNull();
+ expect(form.columnsField.errorText).toBeNull();
+ });
+
+ it("accepts the largest sizes and rejects one more", () => {
+ getInput(form.rowsField).value = String(MAX_TABLE_ROWS);
+ getInput(form.columnsField).value = String(MAX_TABLE_COLUMNS);
+ expect(form.validate()).toEqual({ rows: MAX_TABLE_ROWS, columns: MAX_TABLE_COLUMNS });
+
+ getInput(form.rowsField).value = String(MAX_TABLE_ROWS + 1);
+ getInput(form.columnsField).value = String(MAX_TABLE_COLUMNS + 1);
+ expect(form.validate()).toBeNull();
+ expect(form.rowsField.errorText)
+ .toBe(`Enter a whole number between 1 and ${MAX_TABLE_ROWS}.`);
+ expect(form.columnsField.errorText)
+ .toBe(`Enter a whole number between 1 and ${MAX_TABLE_COLUMNS}.`);
+ });
+
+ it("shows the error of an invalid field and focuses it", () => {
+ getInput(form.rowsField).value = "5";
+ getInput(form.columnsField).value = "0";
+
+ expect(form.validate()).toBeNull();
+ expectValid(form.rowsField);
+ expectInvalid(form.columnsField);
+ expect(document.activeElement).toBe(getInput(form.columnsField));
+ });
+
+ it("focuses the first invalid field when both are invalid", () => {
+ getInput(form.rowsField).value = "";
+ getInput(form.columnsField).value = "0";
+
+ expect(form.validate()).toBeNull();
+ expectInvalid(form.rowsField);
+ expectInvalid(form.columnsField);
+ expect(document.activeElement).toBe(getInput(form.rowsField));
+ });
+
+ it("clears the error of a field when its value is edited", async () => {
+ getInput(form.rowsField).value = "0";
+ getInput(form.columnsField).value = "0";
+ form.validate();
+
+ await userEvent.fill(getInput(form.rowsField), "3");
+
+ expectValid(form.rowsField);
+ expectInvalid(form.columnsField);
+ });
+
+ it("reset() restores the default size and clears the errors", async () => {
+ await userEvent.fill(getInput(form.rowsField), "9");
+ getInput(form.columnsField).value = "0";
+ form.validate();
+
+ form.reset();
+
+ const defaultText = String(DEFAULT_TABLE_SIZE);
+ expect(getInput(form.rowsField).value).toBe(defaultText);
+ expect(getInput(form.columnsField).value).toBe(defaultText);
+ expectValid(form.rowsField);
+ expectValid(form.columnsField);
+ expect(form.validate()).toEqual({ rows: DEFAULT_TABLE_SIZE, columns: DEFAULT_TABLE_SIZE });
+ });
+
+ it("focus() focuses the Rows field and selects its value", () => {
+ const select = vi.spyOn(form.rowsField.inputView, "select");
+
+ form.focus();
+
+ expect(document.activeElement).toBe(getInput(form.rowsField));
+ expect(select).toHaveBeenCalled();
+ });
+
+ it("cycles the focus with Tab and Shift+Tab", async () => {
+ form.focus();
+
+ await userEvent.keyboard("{Tab}");
+ expect(document.activeElement).toBe(getInput(form.columnsField));
+ await userEvent.keyboard("{Tab}");
+ expect(document.activeElement).toBe(getElement(form.insertButtonView));
+ await userEvent.keyboard("{Tab}");
+ expect(document.activeElement).toBe(getInput(form.rowsField));
+ await userEvent.keyboard("{Shift>}{Tab}{/Shift}");
+ expect(document.activeElement).toBe(getElement(form.insertButtonView));
+ });
+
+ it("fires submit for the Insert button and for Enter", async () => {
+ const submit = vi.fn();
+ form.on("submit", submit);
+
+ await userEvent.click(getElement(form.insertButtonView));
+ expect(submit).toHaveBeenCalledTimes(1);
+
+ form.focus();
+ await userEvent.keyboard("{Enter}");
+ expect(submit).toHaveBeenCalledTimes(2);
+ });
+});
+
+function getElement(view: { element: HTMLElement | null }): HTMLElement {
+ if (!view.element) {
+ throw new Error("The view is not rendered.");
+ }
+ return view.element;
+}
+
+function getInput(field: TableSizeFieldView): HTMLInputElement {
+ return getElement(field.inputView) as HTMLInputElement;
+}
+
+function getError(field: TableSizeFieldView): HTMLElement {
+ const error = getElement(field).querySelector<HTMLElement>(".ck-table-insert-form__error");
+ if (!error) {
+ throw new Error("The field has no error element.");
+ }
+ return error;
+}
+
+function expectInvalid(field: TableSizeFieldView) {
+ const input = getInput(field);
+ const error = getError(field);
+
+ expect(field.errorText).toMatch(/^Enter a whole number between 1 and \d+\.$/);
+ expect(error.textContent).toBe(field.errorText);
+ expect(error.classList.contains("ck-hidden")).toBe(false);
+ expect(error.getAttribute("role")).toBe("alert");
+ expect(input.classList.contains("ck-error")).toBe(true);
+ expect(input.getAttribute("aria-invalid")).toBe("true");
+ expect(input.getAttribute("aria-describedby")).toBe(error.id);
+}
+
+function expectValid(field: TableSizeFieldView) {
+ const input = getInput(field);
+ const error = getError(field);
+
+ expect(field.errorText).toBeNull();
+ expect(error.classList.contains("ck-hidden")).toBe(true);
+ expect(error.hasAttribute("role")).toBe(false);
+ expect(input.classList.contains("ck-error")).toBe(false);
+ expect(input.hasAttribute("aria-invalid")).toBe(false);
+ expect(input.hasAttribute("aria-describedby")).toBe(false);
+}
diff --git a/packages/ckeditor5/src/plugins/table_insert/table_insert_form.ts b/packages/ckeditor5/src/plugins/table_insert/table_insert_form.ts
new file mode 100644
index 0000000000..53c421d047
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_insert/table_insert_form.ts
@@ -0,0 +1,245 @@
+import {
+ ButtonView,
+ FocusCycler,
+ FocusTracker,
+ InputNumberView,
+ KeystrokeHandler,
+ LabelView,
+ submitHandler,
+ uid,
+ View,
+ ViewCollection
+} from "ckeditor5";
+import type { FocusableView, Locale } from "ckeditor5";
+
+/** The largest number of rows the form accepts. */
+export const MAX_TABLE_ROWS = 1000;
+
+/** The largest number of columns the form accepts. */
+export const MAX_TABLE_COLUMNS = 100;
+
+/** The number of rows and columns the form shows when it opens. */
+export const DEFAULT_TABLE_SIZE = 2;
+
+export interface TableSize {
+ rows: number;
+ columns: number;
+}
+
+/**
+ * The balloon form behind "Insert table…": a "Rows" field, a "Columns" field and an Insert button.
+ * Invalid values are reported under their field when the form is submitted.
+ */
+export default class TableInsertFormView extends View {
+
+ public readonly rowsField: TableSizeFieldView;
+ public readonly columnsField: TableSizeFieldView;
+ public readonly insertButtonView: ButtonView;
+
+ public readonly focusTracker = new FocusTracker();
+ public readonly keystrokes = new KeystrokeHandler();
+
+ private readonly focusables = new ViewCollection<FocusableView>();
+ private readonly focusCycler: FocusCycler;
+
+ constructor(locale: Locale) {
+ super(locale);
+ const t = locale.t;
+
+ this.rowsField = new TableSizeFieldView(locale, t("Rows"), MAX_TABLE_ROWS);
+ this.columnsField = new TableSizeFieldView(locale, t("Columns"), MAX_TABLE_COLUMNS);
+
+ this.insertButtonView = new ButtonView(locale);
+ this.insertButtonView.set({
+ label: t("Insert"),
+ withText: true,
+ type: "submit",
+ class: "ck-button-action ck-button-bold"
+ });
+
+ this.setTemplate({
+ tag: "form",
+ attributes: {
+ class: ["ck", "ck-table-insert-form"],
+ tabindex: "-1",
+ "aria-label": t("Insert table"),
+ // The fields are checked by `validate()`, which shows translated errors.
+ novalidate: true
+ },
+ children: [this.rowsField, this.columnsField, this.insertButtonView]
+ });
+
+ this.focusCycler = new FocusCycler({
+ focusables: this.focusables,
+ focusTracker: this.focusTracker,
+ keystrokeHandler: this.keystrokes,
+ actions: {
+ focusPrevious: "shift + tab",
+ focusNext: "tab"
+ }
+ });
+ }
+
+ public override render(): void {
+ super.render();
+
+ // Turns a native form submit, the Enter key included, into the view's `submit` event.
+ submitHandler({ view: this });
+
+ const { rowsField, columnsField, insertButtonView } = this;
+ for (const view of [rowsField.inputView, columnsField.inputView, insertButtonView]) {
+ this.focusables.add(view);
+ /* v8 ignore next -- a child view rendered as part of this template has an element */
+ if (view.element) {
+ this.focusTracker.add(view.element);
+ }
+ }
+
+ /* v8 ignore next -- super.render() has just built this view's element */
+ if (this.element) {
+ this.keystrokes.listenTo(this.element);
+ }
+ }
+
+ public override destroy(): void {
+ super.destroy();
+ this.focusTracker.destroy();
+ this.keystrokes.destroy();
+ }
+
+ /** Focuses the "Rows" field and selects its value. */
+ public focus(): void {
+ this.focusCycler.focusFirst();
+ this.rowsField.inputView.select();
+ }
+
+ /** Sets both fields to {@link DEFAULT_TABLE_SIZE} and clears their errors. */
+ public reset(): void {
+ this.rowsField.reset(DEFAULT_TABLE_SIZE);
+ this.columnsField.reset(DEFAULT_TABLE_SIZE);
+ }
+
+ /**
+ * Returns the entered size, or `null` when a field is invalid. Every invalid field shows its
+ * error, and the first one is focused.
+ */
+ public validate(): TableSize | null {
+ const rows = this.rowsField.validate();
+ const columns = this.columnsField.validate();
+
+ if (rows === null) {
+ this.rowsField.focus();
+ return null;
+ }
+ if (columns === null) {
+ this.columnsField.focus();
+ return null;
+ }
+ return { rows, columns };
+ }
+}
+
+/**
+ * A number field of {@link TableInsertFormView}: a label, the input and the error under it.
+ * The element has `display: contents`, so the three parts are laid out by the form's grid.
+ */
+export class TableSizeFieldView extends View {
+
+ /** The error shown under the input, or `null` when the value is valid. */
+ declare public errorText: string | null;
+
+ public readonly labelView: LabelView;
+ public readonly inputView: InputNumberView;
+
+ private readonly max: number;
+ private readonly invalidText: string;
+
+ constructor(locale: Locale, label: string, max: number) {
+ super(locale);
+
+ const inputId = `ck-table-insert-form-input-${uid()}`;
+ const errorId = `ck-table-insert-form-error-${uid()}`;
+ const bind = this.bindTemplate;
+
+ this.max = max;
+ this.invalidText = locale.t("Enter a whole number between 1 and %0.", max);
+ this.set("errorText", null);
+
+ this.labelView = new LabelView(locale);
+ this.labelView.set({ text: label, for: inputId });
+
+ this.inputView = new InputNumberView(locale, { min: 1, max, step: 1 });
+ this.inputView.set({ id: inputId, inputMode: "numeric" });
+ this.inputView.bind("hasError").to(this, "errorText", (text) => !!text);
+ this.inputView.bind("ariaDescribedById")
+ .to(this, "errorText", (text) => text ? errorId : undefined);
+
+ // The error is cleared as soon as the value is edited.
+ this.inputView.on("input", () => {
+ this.errorText = null;
+ });
+
+ this.setTemplate({
+ tag: "div",
+ attributes: {
+ class: ["ck", "ck-table-insert-form__field"]
+ },
+ children: [
+ this.labelView,
+ this.inputView,
+ {
+ tag: "div",
+ attributes: {
+ id: errorId,
+ class: [
+ "ck",
+ "ck-table-insert-form__error",
+ bind.if("errorText", "ck-hidden", (text) => !text)
+ ],
+ role: bind.if("errorText", "alert")
+ },
+ children: [{ text: bind.to("errorText") }]
+ }
+ ]
+ });
+ }
+
+ /** Focuses the input and selects its value. */
+ public focus(): void {
+ this.inputView.focus();
+ this.inputView.select();
+ }
+
+ /** Shows `value` in the input and clears the error. */
+ public reset(value: number): void {
+ const text = String(value);
+
+ this.errorText = null;
+ // `value` reaches the DOM only when it changes, so an edited input is written directly.
+ this.inputView.value = text;
+ /* v8 ignore next -- the form renders its fields before it can be shown */
+ if (this.inputView.element) {
+ this.inputView.element.value = text;
+ }
+ }
+
+ /** Returns the entered number, or `null` after showing the error. */
+ public validate(): number | null {
+ /* v8 ignore next -- the form renders its fields before it can be submitted */
+ const value = parseTableSize(this.inputView.element?.value ?? "", this.max);
+
+ this.errorText = value === null ? this.invalidText : null;
+ return value;
+ }
+}
+
+/** Parses `value` as a whole number from 1 to `max`. Returns `null` for anything else. */
+export function parseTableSize(value: string, max: number): number | null {
+ const text = value.trim();
+ if (!/^\d+$/.test(text)) {
+ return null;
+ }
+
+ const size = Number(text);
+ return size >= 1 && size <= max ? size : null;
+}
diff --git a/packages/ckeditor5/src/plugins/table_insert/table_insert_ui.spec.ts b/packages/ckeditor5/src/plugins/table_insert/table_insert_ui.spec.ts
new file mode 100644
index 0000000000..54e0f67182
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_insert/table_insert_ui.spec.ts
@@ -0,0 +1,420 @@
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ BlockToolbar,
+ ClassicEditor,
+ ContextualBalloon,
+ DropdownView,
+ Essentials,
+ IconTable,
+ keyCodes,
+ Paragraph,
+ Table,
+ TableUtils
+} from "ckeditor5";
+import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";
+import type { ModelElement } from "ckeditor5";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { userEvent } from "vitest/browser";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import TableInsertFormView, { DEFAULT_TABLE_SIZE, MAX_TABLE_COLUMNS } from "./table_insert_form.js";
+import TableInsertUI from "./table_insert_ui.js";
+
+describe("TableInsertUI", () => {
+ let editor: ClassicEditor;
+ let balloon: ContextualBalloon;
+
+ // The grid, the dropdown panel and the balloon need the editor's stylesheet to have a layout.
+ beforeAll(() => new Promise<void>((resolve, reject) => {
+ const link = document.createElement("link");
+ link.rel = "stylesheet";
+ link.href = editorStylesheetUrl;
+ link.onload = () => resolve();
+ link.onerror = () => reject(new Error("the editor stylesheet did not load"));
+ document.head.appendChild(link);
+ }));
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, Table, TableInsertUI], {
+ toolbar: ["insertTable"]
+ });
+ balloon = editor.plugins.get(ContextualBalloon);
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
+ editor.editing.view.focus();
+ });
+
+ describe("dropdown", () => {
+ it("keeps the button of the upstream dropdown", () => {
+ expect(getToolbarDropdown(editor).buttonView).toMatchObject({
+ label: "Insert table",
+ icon: IconTable,
+ tooltip: true
+ });
+ });
+
+ it("is enabled with the insertTable command", () => {
+ const dropdown = getToolbarDropdown(editor);
+ expect(dropdown.isEnabled).toBe(true);
+
+ editor.enableReadOnlyMode("spec");
+ expect(dropdown.isEnabled).toBe(false);
+
+ editor.disableReadOnlyMode("spec");
+ expect(dropdown.isEnabled).toBe(true);
+ });
+
+ it("shows the Insert table… button, a separator and the size grid", async () => {
+ const dropdown = getToolbarDropdown(editor);
+ expect(dropdown.panelView.children.length).toBe(0);
+
+ await openDropdown(dropdown);
+
+ const panel = getElement(dropdown.panelView);
+ const button = getFormButton(dropdown);
+ const separator = panel.querySelector(".ck-list__separator");
+ const grid = panel.querySelector(".ck-insert-table-dropdown__grid");
+ expect(button.textContent).toBe("Insert table…");
+ expect(button.classList.contains("ck-button_with-text")).toBe(true);
+ expect(button.parentElement?.classList.contains("ck-list__item")).toBe(true);
+ expect(button.compareDocumentPosition(separator as Node))
+ .toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(separator?.compareDocumentPosition(grid as Node))
+ .toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+
+ // The grid keeps the size label of the upstream dropdown.
+ expect(panel.querySelector(".ck-insert-table-dropdown__label")?.textContent)
+ .toBe("1 × 1");
+
+ // The panel is built once, not on every opening.
+ dropdown.isOpen = false;
+ dropdown.isOpen = true;
+ expect(dropdown.panelView.children.length).toBe(1);
+ expect(panel.querySelectorAll(".ck-list__item")).toHaveLength(1);
+ });
+
+ it("inserts the table picked in the grid", async () => {
+ const dropdown = getToolbarDropdown(editor);
+ await openDropdown(dropdown);
+
+ const box = getElement(dropdown.panelView)
+ .querySelector<HTMLElement>("[data-row=\"3\"][data-column=\"4\"]");
+ if (!box) {
+ throw new Error("The grid has no 3 × 4 box.");
+ }
+ await userEvent.hover(box);
+ await userEvent.click(box);
+
+ expect(getTableSize(editor)).toEqual({ rows: 3, columns: 4 });
+ expect(dropdown.isOpen).toBe(false);
+ expect(balloon.visibleView).toBeNull();
+ expect(editor.editing.view.document.isFocused).toBe(true);
+ });
+
+ it("moves the focus between the grid and the button with Tab", async () => {
+ const dropdown = getToolbarDropdown(editor);
+ // Keeps the pointer off the grid, whose boxes take the focus on hover.
+ await userEvent.hover(getElement(dropdown.buttonView));
+ getElement(dropdown.buttonView).focus();
+
+ await userEvent.keyboard("{ArrowDown}");
+ expect(dropdown.isOpen).toBe(true);
+ const firstBox = getElement(dropdown.panelView)
+ .querySelector(".ck-insert-table-dropdown-grid-box");
+ expect(document.activeElement).toBe(firstBox);
+
+ await userEvent.keyboard("{Tab}");
+ expect(document.activeElement).toBe(getFormButton(dropdown));
+ await userEvent.keyboard("{Tab}");
+ expect(document.activeElement).toBe(firstBox);
+ await userEvent.keyboard("{Shift>}{Tab}{/Shift}");
+ expect(document.activeElement).toBe(getFormButton(dropdown));
+
+ await userEvent.keyboard("{Enter}");
+ expect(dropdown.isOpen).toBe(false);
+ expect(document.activeElement).toBe(getForm(balloon).rowsField.inputView.element);
+ });
+ });
+
+ describe("form", () => {
+ it("opens at the caret when Insert table… is clicked", async () => {
+ const dropdown = getToolbarDropdown(editor);
+ await openDropdown(dropdown);
+
+ await userEvent.click(getFormButton(dropdown));
+
+ expect(dropdown.isOpen).toBe(false);
+ const form = getForm(balloon);
+ expect(getInput(form, "rows").value).toBe(String(DEFAULT_TABLE_SIZE));
+ expect(getInput(form, "columns").value).toBe(String(DEFAULT_TABLE_SIZE));
+ expect(document.activeElement).toBe(getInput(form, "rows"));
+
+ // The balloon points at the caret, after "foo".
+ const caret = getCaretRect(editor);
+ const panel = getElement(balloon.view).getBoundingClientRect();
+ expect(balloon.view.isVisible).toBe(true);
+ expect(caret.left).toBeGreaterThanOrEqual(panel.left);
+ expect(caret.left).toBeLessThanOrEqual(panel.right);
+ const gap = Math.min(
+ Math.abs(panel.top - caret.bottom),
+ Math.abs(caret.top - panel.bottom)
+ );
+ expect(gap).toBeLessThan(30);
+ });
+
+ it("inserts a table of the typed size and closes", async () => {
+ const form = await openForm(editor);
+
+ await userEvent.fill(getInput(form, "rows"), "5");
+ await userEvent.fill(getInput(form, "columns"), "7");
+ await userEvent.click(getElement(form.insertButtonView));
+
+ expect(getTableSize(editor)).toEqual({ rows: 5, columns: 7 });
+ expect(balloon.hasView(form)).toBe(false);
+ expect(editor.editing.view.document.isFocused).toBe(true);
+ expect(editor.model.document.selection.getFirstPosition()?.findAncestor("tableCell"))
+ .not.toBeNull();
+
+ // One undo step removes the table.
+ editor.execute("undo");
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe("<paragraph>foo</paragraph>");
+ });
+
+ it("inserts the table on Enter", async () => {
+ const form = await openForm(editor);
+
+ await userEvent.fill(getInput(form, "columns"), "3");
+ await userEvent.keyboard("{Enter}");
+
+ expect(getTableSize(editor)).toEqual({ rows: DEFAULT_TABLE_SIZE, columns: 3 });
+ expect(balloon.hasView(form)).toBe(false);
+ });
+
+ it("stays open and reports invalid values", async () => {
+ const form = await openForm(editor);
+
+ await userEvent.fill(getInput(form, "rows"), "0");
+ await userEvent.fill(getInput(form, "columns"), String(MAX_TABLE_COLUMNS + 1));
+ await userEvent.keyboard("{Enter}");
+
+ expect(getTableSize(editor)).toBeNull();
+ expect(balloon.visibleView).toBe(form);
+ expect(form.rowsField.errorText).not.toBeNull();
+ expect(form.columnsField.errorText).not.toBeNull();
+ expect(document.activeElement).toBe(getInput(form, "rows"));
+
+ await userEvent.fill(getInput(form, "rows"), "3");
+ await userEvent.keyboard("{Enter}");
+ expect(getTableSize(editor)).toBeNull();
+ expect(document.activeElement).toBe(getInput(form, "columns"));
+
+ await userEvent.fill(getInput(form, "columns"), "4");
+ await userEvent.keyboard("{Enter}");
+ expect(getTableSize(editor)).toEqual({ rows: 3, columns: 4 });
+ });
+
+ it("closes on Esc without inserting", async () => {
+ const form = await openForm(editor);
+ await userEvent.fill(getInput(form, "rows"), "4");
+
+ await userEvent.keyboard("{Escape}");
+
+ expect(balloon.hasView(form)).toBe(false);
+ expect(getTableSize(editor)).toBeNull();
+ expect(editor.editing.view.document.isFocused).toBe(true);
+
+ // Closing a closed form does nothing.
+ expect(() => form.keystrokes.press(createEscEvent())).not.toThrow();
+ expect(balloon.visibleView).toBeNull();
+ });
+
+ it("closes on a click outside without inserting", async () => {
+ const form = await openForm(editor);
+
+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+
+ expect(balloon.hasView(form)).toBe(false);
+ expect(getTableSize(editor)).toBeNull();
+ });
+
+ it("stays open on a click inside", async () => {
+ const form = await openForm(editor);
+
+ await userEvent.click(getInput(form, "columns"));
+
+ expect(balloon.visibleView).toBe(form);
+ });
+
+ it("opens with the default size every time", async () => {
+ let form = await openForm(editor);
+ await userEvent.fill(getInput(form, "rows"), "0");
+ await userEvent.keyboard("{Enter}");
+ await userEvent.keyboard("{Escape}");
+
+ form = await openForm(editor);
+
+ expect(getInput(form, "rows").value).toBe(String(DEFAULT_TABLE_SIZE));
+ expect(form.rowsField.errorText).toBeNull();
+ });
+
+ it("showForm() leaves an open form alone", async () => {
+ const form = await openForm(editor);
+ await userEvent.fill(getInput(form, "rows"), "9");
+ const add = vi.spyOn(balloon, "add");
+
+ editor.plugins.get(TableInsertUI).showForm();
+
+ expect(add).not.toHaveBeenCalled();
+ expect(getInput(form, "rows").value).toBe("9");
+ });
+
+ it("does not insert while the insertTable command is disabled", async () => {
+ const form = await openForm(editor);
+
+ editor.enableReadOnlyMode("spec");
+ expect(form.insertButtonView.isEnabled).toBe(false);
+ form.fire("submit");
+
+ expect(getTableSize(editor)).toBeNull();
+ expect(balloon.visibleView).toBe(form);
+
+ editor.disableReadOnlyMode("spec");
+ expect(form.insertButtonView.isEnabled).toBe(true);
+ });
+
+ it("translates its strings", async () => {
+ const translated = await createTestEditor([Essentials, Paragraph, TableInsertUI], {
+ toolbar: ["insertTable"],
+ translations: [{}, {
+ en: {
+ dictionary: {
+ "Insert table…": "Tabel personalizat…",
+ "Rows": "Rânduri",
+ "Columns": "Coloane",
+ "Enter a whole number between 1 and %0.": "Între 1 și %0."
+ }
+ }
+ }]
+ });
+ const dropdown = getToolbarDropdown(translated);
+ dropdown.isOpen = true;
+ expect(getFormButton(dropdown).textContent).toBe("Tabel personalizat…");
+
+ getFormButton(dropdown).click();
+ const form = getForm(translated.plugins.get(ContextualBalloon));
+ const labels = Array.from(getElement(form).querySelectorAll("label"))
+ .map((label) => label.textContent);
+ expect(labels).toEqual(["Rânduri", "Coloane"]);
+
+ getInput(form, "rows").value = "0";
+ form.validate();
+ expect(form.rowsField.errorText).toBe("Între 1 și 1000.");
+ });
+ });
+
+ describe("in a block toolbar", () => {
+ it("hides the block toolbar and focuses the form", async () => {
+ const blockEditor = await createTestEditor(
+ [Essentials, Paragraph, Table, TableInsertUI, BlockToolbar],
+ { toolbar: [], blockToolbar: ["insertTable"] }
+ );
+ setModelData(blockEditor.model, "<paragraph>foo[]</paragraph>");
+ blockEditor.editing.view.focus();
+
+ const blockToolbar = blockEditor.plugins.get(BlockToolbar);
+ blockToolbar.panelView.isVisible = true;
+ const dropdown = getDropdown(blockToolbar.toolbarView.items.first);
+ dropdown.isOpen = true;
+
+ getFormButton(dropdown).click();
+
+ expect(blockToolbar.panelView.isVisible).toBe(false);
+ const form = getForm(blockEditor.plugins.get(ContextualBalloon));
+ expect(document.activeElement).toBe(getInput(form, "rows"));
+ });
+ });
+});
+
+function getElement(view: { element: HTMLElement | null }): HTMLElement {
+ if (!view.element) {
+ throw new Error("The view is not rendered.");
+ }
+ return view.element;
+}
+
+function getDropdown(view: unknown): DropdownView {
+ expect(view).toBeInstanceOf(DropdownView);
+ return view as DropdownView;
+}
+
+function getToolbarDropdown(editor: ClassicEditor): DropdownView {
+ return getDropdown(editor.ui.view.toolbar.items.first);
+}
+
+async function openDropdown(dropdown: DropdownView) {
+ await userEvent.click(getElement(dropdown.buttonView));
+ expect(dropdown.isOpen).toBe(true);
+}
+
+function getFormButton(dropdown: DropdownView): HTMLElement {
+ const button = getElement(dropdown.panelView)
+ .querySelector<HTMLElement>(".ck-insert-table-dropdown__content .ck-list__item > button");
+ if (!button) {
+ throw new Error("The dropdown has no Insert table… button.");
+ }
+ return button;
+}
+
+function getForm(balloon: ContextualBalloon): TableInsertFormView {
+ const form = balloon.visibleView;
+ expect(form).toBeInstanceOf(TableInsertFormView);
+ return form as TableInsertFormView;
+}
+
+async function openForm(editor: ClassicEditor): Promise<TableInsertFormView> {
+ const dropdown = getToolbarDropdown(editor);
+ await openDropdown(dropdown);
+ await userEvent.click(getFormButton(dropdown));
+ return getForm(editor.plugins.get(ContextualBalloon));
+}
+
+function getInput(form: TableInsertFormView, field: "rows" | "columns"): HTMLInputElement {
+ const view = field === "rows" ? form.rowsField.inputView : form.columnsField.inputView;
+ return getElement(view) as HTMLInputElement;
+}
+
+/** The size of the table in the document, or `null` when there is none. */
+function getTableSize(editor: ClassicEditor): { rows: number; columns: number } | null {
+ const root = editor.model.document.getRoot();
+ const children = root ? Array.from(root.getChildren()) : [];
+ const table = children.find((child) => child.is("element", "table")) as
+ ModelElement | undefined;
+ if (!table) {
+ return null;
+ }
+
+ const tableUtils = editor.plugins.get(TableUtils);
+ return { rows: tableUtils.getRows(table), columns: tableUtils.getColumns(table) };
+}
+
+function getCaretRect(editor: ClassicEditor): DOMRect {
+ const view = editor.editing.view;
+ const range = view.document.selection.getFirstRange();
+ if (!range) {
+ throw new Error("The editing view has no selection.");
+ }
+ return view.domConverter.viewRangeToDom(range).getBoundingClientRect();
+}
+
+function createEscEvent() {
+ return {
+ keyCode: keyCodes.esc,
+ altKey: false,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ preventDefault: () => undefined,
+ stopPropagation: () => undefined
+ };
+}
diff --git a/packages/ckeditor5/src/plugins/table_insert/table_insert_ui.ts b/packages/ckeditor5/src/plugins/table_insert/table_insert_ui.ts
new file mode 100644
index 0000000000..be50ca54eb
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_insert/table_insert_ui.ts
@@ -0,0 +1,273 @@
+import {
+ _InsertTableView as InsertTableView,
+ ButtonView,
+ clickOutsideHandler,
+ ContextualBalloon,
+ createDropdown,
+ FocusCycler,
+ FocusTracker,
+ IconTable,
+ KeystrokeHandler,
+ ListItemView,
+ ListSeparatorView,
+ ListView,
+ Plugin,
+ Table,
+ View,
+ ViewCollection
+} from "ckeditor5";
+import type {
+ DomOptimalPositionOptions,
+ DropdownView,
+ Editor,
+ FocusableView,
+ InsertTableCommand,
+ Locale
+} from "ckeditor5";
+
+import "../../theme/table_insert.css";
+
+import TableInsertFormView from "./table_insert_form.js";
+
+/**
+ * Replaces the `insertTable` dropdown with one that has an "Insert table…" button above the size
+ * grid. The button opens {@link TableInsertFormView} in a balloon at the caret, where the number
+ * of rows and columns is typed.
+ */
+export default class TableInsertUI extends Plugin {
+
+ static get requires() {
+ return [Table, ContextualBalloon] as const;
+ }
+
+ static get pluginName() {
+ return "TableInsertUI" as const;
+ }
+
+ private formView: TableInsertFormView | null = null;
+
+ init() {
+ // Replaces the dropdown of `TableUI`, which `Table` initializes before this plugin.
+ this.editor.ui.componentFactory.add("insertTable", (locale) => this.createDropdown(locale));
+ }
+
+ override destroy() {
+ super.destroy();
+ this.formView?.destroy();
+ }
+
+ /** Opens the form at the caret. Does nothing when the form is already open. */
+ showForm() {
+ const editor = this.editor;
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const form = this.getFormView();
+
+ if (balloon.hasView(form)) {
+ return;
+ }
+
+ form.reset();
+ balloon.add({
+ view: form,
+ position: getCaretPosition(editor)
+ });
+ form.focus();
+ }
+
+ private hideForm(form: TableInsertFormView) {
+ const balloon = this.editor.plugins.get(ContextualBalloon);
+ if (!balloon.hasView(form)) {
+ return;
+ }
+
+ balloon.remove(form);
+ this.editor.editing.view.focus();
+ }
+
+ private createDropdown(locale: Locale): DropdownView {
+ const editor = this.editor;
+ // Always registered: `Table` loads `TableEditing`.
+ const command = editor.commands.get("insertTable") as InsertTableCommand;
+ const dropdownView = createDropdown(locale);
+
+ dropdownView.bind("isEnabled").to(command);
+ dropdownView.buttonView.set({
+ icon: IconTable,
+ label: editor.t("Insert table"),
+ tooltip: true
+ });
+
+ // The panel is built on the first opening, like the one of the upstream dropdown.
+ let panelView: InsertTablePanelView | null = null;
+ dropdownView.on("change:isOpen", () => {
+ if (panelView) {
+ return;
+ }
+
+ const panel = new InsertTablePanelView(locale);
+ panelView = panel;
+ dropdownView.panelView.children.add(panel);
+
+ // Delegated so that the dropdown closes, and a block toolbar hides, on either one.
+ panel.gridView.delegate("execute").to(dropdownView);
+ panel.formButtonView.delegate("execute").to(dropdownView);
+
+ // Runs after the dropdown and the block toolbar close and move the focus, so the form
+ // opened here keeps it.
+ dropdownView.on("execute", (evt) => {
+ if (evt.source === panel.formButtonView) {
+ this.showForm();
+ return;
+ }
+
+ const { rows, columns } = panel.gridView;
+ editor.execute("insertTable", { rows, columns });
+ editor.editing.view.focus();
+ });
+ });
+
+ return dropdownView;
+ }
+
+ private getFormView(): TableInsertFormView {
+ if (this.formView) {
+ return this.formView;
+ }
+
+ const editor = this.editor;
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const form = new TableInsertFormView(editor.locale);
+ this.formView = form;
+
+ // Always registered: `Table` loads `TableEditing`.
+ const command = editor.commands.get("insertTable") as InsertTableCommand;
+ form.insertButtonView.bind("isEnabled").to(command);
+
+ form.on("submit", () => {
+ if (!command.isEnabled) {
+ return;
+ }
+
+ const size = form.validate();
+ if (size) {
+ editor.execute("insertTable", size);
+ this.hideForm(form);
+ }
+ });
+
+ // Esc and a click outside close the form, as they do for the link balloon.
+ form.keystrokes.set("Esc", (_data, cancel) => {
+ this.hideForm(form);
+ cancel();
+ });
+ clickOutsideHandler({
+ emitter: form,
+ activator: () => balloon.hasView(form),
+ /* v8 ignore next -- the balloon renders its panel as the editor starts up */
+ contextElements: () => balloon.view.element ? [balloon.view.element] : [],
+ callback: () => this.hideForm(form)
+ });
+
+ return form;
+ }
+}
+
+/**
+ * The content of the `insertTable` dropdown: the "Insert table…" button, a separator and the
+ * upstream size grid. The button and the separator form a dropdown list, so they look like the
+ * items of the other dropdowns. Tab and Shift+Tab move the focus between the list and the grid.
+ */
+class InsertTablePanelView extends View {
+
+ public readonly formButtonView: ButtonView;
+ public readonly listView: ListView;
+ public readonly gridView: InsertTableView;
+
+ public readonly focusTracker = new FocusTracker();
+ public readonly keystrokes = new KeystrokeHandler();
+
+ private readonly focusables = new ViewCollection<FocusableView>();
+ private readonly focusCycler: FocusCycler;
+
+ constructor(locale: Locale) {
+ super(locale);
+
+ this.formButtonView = new ButtonView(locale);
+ this.formButtonView.set({
+ label: locale.t("Insert table…"),
+ withText: true
+ });
+
+ const itemView = new ListItemView(locale);
+ itemView.children.add(this.formButtonView);
+
+ this.listView = new ListView(locale);
+ this.listView.items.addMany([itemView, new ListSeparatorView(locale)]);
+
+ this.gridView = new InsertTableView(locale);
+
+ this.setTemplate({
+ tag: "div",
+ attributes: {
+ class: ["ck", "ck-insert-table-dropdown__content"]
+ },
+ children: [this.listView, this.gridView]
+ });
+
+ this.focusCycler = new FocusCycler({
+ focusables: this.focusables,
+ focusTracker: this.focusTracker,
+ keystrokeHandler: this.keystrokes,
+ actions: {
+ focusPrevious: "shift + tab",
+ focusNext: "tab"
+ }
+ });
+ }
+
+ public override render(): void {
+ super.render();
+
+ for (const view of [this.listView, this.gridView]) {
+ this.focusables.add(view);
+ /* v8 ignore next -- a child view rendered as part of this template has an element */
+ if (view.element) {
+ this.focusTracker.add(view.element);
+ }
+ }
+
+ /* v8 ignore next -- super.render() has just built this view's element */
+ if (this.element) {
+ this.keystrokes.listenTo(this.element);
+ }
+ }
+
+ public override destroy(): void {
+ super.destroy();
+ this.focusTracker.destroy();
+ this.keystrokes.destroy();
+ }
+
+ /**
+ * Focuses the grid, as the upstream dropdown does when it opens. The focused grid box sets the
+ * 1 × 1 size the grid label shows.
+ */
+ public focus(): void {
+ this.gridView.focus();
+ }
+}
+
+/** Places the balloon at the selection, the way the link balloon is placed. */
+function getCaretPosition(editor: Editor): Partial<DomOptimalPositionOptions> {
+ return {
+ target: () => {
+ const view = editor.editing.view;
+ const range = view.document.selection.getFirstRange();
+ /* v8 ignore next 3 -- the editing view has a selection once the editor is ready */
+ if (!range) {
+ return editor.ui.getEditableElement() as HTMLElement;
+ }
+ return view.domConverter.viewRangeToDom(range);
+ }
+ };
+}
diff --git a/packages/ckeditor5/src/theme/table_insert.css b/packages/ckeditor5/src/theme/table_insert.css
new file mode 100644
index 0000000000..e2dc012916
--- /dev/null
+++ b/packages/ckeditor5/src/theme/table_insert.css
@@ -0,0 +1,43 @@
+:where(:root) {
+ --ck-table-insert-form-error-color: var(--ck-color-base-error);
+}
+
+.ck.ck-table-insert-form {
+ display: grid;
+ grid-template-columns: auto auto;
+ align-items: center;
+ gap: var(--ck-spacing-standard) var(--ck-spacing-large);
+ padding: var(--ck-spacing-large);
+
+ &:focus {
+ outline: none;
+ }
+
+ .ck-table-insert-form__field {
+ display: contents;
+ }
+
+ .ck.ck-label {
+ font-weight: normal;
+ }
+
+ .ck.ck-input-number {
+ min-width: 0;
+ width: 10em;
+ }
+
+ /* `width: 0` keeps the message from widening the column; it wraps under the input instead. */
+ .ck-table-insert-form__error {
+ grid-column: 2;
+ min-width: 100%;
+ width: 0;
+ color: var(--ck-table-insert-form-error-color);
+ font-size: var(--ck-font-size-small);
+ white-space: normal;
+ }
+
+ .ck.ck-button-action {
+ grid-column: 2;
+ justify-self: start;
+ }
+}