Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: add support for scrolling wide tables

Adorian Doranbc0cc4dcb983
diff --git a/apps/client/src/index.ts b/apps/client/src/index.ts
index 64c0a80195..62fbc63919 100644
--- a/apps/client/src/index.ts
+++ b/apps/client/src/index.ts
@@ -8,6 +8,7 @@ import "@triliumnext/ckeditor5/src/theme/external_links.css";
import "@triliumnext/ckeditor5/src/theme/footnotes.css";
import "@triliumnext/ckeditor5/src/theme/headings.css";
import "@triliumnext/ckeditor5/src/theme/reference_links.css";
+import "@triliumnext/ckeditor5/src/theme/table_scroll.css";
import "@triliumnext/ckeditor5/src/theme/todo_lists.css";
import { createFontStylesheetLink } from "./services/font";
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index c7b0911948..55d335c8ba 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -266,6 +266,16 @@ describe("Text content renderer", () => {
expect(emptied.querySelector("a")?.textContent).toBe("Child note");
});
+ it("sizes the tables of the content for scrolling", async () => {
+ const note = buildNote({ title: "Tables" });
+ const contentEl = document.createElement("div");
+ const table = "<table><tbody><tr><td>a</td></tr></tbody></table>";
+ const html = `<figure class="table" style="width:800px;">${table}</figure>`;
+ await renderTextContent(note, html, $(contentEl));
+ const figure = contentEl.querySelector<HTMLElement>(".ck-content > figure.table");
+ expect(figure?.style.getPropertyValue("--table-width")).toBe("800px");
+ });
+
it("renders nothing for an empty note with no children when noChildrenList is set", async () => {
const contentEl = document.createElement("div");
const note = buildNote({ title: "Empty note" });
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 4939d0203b..288be46583 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -1,3 +1,4 @@
+import { applyTableScroll } from "@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js";
import {
BLOCK_ID_ATTRIBUTE, type ContentEmbedContext, getAttachmentEmbedHref, getEmbedKey,
getNestedEmbedOptions, getNoteEmbedHref, KATEX_MACROS, resolveContentEmbed,
@@ -40,6 +41,7 @@ export async function renderTextContent(
const $content = $('<div class="ck-content">')
.html(hasContent ? resolveContentImageUrls(sanitizeNoteContentHtml(content)) : "");
applyNoteImageVersions($content[0]);
+ applyTableScroll($content[0]);
if (options.block !== undefined && !sliceToBlockReference($content[0], options.block)) {
$renderedContent.append($("<p>")
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index ee85d3cb1f..9e15d4fcec 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1887,6 +1887,11 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
--max-content-width: unset;
}
+body.mobile {
+ /* The full width of a text note table, read by `TriliumTableScroll` and `table_scroll.css`. */
+ --table-reference-width: var(--preferred-max-content-width);
+}
+
button.close:hover {
text-shadow: none;
color: currentColor;
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
index 5715852f31..d213f3f592 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -435,3 +435,20 @@ describe("ReadOnlyText embedded notes", () => {
harness.container.remove();
});
});
+
+describe("ReadOnlyText tables", () => {
+ it("sizes the tables of its content for scrolling", async () => {
+ const harness = setupHarness({ isVisible: true });
+ harness.note.getBlob = async () => ({
+ content: "<figure class=\"table\" style=\"width:150%;\"><table></table></figure>"
+ }) as never;
+
+ await harness.mount();
+
+ const figure = harness.container.querySelector<HTMLElement>("figure.table");
+ expect(figure?.style.getPropertyValue("--table-width"))
+ .toBe("calc(var(--table-reference-width, 100%) * 150 / 100)");
+ await act(async () => render(null, harness.container));
+ harness.container.remove();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 8663606af2..6b4d4f3b14 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -4,6 +4,7 @@ import "./ReadOnlyText.css";
// (see https://github.com/zadam/trilium/issues/1590 for example of such conflict)
import "@triliumnext/ckeditor5";
+import { applyTableScroll } from "@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js";
import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
import clsx from "clsx";
import { Ref } from "preact";
@@ -147,6 +148,7 @@ export function ReadOnlyTextContent({
]));
applyNoteImageVersions(container);
+ applyTableScroll(container);
applyMath(container);
applyTabs(container, { placeholder: t("text-editor.ck.tab-title") });
setupImageOpening(container, true);
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.html
index b7597f2f8b..eef98ee032 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.html
@@ -23,6 +23,9 @@
<li>Or manually apply the <code>fullContentWidth</code> <a href="#root/_help_HI6GBBIduIgv">label</a> to
the note.</li>
</ul>
+<p>Since v0.107.0, a single table can also be made wider than the content
+ width, in which case it scrolls sideways. See&nbsp;<a class="reference-link"
+ href="#root/_help_NdowYOC1GFKS">Tables</a>.</p>
<aside class="admonition note">
<p>Some <a href="#root/_help_KSZ04uQ2D1St">note types</a> are full width by
default, such as the&nbsp;<a class="reference-link" href="#root/_help_grjYqerjn243">Canvas</a>.
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
index 993d285bbe..02e6559429 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,35 @@ src="3_Tables_image.png" width="384" height="100">
<li>To adjust exactly the width (in pixels or percentages) of a cell, select
the&nbsp;<span class="tn-icon cke cke-table-cell-properties"></span> button.</li>
</ul>
+<h2>Wide tables</h2>
+<p>Since v0.107.0, a table can be wider than the&nbsp;<a class="reference-link"
+ href="#root/_help_t596jLvPrqkS">Content width</a>. Such a table scrolls
+ sideways, while the rest of the note keeps its width.</p>
+<ul>
+ <li>A new table is as wide as the content. To make it wider, drag the right
+ border of its last column past the edge of the content. The border snaps
+ to the edge and holds there briefly, so the table is easy to bring back
+ to the width of the content.</li>
+ <li>To set an exact width, enter a percentage above <code>100%</code> or a width
+ in pixels in the&nbsp;<span class="tn-icon cke cke-table-properties"></span> <a
+ href="#table-properties">table properties</a>.</li>
+ <li>A table whose content needs more room than the note, such as a pasted
+ table with many columns, also scrolls instead of stretching the note.</li>
+ <li>Wide tables scroll the same way in read-only notes and on shared pages.</li>
+ <li>When printing or exporting to PDF, a wide table is shrunk to fit the page.</li>
+</ul>
+<p>Tables inside other blocks, such as block quotes, admonitions, collapsible
+ blocks, columns or tabs, are limited to the width of their block and do
+ not scroll.</p>
+<h3>Mobile support</h3>
+<p>On the&nbsp;<a class="reference-link" href="#root/_help_RDslemsQ6gCp">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 <em>Max content width</em> set in&nbsp;<a class="reference-link"
+ href="#root/_help_4TIF1oA4VQRO">Options</a> → <em>Appearance</em> → <em>Content Width</em> on
+ the mobile device, 1200 pixels by default. For example, a table set to <code>50%</code> is
+ 600 pixels wide.</p>
+<p>Columns cannot be resized by dragging on mobile.</p>
<h2>Inserting new rows and new columns</h2>
<ul>
<li>To insert a new column, click on a desired location, then press the&nbsp;<span
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.md b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.md
index 6c0cebdef4..4fc34a5fe7 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Content width.md
@@ -18,6 +18,8 @@ For notes with large elements such as <a class="reference-link" href="../../Not
* Go to <a class="reference-link" href="Note%20menu.md">Note menu</a> and toggle _Full width_.
* Or manually apply the `fullContentWidth` [label](../../Advanced%20Usage/Attributes/Labels.md) to the note.
+Since v0.107.0, a single table can also be made wider than the content width, in which case it scrolls sideways. See <a class="reference-link" href="../../Note%20Types/Text/Tables.md">Tables</a>.
+
> [!NOTE]
> Some [note types](../../Note%20Types.md) are full width by default, such as the <a class="reference-link" href="../../Note%20Types/Canvas.md">Canvas</a>. In that case the _Full width_ toggle will not be displayed and the label will have no effect.
diff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.md
index c95a4e9e16..cb8f9ffd05 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,24 @@ 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.
+## Wide tables
+
+Since 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.
+
+* A new table is as wide as the content. To make it wider, drag the right border of its last column past the edge of the content. The border snaps to the edge and holds there briefly, so the table is easy to bring back to the width of the content.
+* To set an exact width, enter a percentage above `100%` or a width in pixels in the <span class="tn-icon cke cke-table-properties"></span> [table properties](#table-properties).
+* A table whose content needs more room than the note, such as a pasted table with many columns, also scrolls instead of stretching the note.
+* Wide tables scroll the same way in read-only notes and on shared pages.
+* When printing or exporting to PDF, a wide table is shrunk to fit the page.
+
+Tables inside other blocks, such as block quotes, admonitions, collapsible blocks, columns or tabs, are limited to the width of their block and do not scroll.
+
+### Mobile support
+
+On 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.
+
## Inserting new rows and new columns
* To insert a new column, click on a desired location, then press the <span class="tn-icon cke cke-table-column"></span> button from the formatting toolbar and select _Insert column left or right._
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index f82017f079..b438a94cf0 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -73,6 +73,7 @@ import TablePasteRows from "./plugins/table_paste_rows.js";
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 ToolbarGroupMenu from "./plugins/toolbar_group_menu.js";
import BlockDragHandle from "./plugins/block_drag_handle.js";
@@ -117,6 +118,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
TableSort,
TableInsertUI,
TableToolbarDropdowns,
+ TriliumTableScroll,
ToolbarGroupMenu,
CopyAnchorLinkButton,
CopyLinkUrlButton,
diff --git a/packages/ckeditor5/src/plugins/table_distribute_columns.spec.ts b/packages/ckeditor5/src/plugins/table_distribute_columns.spec.ts
index 90d10a1f02..44153f3a53 100644
--- a/packages/ckeditor5/src/plugins/table_distribute_columns.spec.ts
+++ b/packages/ckeditor5/src/plugins/table_distribute_columns.spec.ts
@@ -8,13 +8,14 @@ import {
TableSelection
} from "ckeditor5";
import type { ClassicEditor, ModelElement } from "ckeditor5";
-import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, onTestFinished } 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";
+import TriliumTableScroll, { REFERENCE_WIDTH_PROPERTY } from "./table_scroll.js";
const PLUGINS = [Essentials, Paragraph, Table, TableSelection, TableColumnResize, TableContextMenu];
const COMMAND = "triliumDistributeTableColumns";
@@ -216,6 +217,29 @@ describe("DistributeTableColumnsCommand", () => {
expectDistributed(rtlEditor, shares);
});
+ it("measures the table width as a share of the reference width", async () => {
+ const scrollEditor = await createTestEditor([...PLUGINS, TriliumTableScroll]);
+ for (const target of [editor, scrollEditor]) {
+ target.ui.element?.style.setProperty("width", "400px");
+ setModelData(target.model, modelTable([["a", "b"]]));
+ selectCells(target, [0, 0], [0, 1]);
+ target.execute(COMMAND);
+ }
+ expect(firstTable(scrollEditor).getAttribute("tableWidth"))
+ .toBe(firstTable(editor).getAttribute("tableWidth"));
+
+ document.body.style.setProperty(REFERENCE_WIDTH_PROPERTY, "800px");
+ onTestFinished(() => {
+ document.body.style.removeProperty(REFERENCE_WIDTH_PROPERTY);
+ });
+ setModelData(scrollEditor.model, modelTable([["a", "b"]]));
+ const domTable = scrollEditor.editing.view.getDomRoot()?.querySelector("table");
+ expect(domTable?.getBoundingClientRect().width).toBeCloseTo(800, 0);
+ selectCells(scrollEditor, [0, 0], [0, 1]);
+ scrollEditor.execute(COMMAND);
+ expect(firstTable(scrollEditor).getAttribute("tableWidth")).toBe("100%");
+ });
+
it("changes nothing while the table cannot be measured", () => {
setModelData(editor.model, modelTable([["a", "b"]]));
selectCells(editor, [0, 0], [0, 1]);
diff --git a/packages/ckeditor5/src/plugins/table_distribute_columns.ts b/packages/ckeditor5/src/plugins/table_distribute_columns.ts
index 55fdcdec79..dfadbd061a 100644
--- a/packages/ckeditor5/src/plugins/table_distribute_columns.ts
+++ b/packages/ckeditor5/src/plugins/table_distribute_columns.ts
@@ -10,6 +10,7 @@ import {
} from "ckeditor5";
import type { Editor, ModelElement } from "ckeditor5";
+import TriliumTableScroll from "./table_scroll.js";
import type { IndexRange } from "./table_move/table_move_groups.js";
/**
@@ -229,7 +230,8 @@ function measureColumnWidths(
/**
* 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.
+ * stores as `tableWidth` when a table is resized for the first time. Where a reference width
+ * applies, the percentage is a share of that width instead.
*/
function measureTableWidthShare(editor: Editor, table: ModelElement): string | null {
const viewFigure = editor.editing.mapper.toViewElement(table);
@@ -240,7 +242,10 @@ function measureTableWidthShare(editor: Editor, table: ModelElement): string | n
return null;
}
- const parentWidth = getElementWidthInPixels(domParent);
+ const tableScroll = editor.plugins.has(TriliumTableScroll)
+ ? editor.plugins.get(TriliumTableScroll)
+ : null;
+ const parentWidth = tableScroll?.getReferenceWidth(table) ?? getElementWidthInPixels(domParent);
if (!(parentWidth > 0)) {
return null;
}
diff --git a/packages/ckeditor5/src/plugins/table_scroll.spec.ts b/packages/ckeditor5/src/plugins/table_scroll.spec.ts
new file mode 100644
index 0000000000..d170279f06
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_scroll.spec.ts
@@ -0,0 +1,336 @@
+import "../theme/table_scroll.css";
+
+import {
+ _setModelData as setModelData,
+ BlockQuote,
+ Essentials,
+ List,
+ Paragraph,
+ Table,
+ TableCaption,
+ TableColumnResize
+} from "ckeditor5";
+import type { ClassicEditor, ModelElement } from "ckeditor5";
+import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { modelTable } from "../../test/table-kit.js";
+import TriliumTableScroll, { REFERENCE_WIDTH_PROPERTY } from "./table_scroll.js";
+
+const PLUGINS = [Essentials, Paragraph, BlockQuote, Table, TableColumnResize, TriliumTableScroll];
+const LONG_WORD = "x".repeat(400);
+
+describe("TriliumTableScroll", () => {
+ describe("without a reference width", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor(PLUGINS);
+ setEditableWidth(editor, 400);
+ });
+
+ it("keeps the upstream plugin name and column resizing", () => {
+ expect(editor.plugins.get("TableScrollEditing")).toBeInstanceOf(TriliumTableScroll);
+ expect(editor.plugins.get("TableColumnResize").isEnabled).toBe(true);
+ });
+
+ it("scrolls a table wider than the editable and sizes it by its percentage", () => {
+ setModelData(editor.model, modelTable([["a", "b"]], 'tableWidth="150%"'));
+ expectScrolling(editor, "150%");
+
+ setModelData(editor.model, modelTable([["a", "b"]], 'tableWidth="50%"'));
+ expectFitting(editor, "50%");
+ });
+
+ it("has no reference width for any table", () => {
+ setModelData(editor.model, modelTable([["a", "b"]]));
+ expect(tableScroll(editor).getReferenceWidth(firstTable(editor))).toBeNull();
+ });
+ });
+
+ describe("with a reference width", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ setReferenceWidth("1200px");
+ editor = await createTestEditor(PLUGINS);
+ setEditableWidth(editor, 400);
+ });
+
+ it("sizes a table with no width at the reference width", () => {
+ setModelData(editor.model, modelTable([["a", "b"]]));
+ expectScrolling(editor, "1200px");
+ expect(tableScroll(editor).getReferenceWidth(firstTable(editor))).toBe(1200);
+ });
+
+ it("sizes a percentage width as a share of the reference width", () => {
+ setModelData(editor.model, modelTable([["a", "b"]], 'tableWidth="50%"'));
+ expectScrolling(editor, "600px");
+ });
+
+ it("keeps a width in other units", () => {
+ setModelData(editor.model, modelTable([["a", "b"]], 'tableWidth="300px"'));
+ expectFitting(editor, "300px");
+ });
+
+ it("fits a table into an editable wider than the reference width", () => {
+ setEditableWidth(editor, 1500);
+ setModelData(editor.model, modelTable([["a", "b"]]));
+ expectFitting(editor, "1200px");
+ });
+
+ it("converts the widths of a column resize", () => {
+ setModelData(editor.model, modelTable([["a", "b"]], 'tableWidth="50%"'));
+ const table = firstTable(editor);
+
+ tableScroll(editor)._updateTableScrollOverflowState(table, "75%");
+ expectScrolling(editor, "900px");
+
+ tableScroll(editor)._updateTableScrollOverflowState(table, null);
+ expectScrolling(editor, "1200px");
+ });
+
+ it("sizes a table in a list", async () => {
+ const listEditor = await createTestEditor([...PLUGINS, List]);
+ setEditableWidth(listEditor, 400);
+ setModelData(listEditor.model, '<table listIndent="0" listItemId="a00" '
+ + 'listType="bulleted"><tableRow><tableCell><paragraph>a</paragraph></tableCell>'
+ + "</tableRow></table>");
+ const figure = listEditor.editing.view.getDomRoot()?.querySelector("li > figure.table");
+ expect(figure).toBeInstanceOf(HTMLElement);
+ expect(figure?.classList.contains("ck-table-overflowing")).toBe(true);
+ expect(figure?.querySelector("table")?.style.width).toBe("1200px");
+ });
+
+ it("leaves a table that cannot scroll alone", () => {
+ setModelData(editor.model, `<blockQuote>${modelTable([["a", "b"]])}</blockQuote>`);
+ const figure = editor.editing.view.getDomRoot()?.querySelector("figure.table");
+ expect(figure).toBeInstanceOf(HTMLElement);
+ expect(figure?.classList.contains("ck-table-overflowing")).toBe(false);
+ expect((figure as HTMLElement | null)?.style.width).toBe("");
+ });
+
+ it("has no reference width while the editable is detached", () => {
+ setModelData(editor.model, modelTable([["a", "b"]]));
+ vi.spyOn(editor.editing.view, "getDomRoot").mockReturnValueOnce(undefined);
+ expect(tableScroll(editor).getReferenceWidth(firstTable(editor))).toBeNull();
+ });
+
+ it("turns column resizing off", () => {
+ expect(editor.plugins.get("TableColumnResize").isEnabled).toBe(false);
+ });
+
+ it("works without column resizing", async () => {
+ const plain = await createTestEditor([
+ Essentials, Paragraph, Table, TriliumTableScroll
+ ]);
+ setEditableWidth(plain, 400);
+ setModelData(plain.model, modelTable([["a", "b"]]));
+ expect(plain.plugins.has("TableColumnResize")).toBe(false);
+ expectScrolling(plain, "1200px");
+ });
+ });
+});
+
+describe("a table with content wider than the editable", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor(PLUGINS);
+ setEditableWidth(editor, 400);
+ });
+
+ it("scrolls, at the width of its content, until the content fits", () => {
+ setModelData(editor.model, modelTable([["a", LONG_WORD]]));
+ expectContentScrolling(editor);
+
+ replaceLastCellText(editor, "b");
+ const figure = domFigure(editor);
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(false);
+ expect(figure.style.width).toBe("");
+ });
+
+ it("gets its saved width back once the content fits", () => {
+ setModelData(editor.model, modelTable([["a", LONG_WORD]], 'tableWidth="50%"'));
+ expectContentScrolling(editor);
+
+ replaceLastCellText(editor, "b");
+ expectFitting(editor, "50%");
+ });
+
+ it("keeps scrolling through an update of the upstream state", () => {
+ setModelData(editor.model, modelTable([["a", LONG_WORD]]));
+ const table = firstTable(editor);
+
+ tableScroll(editor)._updateTableScrollOverflowState(table);
+ expectContentScrolling(editor);
+
+ tableScroll(editor)._updateTableScrollOverflowState(table, "140%");
+ expectScrolling(editor, "140%");
+ });
+
+ it("checks again when an image in the editable loads", () => {
+ setModelData(editor.model, modelTable([["a", "b"]]));
+ const figure = domFigure(editor);
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(false);
+
+ figure.querySelector("table")?.style.setProperty("min-width", "2000px");
+ figure.querySelector("td")?.dispatchEvent(new Event("load"));
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(true);
+ });
+
+ it("leaves a table that cannot scroll alone", async () => {
+ const fixed = await createTestEditor(PLUGINS, {
+ table: { tableScroll: { tableTypes: [] } }
+ });
+ setEditableWidth(fixed, 400);
+ setModelData(fixed.model, `<paragraph>a</paragraph>${modelTable([["a", LONG_WORD]])}`);
+ expect(domFigure(fixed).classList.contains("ck-table-overflowing")).toBe(false);
+ });
+
+ it("gets the reference width back once the content fits", () => {
+ setReferenceWidth("1200px");
+ setEditableWidth(editor, 1500);
+ setModelData(editor.model, modelTable([["a", LONG_WORD]]));
+ expectContentScrolling(editor);
+
+ replaceLastCellText(editor, "b");
+ expectFitting(editor, "1200px");
+ });
+});
+
+describe("the controls of a scrolling table", () => {
+ const link = document.createElement("link");
+
+ 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();
+ });
+
+ it("keeps the caption, the handle and the buttons whole and in view", async () => {
+ const editor = await createTestEditor([...PLUGINS, TableCaption]);
+ setEditableWidth(editor, 400);
+ setModelData(editor.model, '<table tableWidth="150%"><tableRow><tableCell>'
+ + "<paragraph>a</paragraph></tableCell></tableRow><caption>Caption</caption></table>");
+ const figure = domFigure(editor);
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(true);
+ const controls = [
+ "figcaption",
+ ".ck-widget__selection-handle",
+ ".ck-widget__type-around__button_before",
+ ".ck-widget__type-around__button_after"
+ ].map((selector) => figure.querySelector(selector));
+ for (const control of controls) {
+ expect(control).toBeInstanceOf(HTMLElement);
+ }
+
+ const lefts = controls.map((control) => expectInside(figure, control));
+ figure.scrollLeft = 100;
+ expect(figure.scrollLeft).toBe(100);
+ const scrolledLefts = controls.map((control) => expectInside(figure, control));
+ for (const [index, left] of lefts.entries()) {
+ expect(scrolledLefts[index]).toBeCloseTo(left, 0);
+ }
+
+ const [caption, , before] = controls;
+ const table = figure.querySelector("table");
+ expect(caption?.getBoundingClientRect().top)
+ .toBeCloseTo(figure.getBoundingClientRect().top + figure.clientTop, 0);
+ expect(table?.getBoundingClientRect().top)
+ .toBeCloseTo(caption?.getBoundingClientRect().bottom ?? 0, 0);
+ expect(before && getComputedStyle(before).borderBottomLeftRadius)
+ .toBe(before && getComputedStyle(before).borderTopLeftRadius);
+ });
+});
+
+/** Expects `control` within the visible part of `figure` and returns its left edge. */
+function expectInside(figure: HTMLElement, control: Element | null) {
+ const bounds = figure.getBoundingClientRect();
+ const top = bounds.top + figure.clientTop;
+ const left = bounds.left + figure.clientLeft;
+ const rect = control?.getBoundingClientRect();
+ expect(rect?.top).toBeGreaterThanOrEqual(top - 0.5);
+ expect(rect?.bottom).toBeLessThanOrEqual(top + figure.clientHeight + 0.5);
+ expect(rect?.left).toBeGreaterThanOrEqual(left - 0.5);
+ expect(rect?.right).toBeLessThanOrEqual(left + figure.clientWidth + 0.5);
+ return rect?.left ?? NaN;
+}
+
+function setReferenceWidth(width: string) {
+ document.body.style.setProperty(REFERENCE_WIDTH_PROPERTY, width);
+ onTestFinished(() => {
+ document.body.style.removeProperty(REFERENCE_WIDTH_PROPERTY);
+ });
+}
+
+function setEditableWidth(editor: ClassicEditor, width: number) {
+ editor.ui.element?.style.setProperty("width", `${width}px`);
+}
+
+function tableScroll(editor: ClassicEditor) {
+ return editor.plugins.get(TriliumTableScroll);
+}
+
+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 domFigure(editor: ClassicEditor) {
+ const figure = editor.editing.view.getDomRoot()?.querySelector(":scope > figure.table");
+ if (!(figure instanceof HTMLElement)) {
+ throw new Error("The editable has no table.");
+ }
+ return figure;
+}
+
+/** Expects the table to scroll inside its figure, `width` wide. */
+function expectScrolling(editor: ClassicEditor, width: string) {
+ const figure = domFigure(editor);
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(true);
+ expect(figure.style.width).toBe("");
+ expect(figure.querySelector("table")?.style.width).toBe(width);
+}
+
+/** Expects the table to scroll inside its figure at the width of its content. */
+function expectContentScrolling(editor: ClassicEditor) {
+ const figure = domFigure(editor);
+ const table = figure.querySelector("table");
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(true);
+ expect(figure.style.width).toBe("");
+ expect(table?.style.width).toBe("");
+ expect(table?.getBoundingClientRect().width).toBeGreaterThan(figure.clientWidth);
+}
+
+/** Replaces the text of the last cell of the first table. */
+function replaceLastCellText(editor: ClassicEditor, text: string) {
+ const cells = [...editor.model.createRangeIn(firstTable(editor)).getItems()]
+ .filter((item) => item.is("element", "tableCell"));
+ const paragraph = cells.at(-1)?.getChild(0);
+ if (!paragraph?.is("element", "paragraph")) {
+ throw new Error("The last cell has no paragraph.");
+ }
+ editor.model.change((writer) => {
+ writer.remove(writer.createRangeIn(paragraph));
+ writer.insertText(text, paragraph, 0);
+ });
+}
+
+/** Expects the table to fit, its figure `width` wide. */
+function expectFitting(editor: ClassicEditor, width: string) {
+ const figure = domFigure(editor);
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(false);
+ expect(figure.style.width).toBe(width);
+ expect(figure.querySelector("table")?.style.width).toBe("");
+}
diff --git a/packages/ckeditor5/src/plugins/table_scroll.ts b/packages/ckeditor5/src/plugins/table_scroll.ts
new file mode 100644
index 0000000000..bef5eccdd0
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_scroll.ts
@@ -0,0 +1,219 @@
+import {
+ type ModelElement, TableScrollEditing, type ViewDowncastWriter, type ViewElement
+} from "ckeditor5";
+
+/** The CSS property that sets the width a table takes as its full width. */
+export const REFERENCE_WIDTH_PROPERTY = "--table-reference-width";
+
+const OVERFLOWING_CLASS = "ck-table-overflowing";
+
+/**
+ * CKEditor's `TableScrollEditing`, which lets a table wider than the editable scroll sideways,
+ * extended in two ways:
+ *
+ * - A table also scrolls when its content is wider than the editable, whatever its saved width.
+ * - Where the editable sets `--table-reference-width`, a percentage width is a share of it instead
+ * of the editable's width, and a table with no width spans all of it. The mobile layout sets it
+ * to the maximum content width.
+ *
+ * The plugin keeps the upstream name, which `TableColumnResizeEditing` looks up to let a table grow
+ * past the editable. Column resizing is off while a reference width applies, because the resizer
+ * computes percentages of the editable's width.
+ */
+export default class TriliumTableScroll extends TableScrollEditing {
+
+ /** The figures of the tables that scroll because their content is wider than the editable. */
+ private readonly contentOverflowing = new WeakSet<ViewElement>();
+
+ private readonly onContentLoad = () => this.updateContentOverflow();
+
+ /** The editable that `onContentLoad` listens to. */
+ private loadTarget: HTMLElement | undefined;
+
+ override init() {
+ super.init();
+
+ const { editor } = this;
+ this.listenTo(editor.editing.view, "render", () => this.updateContentOverflow());
+ editor.once("ready", () => {
+ // An image that loads after a render can make its table wider.
+ this.loadTarget = editor.editing.view.getDomRoot();
+ this.loadTarget?.addEventListener("load", this.onContentLoad, true);
+
+ if (this.readReferenceWidth() !== null && editor.plugins.has("TableColumnResize")) {
+ editor.plugins.get("TableColumnResize").forceDisabled("TriliumTableScroll");
+ }
+ });
+ }
+
+ override destroy() {
+ this.loadTarget?.removeEventListener("load", this.onContentLoad, true);
+ super.destroy();
+ }
+
+ override _updateTableScrollOverflowState(
+ table: ModelElement,
+ tableWidthOverride?: string | null
+ ) {
+ // The upstream state replaces the content overflow, which the next render checks again.
+ const viewFigure = this.editor.editing.mapper.toViewElement(table);
+ if (viewFigure && this.contentOverflowing.delete(viewFigure)) {
+ this.editor.editing.view.change((writer) => {
+ setContentOverflow(writer, viewFigure, false);
+ });
+ }
+
+ const referenceWidth = this.getReferenceWidth(table);
+ if (referenceWidth === null) {
+ super._updateTableScrollOverflowState(table, tableWidthOverride);
+ return;
+ }
+
+ const tableWidth = tableWidthOverride === undefined
+ ? getSavedWidth(table)
+ : tableWidthOverride;
+ super._updateTableScrollOverflowState(table, toReferencePixels(tableWidth, referenceWidth));
+ }
+
+ /**
+ * The full width of `table` in pixels, or `null` when no reference width applies to it: the
+ * editable does not set one, or the table cannot scroll.
+ */
+ getReferenceWidth(table: ModelElement): number | null {
+ return this._isTableScrollable(table) ? this.readReferenceWidth() : null;
+ }
+
+ /** The `--table-reference-width` of the editable in pixels, or `null` when it is not set. */
+ private readReferenceWidth() {
+ const domRoot = this.editor.editing.view.getDomRoot();
+ if (!domRoot) {
+ return null;
+ }
+
+ const value = getComputedStyle(domRoot).getPropertyValue(REFERENCE_WIDTH_PROPERTY);
+ const width = parseFloat(value);
+ return width > 0 ? width : null;
+ }
+
+ /**
+ * Lets each scrollable table whose saved width fits the editable scroll while its content is
+ * wider, and stop once the content fits again.
+ */
+ private updateContentOverflow() {
+ const { editing } = this.editor;
+ const changes: ContentOverflowChange[] = [];
+ const tables = [...editing.model.document.getRoots()]
+ .flatMap((root) => [...root.getChildren()]);
+ for (const table of tables) {
+ if (!table.is("element", "table") || !this._isTableScrollable(table)) {
+ continue;
+ }
+
+ const viewFigure = editing.mapper.toViewElement(table);
+ /* v8 ignore next 3 -- defensive: a root table is converted before the view renders */
+ if (!viewFigure) {
+ continue;
+ }
+
+ const wasOverflowing = this.contentOverflowing.has(viewFigure);
+ if (viewFigure.hasClass(OVERFLOWING_CLASS) && !wasOverflowing) {
+ continue;
+ }
+
+ const isOverflowing = this.isWiderThanContainer(viewFigure);
+ if (isOverflowing !== wasOverflowing) {
+ changes.push({ table, viewFigure, isOverflowing });
+ }
+ }
+ if (!changes.length) {
+ return;
+ }
+
+ editing.view.change((writer) => {
+ for (const { viewFigure, isOverflowing } of changes) {
+ setContentOverflow(writer, viewFigure, isOverflowing);
+ if (isOverflowing) {
+ this.contentOverflowing.add(viewFigure);
+ } else {
+ this.contentOverflowing.delete(viewFigure);
+ }
+ }
+ });
+
+ // The upstream state of a table that fits again brings back its width.
+ for (const { table, isOverflowing } of changes) {
+ if (!isOverflowing) {
+ this._updateTableScrollOverflowState(table);
+ }
+ }
+ }
+
+ /** Whether the table of `viewFigure` extends past the content box of the figure's parent. */
+ private isWiderThanContainer(viewFigure: ViewElement) {
+ const domFigure = this.editor.editing.view.domConverter.mapViewToDom(viewFigure);
+ const domTable = domFigure?.querySelector(":scope > table");
+ const domParent = domFigure?.parentElement;
+ /* v8 ignore next 3 -- defensive: a rendered figure has a table and a parent element */
+ if (!domTable || !domParent) {
+ return false;
+ }
+
+ const container = getContentBox(domParent);
+ const table = domTable.getBoundingClientRect();
+ return table.left < container.left - 0.5 || table.right > container.right + 0.5;
+ }
+
+}
+
+interface ContentOverflowChange {
+ table: ModelElement;
+ viewFigure: ViewElement;
+ isOverflowing: boolean;
+}
+
+/**
+ * Puts `viewFigure` into the scrolling state, or takes it out of it. In the scrolling state the
+ * table keeps the width its content needs, and the figure has no width.
+ */
+function setContentOverflow(
+ writer: ViewDowncastWriter,
+ viewFigure: ViewElement,
+ isOverflowing: boolean
+) {
+ if (isOverflowing) {
+ writer.addClass(OVERFLOWING_CLASS, viewFigure);
+ writer.removeStyle("width", viewFigure);
+ } else {
+ writer.removeClass(OVERFLOWING_CLASS, viewFigure);
+ writer.removeStyle("--ck-table-scroll-offset", viewFigure);
+ }
+}
+
+function getSavedWidth(table: ModelElement) {
+ const width = table.getAttribute("tableWidth");
+ return typeof width === "string" ? width : null;
+}
+
+/** The left and right edges of the content box of `element`, in viewport coordinates. */
+function getContentBox(element: HTMLElement) {
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return {
+ left: rect.left + parseFloat(style.borderLeftWidth) + parseFloat(style.paddingLeft),
+ right: rect.right - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight)
+ };
+}
+
+/**
+ * Converts the saved table `width` to pixels of `referenceWidth`: a percentage is a share of it,
+ * no width is all of it, and other units stay as they are.
+ */
+function toReferencePixels(width: string | null, referenceWidth: number) {
+ if (!width) {
+ return `${referenceWidth}px`;
+ }
+ if (width.endsWith("%")) {
+ return `${parseFloat(width) / 100 * referenceWidth}px`;
+ }
+ return width;
+}
diff --git a/packages/ckeditor5/src/plugins/table_scroll_read_only.spec.ts b/packages/ckeditor5/src/plugins/table_scroll_read_only.spec.ts
new file mode 100644
index 0000000000..beedd8a2a0
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_scroll_read_only.spec.ts
@@ -0,0 +1,161 @@
+import "../theme/table_scroll.css";
+
+import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";
+import { afterAll, beforeAll, describe, expect, it, onTestFinished } from "vitest";
+
+import { applyTableScroll } from "./table_scroll_read_only.js";
+
+const TABLE = "<table><tbody><tr><td>a</td><td>b</td></tr></tbody></table>";
+
+describe("applyTableScroll", () => {
+ const link = document.createElement("link");
+
+ 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();
+ });
+
+ it("sets the width of each content table relative to the reference width", () => {
+ const container = renderContent([
+ tableFigure("width:150%;"),
+ tableFigure(""),
+ tableFigure("width:800px;"),
+ `<figure class="table layout-table">${TABLE}</figure>`,
+ `<blockquote>${tableFigure("width:150%;")}</blockquote>`,
+ `<ul><li>${tableFigure("width:50%;")}<ol><li>${tableFigure("")}</li></ol></li></ul>`,
+ `<ul><li><blockquote>${tableFigure("")}</blockquote></li></ul>`
+ ].join(""), 600);
+
+ const [wide, unsized, pixels, layout, quoted, listed, nestedListed, quotedInList]
+ = container.querySelectorAll("figure");
+ expect(widthOf(wide)).toBe("calc(var(--table-reference-width, 100%) * 150 / 100)");
+ expect(wide.style.width).toBe("150%");
+ expect(widthOf(unsized)).toBe("var(--table-reference-width, 100%)");
+ expect(widthOf(pixels)).toBe("800px");
+ expect(widthOf(layout)).toBe("");
+ expect(widthOf(quoted)).toBe("");
+ expect(widthOf(listed)).toBe("calc(var(--table-reference-width, 100%) * 50 / 100)");
+ expect(widthOf(nestedListed)).toBe("var(--table-reference-width, 100%)");
+ expect(widthOf(quotedInList)).toBe("");
+ });
+
+ it("scrolls a table wider than the content", () => {
+ const container = renderContent(tableFigure("width:150%;"), 600);
+ expectLayout(container, { figure: 600, table: 900 });
+
+ container.innerHTML = tableFigure("width:800px;");
+ applyTableScroll(container);
+ expectLayout(container, { figure: 600, table: 800 });
+
+ const wideContent = TABLE.replace(">b<", `>${"x".repeat(400)}<`);
+ container.innerHTML = `<figure class="table">${wideContent}</figure>`;
+ applyTableScroll(container);
+ const figure = firstFigure(container);
+ expect(figure.getBoundingClientRect().width).toBeCloseTo(600, 0);
+ expect(figure.scrollWidth).toBeGreaterThan(figure.clientWidth);
+
+ container.innerHTML = `<ul><li>${tableFigure("width:150%;")}</li></ul>`;
+ applyTableScroll(container);
+ const listed = container.querySelector<HTMLElement>("li > figure");
+ const item = container.querySelector("li");
+ expect(listed?.getBoundingClientRect().width)
+ .toBeCloseTo(item?.getBoundingClientRect().width ?? 0, 0);
+ expect(listed?.scrollWidth).toBeGreaterThan(listed?.clientWidth ?? Infinity);
+ });
+
+ it("keeps a table narrower than the content as it is", () => {
+ const container = renderContent(tableFigure("width:50%;"), 600);
+ expectLayout(container, { figure: 300, table: 300 });
+ const figure = firstFigure(container);
+ expect(figure.offsetLeft - container.offsetLeft).toBeCloseTo(150, 0);
+
+ container.innerHTML = tableFigure("");
+ applyTableScroll(container);
+ expectLayout(container, { figure: 600, table: 600 });
+ });
+
+ it("sizes tables by the reference width where one is set", () => {
+ const container = renderContent(tableFigure(""), 400);
+ container.style.setProperty("--table-reference-width", "1200px");
+ expectLayout(container, { figure: 400, table: 1200 });
+
+ container.innerHTML = tableFigure("width:50%;");
+ applyTableScroll(container);
+ expectLayout(container, { figure: 400, table: 600 });
+ });
+
+ it("keeps the caption above the table and in view while the table scrolls", () => {
+ const captionHtml = "<figcaption>Caption</figcaption>";
+ const container = renderContent(
+ `<figure class="table" style="width:150%;">${TABLE}${captionHtml}</figure>`,
+ 600
+ );
+ expectLayout(container, { figure: 600, table: 900 });
+ const figure = firstFigure(container);
+ const table = figure.querySelector("table");
+ const caption = figure.querySelector("figcaption");
+ expect(table).toBeInstanceOf(HTMLElement);
+ expect(caption).toBeInstanceOf(HTMLElement);
+ expect(caption?.getBoundingClientRect().bottom)
+ .toBeLessThanOrEqual(table?.getBoundingClientRect().top ?? 0);
+ expect(caption?.getBoundingClientRect().width).toBeCloseTo(600, 0);
+
+ figure.scrollLeft = 200;
+ expect(caption?.getBoundingClientRect().left)
+ .toBeCloseTo(figure.getBoundingClientRect().left, 0);
+ });
+
+ it("leaves the tables of an editor alone", () => {
+ const container = renderContent(
+ `<figure class="table ck-widget" style="width:150%;">${TABLE}</figure>`,
+ 600
+ );
+ expect(widthOf(firstFigure(container))).not.toBe("");
+ expect(getComputedStyle(firstFigure(container)).overflowX).toBe("visible");
+ });
+});
+
+function tableFigure(style: string) {
+ return `<figure class="table"${style ? ` style="${style}"` : ""}>${TABLE}</figure>`;
+}
+
+/** Renders saved HTML the way the read-only view does and applies the pass. */
+function renderContent(html: string, width: number) {
+ const container = document.createElement("div");
+ container.className = "ck-content";
+ container.style.width = `${width}px`;
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ onTestFinished(() => container.remove());
+ applyTableScroll(container);
+ return container;
+}
+
+function widthOf(figure: HTMLElement) {
+ return figure.style.getPropertyValue("--table-width");
+}
+
+function firstFigure(container: HTMLElement) {
+ const figure = container.querySelector(":scope > figure");
+ if (!(figure instanceof HTMLElement)) {
+ throw new Error("The content has no table.");
+ }
+ return figure;
+}
+
+/** Expects the figure and its table at the given widths, the figure scrolling when narrower. */
+function expectLayout(container: HTMLElement, widths: { figure: number; table: number }) {
+ const figure = firstFigure(container);
+ const table = figure.querySelector("table");
+ expect(table).toBeInstanceOf(HTMLElement);
+ expect(figure.getBoundingClientRect().width).toBeCloseTo(widths.figure, 0);
+ expect(table?.getBoundingClientRect().width).toBeCloseTo(widths.table, 0);
+ expect(figure.scrollWidth).toBeCloseTo(Math.max(widths.figure, widths.table), 0);
+}
diff --git a/packages/ckeditor5/src/plugins/table_scroll_read_only.ts b/packages/ckeditor5/src/plugins/table_scroll_read_only.ts
new file mode 100644
index 0000000000..89721ad1a8
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_scroll_read_only.ts
@@ -0,0 +1,43 @@
+/**
+ * Sizes the tables of saved content in `container` the way `TriliumTableScroll` sizes them in the
+ * editor. Each table at the top level of `container` or in its lists gets its width as
+ * `--table-width`, with a percentage turned into a share of `--table-reference-width`, and
+ * `table_scroll.css` lets a table wider than the content scroll sideways. The saved `width` stays
+ * on the figure, so a copied table keeps it.
+ *
+ * The module imports nothing from CKEditor, so pages that only display content can load it.
+ */
+export function applyTableScroll(container: Element) {
+ const figures = container.querySelectorAll<HTMLElement>("figure.table:not(.layout-table)");
+ for (const figure of figures) {
+ if (isScrollable(figure, container)) {
+ figure.style.setProperty("--table-width", toReferenceWidth(figure.style.width));
+ }
+ }
+}
+
+/**
+ * Whether `figure` is at the top level of `container` or in its lists, where the editor keeps
+ * tables at the top level of the document.
+ */
+function isScrollable(figure: HTMLElement, container: Element) {
+ for (let parent = figure.parentElement; parent !== container; parent = parent.parentElement) {
+ if (!parent || !LIST_ELEMENTS.has(parent.tagName)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+const LIST_ELEMENTS = new Set(["UL", "OL", "LI"]);
+
+/** Converts the saved table `width` to a CSS width relative to `--table-reference-width`. */
+function toReferenceWidth(width: string) {
+ if (!width) {
+ return "var(--table-reference-width, 100%)";
+ }
+ if (width.endsWith("%")) {
+ return `calc(var(--table-reference-width, 100%) * ${parseFloat(width)} / 100)`;
+ }
+ return width;
+}
diff --git a/packages/ckeditor5/src/theme/table_scroll.css b/packages/ckeditor5/src/theme/table_scroll.css
new file mode 100644
index 0000000000..926b778c9b
--- /dev/null
+++ b/packages/ckeditor5/src/theme/table_scroll.css
@@ -0,0 +1,88 @@
+.ck-content figure.table:not(.layout-table, .ck-widget)[style*="--table-width"] {
+ display: flex;
+ flex-direction: column;
+ /* Outranks the width that the editor saves on the figure. */
+ width: var(--table-width) !important;
+ max-width: 100%;
+ overflow: auto hidden;
+
+ > table {
+ width: max(100%, var(--table-width));
+ }
+
+ > figcaption {
+ order: -1;
+ position: sticky;
+ inset-inline-start: 0;
+ box-sizing: border-box;
+ width: 100%;
+ }
+
+ @media print {
+ overflow: visible;
+
+ > table {
+ width: 100%;
+ }
+ }
+}
+
+/* The widget controls of a scrolling table stay in view as sticky flex items that take no space. */
+.ck.ck-editor__editable.ck-content figure.table.ck-widget.ck-table-overflowing {
+ > figcaption {
+ position: sticky;
+ inset-inline-start: 0;
+ /* Outranks the table width that `TableScrollEditing` sets on the caption. */
+ width: 100% !important;
+ }
+
+ &.ck-widget_with-selection-handle > .ck-widget__selection-handle {
+ order: -3;
+ align-self: flex-start;
+ position: sticky;
+ inset: auto;
+ inset-inline-start: 0;
+ margin: 0;
+ /* The icon plus the 4px padding that CKEditor gives the handle on each side. */
+ margin-block-end: calc(-1 * (var(--ck-widget-handler-icon-size) + 8px));
+ transform: none;
+ }
+
+ > .ck-widget__type-around {
+ --ck-widget-type-around-button-size: inherit;
+ display: contents;
+
+ > .ck-widget__type-around__button {
+ &.ck-widget__type-around__button_before,
+ &.ck-widget__type-around__button_after {
+ position: sticky;
+ inset: auto;
+ margin: 0;
+ border-radius: var(--ck-widget-type-around-button-border-radius);
+ transform: none;
+
+ &::after {
+ border-radius: inherit;
+ }
+ }
+
+ &.ck-widget__type-around__button_before {
+ --button-inset: calc(min(10%, 30px) + var(--ck-widget-type-around-button-size));
+ order: -2;
+ align-self: flex-start;
+ inset-inline-start: var(--button-inset);
+ margin-block-end: calc(-1 * var(--ck-widget-type-around-button-size));
+ margin-inline-start: var(--button-inset);
+ }
+
+ &.ck-widget__type-around__button_after {
+ order: 1;
+ align-self: flex-end;
+ inset-inline-start:
+ calc(100% - min(10%, 30px) - var(--ck-widget-type-around-button-size));
+ margin-block-start: calc(-1 * var(--ck-widget-type-around-button-size));
+ margin-inline-end: min(10%, 30px);
+ }
+ }
+ }
+}
diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.ts
index f7eabcac41..9d05ce267a 100644
--- a/packages/share-theme/src/index.spec.ts
+++ b/packages/share-theme/src/index.spec.ts
@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({
whenActivated: vi.fn((callback: () => void) => callback()),
setupMath: vi.fn(),
setupMermaid: vi.fn(),
+ applyTableScroll: vi.fn(),
applyTabs: vi.fn(),
revealFragment: vi.fn(),
showBlockReference: vi.fn(),
@@ -36,6 +37,9 @@ vi.mock("./content/mermaid.js", () => ({ default: mocks.setupMermaid }));
vi.mock("./content/app_view.js", () => ({ default: mocks.setupAppView }));
vi.mock("./content/note_view.js", () => ({ default: "mountNoteView" }));
vi.mock("./content/collection_view.js", () => ({ default: "mountCollection" }));
+vi.mock("@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js", () => ({
+ applyTableScroll: mocks.applyTableScroll
+}));
vi.mock("@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js", () => ({
applyTabs: mocks.applyTabs,
revealFragment: mocks.revealFragment
@@ -105,6 +109,7 @@ describe("share theme entry", () => {
expect(mocks.setupMermaid).toHaveBeenCalledOnce();
expect(mocks.setupMath).toHaveBeenCalledOnce();
expect(mocks.enhanceLinkPreviews).toHaveBeenCalledWith(document.body);
+ expect(mocks.applyTableScroll).toHaveBeenCalledWith(content);
expect(mocks.applyTabs).toHaveBeenCalledWith(content, { placeholder: "Tab" });
expect(panel.scrollIntoView).toHaveBeenCalledOnce();
@@ -156,6 +161,7 @@ describe("share theme entry", () => {
document.dispatchEvent(new Event("DOMContentLoaded"));
expect(mocks.setupMath).toHaveBeenCalledTimes(2);
+ expect(mocks.applyTableScroll).toHaveBeenCalledOnce();
expect(mocks.applyTabs).not.toHaveBeenCalled();
});
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index 554917e309..d0b24d0817 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -26,8 +26,10 @@ import "@triliumnext/ckeditor5/src/theme/ck-content.css";
import "@triliumnext/ckeditor5/src/theme/tabs.css";
import "@triliumnext/ckeditor5/src/theme/multicolumn.css";
import "@triliumnext/ckeditor5/src/theme/collapsible_blocks.css";
+import "@triliumnext/ckeditor5/src/theme/table_scroll.css";
import "@triliumnext/ckeditor5/src/theme/todo_lists.css";
+import { applyTableScroll } from "@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js";
import { applyTabs, revealFragment } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
import { enhanceLinkPreviews } from "@triliumnext/commons/src/lib/link_embed_dom.js";
@@ -69,6 +71,7 @@ function setupTextNote() {
const diagrams = $try(setupMermaid);
$try(setupMath);
$try(() => enhanceLinkPreviews(document.body));
+ $try(setupTableScroll);
$try(setupTabs);
return diagrams;
}
@@ -88,6 +91,13 @@ document.addEventListener("DOMContentLoaded", () => {
whenActivated(() => $try(() => showLinkedBlocks(diagrams)));
});
+function setupTableScroll() {
+ const content = document.getElementById("content");
+ if (content) {
+ applyTableScroll(content);
+ }
+}
+
function setupTabs() {
const content = document.getElementById("content");
if (content) {