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: add support for selecting a range of cells using a touchscreen
Adorian Doran6c9a0752eb43
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 a9e69e217b..eb1afea44e 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@@ -137,6 +137,16 @@ src="3_Tables_image.png" width="384" height="100"><li>To select multiple cells, hold <kbd>Shift</kbd> while using the arrow keys.</li></ul></li>+ <li>Using touch:+ <ul>+ <li>Since v0.107.0, touching a table outlines the cell with the cursor, or+ the selected cells, and shows a handle at each corner of the outline.</li>+ <li>To select multiple cells, drag one of the handles across the table. The+ cell at the opposite corner stays selected, so the selection grows or shrinks+ as the finger moves. The note and wide tables scroll when the handle reaches+ the edge of the screen.</li>+ </ul>+ </li></ul><h2>Resizing cells</h2><ul>diff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex 719c8e22ef..bfcc12392e 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -61,6 +61,9 @@ Right-clicking a cell that is not part of the current selection moves the cursor* It's also possible to use <kbd>Tab</kbd> to go to the next cell and Shift+Tab to go to the previous cell.* Unlike arrow keys, pressing <kbd>Tab</kbd> at the end of the table (last row, last column) will create a new row automatically.* To select multiple cells, hold <kbd>Shift</kbd> while using the arrow keys.+* Using touch:+ * Since v0.107.0, touching a table outlines the cell with the cursor, or the selected cells, and shows a handle at each corner of the outline.+ * To select multiple cells, drag one of the handles across the table. The cell at the opposite corner stays selected, so the selection grows or shrinks as the finger moves. The note and wide tables scroll when the handle reaches the edge of the screen.## Resizing cellsdiff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex d93e32248e..e9e9db320a 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -76,6 +76,7 @@ import TableToolbarDropdowns from "./plugins/table_toolbar_dropdowns.js";import TriliumTableScroll from "./plugins/table_scroll.js";import TableStickyHeader from "./plugins/table_sticky_header.js";import TableColumnBar from "./plugins/table_column_bar/table_column_bar.js";+import TableTouchSelection from "./plugins/table_touch_selection/table_touch_selection.js";import ToolbarGroupMenu from "./plugins/toolbar_group_menu.js";import BlockDragHandle from "./plugins/block_drag_handle.js";@@ -123,6 +124,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [TriliumTableScroll,TableStickyHeader,TableColumnBar,+ TableTouchSelection,ToolbarGroupMenu,CopyAnchorLinkButton,CopyLinkUrlButton,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.tsindex 9ab92a1a1d..4554b82cd2 100644--- a/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.ts+++ b/packages/ckeditor5/src/plugins/table_column_bar/table_column_bar.ts@@ -21,6 +21,13 @@ import {measureColumnEdges} from "../table_distribute_columns.js";import TriliumTableScroll from "../table_scroll.js";+import {+ type ClientBox,+ findScroller,+ getAutoScrollStep,+ getClientBox,+ getViewportBottom+} from "../viewport_geometry.js";import { trackPointer } from "./pointer_tracking.js";import TableColumnBarView from "./table_column_bar_view.js";@@ -29,10 +36,6 @@ 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";/**@@ -386,7 +389,7 @@ export default class TableColumnBar extends Plugin {};const scrollStep = () => {- const step = getAutoScrollStep(clientX, this.trackBox);+ const step = getAutoScrollStep(clientX, this.trackBox.left, this.trackBox.right);if (step) {const scroller = findScroller(domTable, "overflowX");const scrollLeft = scroller.scrollLeft;@@ -561,13 +564,6 @@ interface Tap {time: number;}-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.@@ -584,58 +580,6 @@ function getBarArea(domRoot: HTMLElement, toolbar: HTMLElement | null): ClientBoreturn { ...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 thediff --git a/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection.spec.ts b/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection.spec.tsnew file mode 100644index 0000000000..9c8ddf645b--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection.spec.ts@@ -0,0 +1,654 @@+import {+ _setModelData as setModelData,+ ClassicEditor,+ Essentials,+ Paragraph,+ Table,+ TableColumnResize,+ TableSelection+} from "ckeditor5";+import type { Editor, ModelElement } from "ckeditor5";+import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";+import { afterAll, beforeAll, beforeEach, describe, expect, it, onTestFinished } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import { modelTable, scrollFigure } from "../../../test/table-kit.js";+import TriliumTableScroll from "../table_scroll.js";+import TableTouchSelection from "./table_touch_selection.js";++const PLUGINS = [+ Essentials,+ Paragraph,+ Table,+ TableColumnResize,+ TriliumTableScroll,+ TableTouchSelection+];+const TOUCH_ID = 1;+const TOP_LEFT = 0;+const TOP_RIGHT = 1;+const BOTTOM_LEFT = 2;+const BOTTOM_RIGHT = 3;++const GRID = modelTable(+ [["a[]", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]],+ 'tableWidth="100%"'+);++describe("TableTouchSelection", () => {+ const link = document.createElement("link");+ let editor: ClassicEditor;++ 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 () => {+ editor = await createTestEditor(PLUGINS);+ editor.ui.element?.style.setProperty("width", "400px");+ });++ describe("overlay", () => {+ it("outlines the cell with the caret after a touch, until a mouse press", async () => {+ setModelData(editor.model, GRID);+ editor.editing.view.focus();+ await expect.poll(() => editor.ui.focusTracker.isFocused).toBe(true);+ await frames();+ expect(overlay(editor).isVisible).toBe(false);+ expect(touchStartOn(rootOf(editor), 0, 0).defaultPrevented).toBe(false);++ touch();+ touch();+ await expect.poll(() => overlay(editor).isVisible).toBe(true);+ expectAround(editor, [0, 0], [0, 0]);+ expect(overlay(editor).element?.getAttribute("aria-hidden")).toBe("true");++ touch("mouse");+ await expect.poll(() => overlay(editor).isVisible).toBe(false);+ });++ it("outlines the selected cells, and hides for text, outside tables, blurred or disabled",+ async () => {+ await showHandles(editor, `${GRID}<paragraph>x</paragraph>`);+ selectCells(editor, [0, 1], [1, 2]);+ const rightGap = () => outlineRectOf(editor).right - cellRect(editor, 1, 2).right;+ await expect.poll(() => Math.abs(rightGap())).toBeLessThan(1.5);+ expectAround(editor, [0, 1], [1, 2]);++ editor.model.change((writer) => {+ writer.setSelection(writer.createRangeIn(paragraphIn(cell(editor, 1, 1))));+ });+ await expect.poll(() => overlay(editor).isVisible).toBe(false);++ setCaret(editor, cell(editor, 2, 2));+ await expect.poll(() => overlay(editor).isVisible).toBe(true);+ expectAround(editor, [2, 2], [2, 2]);++ setCaret(editor, rootChild(editor, 1));+ await expect.poll(() => overlay(editor).isVisible).toBe(false);+ setCaret(editor, cell(editor, 0, 0));+ await expect.poll(() => overlay(editor).isVisible).toBe(true);++ const tableSelection = editor.plugins.get(TableSelection);+ tableSelection.forceDisabled("spec");+ await expect.poll(() => overlay(editor).isVisible).toBe(false);+ tableSelection.clearForceDisabled("spec");+ await expect.poll(() => overlay(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(() => overlay(editor).isVisible).toBe(false);+ });++ it("hides while the cells are out of view", async () => {+ await showHandles(editor, GRID);+ const editorElement = editor.ui.element as HTMLElement;++ editorElement.style.marginTop = "200vh";+ window.dispatchEvent(new Event("resize"));+ await expect.poll(() => overlay(editor).isVisible).toBe(false);+ expect(touchStartOn(rootOf(editor), 0, 0).defaultPrevented).toBe(false);++ editorElement.style.marginTop = "";+ editorElement.style.marginLeft = "-200vw";+ window.dispatchEvent(new Event("resize"));+ await frames();+ expect(overlay(editor).isVisible).toBe(false);++ editorElement.style.marginLeft = "";+ window.visualViewport?.dispatchEvent(new Event("resize"));+ await expect.poll(() => overlay(editor).isVisible).toBe(true);+ });++ it("hides the handles beyond either side of a table that scrolls sideways", async () => {+ await showHandles(editor, modelTable(+ [["a[]", "b", "c", "d"], ["e", "f", "g", "h"]],+ 'tableWidth="200%"'+ ));+ selectCells(editor, [0, 0], [1, 3]);+ await expect.poll(() => shownHandles(editor)).toEqual([TOP_LEFT, BOTTOM_LEFT]);++ const figure = domCell(editor, cell(editor, 0, 0)).closest("figure");+ if (!figure) {+ throw new Error("The table has no figure.");+ }+ const hidden = { x: cellRect(editor, 0, 3).right, y: cellRect(editor, 0, 3).top };+ touchStartOn(rootOf(editor), hidden.x, hidden.y);+ expect(touchMove(hidden.x - 50, hidden.y + 50).defaultPrevented).toBe(false);+ touchEnd();++ await scrollFigure(figure, figure.scrollWidth);+ await expect.poll(() => shownHandles(editor)).toEqual([TOP_RIGHT, BOTTOM_RIGHT]);+ expectAround(editor, [0, 0], [1, 3]);+ });++ it("hides the handles above the scroll container and behind the viewport offset",+ async () => {+ const scroller = wrapInScroller(editor, 200);+ const paragraphs = "<paragraph>x</paragraph>".repeat(8);+ await showHandles(editor, `<paragraph>x</paragraph>${GRID}${paragraphs}`);+ const scrollerTop = scroller.getBoundingClientRect().top;+ scroller.scrollTop += cellRect(editor, 0, 0, 1).top - scrollerTop + 10;+ await expect.poll(() => shownHandles(editor)).toEqual([BOTTOM_LEFT, BOTTOM_RIGHT]);+ expectAround(editor, [0, 0], [0, 0], 1);++ const ui = editor.ui;+ const bottom = window.innerHeight - cellRect(editor, 0, 0, 1).bottom + 5;+ ui.viewportOffset = { left: 0, right: 0, bottom };+ ui.update();+ await expect.poll(() => shownHandles(editor)).toEqual([]);+ expect(overlay(editor).isVisible).toBe(true);+ });++ it("follows the cells when the table moves and into another table", async () => {+ // A table without a width stays centered, so it moves when the editable resizes.+ const second = modelTable([["c", "d"], ["e", "f"]]);+ const first = modelTable([["a[]", "b"]]);+ await showHandles(editor, `${first}<paragraph>x</paragraph>${second}`);+ editor.ui.element?.style.setProperty("width", "300px");+ const rightGap = () => outlineRectOf(editor).right - cellRect(editor, 0, 0).right;+ await expect.poll(() => Math.abs(rightGap())).toBeLessThan(1.5);++ setCaret(editor, cell(editor, 1, 1, 2));+ const topGap = () => outlineRectOf(editor).top - cellRect(editor, 1, 1, 2).top;+ await expect.poll(() => Math.abs(topGap())).toBeLessThan(1.5);+ expectAround(editor, [1, 1], [1, 1], 2);+ });+ });++ describe("dragging", () => {+ it("grows and shrinks the selection with the handle at the bottom right", async () => {+ await showHandles(editor, GRID);+ const handle = handleCenter(editor, BOTTOM_RIGHT);+ // The finger lands below the handle, which then keeps that distance from it.+ const finger = { x: handle.x - 6, y: handle.y + 20 };+ const moveHandleTo = (row: number, column: number) => {+ const { x, y } = centerOf(cellRect(editor, row, column));+ return touchMove(x - 6, y + 20);+ };++ expect(touchStart(finger.x, finger.y).defaultPrevented).toBe(false);+ expect(overlay(editor).isDragging).toBe(false);++ expect(moveHandleTo(1, 1).defaultPrevented).toBe(true);+ expect(overlay(editor).isDragging).toBe(true);+ expect(overlay(editor).element?.classList.contains("ck-table-touch-selection_dragging"))+ .toBe(true);+ expect(selectedCells(editor)).toEqual(["0,0", "0,1", "1,0", "1,1"]);+ await frames();+ expectAround(editor, [0, 0], [1, 1]);++ moveHandleTo(2, 2);+ expect(selectedCells(editor)).toHaveLength(9);+ moveHandleTo(1, 1);+ expect(selectedCells(editor)).toEqual(["0,0", "0,1", "1,0", "1,1"]);+ moveHandleTo(0, 0);+ expect(selectedCells(editor)).toEqual(["0,0"]);+ moveHandleTo(0, 1);+ expect(selectedCells(editor)).toEqual(["0,0", "0,1"]);++ touchEnd();+ expect(overlay(editor).isDragging).toBe(false);+ await frames();+ expectAround(editor, [0, 0], [0, 1]);+ });++ it("keeps the cell at the opposite corner selected", async () => {+ await showHandles(editor, GRID);+ selectCells(editor, [1, 1], [2, 2]);+ const topGap = () => outlineRectOf(editor).top - cellRect(editor, 1, 1).top;+ await expect.poll(() => Math.abs(topGap())).toBeLessThan(1.5);++ const handle = handleCenter(editor, TOP_LEFT);+ touchStart(handle.x, handle.y);+ moveTo(centerOf(cellRect(editor, 0, 0)));+ expect(selectedCells(editor)).toHaveLength(9);+ moveTo(centerOf(cellRect(editor, 2, 2)));+ expect(selectedCells(editor)).toEqual(["2,2"]);+ moveTo(centerOf(cellRect(editor, 2, 1)));+ expect(selectedCells(editor)).toEqual(["2,1", "2,2"]);+ touchEnd();+ });++ it("drags the closest handle within reach", async () => {+ await showHandles(editor, GRID);+ const rect = cellRect(editor, 0, 0);+ const target = centerOf(cellRect(editor, 1, 0));+ expect(rect.height).toBeLessThan(40);++ // Both handles on the left edge are within reach, and the closer one moves.+ const nearTop = rect.height * 0.4;+ touchStart(rect.left, rect.top + nearTop);+ touchMove(target.x, target.y + nearTop);+ expect(selectedCells(editor)).toEqual(["0,0", "1,0"]);+ touchEnd();++ setCaret(editor, cell(editor, 0, 0));+ await expect.poll(() => selectedCells(editor)).toEqual(["text"]);+ await frames();+ const nearBottom = rect.height * 0.4;+ touchStart(rect.left, rect.bottom - nearBottom);+ touchMove(target.x, target.y - nearBottom);+ expect(selectedCells(editor)).toEqual(["0,0", "1,0"]);+ touchEnd();+ });++ it("leaves taps and touches away from the handles to the browser", async () => {+ await showHandles(editor, GRID);+ const center = centerOf(cellRect(editor, 0, 0));++ touchStart(center.x, center.y);+ expect(touchMove(center.x + 30, center.y + 30).defaultPrevented).toBe(false);+ touchEnd();+ expect(touchMove(center.x, center.y).defaultPrevented).toBe(false);++ const handle = handleCenter(editor, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);+ touchEnd();+ touchEnd();+ expect(touchMove(center.x, center.y).defaultPrevented).toBe(false);+ expect(selectedCells(editor)).toEqual(["text"]);+ });++ it("lets the browser scroll when it does not let the first move be canceled", async () => {+ await showHandles(editor, GRID);+ const handle = handleCenter(editor, BOTTOM_RIGHT);+ const target = centerOf(cellRect(editor, 1, 1));++ touchStart(handle.x, handle.y);+ expect(touchMove(target.x, target.y, { cancelable: false }).defaultPrevented)+ .toBe(false);+ expect(touchMove(target.x, target.y).defaultPrevented).toBe(false);+ expect(overlay(editor).isDragging).toBe(false);+ expect(selectedCells(editor)).toEqual(["text"]);+ });++ it("ends the drag on a second finger, on touchcancel and when the handles hide",+ async () => {+ await showHandles(editor, GRID);+ let handle = handleCenter(editor, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);+ moveTo(centerOf(cellRect(editor, 1, 1)));+ expect(overlay(editor).isDragging).toBe(true);+ secondFingerDown(handle.x, handle.y);+ expect(overlay(editor).isDragging).toBe(false);+ expect(touchMove(handle.x, handle.y).defaultPrevented).toBe(false);+ touchEnd();++ await frames();+ handle = handleCenter(editor, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);+ moveTo(centerOf(cellRect(editor, 2, 2)));+ expect(touchMove(handle.x, handle.y, { identifier: 2 }).defaultPrevented)+ .toBe(false);+ touchEnd(2);+ expect(overlay(editor).isDragging).toBe(true);+ touchEnd(TOUCH_ID, "touchcancel");+ expect(overlay(editor).isDragging).toBe(false);+ expect(selectedCells(editor)).toHaveLength(9);++ await frames();+ handle = handleCenter(editor, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);+ moveTo(centerOf(cellRect(editor, 1, 1)));+ const editorElement = editor.ui.element as HTMLElement;+ editorElement.style.marginTop = "200vh";+ window.dispatchEvent(new Event("resize"));+ await expect.poll(() => overlay(editor).isDragging).toBe(false);+ touchEnd();+ editorElement.style.marginTop = "";++ await showHandles(editor, GRID);+ handle = handleCenter(editor, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);+ moveTo(centerOf(cellRect(editor, 1, 1)));+ (document.activeElement as HTMLElement | null)?.blur();+ await expect.poll(() => overlay(editor).isDragging).toBe(false);+ });++ it("selects up to the cells at the edge when the handle leaves the table", async () => {+ await showHandles(editor, GRID);+ const handle = handleCenter(editor, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);+ touchMove(handle.x + 1000, handle.y + 1000);+ expect(selectedCells(editor)).toHaveLength(9);+ touchMove(handle.x - 1000, handle.y - 1000);+ expect(selectedCells(editor)).toEqual(["0,0"]);+ touchEnd();+ });++ it("selects only cells of its own table", async () => {+ const nested = modelTable([["x", "y"]]);+ await showHandles(editor, "<table><tableRow>" ++ "<tableCell><paragraph>a[]</paragraph></tableCell>" ++ `<tableCell>${nested}</tableCell>` ++ "</tableRow><tableRow>" ++ "<tableCell><paragraph>c</paragraph></tableCell>" ++ "<tableCell><paragraph>d</paragraph></tableCell>" ++ "</tableRow></table>");+ const handle = handleCenter(editor, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);++ moveTo(centerOf(domCell(editor, cellAtPath(editor, [0, 0, 1, 0, 0, 0]))+ .getBoundingClientRect()));+ expect(selectedCells(editor)).toEqual(["0,0", "0,1"]);++ const cover = coverWithForeignTable(cellRect(editor, 1, 0));+ moveTo(centerOf(cover.getBoundingClientRect()));+ expect(selectedCells(editor)).toEqual(["0,0", "1,0"]);++ domCell(editor, cell(editor, 1, 1)).style.pointerEvents = "none";+ moveTo(centerOf(cellRect(editor, 1, 1)));+ expect(selectedCells(editor)).toEqual(["0,0", "1,0"]);+ touchEnd();+ });++ it("scrolls the container of the editable while the handle is near its edge",+ async () => {+ const scroller = wrapInScroller(editor, 150);+ const rows = Array.from({ length: 12 }, (_, row) => [`r${row}`, "x"]);+ rows[0][0] = "a[]";+ await showHandles(editor, modelTable(rows));+ const handle = handleCenter(editor, BOTTOM_RIGHT);+ const scrollerRect = scroller.getBoundingClientRect();++ touchStart(handle.x, handle.y);+ touchMove(handle.x, scrollerRect.top + scroller.clientHeight - 5);+ await expect.poll(() => scroller.scrollTop).toBeGreaterThan(100);+ await expect.poll(() => selectedCells(editor).length).toBeGreaterThan(14);++ touchEnd();+ const scrollTop = scroller.scrollTop;+ await frames();+ expect(scroller.scrollTop).toBe(scrollTop);+ });++ it("scrolls a wide table sideways while the handle is near its edge", async () => {+ await showHandles(editor, modelTable(+ [["a[]", "b", "c", "d"], ["e", "f", "g", "h"]],+ 'tableWidth="200%"'+ ));+ const figure = domCell(editor, cell(editor, 0, 0)).closest("figure");+ if (!figure) {+ throw new Error("The table has no figure.");+ }+ const handle = handleCenter(editor, BOTTOM_RIGHT);+ const figureRect = figure.getBoundingClientRect();++ touchStart(handle.x, handle.y);+ touchMove(figureRect.left + figure.clientWidth - 5, handle.y);+ await expect.poll(() => figure.scrollLeft).toBeGreaterThan(0);+ await expect.poll(() => selectedCells(editor)).toContain("0,3");+ touchEnd();+ });++ it("ends the drag 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 showHandles(own, GRID);++ const handle = handleCenter(own, BOTTOM_RIGHT);+ touchStart(handle.x, handle.y);+ moveTo(centerOf(cellRect(own, 1, 1)));+ await own.destroy();+ element.remove();+ touchMove(handle.x + 20, handle.y + 20);+ touchEnd();+ });+ });+});++let touchTarget: EventTarget = document.body;++/** 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 showHandles(editor: Editor, data: string) {+ setModelData(editor.model, data);+ editor.editing.view.focus();+ touch();+ await expect.poll(() => overlay(editor).isVisible).toBe(true);+}++function touch(pointerType = "touch") {+ document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, pointerType }));+}++/** Puts the finger down at `x`, `y`, on the element there. */+function touchStart(x: number, y: number) {+ return touchStartOn(document.elementFromPoint(x, y) ?? document.body, x, y);+}++function touchStartOn(target: EventTarget, x: number, y: number) {+ touchTarget = target;+ const touch = createTouch(x, y);+ return dispatchTouch("touchstart", [touch], [touch]);+}++function secondFingerDown(x: number, y: number) {+ const second = createTouch(x, y, 2);+ return dispatchTouch("touchstart", [createTouch(x, y), second], [second]);+}++function touchMove(x: number, y: number, { identifier = TOUCH_ID, cancelable = true } = {}) {+ const touch = createTouch(x, y, identifier);+ return dispatchTouch("touchmove", [touch], [touch], cancelable);+}++function moveTo({ x, y }: { x: number; y: number }) {+ return touchMove(x, y);+}++function touchEnd(identifier = TOUCH_ID, type = "touchend") {+ return dispatchTouch(type, [], [createTouch(0, 0, identifier)]);+}++function createTouch(clientX: number, clientY: number, identifier = TOUCH_ID) {+ return new Touch({ identifier, target: touchTarget, clientX, clientY });+}++function dispatchTouch(+ type: string,+ touches: Touch[],+ changedTouches: Touch[],+ cancelable = true+) {+ const event = new TouchEvent(type, {+ bubbles: true,+ cancelable,+ touches,+ targetTouches: touches,+ changedTouches+ });+ touchTarget.dispatchEvent(event);+ return event;+}++function overlay(editor: Editor) {+ return editor.plugins.get(TableTouchSelection).view;+}++function outlineRectOf(editor: Editor) {+ const outline = overlay(editor).element?.querySelector(".ck-table-touch-selection__outline");+ return outline?.getBoundingClientRect() ?? new DOMRect();+}++/** The indexes in `CORNERS` of the handles that are shown. */+function shownHandles(editor: Editor) {+ return overlay(editor).handles.flatMap((handle, index) =>+ handle.classList.contains("ck-hidden") ? [] : [index]);+}++function handleCenter(editor: Editor, corner: number) {+ const handle = overlay(editor).handles[corner];+ if (handle.classList.contains("ck-hidden")) {+ throw new Error(`The handle ${corner} is hidden.`);+ }+ return centerOf(handle.getBoundingClientRect());+}++/**+ * Expects the outline and the handles around the cells from `first` to `last`, given as row and+ * child indexes in the table at `tableIndex` of the root.+ */+function expectAround(+ editor: Editor,+ first: [number, number],+ last: [number, number],+ tableIndex = 0+) {+ const firstRect = cellRect(editor, ...first, tableIndex);+ const lastRect = cellRect(editor, ...last, tableIndex);+ const outlineRect = outlineRectOf(editor);+ expectNear(outlineRect.left, firstRect.left);+ expectNear(outlineRect.top, firstRect.top);+ expectNear(outlineRect.right, lastRect.right);+ expectNear(outlineRect.bottom, lastRect.bottom);++ const corners = [+ { x: firstRect.left, y: firstRect.top },+ { x: lastRect.right, y: firstRect.top },+ { x: firstRect.left, y: lastRect.bottom },+ { x: lastRect.right, y: lastRect.bottom }+ ];+ for (const corner of shownHandles(editor)) {+ const center = handleCenter(editor, corner);+ expectNear(center.x, corners[corner].x);+ expectNear(center.y, corners[corner].y);+ }+}++function expectNear(actual: number, expected: number) {+ expect(Math.abs(actual - expected)).toBeLessThan(1.5);+}++function centerOf(rect: DOMRect) {+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };+}++/** The cell at `row` and child index `column` of the table at `tableIndex` of the root. */+function cell(editor: Editor, row: number, column: number, tableIndex = 0) {+ return cellAtPath(editor, [tableIndex, row, column]);+}++function cellAtPath(editor: Editor, path: number[]): ModelElement {+ const node = editor.model.document.getRoot()?.getNodeByPath(path);+ if (!node?.is("element", "tableCell")) {+ throw new Error(`No table cell at ${path.join(", ")}.`);+ }+ return node;+}++function domCell(editor: Editor, modelCell: ModelElement) {+ const viewCell = editor.editing.mapper.toViewElement(modelCell);+ const element = viewCell && editor.editing.view.domConverter.mapViewToDom(viewCell);+ if (!(element instanceof HTMLElement)) {+ throw new Error("The cell is not rendered.");+ }+ return element;+}++function cellRect(editor: Editor, row: number, column: number, tableIndex = 0) {+ return domCell(editor, cell(editor, row, column, tableIndex)).getBoundingClientRect();+}++function rootChild(editor: Editor, index: number) {+ const child = editor.model.document.getRoot()?.getChild(index);+ if (!child?.is("element")) {+ throw new Error(`No element at ${index} in the root.`);+ }+ return child;+}++function paragraphIn(element: ModelElement) {+ const paragraph = element.getChild(0);+ if (!paragraph?.is("element", "paragraph")) {+ throw new Error("The cell has no paragraph.");+ }+ return paragraph;+}++function setCaret(editor: Editor, element: ModelElement) {+ editor.model.change((writer) => writer.setSelection(element, 0));+}++function selectCells(editor: Editor, anchor: [number, number], target: [number, number]) {+ const tableSelection = editor.plugins.get(TableSelection);+ tableSelection.setCellSelection(cell(editor, ...anchor), cell(editor, ...target));+}++/** The selected cells as `row,column` child indexes, sorted, or `text` for a text selection. */+function selectedCells(editor: Editor) {+ return [...editor.model.document.selection.getRanges()].map((range) => {+ const node = range.start.nodeAfter;+ if (!node?.is("element", "tableCell")) {+ return "text";+ }+ return `${node.findAncestor("tableRow")?.index},${node.index}`;+ }).sort();+}++function rootOf(editor: Editor) {+ const root = editor.editing.view.getDomRoot();+ if (!root) {+ throw new Error("The editor has no editable.");+ }+ return root;+}++/** Puts the editor in a scroll container `height` pixels tall. */+function wrapInScroller(editor: Editor, height: number) {+ const scroller = document.createElement("div");+ scroller.style.cssText = `height: ${height}px; width: 500px; overflow: auto`;+ document.body.append(scroller);+ scroller.append(editor.ui.element as HTMLElement);+ onTestFinished(() => scroller.remove());+ return scroller;+}++/** A table cell outside the editor, drawn over `rect`. */+function coverWithForeignTable(rect: DOMRect) {+ const table = document.createElement("table");+ const cover = table.insertRow().insertCell();+ table.style.cssText = `position: fixed; left: ${rect.left}px; top: ${rect.top}px; ` ++ `width: ${rect.width}px; height: ${rect.height}px; z-index: 10000`;+ document.body.append(table);+ onTestFinished(() => table.remove());+ return cover;+}diff --git a/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection.ts b/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection.tsnew file mode 100644index 0000000000..0afe0a8915--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection.ts@@ -0,0 +1,470 @@+import "../../theme/table_touch_selection.css";++import {+ DomEmitterMixin,+ Plugin,+ Table,+ TableSelection,+ TableUtils,+ TouchObserver+} from "ckeditor5";+import type {+ ModelElement,+ ViewDocumentTouchEndEvent,+ ViewDocumentTouchMoveEvent,+ ViewDocumentTouchStartEvent+} from "ckeditor5";++import {+ type ClientBox,+ findScroller,+ getAutoScrollStep,+ getClientBox,+ getViewportBottom,+ intersectBoxes,+ isEmptyBox,+ isInsideBox+} from "../viewport_geometry.js";+import TableTouchSelectionView, {+ type Corner,+ CORNERS,+ getCornerPoint+} from "./table_touch_selection_view.js";++/** The distance from a handle within which a touch drags it, in pixels. */+const HANDLE_REACH = 24;++/**+ * Handles at the corners of the selected table cells, or of the cell with the caret, shown after a+ * touch. Dragging a handle selects the cells from the opposite corner to the cell under the+ * handle, so the selection grows or shrinks as the finger moves.+ */+export default class TableTouchSelection extends Plugin {++ readonly view: TableTouchSelectionView;+ private isTouch = false;+ private target: SelectionTarget | null = null;+ private layout: SelectionLayout | null = null;+ private gesture: Gesture | null = null;+ private frame = 0;+ private readonly domEmitter = new (DomEmitterMixin())();+ private readonly resizeObserver = new ResizeObserver(() => this.scheduleUpdate());++ static get pluginName() {+ return "TableTouchSelection" as const;+ }++ static get requires() {+ return [Table, TableSelection, TableUtils] as const;+ }++ constructor(editor: Plugin["editor"]) {+ super(editor);+ this.view = new TableTouchSelectionView(editor.locale);+ }++ init() {+ const editor = this.editor;+ const viewDocument = editor.editing.view.document;+ editor.ui.view.body.add(this.view);++ // `TouchObserver` listens without `passive`, so `onTouchMove()` can cancel the scroll.+ editor.editing.view.addObserver(TouchObserver);+ this.listenTo<ViewDocumentTouchStartEvent>(viewDocument, "touchstart", (_evt, data) => {+ this.onTouchStart(data.domEvent);+ });+ this.listenTo<ViewDocumentTouchMoveEvent>(viewDocument, "touchmove", (_evt, data) => {+ this.onTouchMove(data.domEvent);+ });+ this.listenTo<ViewDocumentTouchEndEvent>(viewDocument, "touchend", (_evt, data) => {+ this.onTouchEnd(data.domEvent);+ });+ this.domEmitter.listenTo(document, "touchcancel", (_evt, event: TouchEvent) => {+ this.onTouchEnd(event);+ }, { usePassive: true });++ this.domEmitter.listenTo(document, "pointerdown", (_evt, event: PointerEvent) => {+ this.detectTouch(event);+ }, { useCapture: true });+ this.domEmitter.listenTo(document, "scroll", () => this.scheduleUpdate(), {+ useCapture: true,+ usePassive: true+ });+ this.domEmitter.listenTo(window, "resize", () => this.scheduleUpdate());+ const viewport = window.visualViewport;+ /* v8 ignore next 3 -- defensive: supported browsers have a visual viewport */+ if (viewport) {+ this.domEmitter.listenTo(viewport, "resize", () => this.scheduleUpdate());+ }++ // A change of the selection or the content renders the view, and a render fires `update`.+ this.listenTo(editor.ui, "update", () => this.scheduleUpdate());+ this.listenTo(editor.ui.focusTracker, "change:isFocused", () => this.scheduleUpdate());+ this.listenTo(editor.plugins.get(TableSelection), "change:isEnabled", () => {+ this.scheduleUpdate();+ });+ }++ override destroy() {+ this.endGesture();+ cancelAnimationFrame(this.frame);+ this.domEmitter.stopListening();+ this.resizeObserver.disconnect();+ this.view.destroy();+ super.destroy();+ }++ /** Draws the outline and the handles around the cells at the selection, or hides them. */+ update() {+ const target = this.findTarget();+ if (target?.domTable !== this.target?.domTable) {+ this.endGesture();+ this.resizeObserver.disconnect();+ // A centered table moves without a resize when the editable resizes.+ if (target) {+ this.resizeObserver.observe(target.domTable);+ this.resizeObserver.observe(target.domRoot);+ }+ }++ this.target = target;+ this.layout = target ? this.layOut(target) : null;+ this.view.isVisible = !!this.layout;+ if (!this.layout) {+ this.endGesture();+ }+ }++ private scheduleUpdate() {+ if (this.frame || (!this.isTouch && !this.view.isVisible)) {+ return;+ }++ this.frame = requestAnimationFrame(() => {+ this.frame = 0;+ this.update();+ });+ }++ /** Shows the handles after a touch and hides them after a press of a mouse or pen. */+ private detectTouch(event: PointerEvent) {+ const isTouch = event.pointerType === "touch";+ if (isTouch !== this.isTouch) {+ this.isTouch = isTouch;+ this.scheduleUpdate();+ }+ }++ private findTarget(): SelectionTarget | null {+ const editor = this.editor;+ const isEnabled = editor.plugins.get(TableSelection).isEnabled;+ if (!this.isTouch || !isEnabled || !editor.ui.focusTracker.isFocused) {+ return null;+ }++ const cells = this.getCells();+ const table = cells[0]?.findAncestor("table");+ if (!table) {+ return null;+ }++ const domTable = this.getDomElement(table)?.querySelector<HTMLElement>(":scope > table");+ const domRoot = editor.editing.view.getDomRoot();+ /* v8 ignore next 3 -- defensive: a table in the model is rendered in the editable */+ if (!domTable || !domRoot) {+ return null;+ }++ return { table, cells, domTable, domRoot };+ }++ /** The selected cells, or the cell with the caret. */+ private getCells() {+ const tableUtils = this.editor.plugins.get(TableUtils);+ const selection = this.editor.model.document.selection;+ const selectedCells = tableUtils.getSelectedTableCells(selection);+ if (selectedCells.length || !selection.isCollapsed) {+ return selectedCells;+ }+ return tableUtils.getTableCellsContainingSelection(selection);+ }++ /**+ * Places the outline and the handles around the cells of `target`. Returns `null` when no part+ * of the cells is visible.+ */+ private layOut({ cells, domTable, domRoot }: SelectionTarget): SelectionLayout | null {+ const cellBoxes: ClientBox[] = [];+ for (const cell of cells) {+ const domCell = this.getDomElement(cell);+ /* v8 ignore next 3 -- defensive: a cell in the model is rendered in its table */+ if (!domCell) {+ return null;+ }+ cellBoxes.push(domCell.getBoundingClientRect());+ }++ const range = cellBoxes.reduce<ClientBox>((union, box) => ({+ left: Math.min(union.left, box.left),+ top: Math.min(union.top, box.top),+ right: Math.max(union.right, box.right),+ bottom: Math.max(union.bottom, box.bottom)+ }), cellBoxes[0]);+ const visible = this.getVisibleArea(domTable, domRoot);+ if (isEmptyBox(intersectBoxes(range, visible))) {+ return null;+ }++ this.view.setRange(range, visible);+ return { range, visible, cellBoxes };+ }++ /**+ * The part of the viewport where the table can be seen: inside the element that clips it+ * horizontally, the scroll container of the editable and the viewport offset of the editor.+ */+ private getVisibleArea(domTable: HTMLElement, domRoot: HTMLElement): ClientBox {+ const offset = this.editor.ui.viewportOffset;+ const viewport = {+ left: offset.left ?? 0,+ top: offset.top ?? 0,+ right: document.documentElement.clientWidth - (offset.right ?? 0),+ bottom: Math.min(getViewportBottom(), window.innerHeight - (offset.bottom ?? 0))+ };+ return intersectBoxes(+ getClientBox(findScroller(domTable, "overflowX")),+ getClientBox(findScroller(domRoot, "overflowY")),+ viewport+ );+ }++ private getDomElement(element: ModelElement) {+ const editing = this.editor.editing;+ const viewElement = editing.mapper.toViewElement(element);+ /* v8 ignore next -- defensive: an element in the model is rendered */+ return viewElement ? editing.view.domConverter.mapViewToDom(viewElement) : undefined;+ }++ /** Starts to follow a touch that lands close to a handle. A second finger ends the drag. */+ private onTouchStart(event: TouchEvent) {+ if (event.touches.length > 1) {+ this.endGesture();+ return;+ }++ const { target, layout } = this;+ const touch = event.changedTouches[0];+ const corner = layout && findCorner(layout, touch.clientX, touch.clientY);+ if (!target || !layout || !corner) {+ return;+ }++ const point = getCornerPoint(layout.range, corner);+ const oppositePoint = getCornerPoint(layout.range, getOppositeCorner(corner));+ this.gesture = {+ touchId: touch.identifier,+ offsetX: point.x - touch.clientX,+ offsetY: point.y - touch.clientY,+ x: point.x,+ y: point.y,+ anchor: findClosestCell(target.cells, layout.cellBoxes, oppositePoint),+ focus: findClosestCell(target.cells, layout.cellBoxes, point),+ isDragging: false,+ frame: 0+ };+ }++ /**+ * Drags the handle with the touch. If the browser already scrolls on the first move, the drag+ * ends. Otherwise the drag stops the scroll until the touch ends.+ */+ private onTouchMove(event: TouchEvent) {+ const gesture = this.gesture;+ const touch = gesture && findTouch(event.changedTouches, gesture.touchId);+ if (!gesture || !touch) {+ return;+ }++ if (!event.cancelable) {+ this.endGesture();+ return;+ }++ event.preventDefault();+ if (!gesture.isDragging) {+ gesture.isDragging = true;+ gesture.frame = requestAnimationFrame(this.autoScroll);+ this.view.isDragging = true;+ }++ gesture.x = touch.clientX + gesture.offsetX;+ gesture.y = touch.clientY + gesture.offsetY;+ this.selectTo(gesture);+ }++ private onTouchEnd(event: TouchEvent) {+ const gesture = this.gesture;+ if (gesture && findTouch(event.changedTouches, gesture.touchId)) {+ this.endGesture();+ }+ }++ private endGesture() {+ if (this.gesture) {+ cancelAnimationFrame(this.gesture.frame);+ this.gesture = null;+ this.view.isDragging = false;+ }+ }++ /** Selects the cells from the anchor of `gesture` to the cell under its handle. */+ private selectTo(gesture: Gesture) {+ const cell = this.findCellAt(gesture.x, gesture.y);+ if (cell && cell !== gesture.focus) {+ gesture.focus = cell;+ this.editor.plugins.get(TableSelection).setCellSelection(gesture.anchor, cell);+ }+ }++ /**+ * The cell of the target table at `x`, `y`, or `null` when no cell of the table is there. The+ * point is moved into the visible part of the table first.+ */+ private findCellAt(x: number, y: number) {+ const { target, layout } = this;+ /* v8 ignore next 3 -- defensive: a drag runs while the handles are drawn */+ if (!target || !layout) {+ return null;+ }++ const box = intersectBoxes(target.domTable.getBoundingClientRect(), layout.visible);+ const pointX = Math.min(Math.max(x, box.left + 1), box.right - 1);+ const pointY = Math.min(Math.max(y, box.top + 1), box.bottom - 1);+ for (const element of document.elementsFromPoint(pointX, pointY)) {+ const cell = element instanceof HTMLTableCellElement+ ? this.getModelCell(element)+ : null;+ if (cell?.parent?.parent === target.table) {+ return cell;+ }+ }+ return null;+ }++ private getModelCell(domCell: HTMLTableCellElement) {+ const editing = this.editor.editing;+ const viewCell = editing.view.domConverter.mapDomToView(domCell);+ const cell = viewCell?.is("element") ? editing.mapper.toModelElement(viewCell) : undefined;+ return cell?.is("element", "tableCell") ? cell : null;+ }++ /** Scrolls while the handle is close to an edge of the visible area, once per frame. */+ private readonly autoScroll = () => {+ const { gesture, target, layout } = this;+ /* v8 ignore next 3 -- defensive: the frame is cancelled with the drag */+ if (!gesture || !target || !layout) {+ return;+ }++ const { visible } = layout;+ const stepX = getAutoScrollStep(gesture.x, visible.left, visible.right);+ const stepY = getAutoScrollStep(gesture.y, visible.top, visible.bottom);+ if (stepX) {+ findScroller(target.domTable, "overflowX").scrollLeft += stepX;+ }+ if (stepY) {+ findScroller(target.domRoot, "overflowY").scrollTop += stepY;+ }+ if (stepX || stepY) {+ this.update();+ this.selectTo(gesture);+ }+ gesture.frame = requestAnimationFrame(this.autoScroll);+ };+}++interface SelectionTarget {+ table: ModelElement;+ /** The selected cells, or the cell with the caret. */+ cells: ModelElement[];+ domTable: HTMLElement;+ domRoot: HTMLElement;+}++interface SelectionLayout {+ /** The box around the cells, in the viewport. */+ range: ClientBox;+ /** The part of the viewport where the table can be seen. */+ visible: ClientBox;+ /** The boxes of the cells, in the order of `SelectionTarget.cells`. */+ cellBoxes: ClientBox[];+}++/** A handle dragged by a touch. */+interface Gesture {+ touchId: number;+ /** The position of the handle from the touch point when the touch started, in pixels. */+ offsetX: number;+ offsetY: number;+ /** The position of the handle in the viewport. */+ x: number;+ y: number;+ /** The cell at the opposite corner, which stays selected. */+ anchor: ModelElement;+ /** The cell that the handle selected last. */+ focus: ModelElement;+ /** Whether the touch has moved, so that it drags the handle instead of scrolling. */+ isDragging: boolean;+ /** The animation frame of the auto-scroll. */+ frame: number;+}++/** The corner whose visible handle is the closest to `x`, `y` within reach, or `null`. */+function findCorner({ range, visible }: SelectionLayout, x: number, y: number): Corner | null {+ let closest: Corner | null = null;+ let closestDistance = Infinity;+ for (const corner of CORNERS) {+ const point = getCornerPoint(range, corner);+ const distance = Math.hypot(point.x - x, point.y - y);+ const isReachable = distance <= HANDLE_REACH && isInsideBox(point.x, point.y, visible);+ if (isReachable && distance < closestDistance) {+ closest = corner;+ closestDistance = distance;+ }+ }+ return closest;+}++function getOppositeCorner({ x, y }: Corner): Corner {+ return { x: x === "left" ? "right" : "left", y: y === "top" ? "bottom" : "top" };+}++/** The cell of `cells` whose box, from `boxes`, is the closest to `point`. */+function findClosestCell(+ cells: readonly ModelElement[],+ boxes: readonly ClientBox[],+ point: { x: number; y: number }+) {+ let closest = cells[0];+ let closestDistance = Infinity;+ for (const [index, box] of boxes.entries()) {+ const dx = point.x - Math.min(Math.max(point.x, box.left), box.right);+ const dy = point.y - Math.min(Math.max(point.y, box.top), box.bottom);+ const distance = Math.hypot(dx, dy);+ if (distance < closestDistance) {+ closest = cells[index];+ closestDistance = distance;+ }+ }+ return closest;+}++function findTouch(touches: TouchList, identifier: number) {+ return Array.from(touches).find((touch) => touch.identifier === identifier) ?? null;+}++declare module "ckeditor5" {+ interface PluginsMap {+ [TableTouchSelection.pluginName]: TableTouchSelection;+ }+}diff --git a/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection_view.ts b/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection_view.tsnew file mode 100644index 0000000000..85c8a73ecb--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_touch_selection/table_touch_selection_view.ts@@ -0,0 +1,94 @@+import { type Locale, View } from "ckeditor5";++import { type ClientBox, isInsideBox } from "../viewport_geometry.js";++/** A corner of a box, by its physical sides. */+export interface Corner {+ x: "left" | "right";+ y: "top" | "bottom";+}++export const CORNERS: readonly Corner[] = [+ { x: "left", y: "top" },+ { x: "right", y: "top" },+ { x: "left", y: "bottom" },+ { x: "right", y: "bottom" }+];++/**+ * The overlay of `TableTouchSelection`: an outline around the cells and a handle at each corner+ * of the outline, clipped to the visible part of the table.+ */+export default class TableTouchSelectionView extends View<HTMLDivElement> {++ declare isVisible: boolean;+ declare isDragging: boolean;++ /** The handles, in the order of `CORNERS`. */+ readonly handles = CORNERS.map(() => createElement("ck-table-touch-selection__handle"));+ /** The visible part of the table, which clips the outline. */+ private readonly clip = createElement("ck-table-touch-selection__clip");+ private readonly outline = createElement("ck-table-touch-selection__outline");++ constructor(locale: Locale) {+ super(locale);++ const bind = this.bindTemplate;+ this.set({ isVisible: false, isDragging: false });+ this.clip.append(this.outline);++ this.setTemplate({+ tag: "div",+ attributes: {+ class: [+ "ck",+ "ck-table-touch-selection",+ bind.if("isVisible", "ck-hidden", (isVisible) => !isVisible),+ bind.if("isDragging", "ck-table-touch-selection_dragging")+ ],+ "aria-hidden": "true"+ },+ children: [this.clip, ...this.handles]+ });+ }++ /**+ * Draws the outline around `range` and the handles at its corners, in the viewport. Only the+ * part inside `visible` is drawn.+ */+ setRange(range: ClientBox, visible: ClientBox) {+ setBox(this.clip, visible);+ setBox(this.outline, {+ left: range.left - visible.left,+ top: range.top - visible.top,+ right: range.right - visible.left,+ bottom: range.bottom - visible.top+ });++ for (const [index, corner] of CORNERS.entries()) {+ const { x, y } = getCornerPoint(range, corner);+ const handle = this.handles[index];+ handle.classList.toggle("ck-hidden", !isInsideBox(x, y, visible));+ handle.style.left = `${x}px`;+ handle.style.top = `${y}px`;+ }+ }+}++/** The point of `box` at `corner`. */+export function getCornerPoint(box: ClientBox, corner: Corner) {+ return { x: box[corner.x], y: box[corner.y] };+}++function setBox(element: HTMLElement, box: ClientBox) {+ element.style.left = `${box.left}px`;+ element.style.top = `${box.top}px`;+ element.style.width = `${box.right - box.left}px`;+ element.style.height = `${box.bottom - box.top}px`;+}++function createElement(className: string) {+ const element = document.createElement("div");+ element.className = className;+ return element;+}diff --git a/packages/ckeditor5/src/plugins/viewport_geometry.ts b/packages/ckeditor5/src/plugins/viewport_geometry.tsnew file mode 100644index 0000000000..ac677a58db--- /dev/null+++ b/packages/ckeditor5/src/plugins/viewport_geometry.ts@@ -0,0 +1,87 @@+/** The distance from an edge of a visible area that scrolls it, in pixels. */+const AUTO_SCROLL_EDGE = 40;+/** The largest distance scrolled per frame, in pixels. */+const AUTO_SCROLL_STEP = 16;++/** A box in the viewport, in pixels. */+export interface ClientBox {+ left: number;+ top: number;+ right: number;+ bottom: number;+}++/** The box inside the borders and scroll bars of `element`, in the viewport. */+export 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.+ */+export 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 bottom of the visual viewport, which is above an on-screen keyboard. */+export 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 part of the viewport that all `boxes` cover. See `isEmptyBox` for boxes that do not meet. */+export function intersectBoxes(first: ClientBox, ...others: ClientBox[]): ClientBox {+ let { left, top, right, bottom } = first;+ for (const box of others) {+ left = Math.max(left, box.left);+ top = Math.max(top, box.top);+ right = Math.min(right, box.right);+ bottom = Math.min(bottom, box.bottom);+ }+ return { left, top, right, bottom };+}++export function isEmptyBox({ left, top, right, bottom }: ClientBox) {+ return right <= left || bottom <= top;+}++export function isInsideBox(x: number, y: number, { left, top, right, bottom }: ClientBox) {+ return x >= left && x <= right && y >= top && y <= bottom;+}++/**+ * The distance to scroll by while the pointer is at `position`, between `start` and `end` of the+ * visible area: further the closer it is to either end, and nothing away from them.+ */+export function getAutoScrollStep(position: number, start: number, end: number) {+ let depth = 0;+ if (position > end - AUTO_SCROLL_EDGE) {+ depth = position - (end - AUTO_SCROLL_EDGE);+ } else if (position < start + AUTO_SCROLL_EDGE) {+ depth = position - (start + AUTO_SCROLL_EDGE);+ }++ const ratio = Math.max(-1, Math.min(1, depth / AUTO_SCROLL_EDGE));+ return Math.round(ratio * AUTO_SCROLL_STEP);+}diff --git a/packages/ckeditor5/src/theme/table_touch_selection.css b/packages/ckeditor5/src/theme/table_touch_selection.cssnew file mode 100644index 0000000000..9340fbaa61--- /dev/null+++ b/packages/ckeditor5/src/theme/table_touch_selection.css@@ -0,0 +1,45 @@+:where(:root) {+ --ck-table-touch-selection-color: var(--ck-color-focus-border);+ --ck-table-touch-selection-handle-background:+ var(--main-background-color, var(--ck-color-base-background));++ --ck-table-touch-selection-line-width: 2px;+ --ck-table-touch-selection-handle-size: 14px;+ --ck-table-touch-selection-handle-dragged-scale: 1.3;+}++/* Outranks the `.ck-reset_all` rules of the body collection. */+.ck-reset_all .ck.ck-table-touch-selection {+ position: fixed;+ inset: 0;+ z-index: calc(var(--ck-z-panel) - 1);+ pointer-events: none;++ .ck-table-touch-selection__clip {+ position: fixed;+ overflow: hidden;+ }++ .ck-table-touch-selection__outline {+ position: absolute;+ outline: var(--ck-table-touch-selection-line-width) solid+ var(--ck-table-touch-selection-color);+ outline-offset: calc(var(--ck-table-touch-selection-line-width) / -2);+ }++ .ck-table-touch-selection__handle {+ position: fixed;+ border: var(--ck-table-touch-selection-line-width) solid+ var(--ck-table-touch-selection-color);+ border-radius: 50%;+ box-sizing: border-box;+ width: var(--ck-table-touch-selection-handle-size);+ height: var(--ck-table-touch-selection-handle-size);+ background: var(--ck-table-touch-selection-handle-background);+ translate: -50% -50%;+ }++ &.ck-table-touch-selection_dragging .ck-table-touch-selection__handle {+ scale: var(--ck-table-touch-selection-handle-dragged-scale);+ }+}