Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/tables: implement a touch column bar
Adorian Doran58fa4e342c09
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 4d01c7f72c..e5a69a6ea2 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4449,7 +4449,9 @@"type-the-content-of-the-first-column": "Type the content of the first column","type-the-content-of-the-second-column": "Type the content of the second column","type-the-content-of-the-third-column": "Type the content of the third column",- "type-the-content-of-the-fourth-column": "Type the content of the fourth column"+ "type-the-content-of-the-fourth-column": "Type the content of the fourth column",+ "table-columns": "Table columns",+ "column-0-width-1": "Column %0 width: %1%"},"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.htmlindex 02e6559429..3f26e83066 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@@ -150,6 +150,23 @@ src="3_Tables_image.png" width="384" height="100"><li>To adjust exactly the width (in pixels or percentages) of a cell, selectthe <span class="tn-icon cke cke-table-cell-properties"></span> button.</li></ul>+<h3>Resizing with touch</h3>+<p>Since v0.107.0, touching a table shows a bar at the bottom of the note,+ above the formatting toolbar on mobile. The bar has a segment for each+ column of the table, with a divider at the end of each column.</p>+<ul>+ <li>To resize a column, drag its divider. The table grows or shrinks with+ the column, and scrolls when the divider reaches the edge of the screen.+ The column snaps to its starting width and to the widths of the columns+ beside it.</li>+ <li>To cancel a resize, drag the divider back to where it started, or touch+ the screen with a second finger.</li>+ <li>To give two neighboring columns the same width, double-tap the divider+ between them.</li>+ <li>To select a column, tap its segment. To open the column menu, touch and+ hold the segment.</li>+ <li>To scroll a wide table sideways, swipe along the bar.</li>+</ul><h2>Wide tables</h2><p>Since v0.107.0, a table can be wider than the <a class="reference-link"href="#root/_help_t596jLvPrqkS">Content width</a>. Such a table scrolls@@ -178,7 +195,7 @@ src="3_Tables_image.png" width="384" height="100">href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Appearance</em> → <em>Content Width</em> onthe mobile device, 1200 pixels by default. For example, a table set to <code>50%</code> is600 pixels wide.</p>-<p>Columns cannot be resized by dragging on mobile.</p>+<p>To resize columns on mobile, use the bar described in <a href="#resizing-with-touch">Resizing with touch</a>.</p><h2>Inserting new rows and new columns</h2><ul><li>To insert a new column, click on a desired location, then press the <spandiff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex cb8f9ffd05..f77299ee22 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -69,6 +69,16 @@ Right-clicking a cell that is not part of the current selection moves the cursor* By default, the row height is not adjustable using the mouse, but it can be configured from the cell settings (see below).* To adjust exactly the width (in pixels or percentages) of a cell, select the <span class="tn-icon cke cke-table-cell-properties"></span> button.+### Resizing with touch++Since v0.107.0, touching a table shows a bar at the bottom of the note, above the formatting toolbar on mobile. The bar has a segment for each column of the table, with a divider at the end of each column.++* To resize a column, drag its divider. The table grows or shrinks with the column, and scrolls when the divider reaches the edge of the screen. The column snaps to its starting width and to the widths of the columns beside it.+* To cancel a resize, drag the divider back to where it started, or touch the screen with a second finger.+* To give two neighboring columns the same width, double-tap the divider between them.+* To select a column, tap its segment. To open the column menu, touch and hold the segment.+* To scroll a wide table sideways, swipe along the bar.+## Wide tablesSince v0.107.0, a table can be wider than the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Content%20width.md">Content width</a>. Such a table scrolls sideways, while the rest of the note keeps its width.@@ -85,7 +95,7 @@ Tables inside other blocks, such as block quotes, admonitions, collapsible blockOn the <a class="reference-link" href="../../Installation%20%26%20Setup/Mobile%20Frontend.md">Mobile Frontend</a>, a table keeps the width it has on a desktop and scrolls sideways, instead of squeezing its columns into the width of the screen. The full width of a table is the _Max content width_ set in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Appearance_ → _Content Width_ on the mobile device, 1200 pixels by default. For example, a table set to `50%` is 600 pixels wide.-Columns cannot be resized by dragging on mobile.+To resize columns on mobile, use the bar described in [Resizing with touch](#resizing-with-touch).## Inserting new rows and new columnsdiff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex b438a94cf0..e84e3758ba 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -74,6 +74,7 @@ import TableSort from "./plugins/table_sort.js";import TableInsertUI from "./plugins/table_insert/table_insert_ui.js";import TableToolbarDropdowns from "./plugins/table_toolbar_dropdowns.js";import TriliumTableScroll from "./plugins/table_scroll.js";+import TableColumnBar from "./plugins/table_column_bar/table_column_bar.js";import ToolbarGroupMenu from "./plugins/toolbar_group_menu.js";import BlockDragHandle from "./plugins/block_drag_handle.js";@@ -119,6 +120,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [TableInsertUI,TableToolbarDropdowns,TriliumTableScroll,+ TableColumnBar,ToolbarGroupMenu,CopyAnchorLinkButton,CopyLinkUrlButton,diff --git a/packages/ckeditor5/src/plugins/table_column_bar/pointer_tracking.spec.ts b/packages/ckeditor5/src/plugins/table_column_bar/pointer_tracking.spec.tsnew file mode 100644index 0000000000..ca55f36cfb--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_column_bar/pointer_tracking.spec.ts@@ -0,0 +1,91 @@+import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from "vitest";++import { trackPointer } from "./pointer_tracking.js";++describe("trackPointer", () => {+ let element: HTMLElement;+ let options: Record<"onMove" | "onEnd" | "onCancel", Mock>;++ beforeEach(() => {+ element = document.createElement("div");+ document.body.append(element);+ vi.spyOn(element, "setPointerCapture").mockImplementation(() => {});+ options = { onMove: vi.fn(), onEnd: vi.fn(), onCancel: vi.fn() };+ });++ afterEach(() => {+ element.remove();+ });++ function start() {+ const event = new PointerEvent("pointerdown", { pointerId: 1, clientX: 100, clientY: 50 });+ return trackPointer(event, element, options);+ }++ function dispatch(type: string, init: PointerEventInit = {}) {+ window.dispatchEvent(new PointerEvent(type, { pointerId: 1, ...init }));+ }++ it("reports moves past the threshold and the release", () => {+ start();+ expect(element.setPointerCapture).toHaveBeenCalledWith(1);++ dispatch("pointermove", { clientX: 101, clientY: 51 });+ expect(options.onMove).not.toHaveBeenCalled();+ dispatch("pointermove", { pointerId: 2, clientX: 200, clientY: 50 });+ expect(options.onMove).not.toHaveBeenCalled();++ dispatch("pointermove", { clientX: 104, clientY: 50 });+ dispatch("pointermove", { clientX: 101, clientY: 50 });+ expect(options.onMove.mock.calls).toEqual([[104], [101]]);++ dispatch("pointerup", { pointerId: 2 });+ expect(options.onEnd).not.toHaveBeenCalled();+ dispatch("pointerup");+ expect(options.onEnd).toHaveBeenCalledWith(true);++ dispatch("pointermove", { clientX: 150, clientY: 50 });+ expect(options.onMove).toHaveBeenCalledTimes(2);+ });++ it("reports a release without a move", () => {+ start();+ dispatch("pointerup");+ expect(options.onEnd).toHaveBeenCalledWith(false);+ });++ it("cancels on Escape, a pointercancel, a lost capture and another pointer's press", () => {+ const cancellations = [+ () => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })),+ () => dispatch("pointercancel"),+ () => dispatch("lostpointercapture"),+ () => dispatch("pointerdown", { pointerId: 2 })+ ];++ for (const cancel of cancellations) {+ options.onCancel.mockClear();+ start();+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter" }));+ dispatch("pointercancel", { pointerId: 2 });+ dispatch("pointerdown");+ expect(options.onCancel).not.toHaveBeenCalled();++ cancel();+ expect(options.onCancel).toHaveBeenCalledTimes(1);+ dispatch("pointerup");+ expect(options.onEnd).not.toHaveBeenCalled();+ }+ });++ it("cancels through the returned function once, and not after the release", () => {+ const cancel = start();+ cancel();+ cancel();+ expect(options.onCancel).toHaveBeenCalledTimes(1);++ const cancelLater = start();+ dispatch("pointerup");+ cancelLater();+ expect(options.onCancel).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/ckeditor5/src/plugins/table_column_bar/pointer_tracking.ts b/packages/ckeditor5/src/plugins/table_column_bar/pointer_tracking.tsnew file mode 100644index 0000000000..327ff5df89--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_column_bar/pointer_tracking.ts@@ -0,0 +1,90 @@+/** The distance a pointer moves before a press becomes a drag, in pixels. */+const DRAG_THRESHOLD = 3;++export interface PointerTrackingOptions {+ /** Receives the client x of the pointer on each move, once it has moved past the threshold. */+ onMove: (clientX: number) => void;+ /** Ends the tracking when the pointer is released. */+ onEnd: (isMoved: boolean) => void;+ /** Ends the tracking on Escape, `pointercancel`, a lost capture or a press of another pointer. */+ onCancel: () => void;+}++/**+ * Follows the pointer pressed in `event` until it is released, with the pointer captured by+ * `element`. Returns a function that cancels the tracking.+ */+export function trackPointer(+ event: PointerEvent,+ element: Element,+ options: PointerTrackingOptions+) {+ const { pointerId, clientX: startX, clientY: startY } = event;+ let isMoved = false;+ let isActive = true;++ const onPointerMove = (moveEvent: PointerEvent) => {+ if (moveEvent.pointerId !== pointerId) {+ return;+ }+ const distance = Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY);+ isMoved ||= distance >= DRAG_THRESHOLD;+ if (isMoved) {+ options.onMove(moveEvent.clientX);+ }+ };++ const onPointerUp = (upEvent: PointerEvent) => {+ if (upEvent.pointerId === pointerId) {+ stop();+ options.onEnd(isMoved);+ }+ };++ const onOtherPointerDown = (downEvent: PointerEvent) => {+ if (downEvent.pointerId !== pointerId) {+ cancel();+ }+ };++ const onPointerCancel = (cancelEvent: PointerEvent) => {+ if (cancelEvent.pointerId === pointerId) {+ cancel();+ }+ };++ const onKeyDown = (keyEvent: KeyboardEvent) => {+ if (keyEvent.key === "Escape") {+ keyEvent.preventDefault();+ keyEvent.stopPropagation();+ cancel();+ }+ };++ const stop = () => {+ isActive = false;+ window.removeEventListener("pointermove", onPointerMove, true);+ window.removeEventListener("pointerup", onPointerUp, true);+ window.removeEventListener("pointerdown", onOtherPointerDown, true);+ window.removeEventListener("pointercancel", onPointerCancel, true);+ window.removeEventListener("lostpointercapture", onPointerCancel, true);+ window.removeEventListener("keydown", onKeyDown, true);+ };++ const cancel = () => {+ if (isActive) {+ stop();+ options.onCancel();+ }+ };++ element.setPointerCapture(pointerId);+ window.addEventListener("pointermove", onPointerMove, true);+ window.addEventListener("pointerup", onPointerUp, true);+ window.addEventListener("pointerdown", onOtherPointerDown, true);+ window.addEventListener("pointercancel", onPointerCancel, true);+ window.addEventListener("lostpointercapture", onPointerCancel, true);+ window.addEventListener("keydown", onKeyDown, true);++ return cancel;+}diff --git a/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.spec.ts b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.spec.tsnew file mode 100644index 0000000000..121f7d86f5--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.spec.ts@@ -0,0 +1,695 @@+import {+ _getTableColumnsWidths as getTableColumnsWidths,+ _setModelData as setModelData,+ BalloonEditor,+ ClassicEditor,+ DecoupledEditor,+ Essentials,+ Paragraph,+ Table,+ TableColumnResize,+ TableProperties+} from "ckeditor5";+import type { Editor, ModelElement } from "ckeditor5";+import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ type MockInstance,+ onTestFinished,+ vi+} from "vitest";++import { createTestEditor, createTestEditorOf } from "../../../test/editor-kit.js";+import { cellAt, modelTable } from "../../../test/table-kit.js";+import type { CellSpec } from "../../../test/table-kit.js";+import { REFERENCE_WIDTH_PROPERTY } from "../table_scroll.js";+import TableColumnBar, { findSnapPoint, getCenteredGrowth } from "./table_column_bar.js";++const PLUGINS = [Essentials, Paragraph, Table, TableColumnResize, TableColumnBar];++describe("findSnapPoint", () => {+ it("takes the closest point within the snap distance", () => {+ expect(findSnapPoint(105, [100, 200])).toBe(100);+ expect(findSnapPoint(195, [100, 200, 197])).toBe(197);+ expect(findSnapPoint(150, [100, 200])).toBeNull();+ expect(findSnapPoint(108, [100])).toBe(100);+ expect(findSnapPoint(109, [100])).toBeNull();+ });+});++describe("getCenteredGrowth", () => {+ it("doubles the distance while the table fits and adds the rest of the gap after", () => {+ expect(getCenteredGrowth(30, 76)).toBe(60);+ expect(getCenteredGrowth(-20, 76)).toBe(-40);+ expect(getCenteredGrowth(38, 76)).toBe(76);+ expect(getCenteredGrowth(50, 76)).toBe(88);+ });++ it("follows the distance while the table is wider than its container", () => {+ expect(getCenteredGrowth(10, -24)).toBe(10);+ expect(getCenteredGrowth(-24, -24)).toBe(-24);+ expect(getCenteredGrowth(-30, -24)).toBe(-36);+ expect(getCenteredGrowth(5, 0)).toBe(5);+ });+});++describe("TableColumnBar", () => {+ const link = document.createElement("link");+ let editor: ClassicEditor;+ let vibrate: MockInstance<Navigator["vibrate"]>;++ beforeAll(() => new Promise<void>((resolve, reject) => {+ link.rel = "stylesheet";+ link.href = editorStylesheetUrl;+ link.onload = () => resolve();+ link.onerror = () => reject(new Error("the editor stylesheet did not load"));+ document.head.appendChild(link);+ }));++ afterAll(() => {+ link.remove();+ });++ beforeEach(async () => {+ const capture = vi.spyOn(Element.prototype, "setPointerCapture").mockImplementation(() => {});+ vibrate = vi.spyOn(navigator, "vibrate").mockReturnValue(true);+ onTestFinished(() => {+ capture.mockRestore();+ vibrate.mockRestore();+ });+ editor = await createTestEditor(PLUGINS);+ setEditableWidth(editor, 400);+ });++ describe("visibility", () => {+ it("shows the bar for the table at the selection after a touch", async () => {+ setModelData(editor.model, modelTable([["a[]", "b"]]));+ editor.editing.view.focus();+ await expect.poll(() => editor.ui.focusTracker.isFocused).toBe(true);+ await frames();+ expect(barView(editor).isVisible).toBe(false);++ touch();+ await expect.poll(() => barView(editor).isVisible).toBe(true);+ expect(barView(editor).element?.getAttribute("aria-label")).toBe("Table columns");++ touch("mouse");+ await expect.poll(() => barView(editor).isVisible).toBe(false);+ });++ it("hides the bar outside a table, in read-only mode and while blurred", async () => {+ await showBar(editor, `${modelTable([["a[]", "b"]])}<paragraph>x</paragraph>`);++ setSelectionIn(editor, "paragraph");+ await expect.poll(() => barView(editor).isVisible).toBe(false);+ editor.model.change((writer) => writer.setSelection(cellAt(editor, 0, 1), 0));+ await expect.poll(() => barView(editor).isVisible).toBe(true);++ editor.enableReadOnlyMode("spec");+ await expect.poll(() => barView(editor).isVisible).toBe(false);+ editor.disableReadOnlyMode("spec");+ await expect.poll(() => barView(editor).isVisible).toBe(true);++ // The caret is in the nested editable of a cell, which takes the focus.+ (document.activeElement as HTMLElement | null)?.blur();+ await expect.poll(() => barView(editor).isVisible).toBe(false);+ });++ it("stays shown when a mouse presses the bar, and opens no context menu", async () => {+ await showBar(editor, modelTable([["a[]", "b"]]));++ const track = barView(editor).track;+ track.dispatchEvent(new PointerEvent("pointerdown", {+ bubbles: true,+ pointerType: "mouse",+ isPrimary: true+ }));+ await frames();+ expect(barView(editor).isVisible).toBe(true);++ const contextMenu = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });+ segments(editor)[0].dispatchEvent(contextMenu);+ expect(contextMenu.defaultPrevented).toBe(true);+ });++ it("hides the bar while the table is out of view", async () => {+ await showBar(editor, modelTable([["a[]", "b"]]));+ const editorElement = editor.ui.element as HTMLElement;++ editorElement.style.marginTop = "200vh";+ window.dispatchEvent(new Event("resize"));+ await expect.poll(() => barView(editor).isVisible).toBe(false);++ editorElement.style.marginTop = "";+ editorElement.style.marginLeft = "-200vw";+ window.dispatchEvent(new Event("resize"));+ await frames();+ expect(barView(editor).isVisible).toBe(false);++ editorElement.style.marginLeft = "";+ window.dispatchEvent(new Event("resize"));+ await expect.poll(() => barView(editor).isVisible).toBe(true);+ });+ });++ describe("layout", () => {+ it("lines the segments and dividers up with the columns as the table scrolls", async () => {+ await showBar(editor, modelTable([["a[]", "b"]], 'tableWidth="200%"'));+ const figure = domFigure(editor);+ expect(figure.classList.contains("ck-table-overflowing")).toBe(true);+ expectAligned(editor);+ expect(dividers(editor).map((divider) => divider.getAttribute("aria-label")))+ .toEqual(["Column 1 width: 50%", "Column 2 width: 50%"]);++ figure.scrollLeft = 150;+ await frames();+ expectAligned(editor);+ const trackRect = barView(editor).track.getBoundingClientRect();+ const figureRect = figure.getBoundingClientRect();+ expectNear(trackRect.left, figureRect.left + figure.clientLeft);+ expectNear(trackRect.right, figureRect.left + figure.clientLeft + figure.clientWidth);+ });++ it("spans the bottom of the scroll container of the editable", async () => {+ const scroller = document.createElement("div");+ scroller.style.cssText = "height: 300px; width: 500px; margin-left: 20px; overflow: auto";+ document.body.append(scroller);+ scroller.append(editor.ui.element as HTMLElement);+ onTestFinished(() => scroller.remove());++ const paragraphs = "<paragraph>x</paragraph>".repeat(30);+ await showBar(editor, `<paragraph>x</paragraph>${modelTable([["a[]", "b"]])}${paragraphs}`);+ const barRect = barRectOf(editor);+ const scrollerRect = scroller.getBoundingClientRect();+ expectNear(barRect.left, scrollerRect.left);+ expectNear(barRect.width, scroller.clientWidth);+ expectNear(barRect.bottom, scrollerRect.top + scroller.clientHeight);++ scroller.scrollTop = 20;+ await frames();+ expectAligned(editor);+ });++ it("sits above a toolbar at the bottom and keeps the balloons above itself", async () => {+ const withToolbar = await createTestEditor(PLUGINS, { toolbar: ["undo", "redo"] });+ const toolbar = withToolbar.ui.view.toolbar.element as HTMLElement;+ toolbar.style.cssText = "position: fixed; bottom: 0; left: 0; right: 0";+ const initialOffset = withToolbar.ui.viewportOffset.bottom;++ await showBar(withToolbar, `${modelTable([["a[]", "b"]])}<paragraph>x</paragraph>`);+ const barRect = barRectOf(withToolbar);+ const toolbarRect = toolbar.getBoundingClientRect();+ expect(toolbarRect.height).toBeGreaterThan(0);+ expectNear(barRect.bottom, toolbarRect.top);+ expect(withToolbar.ui.viewportOffset.bottom)+ .toBe(Math.round(window.innerHeight - barRect.top));++ setSelectionIn(withToolbar, "paragraph");+ await expect.poll(() => barView(withToolbar).isVisible).toBe(false);+ expect(withToolbar.ui.viewportOffset.bottom ?? 0).toBe(initialOffset ?? 0);+ });++ it("works with an editor without a toolbar and with a detached one", async () => {+ const balloon = await createTestEditorOf(BalloonEditor, PLUGINS);+ const decoupled = await createTestEditorOf(DecoupledEditor, PLUGINS);+ for (const other of [balloon, decoupled]) {+ await showBar(other, modelTable([["a[]", "b"]]));+ expectNear(barRectOf(other).bottom, document.documentElement.clientHeight);+ }+ });+ });++ describe("segments", () => {+ it("selects the column on a tap", async () => {+ await showBar(editor, modelTable([["a[]", "b"], ["c", "d"]]));++ press(segments(editor)[1]);+ release();+ expect(selectedCells(editor)).toEqual([cellAt(editor, 0, 1), cellAt(editor, 1, 1)]);+ });++ it("opens the column menu on a long press", async () => {+ await showBar(editor, `${modelTable([["a[]", "b"], ["c", "d"]])}<paragraph>x</paragraph>`);+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ onTestFinished(() => {+ vi.useRealTimers();+ });++ const { x, y } = press(segments(editor)[0]);+ vi.advanceTimersByTime(500);+ const menu = barView(editor).menus.first;+ expect(menu?.isOpen).toBe(true);+ expect(vibrate).toHaveBeenCalledWith(10);+ expect(selectedCells(editor)).toEqual([cellAt(editor, 0, 0), cellAt(editor, 1, 0)]);+ const button = menu?.buttonView.element?.getBoundingClientRect();+ const segment = segments(editor)[0].getBoundingClientRect();+ expectNear((button?.left ?? 0) + (button?.width ?? 0) / 2, segment.left + segment.width / 2);++ moveTo(x + 50, y);+ release();+ expect(selectedCells(editor)).toEqual([cellAt(editor, 0, 0), cellAt(editor, 1, 0)]);++ press(segments(editor)[1]);+ expect(menu?.isOpen).toBe(false);+ vi.advanceTimersByTime(500);+ release();+ expect(barView(editor).menus.length).toBe(1);+ expect(menu?.isOpen).toBe(true);++ vi.useRealTimers();+ setSelectionIn(editor, "paragraph");+ await expect.poll(() => menu?.isOpen).toBe(false);+ });++ it("scrolls the table on a swipe", async () => {+ await showBar(editor, modelTable([["a[]", "b"]], 'tableWidth="300%"'));+ const figure = domFigure(editor);++ const { x, y } = press(segments(editor)[0]);+ moveTo(x - 100, y);+ expect(figure.scrollLeft).toBe(100);+ moveTo(x - 40, y);+ expect(figure.scrollLeft).toBe(40);+ release();+ expect(selectedCells(editor)).toEqual([]);+ });++ it("ignores a press of a second finger and cancels the first one's tap", async () => {+ await showBar(editor, modelTable([["a[]", "b"]]));++ press(segments(editor)[0]);+ press(segments(editor)[1], { pointerId: 2, isPrimary: false });+ release(2);+ release();+ expect(selectedCells(editor)).toEqual([]);+ });+ });++ describe("dividers", () => {+ it("shows a resize on the table and saves it to the model on release", async () => {+ await showBar(editor, modelTable([["a[]", "b"]], 'tableWidth="80%"'));+ const table = firstTable(editor);+ const before = columnWidths(editor);+ const edge = endEdgeOf(editor, 0);++ const { x, y } = press(dividers(editor)[0]);+ moveTo(x + 50, y);+ expectNear(endEdgeOf(editor, 0), edge + 50);+ expect(columnWidths(editor)[0]).toBeGreaterThan(before[0] + 50);+ expectNear(columnWidths(editor)[1], before[1]);+ expect(table.getAttribute("tableWidth")).toBe("80%");+ expect(getTableColumnsWidths(table)).toEqual([]);+ await expect.poll(() => isEdgeShown(editor)).toBe(true);+ expectNear(edgeRectOf(editor).left + 1, endEdgeOf(editor, 0));+ expect(dividers(editor)[0].classList.contains("ck-table-column-bar__divider_active"))+ .toBe(true);++ release();+ expectNear(endEdgeOf(editor, 0), edge + 50);+ expectNear(columnWidths(editor)[1], before[1]);+ expect(table.getAttribute("tableWidth")).toMatch(/%$/);+ expect(getTableColumnsWidths(table)).toHaveLength(2);+ expect(domFigure(editor).querySelectorAll("colgroup")).toHaveLength(1);+ await expect.poll(() => isEdgeShown(editor)).toBe(false);++ editor.execute("undo");+ expect(table.getAttribute("tableWidth")).toBe("80%");+ expect(getTableColumnsWidths(table)).toEqual([]);+ });++ it("keeps pixels for a table sized in pixels", async () => {+ const widths = ["100px", "200px"];+ await showBar(editor, resizedTable([["a[]", "b"]], widths, 'tableWidth="300px"'));+ const table = firstTable(editor);+ const edge = endEdgeOf(editor, 1);++ const { x, y } = press(dividers(editor)[1]);+ moveTo(x + 30, y);+ release();+ expectNear(endEdgeOf(editor, 1), edge + 30);+ const tableWidth = parseFloat(String(table.getAttribute("tableWidth")));+ expect(table.getAttribute("tableWidth")).toBe(`${tableWidth}px`);+ const savedWidths = getTableColumnsWidths(table);+ expectNear(parseFloat(savedWidths[0]), 100);+ expectNear(parseFloat(savedWidths[1]), tableWidth - 100);+ });++ it("grows a column by the distance dragged in a table aligned to a side", async () => {+ const aligned = await createTestEditor([...PLUGINS, TableProperties]);+ setEditableWidth(aligned, 400);+ const widths = ["100px", "200px"];+ await showBar(aligned, resizedTable([["a[]", "b"]], widths,+ 'tableWidth="300px" tableAlignment="blockLeft"'));+ const edge = endEdgeOf(aligned, 0);++ const { x, y } = press(dividers(aligned)[0]);+ moveTo(x + 30, y);+ release();+ expectNear(endEdgeOf(aligned, 0), edge + 30);+ expect(getTableColumnsWidths(firstTable(aligned)).map(parseFloat)).toEqual([130, 200]);+ });++ it("measures a percentage against the reference width", async () => {+ document.body.style.setProperty(REFERENCE_WIDTH_PROPERTY, "1200px");+ onTestFinished(() => {+ document.body.style.removeProperty(REFERENCE_WIDTH_PROPERTY);+ });+ const referenced = await createTestEditor(PLUGINS);+ setEditableWidth(referenced, 400);+ await showBar(referenced, modelTable([["a[]", "b"]], 'tableWidth="25%"'));+ const edge = endEdgeOf(referenced, 1);++ const { x, y } = press(dividers(referenced)[1]);+ moveTo(x + 60, y);+ release();+ expectNear(endEdgeOf(referenced, 1), edge + 60);+ const share = columnWidths(referenced).reduce((sum, width) => sum + width) / 1200 * 100;+ const tableWidth = String(firstTable(referenced).getAttribute("tableWidth"));+ expect(tableWidth).toMatch(/%$/);+ expectNear(parseFloat(tableWidth), share);+ });++ it("snaps to the start width and the widths beside it", async () => {+ const widths = ["100px", "200px", "100px"];+ await showBar(editor, resizedTable([["a[]", "b", "c"]], widths, 'tableWidth="400px"'));+ const table = firstTable(editor);++ const { x, y } = press(dividers(editor)[0]);+ moveTo(x + 95, y);+ expectNear(columnWidths(editor)[0], 200);+ expect(vibrate).toHaveBeenCalledTimes(1);+ moveTo(x + 96, y);+ expect(vibrate).toHaveBeenCalledTimes(1);+ moveTo(x + 40, y);+ expectNear(columnWidths(editor)[0], 140);+ moveTo(x + 4, y);+ expectNear(columnWidths(editor)[0], 100);+ expect(vibrate).toHaveBeenCalledTimes(2);++ release();+ expect(getTableColumnsWidths(table)).toEqual(widths);+ expect(table.getAttribute("tableWidth")).toBe("400px");+ });++ it("vibrates only where the device can", async () => {+ vibrate.mockRestore();+ Object.defineProperty(navigator, "vibrate", { value: undefined, configurable: true });+ onTestFinished(() => {+ Reflect.deleteProperty(navigator, "vibrate");+ });+ await showBar(editor, resizedTable([["a[]", "b"]], ["100px", "100px"], 'tableWidth="200px"'));++ const { x, y } = press(dividers(editor)[0]);+ moveTo(x - 30, y);+ moveTo(x + 2, y);+ release();+ expect(getTableColumnsWidths(firstTable(editor))).toEqual(["100px", "100px"]);+ });++ it("keeps a narrow column at its width or wider", async () => {+ await showBar(editor, resizedTable([["a[]", "b"]], ["20px", "200px"], 'tableWidth="220px"'));++ const { x, y } = press(dividers(editor)[0]);+ moveTo(x - 50, y);+ expectNear(columnWidths(editor)[0], 20);+ release();+ });++ it("cancels on a second finger, Escape and a pointercancel", async () => {+ await showBar(editor, modelTable([["a[]", "b"]], 'tableWidth="80%"'));+ const table = firstTable(editor);+ const before = columnWidths(editor);+ const cancellations = [+ () => press(segments(editor)[1], { pointerId: 2, isPrimary: false }),+ () => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })),+ () => window.dispatchEvent(new PointerEvent("pointercancel", { pointerId: 1 }))+ ];++ for (const cancel of cancellations) {+ const { x, y } = press(dividers(editor)[0]);+ moveTo(x + 40, y);+ cancel();+ release();+ expectNear(columnWidths(editor)[0], before[0]);+ expect(table.getAttribute("tableWidth")).toBe("80%");+ expect(domFigure(editor).querySelector("colgroup")).toBeNull();+ expect(domFigure(editor).querySelector("table.ck-table-resized")).toBeNull();+ }+ });++ it("restores the saved widths of a resized table on a cancel", async () => {+ const widths = ["100px", "200px"];+ await showBar(editor, resizedTable([["a[]", "b"]], widths, 'tableWidth="300px"'));++ const { x, y } = press(dividers(editor)[0]);+ moveTo(x + 40, y);+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));+ expectNear(columnWidths(editor)[0], 100);+ expect(getTableColumnsWidths(firstTable(editor))).toEqual(widths);+ expect(domFigure(editor).querySelector("table.ck-table-resized")).not.toBeNull();+ });++ it("cancels a resize when the bar hides", async () => {+ await showBar(editor, modelTable([["a[]", "b"]], 'tableWidth="80%"'));++ const { x, y } = press(dividers(editor)[0]);+ moveTo(x + 40, y);+ editor.enableReadOnlyMode("spec");+ await expect.poll(() => barView(editor).isVisible).toBe(false);+ release();+ expect(firstTable(editor).getAttribute("tableWidth")).toBe("80%");+ expect(domFigure(editor).querySelector("colgroup")).toBeNull();+ });++ it("scrolls the table near the ends of its visible part", async () => {+ await showBar(editor, modelTable([["a[]", "b", "c"]], 'tableWidth="200%"'));+ const figure = domFigure(editor);+ const before = columnWidths(editor);++ const start = press(dividers(editor)[0]);+ const trackRect = barView(editor).track.getBoundingClientRect();+ moveTo(trackRect.right - 5, start.y);+ await expect.poll(() => figure.scrollLeft).toBeGreaterThan(100);+ release();+ const grown = columnWidths(editor)[0];+ expect(grown).toBeGreaterThan(before[0] + (trackRect.right - 5 - start.x) + 50);++ const end = press(dividers(editor)[0]);+ const scrolled = figure.scrollLeft;+ moveTo(trackRect.left + 5, end.y);+ await expect.poll(() => figure.scrollLeft).toBeLessThan(scrolled - 50);+ release();+ expect(columnWidths(editor)[0]).toBeLessThan(grown);+ });++ it("evens out the two columns beside a divider on a double tap", async () => {+ const widths = ["100px", "200px", "100px"];+ await showBar(editor, resizedTable([["a[]", "b", "c"]], widths, 'tableWidth="400px"'));+ const table = firstTable(editor);+ const tap = (column: number) => {+ press(dividers(editor)[column]);+ release();+ };++ tap(0);+ tap(1);+ tap(2);+ tap(2);+ expect(getTableColumnsWidths(table)).toEqual(widths);++ const now = vi.spyOn(performance, "now");+ onTestFinished(() => now.mockRestore());+ now.mockReturnValue(1000);+ tap(0);+ now.mockReturnValue(2000);+ tap(0);+ expect(getTableColumnsWidths(table)).toEqual(widths);++ now.mockReturnValue(2100);+ tap(0);+ expect(getTableColumnsWidths(table)).toEqual(["150px", "150px", "100px"]);+ });++ it("resizes towards the left in right-to-left content", async () => {+ const rtl = await createTestEditor(PLUGINS, { language: { content: "ar" } });+ setEditableWidth(rtl, 400);+ await showBar(rtl, resizedTable([["a[]", "b"]], ["100px", "200px"], 'tableWidth="300px"'));+ expectAligned(rtl);+ const edge = endEdgeOf(rtl, 0);++ const { x, y } = press(dividers(rtl)[0]);+ moveTo(x - 30, y);+ release();+ expectNear(endEdgeOf(rtl, 0), edge - 30);+ const widths = getTableColumnsWidths(firstTable(rtl));+ expect(parseFloat(widths[0])).toBeGreaterThan(130);+ expectNear(parseFloat(widths[1]), 200);+ });++ it("stops the resize when the editor is destroyed", async () => {+ const element = document.createElement("div");+ document.body.append(element);+ const own = await ClassicEditor.create(element, { licenseKey: "GPL", plugins: PLUGINS });+ await showBar(own, modelTable([["a[]", "b"]]));++ const { x, y } = press(dividers(own)[0]);+ moveTo(x + 20, y);+ await own.destroy();+ element.remove();+ moveTo(x + 40, y);+ release();+ });+ });+});++/** Waits for two animation frames, for the updates the plugin schedules. */+async function frames() {+ for (let frame = 0; frame < 2; frame++) {+ await new Promise((resolve) => requestAnimationFrame(resolve));+ }+}++async function showBar(editor: Editor, data: string) {+ setModelData(editor.model, data);+ editor.editing.view.focus();+ touch();+ await expect.poll(() => barView(editor).isVisible).toBe(true);+}++function touch(pointerType = "touch") {+ document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, pointerType }));+}++function press(element: Element, init: PointerEventInit = {}) {+ const rect = element.getBoundingClientRect();+ const x = rect.left + rect.width / 2;+ const y = rect.top + rect.height / 2;+ element.dispatchEvent(new PointerEvent("pointerdown", {+ bubbles: true,+ cancelable: true,+ pointerId: 1,+ isPrimary: true,+ pointerType: "touch",+ clientX: x,+ clientY: y,+ ...init+ }));+ return { x, y };+}++function moveTo(clientX: number, clientY: number) {+ window.dispatchEvent(new PointerEvent("pointermove", { pointerId: 1, clientX, clientY }));+}++function release(pointerId = 1) {+ window.dispatchEvent(new PointerEvent("pointerup", { pointerId }));+}++function barView(editor: Editor) {+ return editor.plugins.get(TableColumnBar).view;+}++function barRectOf(editor: Editor) {+ return barView(editor).element?.getBoundingClientRect() ?? new DOMRect();+}++function segments(editor: Editor) {+ return [...barView(editor).track.querySelectorAll<HTMLElement>(".ck-table-column-bar__segment")];+}++function dividers(editor: Editor) {+ return [...barView(editor).track.querySelectorAll<HTMLElement>(".ck-table-column-bar__divider")];+}++function edgeElementOf(editor: Editor) {+ const edge = barView(editor).element?.querySelector(".ck-table-column-bar__edge");+ if (!(edge instanceof HTMLElement)) {+ throw new Error("The bar has no edge line.");+ }+ return edge;+}++function isEdgeShown(editor: Editor) {+ return !edgeElementOf(editor).classList.contains("ck-hidden");+}++function edgeRectOf(editor: Editor) {+ return edgeElementOf(editor).getBoundingClientRect();+}++/** Expects each segment over its column and each divider at the inline end of its column. */+function expectAligned(editor: Editor) {+ const isRtl = editor.locale.contentLanguageDirection === "rtl";+ for (const [index, cell] of domCells(editor).entries()) {+ const cellRect = cell.getBoundingClientRect();+ const segmentRect = segments(editor)[index].getBoundingClientRect();+ const dividerRect = dividers(editor)[index].getBoundingClientRect();+ expectNear(segmentRect.left, cellRect.left);+ expectNear(segmentRect.right, cellRect.right);+ expectNear(dividerRect.left + dividerRect.width / 2, isRtl ? cellRect.left : cellRect.right);+ }+}++function expectNear(actual: number, expected: number) {+ expect(Math.abs(actual - expected)).toBeLessThan(1.5);+}++function setEditableWidth(editor: Editor, width: number) {+ editor.ui.element?.style.setProperty("width", `${width}px`);+}++function setSelectionIn(editor: Editor, name: string) {+ const root = editor.model.document.getRoot();+ const element = root && [...root.getChildren()].find((child) => child.is("element", name));+ if (!element) {+ throw new Error(`The root has no ${name}.`);+ }+ editor.model.change((writer) => writer.setSelection(element, 0));+}++function firstTable(editor: Editor): ModelElement {+ const table = editor.model.document.getRoot()?.getChild(0);+ if (!table?.is("element", "table")) {+ throw new Error("The first root child is not a table.");+ }+ return table;+}++function domFigure(editor: Editor) {+ const figure = editor.editing.view.getDomRoot()?.querySelector(":scope > figure.table");+ if (!(figure instanceof HTMLElement)) {+ throw new Error("The editable has no table.");+ }+ return figure;+}++function domCells(editor: Editor) {+ return [...domFigure(editor).querySelectorAll<HTMLElement>("tr:first-child > td")];+}++function columnWidths(editor: Editor) {+ return domCells(editor).map((cell) => cell.getBoundingClientRect().width);+}++/** The client x of the inline end of `column`. */+function endEdgeOf(editor: Editor, column: number) {+ const rect = domCells(editor)[column].getBoundingClientRect();+ return editor.locale.contentLanguageDirection === "rtl" ? rect.left : rect.right;+}++function selectedCells(editor: Editor) {+ return [...editor.model.document.selection.getRanges()]+ .map((range) => range.start.nodeAfter)+ .filter((node) => node?.is("element", "tableCell"));+}++function resizedTable(rows: CellSpec[][], widths: string[], attributes: string) {+ const columns = widths.map((width) => `<tableColumn columnWidth="${width}"></tableColumn>`);+ return modelTable(rows, attributes)+ .replace(/<\/table>$/, `<tableColumnGroup>${columns.join("")}</tableColumnGroup></table>`);+}diff --git a/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.ts b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.tsnew file mode 100644index 0000000000..6830b0965a--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.ts@@ -0,0 +1,678 @@+import "../../theme/table_column_bar.css";++import {+ _getElementWidthInPixels as getElementWidthInPixels,+ _getSelectionAffectedTable as getSelectionAffectedTable,+ _getTableColumnsWidths as getTableColumnsWidths,+ _TABLE_COLUMN_MIN_WIDTH_IN_PIXELS as MIN_COLUMN_WIDTH,+ _toPrecision as toPrecision,+ DomEmitterMixin,+ Plugin,+ Table,+ TableColumnResize,+ TableUtils,+ TableWalker+} from "ckeditor5";+import type { DropdownView, ModelElement, ToolbarView, ViewElement } from "ckeditor5";++import {+ distributeColumns,+ getTableWidthBasis,+ measureColumnEdges+} from "../table_distribute_columns.js";+import TriliumTableScroll from "../table_scroll.js";+import { trackPointer } from "./pointer_tracking.js";+import TableColumnBarView from "./table_column_bar_view.js";++const LONG_PRESS_MS = 500;+const DOUBLE_TAP_MS = 400;+const VIBRATION_MS = 10;+/** The distance from a snap point at which a dragged width takes it, in pixels. */+const SNAP_DISTANCE = 8;+/** The distance from the ends of the visible part of the table that scrolls it, in pixels. */+const AUTO_SCROLL_EDGE = 40;+/** The largest distance scrolled per frame, in pixels. */+const AUTO_SCROLL_STEP = 16;+const RESIZED_TABLE_CLASS = "ck-table-resized";++/**+ * A bar along the bottom of the editing area for the table at the selection, shown after a touch.+ * Each segment is a column: a tap selects it, a long press opens the column menu and a swipe+ * scrolls the table. Dragging the divider at the end of a column resizes it, and the table grows+ * or shrinks with it. A double tap on a divider evens out the two columns beside it.+ */+export default class TableColumnBar extends Plugin {++ readonly view: TableColumnBarView;+ private isTouch = false;+ private target: BarTarget | null = null;+ /** The column boundaries of the target table, in pixels from its left edge. */+ private edges: number[] | null = null;+ private isMeasureNeeded = true;+ private frame = 0;+ /** The visible part of the table in the viewport, in pixels. */+ private trackBox = { left: 0, right: 0 };+ private bottomOffset = 0;+ private resizedColumn: number | null = null;+ private cancelGesture: (() => void) | null = null;+ private menu: DropdownView | null = null;+ private lastTap: { column: number; time: number } | null = null;+ private readonly domEmitter = new (DomEmitterMixin())();+ private readonly resizeObserver = new ResizeObserver(() => this.scheduleUpdate(true));++ static get pluginName() {+ return "TableColumnBar" as const;+ }++ static get requires() {+ return [Table, TableColumnResize, TriliumTableScroll] as const;+ }++ constructor(editor: Plugin["editor"]) {+ super(editor);+ this.view = new TableColumnBarView(editor.locale);+ }++ init() {+ const editor = this.editor;+ const view = this.view;+ editor.ui.view.body.add(view);++ this.domEmitter.listenTo(view.track, "pointerdown", (_evt, event: PointerEvent) => {+ this.onPointerDown(event);+ });+ this.domEmitter.listenTo(view.track, "contextmenu", (_evt, event: Event) => {+ event.preventDefault();+ });+ this.domEmitter.listenTo(document, "pointerdown", (_evt, event: PointerEvent) => {+ this.detectTouch(event);+ }, { useCapture: true });+ this.domEmitter.listenTo(document, "scroll", () => this.scheduleUpdate(false), {+ useCapture: true,+ usePassive: true+ });+ this.domEmitter.listenTo(window, "resize", () => this.scheduleUpdate(true));+ const viewport = window.visualViewport;+ /* v8 ignore next 3 -- defensive: supported browsers have a visual viewport */+ if (viewport) {+ this.domEmitter.listenTo(viewport, "resize", () => this.scheduleUpdate(false));+ }++ // The columns are measured again only when the content or the size of the table changes.+ const update = () => this.scheduleUpdate(false);+ this.listenTo(editor.ui, "update", update);+ this.listenTo(editor.ui.focusTracker, "change:isFocused", update);+ this.listenTo(editor, "change:isReadOnly", update);+ this.listenTo(editor.model.document, "change:data", () => this.scheduleUpdate(true));+ }++ override destroy() {+ this.cancelGesture?.();+ cancelAnimationFrame(this.frame);+ this.domEmitter.stopListening();+ this.resizeObserver.disconnect();+ this.view.destroy();+ super.destroy();+ }++ /** Shows the bar for the table at the selection, or hides it. */+ update() {+ const view = this.view;+ const target = this.findTarget();+ if (target?.domTable !== this.target?.domTable) {+ this.cancelGesture?.();+ this.resizeObserver.disconnect();+ if (target) {+ this.resizeObserver.observe(target.domTable);+ }+ this.edges = null;+ }+ this.target = target;++ view.isVisible = !!target;+ const barTop = target ? this.layOut(target) : null;+ if (barTop === null) {+ view.isVisible = false;+ if (this.menu) {+ this.menu.isOpen = false;+ }+ }+ this.setBottomOffset(barTop === null ? 0 : Math.round(window.innerHeight - barTop));+ }++ private scheduleUpdate(isMeasureNeeded: boolean) {+ this.isMeasureNeeded ||= isMeasureNeeded;+ if (this.frame || (!this.isTouch && !this.view.isVisible)) {+ return;+ }++ this.frame = requestAnimationFrame(() => {+ this.frame = 0;+ this.update();+ });+ }++ /** Shows the bar after a touch and hides it after a press of a mouse or pen elsewhere. */+ private detectTouch(event: PointerEvent) {+ const isTouch = event.pointerType === "touch";+ const isOnBar = !!(event.target as Element).closest(".ck-table-column-bar");+ if (isTouch !== this.isTouch && !isOnBar) {+ this.isTouch = isTouch;+ this.scheduleUpdate(true);+ }+ }++ private findTarget(): BarTarget | null {+ const editor = this.editor;+ if (!this.isTouch || editor.isReadOnly || !editor.ui.focusTracker.isFocused) {+ return null;+ }++ const selection = editor.model.document.selection;+ const table: ModelElement | null = getSelectionAffectedTable(selection);+ if (!table || !editor.model.canEditAt(table)) {+ return null;+ }++ const viewFigure = editor.editing.mapper.toViewElement(table);+ const domFigure = viewFigure && editor.editing.view.domConverter.mapViewToDom(viewFigure);+ const domTable = domFigure?.querySelector<HTMLElement>(":scope > table");+ const domContainer = domFigure?.parentElement;+ const domRoot = domTable?.closest<HTMLElement>(".ck-editor__editable");+ /* v8 ignore next 3 -- defensive: a table in the model is rendered in the editable */+ if (!(domFigure instanceof HTMLElement) || !domTable || !domContainer || !domRoot) {+ return null;+ }++ return { table, domFigure, domTable, domContainer, domRoot };+ }++ /** Whether `table` is centered in its container, read as `TableColumnResize` reads it. */+ private isCentered(table: ModelElement) {+ const alignment = table.getAttribute("tableAlignment")+ ?? this.editor.config.get("table.tableProperties.defaultProperties.alignment");+ return !alignment || alignment === "center";+ }++ /**+ * Places the bar and draws the columns of `target`. Returns the top of the bar in the+ * viewport, or `null` when no part of the table is visible above it.+ */+ private layOut(target: BarTarget): number | null {+ const view = this.view;+ const area = getBarArea(target.domRoot, this.getToolbarElement());+ const barTop = area.bottom - view.track.offsetHeight;+ const tableRect = target.domTable.getBoundingClientRect();+ const clip = getClientBox(findScroller(target.domTable, "overflowX"));+ const left = Math.max(tableRect.left, clip.left, area.left);+ const right = Math.min(tableRect.right, clip.right, area.right);+ const top = Math.max(tableRect.top, clip.top, area.top);+ const bottom = Math.min(tableRect.bottom, clip.bottom, barTop);+ if (right <= left || bottom <= top) {+ return null;+ }++ const edges = this.measure(target, tableRect);+ /* v8 ignore next 3 -- defensive: the bar shows a rendered table */+ if (!edges) {+ return null;+ }++ view.set({ left: area.left, top: barTop, width: area.right - area.left });+ view.setTrack(left - area.left, right - left, tableRect.left - left);+ this.trackBox = { left, right };++ const column = this.resizedColumn;+ view.setActiveDivider(column);+ view.setEdge(column === null+ ? null+ : { left: tableRect.left + edges[column + 1], top, height: bottom - top });+ return barTop;+ }++ /** The column boundaries of the target table, measured again when its layout can differ. */+ private measure(target: BarTarget, tableRect: DOMRect) {+ if (this.edges && !this.isMeasureNeeded) {+ return this.edges;+ }++ const editor = this.editor;+ const isRtl = editor.locale.contentLanguageDirection === "rtl";+ const columnCount = editor.plugins.get(TableUtils).getColumns(target.table);+ const measured = measureColumnEdges(editor, target.table, columnCount);+ /* v8 ignore next 3 -- defensive: the bar shows a rendered table */+ if (!measured) {+ return null;+ }++ const edges = measured.map((edge) => (isRtl ? -edge : edge) - tableRect.left);+ const tableWidth = Math.abs(edges[columnCount] - edges[0]);+ const labels: string[] = [];+ for (let column = 0; column < columnCount; column++) {+ const width = Math.abs(edges[column + 1] - edges[column]);+ const share = Math.round(width / tableWidth * 100);+ labels.push(editor.t("Column %0 width: %1%", [column + 1, share]));+ }++ this.view.setColumns(edges, labels);+ this.edges = edges;+ this.isMeasureNeeded = false;+ return edges;+ }++ private getToolbarElement() {+ return (this.editor.ui.view as { toolbar?: ToolbarView }).toolbar?.element ?? null;+ }++ /** Keeps the balloons of the editor and the caret above the bar. */+ private setBottomOffset(offset: number) {+ if (offset === this.bottomOffset) {+ return;+ }++ const ui = this.editor.ui;+ const bottom = (ui.viewportOffset.bottom ?? 0) - this.bottomOffset + offset;+ ui.viewportOffset = { ...ui.viewportOffset, bottom };+ this.bottomOffset = offset;+ ui.update();+ }++ private onPointerDown(event: PointerEvent) {+ const target = this.target;+ const handle = (event.target as Element).closest<HTMLElement>("[data-column]");+ if (!target || !handle || !event.isPrimary) {+ return;+ }++ event.preventDefault();+ if (this.menu) {+ this.menu.isOpen = false;+ }++ const column = Number(handle.dataset.column);+ if (handle.classList.contains("ck-table-column-bar__divider")) {+ this.startResize(event, column, target);+ } else {+ this.startPress(event, column, target);+ }+ }++ /** Selects the column on a tap, opens its menu on a long press and scrolls on a swipe. */+ private startPress(event: PointerEvent, column: number, { table, domTable }: BarTarget) {+ const scroller = findScroller(domTable, "overflowX");+ const startX = event.clientX;+ const startScroll = scroller.scrollLeft;+ let isLongPress = false;+ const timer = setTimeout(() => {+ isLongPress = true;+ vibrate();+ this.selectColumn(table, column);+ this.openMenu(column);+ }, LONG_PRESS_MS);+ const finish = () => {+ clearTimeout(timer);+ this.cancelGesture = null;+ };++ this.cancelGesture = trackPointer(event, this.view.track, {+ onMove: (clientX) => {+ clearTimeout(timer);+ if (!isLongPress) {+ scroller.scrollLeft = startScroll - (clientX - startX);+ }+ },+ onEnd: (isMoved) => {+ finish();+ if (!isMoved && !isLongPress) {+ this.selectColumn(table, column);+ }+ },+ onCancel: finish+ });+ }++ /**+ * Resizes `column` while the divider at its end is dragged. The table shows each width without+ * a change to the model, which takes the width at which the divider is released.+ */+ private startResize(event: PointerEvent, column: number, target: BarTarget) {+ const editor = this.editor;+ const { table, domContainer, domTable } = target;+ const direction = editor.locale.contentLanguageDirection === "rtl" ? -1 : 1;+ const columnCount = editor.plugins.get(TableUtils).getColumns(table);+ const edges = measureColumnEdges(editor, table, columnCount);+ /* v8 ignore next 3 -- defensive: the bar shows a rendered table */+ if (!edges) {+ return;+ }++ const widths = edges.slice(1).map((edge, index) => edge - edges[index]);+ const startWidth = widths[column];+ const minWidth = Math.min(MIN_COLUMN_WIDTH, startWidth);+ const gap = this.isCentered(table)+ ? getElementWidthInPixels(domContainer) - sum(widths)+ : null;+ const snapPoints = [startWidth, widths[column - 1], widths[column + 1]]+ .filter((width) => width !== undefined);+ const startX = event.clientX;+ let clientX = startX;+ let scrolled = 0;+ let width = startWidth;+ let snapPoint: number | null = startWidth;+ let preview: ResizePreview | null = null;+ let frame = 0;++ const resize = () => {+ const distance = (clientX - startX) * direction + scrolled;+ const growth = gap === null ? distance : getCenteredGrowth(distance, gap);+ const freeWidth = Math.max(startWidth + growth, minWidth);+ const nextSnapPoint = findSnapPoint(freeWidth, snapPoints);+ if (nextSnapPoint !== null && nextSnapPoint !== snapPoint) {+ vibrate();+ }+ snapPoint = nextSnapPoint;+ width = snapPoint ?? freeWidth;+ preview ??= this.startPreview(table, domTable, widths.length);+ this.showPreview(preview, replaceAt(widths, column, width));+ };++ const scrollStep = () => {+ const step = getAutoScrollStep(clientX, this.trackBox);+ if (step) {+ const scroller = findScroller(domTable, "overflowX");+ const scrollLeft = scroller.scrollLeft;+ scroller.scrollLeft += step;+ scrolled += (scroller.scrollLeft - scrollLeft) * direction;+ resize();+ }+ frame = requestAnimationFrame(scrollStep);+ };++ const finish = () => {+ cancelAnimationFrame(frame);+ this.cancelGesture = null;+ this.resizedColumn = null;+ if (preview) {+ this.endPreview(preview);+ }+ this.scheduleUpdate(true);+ };++ this.resizedColumn = column;+ this.cancelGesture = trackPointer(event, this.view.track, {+ onMove: (moveX) => {+ clientX = moveX;+ frame ||= requestAnimationFrame(scrollStep);+ resize();+ },+ onEnd: (isMoved) => {+ if (isMoved && width !== startWidth) {+ this.commit(target, replaceAt(widths, column, width));+ }+ finish();+ const isPair = column + 1 < widths.length;+ if (!isMoved && this.isDoubleTap(column) && isPair) {+ distributeColumns(editor, table, { first: column, last: column + 1 });+ }+ },+ onCancel: finish+ });+ this.scheduleUpdate(false);+ }++ /** Adds a column group to the view of `table` if it has none, for the widths of a preview. */+ private startPreview(table: ModelElement, domTable: HTMLElement, columnCount: number) {+ const view = this.editor.editing.view;+ const viewTable = view.domConverter.mapDomToView(domTable) as ViewElement;++ return view.change((writer): ResizePreview => {+ const existing = findColgroup(viewTable);+ const colgroup = existing ?? writer.createContainerElement("colgroup", null,+ Array.from({ length: columnCount }, () => writer.createEmptyElement("col")));+ if (!existing) {+ writer.insert(writer.createPositionAt(viewTable, 0), colgroup);+ }+ const isClassAdded = !viewTable.hasClass(RESIZED_TABLE_CLASS);+ writer.addClass(RESIZED_TABLE_CLASS, viewTable);+ return { table, viewTable, colgroup, isColgroupAdded: !existing, isClassAdded };+ });+ }++ /** Shows `widths` on the columns of the table, in pixels, without a change to the model. */+ private showPreview(preview: ResizePreview, widths: number[]) {+ this.editor.editing.view.change((writer) => {+ for (const [index, col] of getCols(preview.colgroup).entries()) {+ writer.setStyle("width", `${toPrecision(widths[index])}px`, col);+ }+ });+ const tableWidth = `${toPrecision(sum(widths))}px`;+ this.tableScroll._updateTableScrollOverflowState(preview.table, tableWidth);+ this.scheduleUpdate(true);+ }++ /** Shows the widths of the model on the table again. */+ private endPreview(preview: ResizePreview) {+ const { table, viewTable, colgroup, isColgroupAdded, isClassAdded } = preview;+ const savedWidths = getTableColumnsWidths(table);+ this.editor.editing.view.change((writer) => {+ if (isColgroupAdded) {+ if (colgroup.isAttached()) {+ writer.remove(colgroup);+ }+ } else {+ for (const [index, col] of getCols(colgroup).entries()) {+ writer.setStyle("width", savedWidths[index], col);+ }+ }+ if (isClassAdded && !savedWidths.length) {+ writer.removeClass(RESIZED_TABLE_CLASS, viewTable);+ }+ });+ this.tableScroll._updateTableScrollOverflowState(table);+ }++ private get tableScroll() {+ return this.editor.plugins.get(TriliumTableScroll);+ }++ /**+ * Saves `widths`, in pixels, as the column widths of the target table, and their sum as its+ * width. A table sized in pixels keeps pixels, any other one gets percentages.+ */+ private commit({ table, domFigure }: BarTarget, widths: number[]) {+ const editor = this.editor;+ const tableWidth = sum(widths);+ const savedWidth = table.getAttribute("tableWidth");+ if (typeof savedWidth === "string" && savedWidth.trim().endsWith("px")) {+ editor.execute("resizeTableWidth", {+ table,+ tableWidth: `${toPrecision(tableWidth)}px`,+ columnWidths: widths.map((width) => `${toPrecision(width)}px`)+ });+ return;+ }++ const basis = getTableWidthBasis(editor, table, domFigure);+ /* v8 ignore next 3 -- defensive: the bar shows a table with a width */+ if (!basis) {+ return;+ }++ editor.execute("resizeTableWidth", {+ table,+ tableWidth: `${toPrecision(tableWidth / basis * 100)}%`,+ columnWidths: widths.map((width) => `${toPrecision(width / tableWidth * 100)}%`)+ });+ }++ private selectColumn(table: ModelElement, column: number) {+ const editor = this.editor;+ const [slot] = new TableWalker(table, { column, includeAllSlots: true });+ editor.model.change((writer) => writer.setSelection(slot.cell, 0));+ editor.execute("selectTableColumn");+ }++ private openMenu(column: number) {+ if (!this.menu) {+ this.menu = this.editor.ui.componentFactory.create("tableColumn") as DropdownView;+ this.view.menus.add(this.menu);+ }+ this.view.placeMenu(column);+ this.menu.isOpen = true;+ }++ /** Whether a tap on the divider of `column` follows another one on it closely enough. */+ private isDoubleTap(column: number) {+ const now = performance.now();+ const lastTap = this.lastTap;+ const isDoubleTap = lastTap?.column === column && now - lastTap.time < DOUBLE_TAP_MS;+ this.lastTap = isDoubleTap ? null : { column, time: now };+ return isDoubleTap;+ }+}++interface BarTarget {+ table: ModelElement;+ domFigure: HTMLElement;+ domTable: HTMLElement;+ /** The element that holds the figure of the table. */+ domContainer: HTMLElement;+ domRoot: HTMLElement;+}++interface ResizePreview {+ table: ModelElement;+ viewTable: ViewElement;+ colgroup: ViewElement;+ isColgroupAdded: boolean;+ isClassAdded: boolean;+}++interface ClientBox {+ left: number;+ top: number;+ right: number;+ bottom: number;+}++/**+ * The part of the viewport that the bar spans: the visible part of the scroll container of+ * `domRoot`, up to the top of a toolbar at its bottom.+ */+function getBarArea(domRoot: HTMLElement, toolbar: HTMLElement | null): ClientBox {+ const area = getClientBox(findScroller(domRoot, "overflowY"));+ let bottom = Math.min(area.bottom, getViewportBottom());+ const toolbarRect = toolbar?.isConnected ? toolbar.getBoundingClientRect() : null;+ const isToolbarAtBottom = !!toolbarRect+ && toolbarRect.top < bottom && toolbarRect.bottom >= bottom - 1;+ if (isToolbarAtBottom) {+ bottom = toolbarRect.top;+ }+ return { ...area, bottom };+}++/** The bottom of the visual viewport, which is above an on-screen keyboard. */+function getViewportBottom() {+ const viewport = window.visualViewport;+ /* v8 ignore next 3 -- defensive: supported browsers have a visual viewport */+ if (!viewport) {+ return Infinity;+ }+ return viewport.offsetTop + viewport.height;+}++/** The box inside the borders and scroll bars of `element`, in the viewport. */+function getClientBox(element: HTMLElement): ClientBox {+ if (element === document.documentElement) {+ return { left: 0, top: 0, right: element.clientWidth, bottom: element.clientHeight };+ }++ const rect = element.getBoundingClientRect();+ const left = rect.left + element.clientLeft;+ const top = rect.top + element.clientTop;+ return { left, top, right: left + element.clientWidth, bottom: top + element.clientHeight };+}++/**+ * The closest ancestor of `element` that scrolls vertically, or that clips it horizontally, or the+ * document.+ */+function findScroller(element: HTMLElement, overflow: "overflowX" | "overflowY"): HTMLElement {+ const pattern = overflow === "overflowX" ? /auto|scroll|hidden|clip/ : /auto|scroll/;+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {+ if (pattern.test(getComputedStyle(parent)[overflow])) {+ return parent;+ }+ }+ return document.documentElement;+}++/**+ * The distance to scroll the table by while the pointer is at `x`: further the closer it is to an+ * end of the visible part of the table, and nothing away from them.+ */+function getAutoScrollStep(x: number, { left, right }: { left: number; right: number }) {+ let depth = 0;+ if (x > right - AUTO_SCROLL_EDGE) {+ depth = x - (right - AUTO_SCROLL_EDGE);+ } else if (x < left + AUTO_SCROLL_EDGE) {+ depth = x - (left + AUTO_SCROLL_EDGE);+ }++ const ratio = Math.max(-1, Math.min(1, depth / AUTO_SCROLL_EDGE));+ return Math.round(ratio * AUTO_SCROLL_STEP);+}++/**+ * How much a column of a centered table grows to move its end edge by `distance`. `gap` is the+ * width left in the container beside the table. The table stays centered while it fits, so the+ * edge moves half as far as the column grows, and once wider than its container it starts at the+ * container's start, so the edge moves as far as the column grows.+ */+export function getCenteredGrowth(distance: number, gap: number) {+ const room = Math.max(gap, 0);+ return distance >= gap - room / 2 ? distance + room / 2 : 2 * distance - gap + room;+}++/** The point of `points` closest to `width` within the snap distance, or `null`. */+export function findSnapPoint(width: number, points: readonly number[]): number | null {+ let closest: number | null = null;+ for (const point of points) {+ const distance = Math.abs(point - width);+ const isCloser = closest === null || distance < Math.abs(closest - width);+ if (distance <= SNAP_DISTANCE && isCloser) {+ closest = point;+ }+ }+ return closest;+}++function findColgroup(viewTable: ViewElement) {+ return Array.from(viewTable.getChildren())+ .find((child): child is ViewElement => child.is("element", "colgroup"));+}++function getCols(colgroup: ViewElement) {+ return Array.from(colgroup.getChildren())+ .filter((child): child is ViewElement => child.is("element", "col"));+}++function replaceAt(values: readonly number[], index: number, value: number) {+ const result = [...values];+ result[index] = value;+ return result;+}++function sum(values: readonly number[]) {+ return values.reduce((total, value) => total + value, 0);+}++function vibrate() {+ navigator.vibrate?.(VIBRATION_MS);+}++declare module "ckeditor5" {+ interface PluginsMap {+ [TableColumnBar.pluginName]: TableColumnBar;+ }+}diff --git a/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar_view.ts b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar_view.tsnew file mode 100644index 0000000000..fdd431a49d--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar_view.ts@@ -0,0 +1,146 @@+import { type DropdownView, type Locale, toUnit, View, type ViewCollection } from "ckeditor5";++const DIVIDER_CLASS = "ck-table-column-bar__divider";+const ACTIVE_DIVIDER_CLASS = "ck-table-column-bar__divider_active";++/** The place of the edge line in the viewport, in pixels. */+export interface EdgeBox {+ left: number;+ top: number;+ height: number;+}++/**+ * The bar of `TableColumnBar`: a segment for each column of a table and a divider at the end of+ * each segment, clipped to the visible part of the table.+ */+export default class TableColumnBarView extends View<HTMLDivElement> {++ declare isVisible: boolean;+ declare left: number;+ declare top: number;+ declare width: number;+ declare menuLeft: number;++ /** The visible part of the table, where the gestures start. */+ readonly track = createElement("ck-table-column-bar__track");+ readonly menus: ViewCollection<DropdownView>;+ /** The segments and dividers, positioned from the left edge of the table. */+ private readonly strip = createElement("ck-table-column-bar__strip");+ /** The line over the table at the edge being dragged. */+ private readonly edge = createElement("ck-table-column-bar__edge");++ constructor(locale: Locale) {+ super(locale);++ const bind = this.bindTemplate;+ const toPx = toUnit("px");+ this.set({ isVisible: false, left: 0, top: 0, width: 0, menuLeft: 0 });+ this.menus = this.createCollection();+ this.track.append(this.strip);+ this.edge.classList.add("ck-hidden");++ this.setTemplate({+ tag: "div",+ attributes: {+ class: [+ "ck",+ "ck-table-column-bar",+ bind.if("isVisible", "ck-hidden", (isVisible) => !isVisible)+ ],+ role: "group",+ "aria-label": locale.t("Table columns"),+ style: {+ left: bind.to("left", toPx),+ top: bind.to("top", toPx),+ width: bind.to("width", toPx)+ }+ },+ children: [+ this.track,+ this.edge,+ {+ tag: "div",+ attributes: {+ class: "ck-table-column-bar__menu",+ style: { left: bind.to("menuLeft", toPx) }+ },+ children: this.menus+ }+ ]+ });+ }++ /**+ * Shows the part of the table from `left` to `left + width` of the bar. `offset` is the+ * position of the table's left edge in that part.+ */+ setTrack(left: number, width: number, offset: number) {+ this.track.style.left = `${left}px`;+ this.track.style.width = `${width}px`;+ this.strip.style.transform = `translateX(${offset}px)`;+ }++ /**+ * Draws a segment between each two of `edges`, in pixels from the table's left edge, and a+ * divider labeled from `labels` at the end of each segment.+ */+ setColumns(edges: readonly number[], labels: readonly string[]) {+ if (this.strip.childElementCount !== labels.length * 2) {+ this.strip.replaceChildren();+ for (const column of labels.keys()) {+ const segment = createElement("ck-table-column-bar__segment");+ const divider = createElement(DIVIDER_CLASS);+ segment.dataset.column = String(column);+ divider.dataset.column = String(column);+ divider.setAttribute("role", "separator");+ divider.setAttribute("aria-orientation", "vertical");+ this.strip.append(segment, divider);+ }+ }++ for (const [column, label] of labels.entries()) {+ const start = edges[column];+ const end = edges[column + 1];+ const segment = this.strip.children[column * 2] as HTMLElement;+ const divider = this.strip.children[column * 2 + 1] as HTMLElement;+ segment.style.left = `${Math.min(start, end)}px`;+ segment.style.width = `${Math.abs(end - start)}px`;+ divider.style.left = `${end}px`;+ divider.setAttribute("aria-label", label);+ }+ }++ /** Highlights the divider of `column`, or none. */+ setActiveDivider(column: number | null) {+ for (const divider of this.strip.querySelectorAll<HTMLElement>(`.${DIVIDER_CLASS}`)) {+ const isActive = Number(divider.dataset.column) === column;+ divider.classList.toggle(ACTIVE_DIVIDER_CLASS, isActive);+ }+ }++ /** Shows the line over the table at `box`, or hides it. */+ setEdge(box: EdgeBox | null) {+ this.edge.classList.toggle("ck-hidden", !box);+ if (box) {+ this.edge.style.left = `${box.left}px`;+ this.edge.style.top = `${box.top}px`;+ this.edge.style.height = `${box.height}px`;+ }+ }++ /** Places the column menu over the middle of the visible part of the segment of `column`. */+ placeMenu(column: number) {+ const segmentRect = this.strip.children[column * 2].getBoundingClientRect();+ const trackRect = this.track.getBoundingClientRect();+ const left = Math.max(segmentRect.left, trackRect.left);+ const right = Math.min(segmentRect.right, trackRect.right);+ this.menuLeft = (left + right) / 2 - trackRect.left + this.track.offsetLeft;+ }+}++function createElement(className: string) {+ const element = document.createElement("div");+ element.className = className;+ return element;+}diff --git a/packages/ckeditor5/src/plugins/table_distribute_columns.ts b/packages/ckeditor5/src/plugins/table_distribute_columns.tsindex dfadbd061a..70f44aecd6 100644--- a/packages/ckeditor5/src/plugins/table_distribute_columns.ts+++ b/packages/ckeditor5/src/plugins/table_distribute_columns.ts@@ -30,24 +30,12 @@ export class DistributeTableColumnsCommand extends Command {override execute() {const target = this.findTarget();- const resize = this.editor.commands.get("resizeColumnWidths");- /* v8 ignore next 3 -- defensive: disabled without a target; requires TableColumnResize */- if (!target || !(resize instanceof TableWidthsCommand)) {+ /* v8 ignore next 3 -- defensive: disabled without a target */+ if (!target) {return;}- const { table, columns } = target;- const current = readColumnWidths(this.editor, table);- if (!current) {- return;- }-- const widths = equalizeWidths(current.values, columns);- resize.execute({- table,- tableWidth: current.tableWidth,- columnWidths: widths.map((width) => `${width}${current.unit}`)- });+ distributeColumns(this.editor, target.table, target.columns);}private findTarget(): { table: ModelElement; columns: IndexRange } | null {@@ -65,6 +53,27 @@ export class DistributeTableColumnsCommand extends Command {}+/** Gives `columns` of `table` an equal share of their combined width, in one undo step. */+export function distributeColumns(editor: Editor, table: ModelElement, columns: IndexRange) {+ const resize = editor.commands.get("resizeColumnWidths");+ /* v8 ignore next 3 -- defensive: requires TableColumnResize */+ if (!(resize instanceof TableWidthsCommand)) {+ return;+ }++ const current = readColumnWidths(editor, table);+ if (!current) {+ return;+ }++ const widths = equalizeWidths(current.values, columns);+ resize.execute({+ table,+ tableWidth: current.tableWidth,+ columnWidths: widths.map((width) => `${width}${current.unit}`)+ });+}+/*** The columns covered by `cells`, including every column a merged cell spans.* `TableUtils.getColumnIndexes()` only reports the column each cell starts in.@@ -171,15 +180,37 @@ function parseUniformWidths(widths: string[]): { values: number[]; unit: WidthUn}/**- * Measures the rendered width of every column in pixels from the edges of the cells that start or- * end at each column boundary. A boundary that no cell starts or ends at, because merged cells- * cross it in every row, is placed proportionally between its nearest measured neighbors.- * Returns `null` when the table is not rendered with a width, e.g. inside a hidden element.+ * Measures the rendered width of every column in pixels. Returns `null` when the table is not+ * rendered with a width, e.g. inside a hidden element.*/function measureColumnWidths(editor: Editor,table: ModelElement,columnCount: number+): number[] | null {+ const edges = measureColumnEdges(editor, table, columnCount);+ /* v8 ignore next 3 -- defensive: the first and the last boundary always have a cell edge */+ if (!edges) {+ return null;+ }++ const widths: number[] = [];+ for (let column = 0; column < columnCount; column++) {+ widths.push(Math.max(0, edges[column + 1] - edges[column]));+ }+ return widths.some((width) => width > 0) ? widths : null;+}++/**+ * Measures the `columnCount + 1` column boundaries of `table` from the edges of the cells that+ * start or end at each one. A boundary that no cell starts or ends at, because merged cells cross+ * it in every row, is placed proportionally between its nearest measured neighbors. The positions+ * are client x coordinates, negated in right-to-left content so that they grow along the row.+ */+export function measureColumnEdges(+ editor: Editor,+ table: ModelElement,+ columnCount: number): number[] | null {const isRtl = editor.locale.contentLanguageDirection === "rtl";const edgeSamples: number[][] = Array.from({ length: columnCount + 1 }, () => []);@@ -220,12 +251,7 @@ function measureColumnWidths(edges[boundary] = edge;previous = boundary;}-- const widths: number[] = [];- for (let column = 0; column < columnCount; column++) {- widths.push(Math.max(0, edges[column + 1] - edges[column]));- }- return widths.some((width) => width > 0) ? widths : null;+ return edges;}/**@@ -236,17 +262,13 @@ function measureColumnWidths(function measureTableWidthShare(editor: Editor, table: ModelElement): string | null {const viewFigure = editor.editing.mapper.toViewElement(table);const domFigure = viewFigure && editor.editing.view.domConverter.mapViewToDom(viewFigure);- const domParent = domFigure?.parentElement;/* v8 ignore next 3 -- defensive: a measured table is rendered inside the editable */- if (!(domFigure instanceof HTMLElement) || !domParent) {+ if (!(domFigure instanceof HTMLElement)) {return null;}- const tableScroll = editor.plugins.has(TriliumTableScroll)- ? editor.plugins.get(TriliumTableScroll)- : null;- const parentWidth = tableScroll?.getReferenceWidth(table) ?? getElementWidthInPixels(domParent);- if (!(parentWidth > 0)) {+ const parentWidth = getTableWidthBasis(editor, table, domFigure);+ if (!parentWidth) {return null;}@@ -254,3 +276,21 @@ function measureTableWidthShare(editor: Editor, table: ModelElement): string | nconst width = Math.max(tableWidth, getElementWidthInPixels(domFigure));return `${toPrecision(width / parentWidth * 100)}%`;}++/**+ * The width in pixels that a percentage width of `table` is a share of: the reference width where+ * one applies, otherwise the content width of the parent of `domFigure`. `null` when it is zero.+ */+export function getTableWidthBasis(editor: Editor, table: ModelElement, domFigure: HTMLElement) {+ const domParent = domFigure.parentElement;+ /* v8 ignore next 3 -- defensive: a rendered table is inside the editable */+ if (!domParent) {+ return null;+ }++ const tableScroll = editor.plugins.has(TriliumTableScroll)+ ? editor.plugins.get(TriliumTableScroll)+ : null;+ const width = tableScroll?.getReferenceWidth(table) ?? getElementWidthInPixels(domParent);+ return width > 0 ? width : null;+}diff --git a/packages/ckeditor5/src/theme/table_column_bar.css b/packages/ckeditor5/src/theme/table_column_bar.cssnew file mode 100644index 0000000000..028bc63ba2--- /dev/null+++ b/packages/ckeditor5/src/theme/table_column_bar.css@@ -0,0 +1,85 @@+:where(:root) {+ --ck-table-column-bar-background: var(--main-background-color, var(--ck-color-base-background));+ --ck-table-column-bar-border-color: var(--main-border-color, var(--ck-color-base-border));+ --ck-table-column-bar-segment-color:+ var(--accented-background-color, var(--ck-color-base-hover));+ --ck-table-column-bar-divider-color: var(--main-border-color, var(--ck-color-base-border));+ --ck-table-column-bar-active-color: var(--ck-color-focus-border);++ --ck-table-column-bar-height: 28px;+ --ck-table-column-bar-divider-hit-width: 24px;+}++/* Outranks the `.ck-reset_all` rules of the body collection. */+.ck-reset_all .ck.ck-table-column-bar {+ position: fixed;+ z-index: var(--ck-z-panel);+ border-top: 1px solid var(--ck-table-column-bar-border-color);+ box-sizing: border-box;+ height: var(--ck-table-column-bar-height);+ background: var(--ck-table-column-bar-background);+ touch-action: none;+ user-select: none;+ -webkit-user-select: none;+ -webkit-touch-callout: none;++ .ck-table-column-bar__track {+ position: absolute;+ inset-block: 0;+ overflow: hidden;+ }++ .ck-table-column-bar__strip {+ position: absolute;+ inset: 0;+ }++ .ck-table-column-bar__segment {+ position: absolute;+ inset-block: 4px;+ background: var(--ck-table-column-bar-segment-color);+ }++ .ck-table-column-bar__divider {+ position: absolute;+ inset-block: 0;+ width: var(--ck-table-column-bar-divider-hit-width);+ translate: -50%;++ &::after {+ position: absolute;+ inset-block: 2px;+ left: 50%;+ width: 2px;+ content: "";+ background: var(--ck-table-column-bar-divider-color);+ translate: -50%;+ }++ &.ck-table-column-bar__divider_active::after {+ background: var(--ck-table-column-bar-active-color);+ }+ }++ .ck-table-column-bar__edge {+ position: fixed;+ width: 2px;+ background: var(--ck-table-column-bar-active-color);+ translate: -50%;+ pointer-events: none;+ }++ .ck-table-column-bar__menu {+ position: absolute;+ top: 0;+ translate: -50%;++ > .ck-dropdown > .ck-dropdown__button {+ visibility: hidden;+ }++ .ck-dropdown__panel {+ visibility: visible;+ }+ }+}