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 a command to distribute columns evenly
Adorian Doran9344dc66f2ee
diff --git a/apps/client/src/menus/table_context_menu.spec.ts b/apps/client/src/menus/table_context_menu.spec.tsindex 975bb2cc46..54169d26da 100644--- a/apps/client/src/menus/table_context_menu.spec.ts+++ b/apps/client/src/menus/table_context_menu.spec.ts@@ -23,6 +23,8 @@ const SECTION_TITLES = ["table_context_menu.delete_rows","table_context_menu.delete_columns","---",+ "table_context_menu.distribute_columns",+ "---","table_context_menu.merge_cells","table_context_menu.split_cells"];@@ -62,6 +64,7 @@ describe("buildTableMenuItems", () => {"triliumInsertTableColumnsRight","removeTableRow","removeTableColumn",+ "triliumDistributeTableColumns","mergeTableCells","splitTableCellVertically","splitTableCellHorizontally"@@ -73,10 +76,12 @@ describe("buildTableMenuItems", () => {const { editor } = stubEditor(["mergeTableCells","splitTableCellVertically",- "removeTableRow"+ "removeTableRow",+ "triliumDistributeTableColumns"]);const items = buildTableMenuItems(editor, cellElement()) ?? [];+ expect(findItem(items, "table_context_menu.distribute_columns")?.enabled).toBe(false);expect(findItem(items, "table_context_menu.merge_cells")?.enabled).toBe(false);expect(findItem(items, "table_context_menu.split_cells")?.enabled).toBe(false);expect(findItem(items, "table_context_menu.delete_rows")?.enabled).toBe(false);diff --git a/apps/client/src/menus/table_context_menu.ts b/apps/client/src/menus/table_context_menu.tsindex c26362c8bd..12c61709f8 100644--- a/apps/client/src/menus/table_context_menu.ts+++ b/apps/client/src/menus/table_context_menu.ts@@ -7,8 +7,8 @@ import { getTextEditorContaining } from "./text_editor_context_menu.js";/*** The table section of the text editor's right-click menu: row and column insertion sized by the- * selection, deletion of every spanned row or column, and merging or splitting of the selected- * cells.+ * selection, deletion of every spanned row or column, equal widths for the spanned columns, and+ * merging or splitting of the selected cells.** Returns `null` when the click is not on a table cell of the active text editor.*/@@ -61,6 +61,9 @@ export function buildTableMenuItems(commandItem(t("table_context_menu.delete_rows"), "bx bx-trash", "removeTableRow"),commandItem(t("table_context_menu.delete_columns"), "bx bx-trash", "removeTableColumn"),{ kind: "separator" },+ commandItem(t("table_context_menu.distribute_columns"), "bx bx-move-horizontal",+ "triliumDistributeTableColumns"),+ { kind: "separator" },commandItem(t("table_context_menu.merge_cells"), "bx bx-border-outer", "mergeTableCells"),{title: t("table_context_menu.split_cells"),diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 534c83d826..a3eec6c709 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3509,6 +3509,7 @@"insert_columns_right": "Insert column to the right","delete_rows": "Delete rows","delete_columns": "Delete columns",+ "distribute_columns": "Distribute columns evenly","merge_cells": "Merge cells","split_cells": "Split cells","split_vertically": "Vertically",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 501ceccece..5e908e99d7 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@@ -21,6 +21,10 @@ src="3_Tables_image.png" width="384" height="100">the same way for columns.</li><li><em>Delete rows</em> and <em>Delete columns</em> remove every row or columnthe selection touches, even when only some of their cells are selected.</li>+ <li><em>Distribute columns evenly</em> splits the combined width of the columns+ the selection touches equally between them. The other columns and the width+ of the table stay as they are. It needs a selection spanning at least two+ columns; a merged cell counts for every column it covers.</li><li><em>Merge cells</em> merges the selected cells into one. The selected cellsmust form a rectangle.</li><li><em>Split cells</em> splits each selected cell in two, either <em>Vertically</em> or <em>Horizontally</em>.</li>@@ -76,6 +80,8 @@ src="3_Tables_image.png" width="384" height="100"><ul><li>Columns can be resized by hovering the mouse over the border of two adjacentcells and dragging it.</li>+ <li>To give several columns the same width, select cells across them and choose <em>Distribute columns evenly</em> from+ the <a href="#context-menu">context menu</a>.</li><li>By default, the row height is not adjustable using the mouse, but it canbe configured from the cell settings (see below).</li><li>To adjust exactly the width (in pixels or percentages) of a cell, selectdiff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex d5159855db..417bcb512a 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -18,6 +18,7 @@ Since v0.106.0, right-clicking anywhere inside a table opens a context menu with* _Insert row above_ and _Insert row below_ insert a blank row next to the row of the current cell. When the selection spans multiple rows, the same number of rows is inserted.* _Insert column to the left_ and _Insert column to the right_ work the same way for columns.* _Delete rows_ and _Delete columns_ remove every row or column the selection touches, even when only some of their cells are selected.+* _Distribute columns evenly_ splits the combined width of the columns the selection touches equally between them. The other columns and the width of the table stay as they are. It needs a selection spanning at least two columns; a merged cell counts for every column it covers.* _Merge cells_ merges the selected cells into one. The selected cells must form a rectangle.* _Split cells_ splits each selected cell in two, either _Vertically_ or _Horizontally_.* _Cut_, _Copy_ and _Copy as Markdown_, below the table section, act on the selected cells:@@ -44,6 +45,7 @@ Right-clicking a cell that is not part of the current selection moves the cursor## Resizing cells* Columns can be resized by hovering the mouse over the border of two adjacent cells and dragging it.+* To give several columns the same width, select cells across them and choose _Distribute columns evenly_ from the [context menu](#context-menu).* 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.diff --git a/packages/ckeditor5/src/plugins/table_context_menu.ts b/packages/ckeditor5/src/plugins/table_context_menu.tsindex da5c26052f..31b1e1fda7 100644--- a/packages/ckeditor5/src/plugins/table_context_menu.ts+++ b/packages/ckeditor5/src/plugins/table_context_menu.ts@@ -1,20 +1,30 @@-import { Command, MouseObserver, Plugin, Table, TableSelection, TableUtils } from "ckeditor5";+import {+ Command,+ MouseObserver,+ Plugin,+ Table,+ TableColumnResize,+ TableSelection,+ TableUtils+} from "ckeditor5";import type { Editor, ModelElement, ViewDocumentMouseDownEvent } from "ckeditor5";+import { DistributeTableColumnsCommand } from "./table_distribute_columns.js";+/*** Editor-side support for the client's table context menu.** Registers insert commands that honor the size of the current selection (the upstream- * `insertTableRow*` / `insertTableColumn*` commands always insert one row or column), keeps a- * multi-cell selection alive under a right-click, and moves the selection to the cell a context- * menu is opened on. Merge, split and delete need no counterparts here: the upstream- * `mergeTableCells`, `splitTableCell*` and `removeTableRow` / `removeTableColumn` commands already- * act on the whole selection.+ * `insertTableRow*` / `insertTableColumn*` commands always insert one row or column) and+ * `triliumDistributeTableColumns`, keeps a multi-cell selection alive under a right-click, and+ * moves the selection to the cell a context menu is opened on. Merge, split and delete need no+ * counterparts here: the upstream `mergeTableCells`, `splitTableCell*` and `removeTableRow` /+ * `removeTableColumn` commands already act on the whole selection.*/export default class TableContextMenu extends Plugin {static get requires() {- return [Table, TableSelection, TableUtils] as const;+ return [Table, TableColumnResize, TableSelection, TableUtils] as const;}static get pluginName() {@@ -32,6 +42,8 @@ export default class TableContextMenu extends Plugin {new TableMultiInsertCommand(editor, "left"));editor.commands.add("triliumInsertTableColumnsRight",new TableMultiInsertCommand(editor, "right"));+ editor.commands.add("triliumDistributeTableColumns",+ new DistributeTableColumnsCommand(editor));const view = editor.editing.view;view.addObserver(MouseObserver);@@ -161,5 +173,6 @@ declare module "ckeditor5" {triliumInsertTableRowsBelow: TableMultiInsertCommand;triliumInsertTableColumnsLeft: TableMultiInsertCommand;triliumInsertTableColumnsRight: TableMultiInsertCommand;+ triliumDistributeTableColumns: DistributeTableColumnsCommand;}}diff --git a/packages/ckeditor5/src/plugins/table_distribute_columns.spec.ts b/packages/ckeditor5/src/plugins/table_distribute_columns.spec.tsnew file mode 100644index 0000000000..90d10a1f02--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_distribute_columns.spec.ts@@ -0,0 +1,307 @@+import {+ _getTableColumnsWidths as getTableColumnsWidths,+ _setModelData as setModelData,+ Essentials,+ Paragraph,+ Table,+ TableColumnResize,+ TableSelection+} from "ckeditor5";+import type { ClassicEditor, ModelElement } from "ckeditor5";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";++import { createTestEditor } from "../../test/editor-kit.js";+import { cellAt, modelTable, selectCells } from "../../test/table-kit.js";+import type { CellSpec } from "../../test/table-kit.js";+import { equalizeWidths } from "./table_distribute_columns.js";+import TableContextMenu from "./table_context_menu.js";++const PLUGINS = [Essentials, Paragraph, Table, TableSelection, TableColumnResize, TableContextMenu];+const COMMAND = "triliumDistributeTableColumns";++describe("equalizeWidths", () => {+ it("averages the range and leaves the other widths alone", () => {+ expect(equalizeWidths([20, 30, 50], { first: 0, last: 1 })).toEqual([25, 25, 50]);+ expect(equalizeWidths([50, 100, 200], { first: 1, last: 2 })).toEqual([50, 150, 150]);+ expect(equalizeWidths([10, 10, 10, 70], { first: 0, last: 2 })).toEqual([10, 10, 10, 70]);+ });++ it("gives the rounding remainder to the last column of the range", () => {+ expect(equalizeWidths([10, 20, 40, 30], { first: 0, last: 2 }))+ .toEqual([23.33, 23.33, 23.34, 30]);+ });+});++describe("DistributeTableColumnsCommand", () => {+ let editor: ClassicEditor;+ let collapsedBorders: HTMLStyleElement;++ // The spec does not load the editor stylesheet; the default border spacing would put gaps+ // between the cells that the collapsed borders of a real note table do not have.+ beforeAll(() => {+ collapsedBorders = document.createElement("style");+ collapsedBorders.textContent = "table { border-collapse: collapse; }";+ document.head.appendChild(collapsedBorders);+ });++ afterAll(() => {+ collapsedBorders.remove();+ });++ beforeEach(async () => {+ editor = await createTestEditor(PLUGINS);+ });++ describe("isEnabled", () => {+ it("requires a selection spanning two or more columns of a table", () => {+ setModelData(editor.model, "<paragraph>fo[]o</paragraph>");+ expect(isEnabled(editor)).toBe(false);++ setModelData(editor.model, modelTable([["a[]", "b"], ["c", "d"]]));+ expect(isEnabled(editor)).toBe(false);++ selectCells(editor, [0, 0], [1, 0]);+ expect(isEnabled(editor)).toBe(false);++ selectCells(editor, [0, 0], [0, 1]);+ expect(isEnabled(editor)).toBe(true);+ });++ it("counts every column a merged cell spans", () => {+ setModelData(editor.model, modelTable([[{ contents: "a[]", colspan: 2 }], ["b", "c"]]));+ expect(isEnabled(editor)).toBe(true);+ });++ it("is disabled in read-only mode", () => {+ setModelData(editor.model, modelTable([["a", "b"]]));+ selectCells(editor, [0, 0], [0, 1]);+ editor.enableReadOnlyMode("spec");+ expect(isEnabled(editor)).toBe(false);+ });+ });++ describe("on a resized table", () => {+ it("equalizes the selected columns and keeps the rest and the table width", () => {+ setModelData(editor.model,+ resizedTable([["a", "b", "c"]], ["20%", "30%", "50%"], 'tableWidth="80%"'));+ selectCells(editor, [0, 0], [0, 1]);++ editor.execute(COMMAND);++ expect(storedWidths(editor)).toEqual(["25%", "25%", "50%"]);+ expect(firstTable(editor).getAttribute("tableWidth")).toBe("80%");+ expect(editor.getData()).toContain('<col style="width:25%;">');+ });++ it("keeps the cell selection and undoes in one step", () => {+ setModelData(editor.model, resizedTable([["a", "b", "c"]], ["20%", "30%", "50%"]));+ selectCells(editor, [0, 1], [0, 2]);++ editor.execute(COMMAND);+ expect(storedWidths(editor)).toEqual(["20%", "40%", "40%"]);+ expect(editor.plugins.get(TableSelection).getSelectedTableCells())+ .toEqual([cellAt(editor, 0, 1), cellAt(editor, 0, 2)]);+ expect(firstTable(editor).hasAttribute("tableWidth")).toBe(false);++ editor.execute("undo");+ expect(storedWidths(editor)).toEqual(["20%", "30%", "50%"]);+ });++ it("distributes the whole table when every column is selected", () => {+ setModelData(editor.model, resizedTable([["a", "b", "c"]], ["20%", "30%", "50%"]));+ selectCells(editor, [0, 0], [0, 2]);++ editor.execute(COMMAND);++ expect(storedWidths(editor)).toEqual(["33.33%", "33.33%", "33.34%"]);+ });++ it("includes the columns under a merged cell", () => {+ setModelData(editor.model, resizedTable(+ [[{ contents: "a[]", colspan: 2 }, "b"], ["c", "d", "e"]],+ ["20%", "30%", "50%"]+ ));++ editor.execute(COMMAND);++ expect(storedWidths(editor)).toEqual(["25%", "25%", "50%"]);+ });++ it("keeps pixel widths in pixels", () => {+ setModelData(editor.model, resizedTable(+ [["a", "b", "c"]], ["100px", "100px", "200px"], 'tableWidth="400px"'+ ));+ selectCells(editor, [0, 1], [0, 2]);++ editor.execute(COMMAND);++ expect(storedWidths(editor)).toEqual(["100px", "150px", "150px"]);+ expect(firstTable(editor).getAttribute("tableWidth")).toBe("400px");+ });++ it("measures the rendered columns when the stored widths mix units", () => {+ setModelData(editor.model,+ resizedTable([["a", LONG_TEXT, "c"]], ["50%", "100px", "50%"]));+ selectCells(editor, [0, 0], [0, 1]);++ editor.execute(COMMAND);++ const widths = percentages(storedWidths(editor));+ expect(widths[0]).toBeCloseTo(widths[1], 1);+ expect(sum(widths)).toBeCloseTo(100, 1);+ });+ });++ describe("on a table that was never resized", () => {+ it("stores the measured widths with the selected columns equalized", () => {+ setModelData(editor.model, modelTable([["a", LONG_TEXT, "c"], ["d", "e", "f"]]));+ const shares = renderedShares(editor, 0);+ selectCells(editor, [0, 0], [1, 1]);++ editor.execute(COMMAND);++ expectDistributed(editor, shares);+ expect(String(firstTable(editor).getAttribute("tableWidth"))).toMatch(/^\d+(\.\d+)?%$/);+ });++ it("keeps a table width set in percent", () => {+ setModelData(editor.model, modelTable([["a", LONG_TEXT, "c"]], 'tableWidth="90%"'));+ const shares = renderedShares(editor, 0);+ selectCells(editor, [0, 0], [0, 1]);++ editor.execute(COMMAND);++ expectDistributed(editor, shares);+ expect(firstTable(editor).getAttribute("tableWidth")).toBe("90%");+ });++ it("stores pixel widths that add up to a table width set in pixels", () => {+ setModelData(editor.model, modelTable([["a", LONG_TEXT, "c"]], 'tableWidth="600px"'));+ selectCells(editor, [0, 0], [0, 1]);++ editor.execute(COMMAND);++ const stored = storedWidths(editor);+ expect(stored.every((width) => width.endsWith("px"))).toBe(true);+ const widths = stored.map((width) => parseFloat(width));+ expect(widths[0]).toBeCloseTo(widths[1], 1);+ expect(sum(widths)).toBeCloseTo(600, 0);+ expect(firstTable(editor).getAttribute("tableWidth")).toBe("600px");+ });++ it("splits columns that merged cells always join in proportion", () => {+ setModelData(editor.model, modelTable([+ [{ contents: LONG_TEXT, colspan: 2 }, "c", "d"],+ [{ contents: "e", colspan: 2 }, "f", "g"]+ ]));+ const [merged] = renderedShares(editor, 0);+ selectCells(editor, [0, 1], [1, 2]);++ editor.execute(COMMAND);++ const widths = percentages(storedWidths(editor));+ expect(widths[0]).toBeCloseTo(merged / 2, 0);+ expect(widths[1]).toBeCloseTo(merged / 2, 0);+ expect(widths[2]).toBeCloseTo(widths[3], 1);+ });++ it("measures right-to-left content", async () => {+ const rtlEditor = await createTestEditor(PLUGINS, { language: { content: "ar" } });+ setModelData(rtlEditor.model, modelTable([["a", LONG_TEXT, "c"]]));+ const shares = renderedShares(rtlEditor, 0);+ selectCells(rtlEditor, [0, 0], [0, 1]);++ rtlEditor.execute(COMMAND);++ expectDistributed(rtlEditor, shares);+ });++ it("changes nothing while the table cannot be measured", () => {+ setModelData(editor.model, modelTable([["a", "b"]]));+ selectCells(editor, [0, 0], [0, 1]);+ editor.ui.element?.style.setProperty("display", "none");++ editor.execute(COMMAND);++ expect(storedWidths(editor)).toEqual([]);+ expect(firstTable(editor).hasAttribute("tableWidth")).toBe(false);+ });++ it("changes nothing while the editable has no width to relate the table to", () => {+ setModelData(editor.model, modelTable([["a", "b"]]));+ selectCells(editor, [0, 0], [0, 1]);+ const root = editor.editing.view.getDomRoot();+ expect(root).toBeInstanceOf(HTMLElement);+ root?.style.setProperty("width", "0");+ root?.style.setProperty("padding", "0");++ editor.execute(COMMAND);++ expect(storedWidths(editor)).toEqual([]);+ });+ });+});++const LONG_TEXT = "a considerably longer cell content";++function isEnabled(editor: ClassicEditor) {+ return editor.commands.get(COMMAND)?.isEnabled;+}++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>`);+}++function firstTable(editor: ClassicEditor): 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 storedWidths(editor: ClassicEditor): string[] {+ return getTableColumnsWidths(firstTable(editor));+}++function percentages(widths: string[]): number[] {+ expect(widths.every((width) => width.endsWith("%"))).toBe(true);+ return widths.map((width) => parseFloat(width));+}++function sum(values: number[]): number {+ return values.reduce((total, value) => total + value, 0);+}++/** The rendered width of each cell in a row, in percent of the row's width. */+function renderedShares(editor: ClassicEditor, rowIndex: number): number[] {+ const row = firstTable(editor).getChild(rowIndex);+ if (!row?.is("element", "tableRow")) {+ throw new Error(`No table row at index ${rowIndex}.`);+ }++ const widths = [...row.getChildren()].map((cell) => {+ const viewCell = cell.is("element") && editor.editing.mapper.toViewElement(cell);+ const domCell = viewCell && editor.editing.view.domConverter.mapViewToDom(viewCell);+ if (!(domCell instanceof HTMLElement)) {+ throw new Error("A table cell is not rendered.");+ }+ return domCell.getBoundingClientRect().width;+ });+ const total = sum(widths);+ expect(total).toBeGreaterThan(0);+ return widths.map((width) => width / total * 100);+}++/** Asserts that the first two of three columns are equal and the third keeps its share. */+function expectDistributed(editor: ClassicEditor, shares: number[]) {+ expect(shares[1]).toBeGreaterThan(shares[0] + 10);++ const widths = percentages(storedWidths(editor));+ expect(widths).toHaveLength(3);+ expect(widths[0]).toBeCloseTo(widths[1], 1);+ expect(widths[2]).toBeCloseTo(shares[2], 0);+ expect(sum(widths)).toBeCloseTo(100, 1);+}diff --git a/packages/ckeditor5/src/plugins/table_distribute_columns.ts b/packages/ckeditor5/src/plugins/table_distribute_columns.tsnew file mode 100644index 0000000000..55fdcdec79--- /dev/null+++ b/packages/ckeditor5/src/plugins/table_distribute_columns.ts@@ -0,0 +1,251 @@+import {+ _getElementWidthInPixels as getElementWidthInPixels,+ _getTableColumnsWidths as getTableColumnsWidths,+ _getTableWidthInPixels as getTableWidthInPixels,+ _toPrecision as toPrecision,+ Command,+ TableUtils,+ TableWalker,+ TableWidthsCommand+} from "ckeditor5";+import type { Editor, ModelElement } from "ckeditor5";++import type { IndexRange } from "./table_move/table_move_groups.js";++/**+ * Gives the columns touched by the selection an equal share of their combined width. The other+ * columns and the table width stay as they are. Enabled when the selection spans at least two+ * columns of one table.+ *+ * The widths are written through the `resizeColumnWidths` command of `TableColumnResize`, so a+ * table that was never resized gets the same `tableColumnGroup` and `tableWidth` a first drag of a+ * column border would give it.+ */+export class DistributeTableColumnsCommand extends Command {++ override refresh() {+ this.isEnabled = this.findTarget() !== null;+ }++ 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)) {+ 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}`)+ });+ }++ private findTarget(): { table: ModelElement; columns: IndexRange } | null {+ const tableUtils = this.editor.plugins.get(TableUtils);+ const selection = this.editor.model.document.selection;+ const cells = tableUtils.getSelectionAffectedTableCells(selection);+ const table = cells[0]?.findAncestor("table");+ if (!table) {+ return null;+ }++ const columns = getSpannedColumns(table, cells);+ return columns.last > columns.first ? { table, columns } : null;+ }++}++/**+ * The columns covered by `cells`, including every column a merged cell spans.+ * `TableUtils.getColumnIndexes()` only reports the column each cell starts in.+ */+function getSpannedColumns(table: ModelElement, cells: readonly ModelElement[]): IndexRange {+ const selected = new Set(cells);+ let first = Infinity;+ let last = -1;++ for (const slot of new TableWalker(table)) {+ if (selected.has(slot.cell)) {+ first = Math.min(first, slot.column);+ last = Math.max(last, slot.column + slot.cellWidth - 1);+ }+ }++ return { first, last };+}++/**+ * Replaces the widths in `range` (inclusive) with their average, rounded like the widths+ * `TableColumnResize` stores. The last column of the range takes the rounding remainder, so the+ * range keeps its total.+ */+export function equalizeWidths(widths: readonly number[], range: IndexRange): number[] {+ const { first, last } = range;+ const count = last - first + 1;+ const total = widths.slice(first, last + 1).reduce((sum, width) => sum + width, 0);+ const share = toPrecision(total / count);++ return widths.map((width, index) => {+ if (index < first || index > last) {+ return width;+ }+ return index === last ? toPrecision(total - share * (count - 1)) : share;+ });+}++type WidthUnit = "%" | "px";++interface ColumnWidths {+ values: number[];+ unit: WidthUnit;+ tableWidth: string | undefined;+}++/**+ * Reads the width of every column of `table`: from its `tableColumnGroup` when that holds one+ * width per column in a single unit, otherwise from the rendered cells. Returns `null` when the+ * table is not rendered with a measurable width.+ */+function readColumnWidths(editor: Editor, table: ModelElement): ColumnWidths | null {+ const columnCount = editor.plugins.get(TableUtils).getColumns(table);+ const tableWidthAttribute = table.getAttribute("tableWidth");+ const tableWidth = typeof tableWidthAttribute === "string" ? tableWidthAttribute : undefined;++ const stored = getTableColumnsWidths(table);+ const parsed = stored.length === columnCount ? parseUniformWidths(stored) : null;+ if (parsed) {+ return { ...parsed, tableWidth };+ }++ const measured = measureColumnWidths(editor, table, columnCount);+ if (!measured) {+ return null;+ }+ const measuredTotal = measured.reduce((sum, width) => sum + width, 0);++ if (tableWidth?.trim().endsWith("px")) {+ const scale = parseFloat(tableWidth) / measuredTotal;+ return {+ values: measured.map((width) => toPrecision(width * scale)),+ unit: "px",+ tableWidth+ };+ }++ const resolvedTableWidth = tableWidth ?? measureTableWidthShare(editor, table);+ if (!resolvedTableWidth) {+ return null;+ }+ return {+ values: measured.map((width) => toPrecision(width / measuredTotal * 100)),+ unit: "%",+ tableWidth: resolvedTableWidth+ };+}++/** Parses widths such as `"25%"` or `"120px"`; returns `null` unless all share one unit. */+function parseUniformWidths(widths: string[]): { values: number[]; unit: WidthUnit } | null {+ const values: number[] = [];+ let unit: WidthUnit | null = null;++ for (const width of widths) {+ const match = /^\s*(\d+(?:\.\d+)?)(%|px)\s*$/.exec(width);+ if (!match || (unit && match[2] !== unit)) {+ return null;+ }+ unit = match[2] as WidthUnit;+ values.push(parseFloat(match[1]));+ }++ return unit && { values, unit };+}++/**+ * 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.+ */+function measureColumnWidths(+ editor: Editor,+ table: ModelElement,+ columnCount: number+): number[] | null {+ const isRtl = editor.locale.contentLanguageDirection === "rtl";+ const edgeSamples: number[][] = Array.from({ length: columnCount + 1 }, () => []);++ for (const slot of new TableWalker(table)) {+ const viewCell = editor.editing.mapper.toViewElement(slot.cell);+ const domCell = viewCell && editor.editing.view.domConverter.mapViewToDom(viewCell);+ /* v8 ignore next 3 -- defensive: every model cell of a rendered table maps to a DOM cell */+ if (!(domCell instanceof HTMLElement)) {+ continue;+ }++ const rect = domCell.getBoundingClientRect();+ edgeSamples[slot.column].push(isRtl ? -rect.right : rect.left);+ edgeSamples[slot.column + slot.cellWidth].push(isRtl ? -rect.left : rect.right);+ }++ const measured = edgeSamples.map((samples) => samples.length+ ? samples.reduce((sum, value) => sum + value, 0) / samples.length+ : null);+ const firstEdge = measured[0];+ /* v8 ignore next 3 -- defensive: the first and the last boundary always have a cell edge */+ if (firstEdge === null || measured[columnCount] === null) {+ return null;+ }++ const edges = [firstEdge];+ let previous = 0;+ for (let boundary = 1; boundary <= columnCount; boundary++) {+ const edge = measured[boundary];+ if (edge === null) {+ continue;+ }+ for (let missing = previous + 1; missing < boundary; missing++) {+ const ratio = (missing - previous) / (boundary - previous);+ edges[missing] = edges[previous] + (edge - edges[previous]) * ratio;+ }+ 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;+}++/**+ * The rendered width of `table` as a percentage of its container, the value `TableColumnResize`+ * stores as `tableWidth` when a table is resized for the first time.+ */+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) {+ return null;+ }++ const parentWidth = getElementWidthInPixels(domParent);+ if (!(parentWidth > 0)) {+ return null;+ }++ const tableWidth = getTableWidthInPixels(table, editor);+ const width = Math.max(tableWidth, getElementWidthInPixels(domFigure));+ return `${toPrecision(width / parentWidth * 100)}%`;+}