Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: add support for sticky headers

Adorian Doran0b29678c7cbe
diff --git a/apps/client/src/index.ts b/apps/client/src/index.ts
index 62fbc63919..df8ce4aec9 100644
--- a/apps/client/src/index.ts
+++ b/apps/client/src/index.ts
@@ -9,6 +9,7 @@ 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/table_sticky_header.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 8d095e354d..99cfce9a52 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -53,6 +53,11 @@ vi.mock("./math.js", async (importOriginal) => {
};
});
+const applyStickyTableHeaders = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/ckeditor5/src/plugins/table_sticky_header_read_only.js", () => ({
+ applyStickyTableHeaders
+}));
+
import renderText, {
applyInlineMermaid,
postProcessRichContent,
@@ -268,7 +273,7 @@ describe("Text content renderer", () => {
expect(emptied.querySelector("a")?.textContent).toBe("Child note");
});
- it("sizes the tables of the content for scrolling, in an excerpt too", async () => {
+ it("sizes the tables for scrolling and keeps their header rows in view", async () => {
const note = buildNote({ title: "Tables" });
const table = `<figure class="table" style="width:800px;" data-trilium-block-id="t1">`
+ "<table><tbody><tr><td>a</td></tr></tbody></table></figure>";
@@ -279,6 +284,7 @@ describe("Text content renderer", () => {
const full = document.createElement("div");
await renderTextContent(note, table, $(full));
expect(tableWidth(full)).toBe("800px");
+ expect(applyStickyTableHeaders).toHaveBeenCalledWith(full.querySelector(".ck-content"));
// The excerpt of a table in one column of a layout has the table at its top level.
const excerpt = document.createElement("div");
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 036f16685e..4d2123bc7e 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -1,4 +1,7 @@
import { applyTableScroll } from "@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js";
+import {
+ applyStickyTableHeaders
+} from "@triliumnext/ckeditor5/src/plugins/table_sticky_header_read_only.js";
import {
BLOCK_ID_ATTRIBUTE, type ContentEmbedContext, getAttachmentEmbedHref, getEmbedKey,
getNestedEmbedOptions, getNoteEmbedHref, KATEX_MACROS, resolveContentEmbed,
@@ -48,6 +51,7 @@ export async function renderTextContent(
.text(t("block_reference.broken")));
} else if (hasContent) {
applyTableScroll($content[0]);
+ applyStickyTableHeaders($content[0]);
// Runs before `postProcessRichContent()` renders embeds, so their blocks are not searched.
if (options.highlightBlock) {
highlightBlockReference($content[0], options.highlightBlock);
diff --git a/apps/client/src/stylesheets/scroll_driven_animations.spec.ts b/apps/client/src/stylesheets/scroll_driven_animations.spec.ts
new file mode 100644
index 0000000000..561d1219a4
--- /dev/null
+++ b/apps/client/src/stylesheets/scroll_driven_animations.spec.ts
@@ -0,0 +1,27 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { transform } from "lightningcss";
+import { describe, expect, it } from "vitest";
+
+const THEME_DIR = join(__dirname, "../../../../packages/ckeditor5/src/theme");
+
+/**
+ * The client builds its stylesheets with Lightning CSS, which expands an `animation` shorthand
+ * with a `0s` duration. A scroll-driven animation needs `auto`, or it ends as soon as it starts.
+ */
+describe("scroll-driven animations in the content stylesheets", () => {
+ it("keep an automatic duration through Lightning CSS", () => {
+ const checked: string[] = [];
+ for (const filename of readdirSync(THEME_DIR).filter((name) => name.endsWith(".css"))) {
+ const source = readFileSync(join(THEME_DIR, filename));
+ const css = transform({ filename, code: source }).code.toString();
+ if (css.includes("animation-timeline")) {
+ checked.push(filename);
+ expect(css, filename).not.toMatch(/animation-duration:[^;]*\b0s/);
+ }
+ }
+
+ expect(checked).toContain("table_sticky_header.css");
+ });
+});
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 d213f3f592..4bb80cb3f6 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -47,6 +47,11 @@ vi.mock("./utils", async (importOriginal) => ({
loadEmbeddedNote
}));
+const applyStickyTableHeaders = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/ckeditor5/src/plugins/table_sticky_header_read_only.js", () => ({
+ applyStickyTableHeaders
+}));
+
vi.stubGlobal("logError", vi.fn());
vi.stubGlobal("logInfo", vi.fn());
@@ -437,7 +442,7 @@ describe("ReadOnlyText embedded notes", () => {
});
describe("ReadOnlyText tables", () => {
- it("sizes the tables of its content for scrolling", async () => {
+ it("sizes its tables for scrolling and keeps their header rows in view", async () => {
const harness = setupHarness({ isVisible: true });
harness.note.getBlob = async () => ({
content: "<figure class=\"table\" style=\"width:150%;\"><table></table></figure>"
@@ -448,6 +453,7 @@ describe("ReadOnlyText tables", () => {
const figure = harness.container.querySelector<HTMLElement>("figure.table");
expect(figure?.style.getPropertyValue("--table-width"))
.toBe("calc(var(--table-reference-width, 100%) * 150 / 100)");
+ expect(applyStickyTableHeaders).toHaveBeenCalledWith(figure?.parentElement);
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 6b4d4f3b14..bf4356d93c 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -5,6 +5,9 @@ import "./ReadOnlyText.css";
import "@triliumnext/ckeditor5";
import { applyTableScroll } from "@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js";
+import {
+ applyStickyTableHeaders
+} from "@triliumnext/ckeditor5/src/plugins/table_sticky_header_read_only.js";
import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
import clsx from "clsx";
import { Ref } from "preact";
@@ -149,6 +152,7 @@ export function ReadOnlyTextContent({
applyNoteImageVersions(container);
applyTableScroll(container);
+ applyStickyTableHeaders(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/Note Types/Text/Tables.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
index 3f26e83066..b2208bb77a 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
@@ -196,6 +196,14 @@ src="3_Tables_image.png" width="384" height="100">
the mobile device, 1200 pixels by default. For example, a table set to <code>50%</code> is
600 pixels wide.</p>
<p>To resize columns on mobile, use the bar described in <a href="#resizing-with-touch">Resizing with touch</a>.</p>
+<h2>Long tables</h2>
+<p>Since v0.107.0, the header rows of a table stay visible at the top of
+ the note while you scroll through the rest of the table, and leave with
+ the end of the table. This also works in read-only notes, on shared pages
+ and in wide tables.</p>
+<p>To turn rows into header rows, use <em>Set as header</em> in the <a href="#context-menu">context menu</a>,
+ or <em>Header row</em> in the <span class="tn-icon cke cke-table-row"></span> button
+ of the formatting toolbar.</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/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.md
index f77299ee22..d32f19f76e 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md
@@ -97,6 +97,12 @@ On the <a class="reference-link" href="../../Installation%20%26%20Setup/Mobile%
To resize columns on mobile, use the bar described in [Resizing with touch](#resizing-with-touch).
+## Long tables
+
+Since v0.107.0, the header rows of a table stay visible at the top of the note while you scroll through the rest of the table, and leave with the end of the table. This also works in read-only notes, on shared pages and in wide tables.
+
+To turn rows into header rows, use _Set as header_ in the [context menu](#context-menu), or _Header row_ in the <span class="tn-icon cke cke-table-row"></span> button of the formatting toolbar.
+
## 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 e84e3758ba..d93e32248e 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -74,6 +74,7 @@ import TableSort from "./plugins/table_sort.js";
import TableInsertUI from "./plugins/table_insert/table_insert_ui.js";
import TableToolbarDropdowns from "./plugins/table_toolbar_dropdowns.js";
import TriliumTableScroll from "./plugins/table_scroll.js";
+import TableStickyHeader from "./plugins/table_sticky_header.js";
import TableColumnBar from "./plugins/table_column_bar/table_column_bar.js";
import ToolbarGroupMenu from "./plugins/toolbar_group_menu.js";
import BlockDragHandle from "./plugins/block_drag_handle.js";
@@ -120,6 +121,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
TableInsertUI,
TableToolbarDropdowns,
TriliumTableScroll,
+ TableStickyHeader,
TableColumnBar,
ToolbarGroupMenu,
CopyAnchorLinkButton,
diff --git a/packages/ckeditor5/src/plugins/table_sticky_header.spec.ts b/packages/ckeditor5/src/plugins/table_sticky_header.spec.ts
new file mode 100644
index 0000000000..7f5a9c97fb
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_sticky_header.spec.ts
@@ -0,0 +1,100 @@
+import "../theme/table_sticky_header.css";
+
+import { _setModelData as setModelData, Essentials, Paragraph, Table } from "ckeditor5";
+import type { ClassicEditor, ModelElement } from "ckeditor5";
+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import { modelTable } from "../../test/table-kit.js";
+import TableStickyHeader from "./table_sticky_header.js";
+import { START_PROPERTY, TRAVEL_PROPERTY } from "./table_sticky_header_read_only.js";
+
+describe("TableStickyHeader", () => {
+ let editor: ClassicEditor;
+ let scroller: HTMLDivElement;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([ Essentials, Paragraph, Table, TableStickyHeader ]);
+ scroller = document.createElement("div");
+ scroller.style.cssText = "position:fixed;top:0;left:0;height:200px;width:400px;"
+ + "overflow:auto;";
+ document.body.appendChild(scroller);
+ if (editor.ui.element) {
+ scroller.appendChild(editor.ui.element);
+ }
+ });
+
+ afterEach(() => {
+ scroller.remove();
+ });
+
+ it("keeps the header rows in view and measures them again when they change", async () => {
+ setModelData(editor.model, modelTable(rows(30), 'headingRows="1"'));
+ await settle();
+
+ const thead = domHead(editor);
+ const travel = parseFloat(thead.style.getPropertyValue(TRAVEL_PROPERTY));
+ expect(thead.style.getPropertyValue(START_PROPERTY)).not.toBe("");
+ expect(travel).toBeGreaterThan(500);
+
+ const scrollerTop = scroller.getBoundingClientRect().top;
+ scroller.scrollTop = thead.getBoundingClientRect().top - scrollerTop + 200;
+ await settle();
+ expect(thead.getBoundingClientRect().top - scrollerTop).toBeCloseTo(0, 0);
+
+ scroller.scrollTop = 0;
+ editor.model.change((writer) => writer.setAttribute("headingRows", 2, firstTable(editor)));
+ await settle();
+ const newHead = domHead(editor);
+ const tableBottom = newHead.closest("table")?.getBoundingClientRect().bottom ?? 0;
+ expect(parseFloat(newHead.style.getPropertyValue(TRAVEL_PROPERTY)))
+ .toBeCloseTo(tableBottom - newHead.getBoundingClientRect().bottom, 1);
+ expect(parseFloat(newHead.style.getPropertyValue(TRAVEL_PROPERTY))).toBeLessThan(travel);
+ });
+
+ it("stops measuring removed tables, and all of them on destroy", () => {
+ const unobserve = vi.spyOn(ResizeObserver.prototype, "unobserve");
+ const disconnect = vi.spyOn(ResizeObserver.prototype, "disconnect");
+ onTestFinished(() => {
+ unobserve.mockRestore();
+ disconnect.mockRestore();
+ });
+ setModelData(editor.model, modelTable(rows(3), 'headingRows="1"'));
+ const thead = domHead(editor);
+ const figure = thead.closest("figure");
+
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ expect(unobserve.mock.calls).toEqual([ [ figure ], [ thead ] ]);
+
+ editor.plugins.get(TableStickyHeader).destroy();
+ expect(disconnect).toHaveBeenCalledOnce();
+ });
+});
+
+function rows(count: number) {
+ return Array.from({ length: count }, (_, index) => [ `Row ${index}`, "Second" ]);
+}
+
+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 domHead(editor: ClassicEditor) {
+ const thead = editor.editing.view.getDomRoot()
+ ?.querySelector<HTMLTableSectionElement>("figure.table > table > thead");
+ if (!thead) {
+ throw new Error("The editor has no table with header rows.");
+ }
+ return thead;
+}
+
+/** Waits for a resize to be observed, and for the frame in which the header rows are measured. */
+async function settle() {
+ for (let frame = 0; frame < 3; frame++) {
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/table_sticky_header.ts b/packages/ckeditor5/src/plugins/table_sticky_header.ts
new file mode 100644
index 0000000000..353de27407
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_sticky_header.ts
@@ -0,0 +1,37 @@
+import { Plugin } from "ckeditor5";
+
+import { StickyTableHeaders } from "./table_sticky_header_read_only.js";
+
+/**
+ * Keeps the header rows of a table at the top of the scrolled area while the rest of the table
+ * passes under them. `table_sticky_header.css` moves the rows; this plugin measures them.
+ */
+export default class TableStickyHeader extends Plugin {
+
+ private readonly headers = new StickyTableHeaders();
+
+ static get pluginName() {
+ return "TableStickyHeader" as const;
+ }
+
+ init() {
+ const view = this.editor.editing.view;
+ this.listenTo(view, "render", () => {
+ for (const domRoot of view.domRoots.values()) {
+ this.headers.observe(domRoot);
+ }
+ });
+ }
+
+ override destroy() {
+ this.headers.disconnect();
+ super.destroy();
+ }
+
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [TableStickyHeader.pluginName]: TableStickyHeader;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/table_sticky_header_read_only.spec.ts b/packages/ckeditor5/src/plugins/table_sticky_header_read_only.spec.ts
new file mode 100644
index 0000000000..f79508b05c
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_sticky_header_read_only.spec.ts
@@ -0,0 +1,223 @@
+import "../theme/table_scroll.css";
+import "../theme/table_sticky_header.css";
+
+import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";
+import { afterAll, beforeAll, describe, expect, it, onTestFinished, vi } from "vitest";
+
+import { applyTableScroll } from "./table_scroll_read_only.js";
+import {
+ applyStickyTableHeaders, START_PROPERTY, StickyTableHeaders, TRAVEL_PROPERTY
+} from "./table_sticky_header_read_only.js";
+
+const SCROLLER_HEIGHT = 200;
+
+describe("applyStickyTableHeaders", () => {
+ 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 header rows at the top of the scrolled area until the table ends", async () => {
+ const { scroller, content } = renderContent(tableFigure(2, 20, "Caption"));
+ applyStickyTableHeaders(content);
+ await settle();
+
+ const { figure, table, thead } = parts(content);
+ const header = thead.getBoundingClientRect();
+ const tableBox = table.getBoundingClientRect();
+ const start = header.top - figure.getBoundingClientRect().top;
+ expect(start).toBeGreaterThan(10);
+ expect(lengthOf(thead, START_PROPERTY)).toBeCloseTo(start, 1);
+ expect(lengthOf(thead, TRAVEL_PROPERTY)).toBeCloseTo(tableBox.bottom - header.bottom, 1);
+ expect(bordersOf(thead)).toBe("none");
+
+ await scrollTo(scroller, offsetIn(scroller, thead) + 150);
+ expect(topIn(scroller, thead)).toBeCloseTo(0, 0);
+ expect(bordersOf(thead)).toBe("block");
+ const hit = document.elementFromPoint(
+ thead.getBoundingClientRect().left + 10, scroller.getBoundingClientRect().top + 5);
+ expect(hit?.closest("thead")).toBe(thead);
+
+ await scrollTo(scroller, offsetIn(scroller, table) + table.offsetHeight - 10);
+ expect(thead.getBoundingClientRect().bottom)
+ .toBeCloseTo(table.getBoundingClientRect().bottom - 1, 0);
+
+ await scrollTo(scroller, 0);
+ expect(getComputedStyle(thead).translate).toBe("none");
+ expect(bordersOf(thead)).toBe("none");
+ });
+
+ it("measures the header rows again when the table grows while they stick", async () => {
+ const { scroller, content } = renderContent(tableFigure(1, 20));
+ applyStickyTableHeaders(content);
+ await settle();
+
+ const { table, thead } = parts(content);
+ const start = thead.style.getPropertyValue(START_PROPERTY);
+ const travel = lengthOf(thead, TRAVEL_PROPERTY);
+ await scrollTo(scroller, offsetIn(scroller, thead) + 100);
+ expect(getComputedStyle(thead).translate).not.toBe("none");
+
+ const row = table.tBodies[0].rows[0];
+ row.after(row.cloneNode(true));
+ await settle();
+ expect(thead.style.getPropertyValue(START_PROPERTY)).toBe(start);
+ expect(lengthOf(thead, TRAVEL_PROPERTY)).toBeCloseTo(travel + row.offsetHeight, 0);
+ expect(topIn(scroller, thead)).toBeCloseTo(0, 0);
+ });
+
+ it("sticks below the scroll padding of the scrolled area", async () => {
+ const { scroller, content } = renderContent(tableFigure(1, 20));
+ scroller.style.scrollPaddingTop = "30px";
+ applyStickyTableHeaders(content);
+ await settle();
+
+ const { thead } = parts(content);
+ await scrollTo(scroller, offsetIn(scroller, thead) + 100);
+ expect(topIn(scroller, thead)).toBeCloseTo(30, 0);
+ });
+
+ it("keeps the header rows of a table that scrolls sideways in view", async () => {
+ const html = tableFigure(1, 20, "Caption", "width:300%;");
+ const { scroller, content } = renderContent(html);
+ applyTableScroll(content);
+ applyStickyTableHeaders(content);
+ await settle();
+
+ const { figure, thead } = parts(content);
+ expect(getComputedStyle(figure).overflowX).toBe("auto");
+ expect(lengthOf(thead, START_PROPERTY)).toBeCloseTo(
+ thead.getBoundingClientRect().top - figure.getBoundingClientRect().top, 1);
+ await scrollTo(scroller, offsetIn(scroller, thead) + 100);
+ expect(topIn(scroller, thead)).toBeCloseTo(0, 0);
+ });
+
+ it("measures content attached after the call", async () => {
+ const { scroller, content } = renderContent(tableFigure(1, 20));
+ content.remove();
+ applyStickyTableHeaders(content);
+ await settle();
+ const { thead } = parts(content);
+ expect(thead.style.getPropertyValue(START_PROPERTY)).toBe("");
+
+ scroller.appendChild(content);
+ await settle();
+ expect(thead.style.getPropertyValue(START_PROPERTY)).not.toBe("");
+ });
+
+ it("leaves out tables without header rows and layout tables", () => {
+ const observe = vi.spyOn(ResizeObserver.prototype, "observe");
+ onTestFinished(() => observe.mockRestore());
+ const layout = tableFigure(1, 2).replace("class=\"table\"", "class=\"table layout-table\"");
+ const { content } = renderContent(tableFigure(0, 2) + layout);
+
+ applyStickyTableHeaders(content);
+ expect(observe).not.toHaveBeenCalled();
+ });
+
+ it("stops measuring the tables removed from the container", async () => {
+ const unobserve = vi.spyOn(ResizeObserver.prototype, "unobserve");
+ const disconnect = vi.spyOn(ResizeObserver.prototype, "disconnect");
+ onTestFinished(() => {
+ unobserve.mockRestore();
+ disconnect.mockRestore();
+ });
+ const { content } = renderContent(tableFigure(1, 2) + tableFigure(1, 2));
+ const headers = new StickyTableHeaders();
+ headers.observe(content);
+ headers.observe(content);
+ expect(unobserve).not.toHaveBeenCalled();
+
+ const [ removed, kept ] = content.querySelectorAll("figure");
+ const removedHead = parts(removed).thead;
+ removed.remove();
+ headers.observe(content);
+ expect(unobserve.mock.calls).toEqual([ [ removed ], [ removedHead ] ]);
+
+ parts(kept).thead.remove();
+ await settle();
+ headers.disconnect();
+ expect(disconnect).toHaveBeenCalledOnce();
+ });
+});
+
+/** A table figure with header rows and body rows, and a caption when `caption` is set. */
+function tableFigure(headerRows: number, bodyRows: number, caption = "", style = "") {
+ const row = (cell: string, index: number) => `<tr><${cell}>${cell} ${index}</${cell}>`
+ + `<${cell}>Second</${cell}><${cell}>Third</${cell}></tr>`;
+ const headRows = Array.from({ length: headerRows }, (_, index) => row("th", index)).join("");
+ const head = headerRows ? `<thead>${headRows}</thead>` : "";
+ const body = Array.from({ length: bodyRows }, (_, index) => row("td", index)).join("");
+ const figcaption = caption ? `<figcaption>${caption}</figcaption>` : "";
+ return `<figure class="table" style="${style}"><table>${head}<tbody>${body}</tbody></table>`
+ + `${figcaption}</figure>`;
+}
+
+/** Renders `html` as content in a scrolled area with room above and below it. */
+function renderContent(html: string) {
+ const scroller = document.createElement("div");
+ scroller.style.cssText = "position:fixed;top:0;left:0;"
+ + `height:${SCROLLER_HEIGHT}px;width:400px;overflow:auto;`;
+ const content = document.createElement("div");
+ content.className = "ck-content";
+ content.innerHTML = `<div style="height:100px"></div>${html}`
+ + `<div style="height:${SCROLLER_HEIGHT * 2}px"></div>`;
+ scroller.appendChild(content);
+ document.body.appendChild(scroller);
+ onTestFinished(() => scroller.remove());
+ return { scroller, content };
+}
+
+function parts(container: Element) {
+ const figure = container.matches("figure") ? container : container.querySelector("figure");
+ const table = figure?.querySelector<HTMLTableElement>(":scope > table");
+ const thead = table?.querySelector<HTMLElement>(":scope > thead");
+ if (!(figure instanceof HTMLElement) || !table || !thead) {
+ throw new Error("The content has no table with header rows.");
+ }
+ return { figure, table, thead };
+}
+
+function lengthOf(element: HTMLElement, property: string) {
+ return parseFloat(element.style.getPropertyValue(property));
+}
+
+function bordersOf(thead: HTMLElement) {
+ const cell = thead.querySelector("th");
+ if (!cell) {
+ throw new Error("The header rows have no cell.");
+ }
+ return getComputedStyle(cell, "::before").display;
+}
+
+/** The distance from the top of `scroller` to `element`, as laid out without scrolling. */
+function offsetIn(scroller: HTMLElement, element: HTMLElement) {
+ return element.getBoundingClientRect().top - scroller.getBoundingClientRect().top
+ + scroller.scrollTop;
+}
+
+/** The distance from the top of `scroller` to where `element` is drawn. */
+function topIn(scroller: HTMLElement, element: HTMLElement) {
+ return element.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
+}
+
+async function scrollTo(scroller: HTMLElement, top: number) {
+ scroller.scrollTop = top;
+ await settle();
+}
+
+/** Waits for a resize to be observed, and for the frame in which the header rows are measured. */
+async function settle() {
+ for (let frame = 0; frame < 3; frame++) {
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/table_sticky_header_read_only.ts b/packages/ckeditor5/src/plugins/table_sticky_header_read_only.ts
new file mode 100644
index 0000000000..e28866f31c
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/table_sticky_header_read_only.ts
@@ -0,0 +1,119 @@
+/**
+ * Measures the header rows of content tables for `table_sticky_header.css`, which keeps them at
+ * the top of the scrolled area while the rest of their table passes under them.
+ *
+ * The module imports nothing from CKEditor, so pages that only display content can load it.
+ */
+
+/** The distance from the top of the figure to the header rows, set on the `thead`. */
+export const START_PROPERTY = "--table-header-start";
+
+/** The distance from the bottom of the header rows to the bottom of the table. */
+export const TRAVEL_PROPERTY = "--table-header-travel";
+
+/** Keeps the header rows of the tables in `container` in view while it scrolls. */
+export function applyStickyTableHeaders(container: Element) {
+ new StickyTableHeaders().observe(container);
+}
+
+/** Measures header rows again whenever their figure or the rows themselves change size. */
+export class StickyTableHeaders {
+
+ private observer: ResizeObserver | undefined;
+
+ private readonly observed = new Set<Element>();
+
+ /** The figures to measure in the next animation frame. */
+ private readonly resized = new Set<Element>();
+
+ private frame: number | undefined;
+
+ /**
+ * Starts measuring the header rows in `container` that are not measured yet, and stops
+ * measuring the ones removed from the document.
+ */
+ observe(container: Element) {
+ for (const element of this.observed) {
+ if (!element.isConnected) {
+ this.observer?.unobserve(element);
+ this.observed.delete(element);
+ }
+ }
+
+ const figures = container.querySelectorAll("figure.table:not(.layout-table)");
+ for (const figure of figures) {
+ const thead = figure.querySelector(":scope > table > thead");
+ if (thead) {
+ this.watch(figure);
+ this.watch(thead);
+ }
+ }
+ }
+
+ disconnect() {
+ this.observer?.disconnect();
+ this.observed.clear();
+ this.resized.clear();
+ }
+
+ private watch(element: Element) {
+ if (!this.observed.has(element)) {
+ this.observer ??= new ResizeObserver((entries) => this.onResize(entries));
+ this.observer.observe(element);
+ this.observed.add(element);
+ }
+ }
+
+ private onResize(entries: ResizeObserverEntry[]) {
+ for (const { target } of entries) {
+ const figure = target.closest("figure");
+ if (figure) {
+ this.resized.add(figure);
+ }
+ }
+
+ // Chromium drops a range change made in the frame that creates the animation.
+ this.frame ??= requestAnimationFrame(() => this.measureResized());
+ }
+
+ private measureResized() {
+ this.frame = undefined;
+ for (const figure of this.resized) {
+ if (figure.isConnected) {
+ measure(figure);
+ }
+ }
+ this.resized.clear();
+ }
+
+}
+
+/** Sets the start and the travel of the header rows, measured without the shift of sticking. */
+function measure(figure: Element) {
+ const table = figure.querySelector(":scope > table");
+ const thead = table?.querySelector<HTMLElement>(":scope > thead");
+ if (!table || !thead) {
+ return;
+ }
+
+ const shift = getShift(thead);
+ const header = thead.getBoundingClientRect();
+ const start = header.top - shift - figure.getBoundingClientRect().top;
+ const travel = table.getBoundingClientRect().bottom - (header.bottom - shift);
+ setLength(thead, START_PROPERTY, start);
+ setLength(thead, TRAVEL_PROPERTY, travel);
+}
+
+/** The vertical `translate` that the running animation gives `element`. */
+function getShift(element: HTMLElement) {
+ const [ , y = "0" ] = getComputedStyle(element).translate.split(" ");
+ return parseFloat(y);
+}
+
+/** Sets a length in pixels, leaving the style alone when the value is the same. */
+function setLength(element: HTMLElement, property: string, pixels: number) {
+ const value = `${Math.round(pixels * 100) / 100}px`;
+ if (element.style.getPropertyValue(property) !== value) {
+ element.style.setProperty(property, value);
+ }
+}
diff --git a/packages/ckeditor5/src/theme/table_sticky_header.css b/packages/ckeditor5/src/theme/table_sticky_header.css
new file mode 100644
index 0000000000..a5017e294d
--- /dev/null
+++ b/packages/ckeditor5/src/theme/table_sticky_header.css
@@ -0,0 +1,77 @@
+/* Without a scroll timeline, an `animation` runs on time and ends at once. Longhands only: Lightning
+ CSS expands the `animation` shorthand with a `0s` duration, which ends a scroll-driven one too. */
+@supports (view-timeline-name: --table-header) {
+ .ck-content figure.table:not(.layout-table) {
+ view-timeline: --table-header block;
+ view-timeline-inset: auto;
+
+ > table {
+ animation-name: table-header-isolate;
+ animation-duration: auto;
+ animation-timeline: --table-header;
+ animation-range: exit-crossing 0% exit-crossing 100%;
+ }
+
+ /* `StickyTableHeaders` sets `--table-header-start` and `--table-header-travel`. */
+ > table > thead {
+ /* Leaves room for the 1px that the borders of `th::before` reach past the cells. */
+ --table-header-end: calc(var(--table-header-travel, 1px) - 1px);
+
+ position: relative;
+ animation-name: table-header-stick, table-header-stuck;
+ animation-duration: auto;
+ animation-timing-function: linear;
+ animation-fill-mode: forwards;
+ animation-timeline: --table-header;
+ animation-range:
+ exit-crossing var(--table-header-start, 0px)
+ exit-crossing calc(var(--table-header-start, 0px) + var(--table-header-end));
+
+ > tr > th {
+ position: relative;
+
+ /* Collapsed borders stay at the rest position of the header rows. */
+ &::before {
+ content: "";
+ display: var(--table-header-borders, none);
+ position: absolute;
+ inset: -1px;
+ border: inherit;
+ pointer-events: none;
+ }
+ }
+ }
+
+ @media print {
+ > table,
+ > table > thead {
+ animation-name: none;
+ }
+ }
+ }
+}
+
+@keyframes table-header-stick {
+ from {
+ translate: 0 0;
+ }
+
+ to {
+ translate: 0 var(--table-header-end);
+ }
+}
+
+@keyframes table-header-stuck {
+ from,
+ to {
+ z-index: 2;
+ --table-header-borders: block;
+ }
+}
+
+@keyframes table-header-isolate {
+ from,
+ to {
+ isolation: isolate;
+ }
+}
diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.ts
index b2175504c1..afe5c1ad5d 100644
--- a/packages/share-theme/src/index.spec.ts
+++ b/packages/share-theme/src/index.spec.ts
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
setupMath: vi.fn(),
setupMermaid: vi.fn(),
applyTableScroll: vi.fn(),
+ applyStickyTableHeaders: vi.fn(),
applyTabs: vi.fn(),
revealFragment: vi.fn(),
showBlockReference: vi.fn(),
@@ -40,6 +41,9 @@ 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/table_sticky_header_read_only.js", () => ({
+ applyStickyTableHeaders: mocks.applyStickyTableHeaders
+}));
vi.mock("@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js", () => ({
applyTabs: mocks.applyTabs,
revealFragment: mocks.revealFragment
@@ -112,6 +116,7 @@ describe("share theme entry", () => {
expect(mocks.enhanceLinkPreviews).toHaveBeenCalledWith(document.body);
expect(mocks.applyTableScroll.mock.calls)
.toEqual([ [ content ], [ content?.querySelector(".include-note") ] ]);
+ expect(mocks.applyStickyTableHeaders.mock.calls).toEqual([ [ content ] ]);
expect(mocks.applyTabs).toHaveBeenCalledWith(content, { placeholder: "Tab" });
expect(panel.scrollIntoView).toHaveBeenCalledOnce();
@@ -164,6 +169,7 @@ describe("share theme entry", () => {
expect(mocks.setupMath).toHaveBeenCalledTimes(2);
expect(mocks.applyTableScroll).toHaveBeenCalledOnce();
+ expect(mocks.applyStickyTableHeaders).toHaveBeenCalledOnce();
expect(mocks.applyTabs).not.toHaveBeenCalled();
});
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index a7aa44e100..b85225effa 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -27,9 +27,13 @@ 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/table_sticky_header.css";
import "@triliumnext/ckeditor5/src/theme/todo_lists.css";
import { applyTableScroll } from "@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js";
+import {
+ applyStickyTableHeaders
+} from "@triliumnext/ckeditor5/src/plugins/table_sticky_header_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";
@@ -72,6 +76,7 @@ function setupTextNote() {
$try(setupMath);
$try(() => enhanceLinkPreviews(document.body));
$try(setupTableScroll);
+ $try(setupStickyTableHeaders);
$try(setupTabs);
return diagrams;
}
@@ -104,6 +109,13 @@ function setupTableScroll() {
}
}
+function setupStickyTableHeaders() {
+ const content = document.getElementById("content");
+ if (content) {
+ applyStickyTableHeaders(content);
+ }
+}
+
function setupTabs() {
const content = document.getElementById("content");
if (content) {