Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: use faded edge to indicate overflowing tables

Adorian Doran45e79db215bf
diff --git a/apps/client/src/index.ts b/apps/client/src/index.ts
index df8ce4aec9..d809a78e57 100644
--- a/apps/client/src/index.ts
+++ b/apps/client/src/index.ts
@@ -11,6 +11,7 @@ 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 "@triliumnext/commons/src/lib/scroll_fade.css";
import { createFontStylesheetLink } from "./services/font";
import {
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index 99cfce9a52..30e5e48ce9 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -58,6 +58,13 @@ vi.mock("@triliumnext/ckeditor5/src/plugins/table_sticky_header_read_only.js", (
applyStickyTableHeaders
}));
+// jsdom has no `ResizeObserver`.
+const watchScrollFade = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/commons/src/lib/scroll_fade.js", async (importOriginal) => ({
+ ...await importOriginal<object>(),
+ watchScrollFade
+}));
+
import renderText, {
applyInlineMermaid,
postProcessRichContent,
@@ -285,6 +292,8 @@ describe("Text content renderer", () => {
await renderTextContent(note, table, $(full));
expect(tableWidth(full)).toBe("800px");
expect(applyStickyTableHeaders).toHaveBeenCalledWith(full.querySelector(".ck-content"));
+ expect(watchScrollFade).toHaveBeenCalledWith(full.querySelector("figure.table"),
+ expect.any(Function), { direction: "horizontal" });
// 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/widgets/react/scroll_fade.spec.tsx b/apps/client/src/widgets/react/scroll_fade.spec.tsx
index 64365ff717..8f0eb5d69f 100644
--- a/apps/client/src/widgets/react/scroll_fade.spec.tsx
+++ b/apps/client/src/widgets/react/scroll_fade.spec.tsx
@@ -3,7 +3,7 @@ import { useRef, useState } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { ScrollFadeOptions, useScrollFade } from "./scroll_fade";
+import { ScrollFade, ScrollFadeOptions, useScrollFade } from "./scroll_fade";
describe("useScrollFade", () => {
let container: HTMLElement | undefined;
@@ -52,57 +52,30 @@ describe("useScrollFade", () => {
}
});
- it("fades the end alone while the content is scrolled to the start", () => {
+ it("names the faded edges in its classes as the content scrolls", () => {
const scroller = setup();
-
expect(scroller.className).toContain("scroll-fade-end");
expect(scroller.className).not.toContain("scroll-fade-start");
- });
-
- it("fades both ends once the content is scrolled between them", () => {
- const scroller = setup();
scrollTo(scroller, 400);
-
expect(scroller.className).toContain("scroll-fade-start");
expect(scroller.className).toContain("scroll-fade-end");
- });
-
- it("fades the start alone once the content is scrolled to the end", () => {
- const scroller = setup();
scrollTo(scroller, 800);
-
expect(scroller.className).toContain("scroll-fade-start");
expect(scroller.className).not.toContain("scroll-fade-end");
});
- it("fades neither end while the content fits", () => {
- const scroller = setup({ contentSize: 150 });
-
- expect(scroller.className).not.toContain("scroll-fade-start");
- expect(scroller.className).not.toContain("scroll-fade-end");
- });
-
- /**
- * A fade reaching 20px into a container that scrolls 2px covers ten times what it hides, and
- * reads as content below that scrolling never reaches.
- */
- it("leaves both ends alone while there is less to scroll than the fade reaches", () => {
- const scroller = setup({ contentSize: 218 });
-
- expect(scroller.className).not.toContain("scroll-fade-end");
+ it("reports the overflow and measures on request", () => {
+ let fade: ScrollFade | undefined;
+ setup({ onRender: (result) => { fade = result; } });
+ expect(fade?.overflow).toBe(800);
- // Past the fade's own reach, so the fade now stands for something.
- content = 222;
- act(() => {
- scroller.dispatchEvent(new Event("scroll"));
- vi.advanceTimersByTime(20);
- });
- expect(scroller.className).toContain("scroll-fade-end");
+ content = 600;
+ act(() => { fade?.measure(); });
+ expect(fade?.overflow).toBe(400);
});
- /** A line of text cut off by a character still has to read as cut off. */
it("fades a smaller overflow for a caller that asks for one", () => {
const scroller = setup({ contentSize: 205, options: { minOverflow: 1 } });
@@ -164,9 +137,10 @@ describe("useScrollFade", () => {
.toContain("scroll-fade-end");
});
- function setup({ contentSize, options }: {
+ function setup({ contentSize, options, onRender }: {
contentSize?: number,
- options?: ScrollFadeOptions
+ options?: ScrollFadeOptions,
+ onRender?: (fade: ScrollFade) => void
} = {}) {
if (contentSize !== undefined) content = contentSize;
@@ -176,8 +150,9 @@ describe("useScrollFade", () => {
function Harness() {
const ref = useRef<HTMLDivElement>(null);
- const { className, style } = useScrollFade(ref, options);
- return <div ref={ref} className={className} style={style} />;
+ const fade = useScrollFade(ref, options);
+ onRender?.(fade);
+ return <div ref={ref} className={fade.className} style={fade.style} />;
}
act(() => { render(<Harness />, mountPoint); });
diff --git a/apps/client/src/widgets/react/scroll_fade.ts b/apps/client/src/widgets/react/scroll_fade.ts
index 5f624f7942..b5feac8ee9 100644
--- a/apps/client/src/widgets/react/scroll_fade.ts
+++ b/apps/client/src/widgets/react/scroll_fade.ts
@@ -1,42 +1,27 @@
-import "./scroll_fade.css";
+import "@triliumnext/commons/src/lib/scroll_fade.css";
-import clsx from "clsx";
+import {
+ getScrollFadeClasses, NO_SCROLL_FADE, type ScrollFadeWatch, type ScrollFadeWatchOptions,
+ watchScrollFade
+} from "@triliumnext/commons";
import { CSSProperties, RefObject } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { useTrackedElement } from "./hooks";
-/** Fractional scroll offsets are reported at sub-pixel precision, so an edge is never tested exactly. */
-const EDGE_EPSILON = 1;
-
-/** How far a fade reaches from an edge when the caller names no size. Matches `scroll_fade.css`. */
-const DEFAULT_FADE_SIZE = 20;
-
-export interface ScrollFadeOptions {
- /** Which way the container scrolls. */
- direction?: "horizontal" | "vertical";
- /** How far the fade reaches from each edge, in pixels. */
- size?: number;
+export interface ScrollFadeOptions extends ScrollFadeWatchOptions {
/** How long a fade takes to arrive and to leave, in milliseconds. */
duration?: number;
- /**
- * The least a container has to scroll for its edges to be faded at all, in pixels.
- *
- * Defaults to the fade's own size, a fade reaching further than the container can scroll
- * covering more than it hides. Lower it where a few hidden pixels still have to be reported,
- * such as a line of text cut off by a character.
- */
- minOverflow?: number;
}
export interface ScrollFade {
- /** Goes on the scroll container, alongside whatever else it wears. */
+ /** The classes of the scroll container. */
className: string;
- /** Carries the size and duration, which CSS reads as lengths and times. */
+ /** The size and duration of the fade, as CSS custom properties. */
style: CSSProperties;
/** How much of the content lies outside the box, along the scrolling axis. */
overflow: number;
- /** Re-measures, for content that changes without the DOM or the box saying so. */
+ /** Measures again, for content that changes without a resize or a DOM mutation. */
measure: () => void;
}
@@ -48,97 +33,32 @@ export interface ScrollFade {
* @param options which way it scrolls, how far each fade reaches and how long it takes.
*/
export function useScrollFade(ref: RefObject<HTMLElement | null>, options: ScrollFadeOptions = {}): ScrollFade {
- const {
- direction = "vertical", size, duration, minOverflow = size ?? DEFAULT_FADE_SIZE
- } = options;
- const [ fades, setFades ] = useState({ start: false, end: false });
- const [ overflow, setOverflow ] = useState(0);
- const frameRef = useRef<number | undefined>(undefined);
+ const { direction = "vertical", size, duration, minOverflow } = options;
+ const [ state, setState ] = useState(NO_SCROLL_FADE);
+ const watchRef = useRef<ScrollFadeWatch | null>(null);
const element = useTrackedElement(ref);
- const measure = useCallback(() => {
- if (!element) return;
-
- const horizontal = direction === "horizontal";
- // Read as a distance travelled rather than as a coordinate: a right-to-left page scrolls the
- // same content towards negative offsets, and both ends ask the same question either way.
- const travelled = Math.abs(horizontal ? element.scrollLeft : element.scrollTop);
- const total = horizontal
- ? element.scrollWidth - element.clientWidth
- : element.scrollHeight - element.clientHeight;
-
- setOverflow(total);
- setFades((current) => {
- const isFaded = total > minOverflow;
- const next = {
- start: isFaded && travelled > EDGE_EPSILON,
- end: isFaded && travelled < total - EDGE_EPSILON
- };
- return current.start === next.start && current.end === next.end ? current : next;
- });
- }, [ element, direction, minOverflow ]);
-
useEffect(() => {
if (!element) return;
- // Coalesced, for the observers alone: a batch of cards arriving fires one per change, and
- // each measurement reads a layout the last one just invalidated. A scroll is measured as it
- // happens, so the fade keeps up with the finger rather than trailing it by a frame.
- const request = () => {
- if (frameRef.current === undefined) {
- frameRef.current = requestAnimationFrame(() => {
- frameRef.current = undefined;
- measure();
- });
- }
- };
-
- measure();
-
- // The box is resized by everything from a window to a pane being dragged; the content grows
- // and shrinks without either, which no resize reports.
- const resize = new ResizeObserver(request);
- resize.observe(element);
-
- // The children too: one of them growing changes how much there is to scroll while the box
- // it grows inside keeps its size, and an animated height is not a change to the page that
- // anything else here would hear about.
- const watchChildren = () => {
- for (const child of element.children) {
- resize.observe(child);
- }
- };
- watchChildren();
-
- const mutations = new MutationObserver(() => {
- watchChildren();
- request();
- });
- mutations.observe(element, { childList: true, subtree: true, characterData: true });
- element.addEventListener("scroll", measure, { passive: true });
-
+ const watch = watchScrollFade(element, setState, { direction, size, minOverflow });
+ watchRef.current = watch;
return () => {
- resize.disconnect();
- mutations.disconnect();
- element.removeEventListener("scroll", measure);
- if (frameRef.current !== undefined) {
- cancelAnimationFrame(frameRef.current);
- frameRef.current = undefined;
- }
+ watch.disconnect();
+ watchRef.current = null;
};
- }, [ element, measure ]);
+ }, [ element, direction, size, minOverflow ]);
+
+ const measure = useCallback(() => watchRef.current?.measure(), []);
return {
- className: clsx("scroll-fade", `scroll-fade-${direction}`, {
- "scroll-fade-start": fades.start,
- "scroll-fade-end": fades.end
- }),
+ className: getScrollFadeClasses(direction, state).join(" "),
style: {
...(size !== undefined && { "--scroll-fade-size": `${size}px` }),
...(duration !== undefined && { "--scroll-fade-duration": `${duration}ms` })
} as CSSProperties,
- overflow,
+ overflow: state.overflow,
measure
};
}
diff --git a/packages/ckeditor5/src/plugins/table_scroll.spec.ts b/packages/ckeditor5/src/plugins/table_scroll.spec.ts
index d170279f06..976c1a81bf 100644
--- a/packages/ckeditor5/src/plugins/table_scroll.spec.ts
+++ b/packages/ckeditor5/src/plugins/table_scroll.spec.ts
@@ -1,3 +1,4 @@
+import "@triliumnext/commons/src/lib/scroll_fade.css";
import "../theme/table_scroll.css";
import {
@@ -15,8 +16,10 @@ 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";
+import { fadeClasses, modelTable, scrollFigure } from "../../test/table-kit.js";
+import TriliumTableScroll, {
+ REFERENCE_WIDTH_PROPERTY, VIEWPORT_WIDTH_PROPERTY
+} from "./table_scroll.js";
const PLUGINS = [Essentials, Paragraph, BlockQuote, Table, TableColumnResize, TriliumTableScroll];
const LONG_WORD = "x".repeat(400);
@@ -175,8 +178,9 @@ describe("a table with content wider than the editable", () => {
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"));
+ const cell = figure.querySelector("td");
+ cell?.style.setProperty("min-width", "2000px");
+ cell?.dispatchEvent(new Event("load"));
expect(figure.classList.contains("ck-table-overflowing")).toBe(true);
});
@@ -201,19 +205,7 @@ describe("a table with content wider than the editable", () => {
});
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();
- });
+ useEditorStylesheet();
it("keeps the caption, the handle and the buttons whole and in view", async () => {
const editor = await createTestEditor([...PLUGINS, TableCaption]);
@@ -251,6 +243,99 @@ describe("the controls of a scrolling table", () => {
});
});
+describe("the edge fades of a scrolling table", () => {
+ useEditorStylesheet();
+
+ it("masks the visible part of the table as it scrolls, and stops once it fits", async () => {
+ const editor = await createTestEditor(PLUGINS);
+ setEditableWidth(editor, 400);
+ setModelData(editor.model, modelTable([ [ "a", "b" ] ], 'tableWidth="150%"'));
+ const figure = domFigure(editor);
+ const table = domTable(figure);
+ expect(figure.classList.contains("ck-table-overflowing")).toBe(true);
+ expect(fadeClasses(figure)).toEqual([]);
+ expect(fadeClasses(table))
+ .toEqual([ "scroll-fade", "scroll-fade-horizontal", "scroll-fade-end" ]);
+ expect(table.style.getPropertyValue(VIEWPORT_WIDTH_PROPERTY))
+ .toBe(`${figure.clientWidth}px`);
+ expect(getComputedStyle(table).maskImage).toContain("linear-gradient");
+ await expect.poll(() => getComputedStyle(table).getPropertyValue("--scroll-fade-end"))
+ .toBe("2.5%");
+
+ await scrollFigure(figure, 100);
+ expect(fadeClasses(table)).toContain("scroll-fade-start");
+ expect(fadeClasses(table)).toContain("scroll-fade-end");
+ const maskLeft = table.getBoundingClientRect().left
+ + parseFloat(getComputedStyle(table).maskPosition);
+ expect(maskLeft).toBeCloseTo(figure.getBoundingClientRect().left + figure.clientLeft, 0);
+
+ await scrollFigure(figure, figure.scrollWidth - figure.clientWidth);
+ expect(fadeClasses(table)).toContain("scroll-fade-start");
+ expect(fadeClasses(table)).not.toContain("scroll-fade-end");
+
+ editor.model.change((writer) => {
+ writer.setAttribute("tableWidth", "50%", firstTable(editor));
+ });
+ const fitting = domTable(domFigure(editor));
+ expect(domFigure(editor).classList.contains("ck-table-overflowing")).toBe(false);
+ expect(fadeClasses(fitting)).toEqual([]);
+ expect(fitting.style.getPropertyValue(VIEWPORT_WIDTH_PROPERTY)).toBe("");
+
+ // A table that replaces a scrolling one gets a fade of its own.
+ editor.model.change((writer) => {
+ writer.setAttribute("tableWidth", "150%", firstTable(editor));
+ });
+ setModelData(editor.model, modelTable([ [ "c", "d" ] ], 'tableWidth="200%"'));
+ expect(fadeClasses(domTable(domFigure(editor)))).toContain("scroll-fade-end");
+ });
+
+ it("anchors the mask on the right of a right-to-left table", async () => {
+ const editor = await createTestEditor(PLUGINS, { language: { content: "ar" } });
+ setEditableWidth(editor, 400);
+ setModelData(editor.model, modelTable([ [ "a", "b" ] ], 'tableWidth="150%"'));
+ const figure = domFigure(editor);
+ const table = domTable(figure);
+ expect(getComputedStyle(figure).direction).toBe("rtl");
+ expect(fadeClasses(table)).toEqual([
+ "scroll-fade", "scroll-fade-horizontal", "scroll-fade-end", "scroll-fade-rtl"
+ ]);
+ expect(getComputedStyle(table).getPropertyValue("--scroll-fade-direction")).toBe("to left");
+ expect(getComputedStyle(table).maskPosition).toContain("100%");
+
+ // `table_scroll.css` puts the mask at the full overflow plus the negative `scrollLeft`.
+ await scrollFigure(figure, -100);
+ const visibleLeft = figure.getBoundingClientRect().left + figure.clientLeft;
+ expect(visibleLeft - table.getBoundingClientRect().left)
+ .toBeCloseTo(table.offsetWidth - figure.clientWidth - 100, 0);
+ expect(fadeClasses(table)).toContain("scroll-fade-start");
+ });
+});
+
+/** Loads the stylesheet of the editor for the tests of the enclosing `describe`. */
+function useEditorStylesheet() {
+ 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();
+ });
+}
+
+function domTable(figure: HTMLElement) {
+ const table = figure.querySelector(":scope > table");
+ if (!(table instanceof HTMLTableElement)) {
+ throw new Error("The figure has no table.");
+ }
+ return table;
+}
+
/** Expects `control` within the visible part of `figure` and returns its left edge. */
function expectInside(figure: HTMLElement, control: Element | null) {
const bounds = figure.getBoundingClientRect();
diff --git a/packages/ckeditor5/src/plugins/table_scroll.ts b/packages/ckeditor5/src/plugins/table_scroll.ts
index bef5eccdd0..b8d671d001 100644
--- a/packages/ckeditor5/src/plugins/table_scroll.ts
+++ b/packages/ckeditor5/src/plugins/table_scroll.ts
@@ -1,11 +1,22 @@
import {
- type ModelElement, TableScrollEditing, type ViewDowncastWriter, type ViewElement
+ NO_SCROLL_FADE, SCROLL_FADE_CLASSES, type ScrollFadeState, type ScrollFadeWatch,
+ watchScrollFade
+} from "@triliumnext/commons";
+import {
+ type EditingView, type ModelElement, TableScrollEditing, type ViewDowncastWriter,
+ type ViewElement
} from "ckeditor5";
+import { getTableFadeClasses } from "./table_scroll_read_only.js";
+
/** The CSS property that sets the width a table takes as its full width. */
export const REFERENCE_WIDTH_PROPERTY = "--table-reference-width";
+/** The width of the visible part of a scrolling table, which sizes its edge fades. */
+export const VIEWPORT_WIDTH_PROPERTY = "--table-viewport-width";
+
const OVERFLOWING_CLASS = "ck-table-overflowing";
+const OVERFLOWING_SELECTOR = `figure.table.${OVERFLOWING_CLASS}`;
/**
* CKEditor's `TableScrollEditing`, which lets a table wider than the editable scroll sideways,
@@ -19,12 +30,18 @@ const OVERFLOWING_CLASS = "ck-table-overflowing";
* 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.
+ *
+ * The edges that a scrolling table continues past fade through `scroll_fade.css`. The fade masks
+ * the `table` instead of the figure, so the widget outline and controls of the figure stay whole.
*/
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>();
+ /** The edge fades of the scrolling tables, by view `table`. */
+ private readonly fades = new Map<ViewElement, TableFade>();
+
private readonly onContentLoad = () => this.updateContentOverflow();
/** The editable that `onContentLoad` listens to. */
@@ -34,7 +51,10 @@ export default class TriliumTableScroll extends TableScrollEditing {
super.init();
const { editor } = this;
- this.listenTo(editor.editing.view, "render", () => this.updateContentOverflow());
+ this.listenTo(editor.editing.view, "render", () => {
+ this.updateContentOverflow();
+ this.updateFades();
+ });
editor.once("ready", () => {
// An image that loads after a render can make its table wider.
this.loadTarget = editor.editing.view.getDomRoot();
@@ -48,6 +68,10 @@ export default class TriliumTableScroll extends TableScrollEditing {
override destroy() {
this.loadTarget?.removeEventListener("load", this.onContentLoad, true);
+ for (const { watch } of this.fades.values()) {
+ watch.disconnect();
+ }
+ this.fades.clear();
super.destroy();
}
@@ -163,6 +187,62 @@ export default class TriliumTableScroll extends TableScrollEditing {
return table.left < container.left - 0.5 || table.right > container.right + 0.5;
}
+ /**
+ * Starts the edge fade of each table that begins to scroll, and stops the others. The renderer
+ * can bind a DOM figure to a new view figure, so a fade belongs to a view `table` and its DOM
+ * figure together.
+ */
+ private updateFades() {
+ const view = this.editor.editing.view;
+ const figures = new Map<ViewElement, HTMLElement>();
+ for (const domRoot of view.domRoots.values()) {
+ for (const figure of domRoot.querySelectorAll<HTMLElement>(OVERFLOWING_SELECTOR)) {
+ const viewTable = getViewTable(view, figure);
+ if (viewTable) {
+ figures.set(viewTable, figure);
+ }
+ }
+ }
+
+ const removed = [ ...this.fades ]
+ .filter(([ viewTable, { figure } ]) => figures.get(viewTable) !== figure);
+ const added = [ ...figures ]
+ .filter(([ viewTable, figure ]) => this.fades.get(viewTable)?.figure !== figure);
+ if (!removed.length && !added.length) {
+ return;
+ }
+
+ // One change block: the `setFade()` calls inside it render together, after the loops.
+ view.change(() => {
+ for (const [ viewTable, { watch } ] of removed) {
+ watch.disconnect();
+ this.fades.delete(viewTable);
+ this.setFade(viewTable, NO_SCROLL_FADE);
+ }
+ for (const [ viewTable, figure ] of added) {
+ const watch = watchScrollFade(figure, (state) => this.setFade(viewTable, state), {
+ direction: "horizontal"
+ });
+ this.fades.set(viewTable, { figure, watch });
+ }
+ });
+ }
+
+ /** Puts the fade classes for `state` and the visible width on `viewTable`. */
+ private setFade(viewTable: ViewElement, state: ScrollFadeState) {
+ const view = this.editor.editing.view;
+ const classes = getTableFadeClasses(state);
+ view.change((writer) => {
+ writer.removeClass([ ...SCROLL_FADE_CLASSES ], viewTable);
+ writer.addClass(classes, viewTable);
+ if (classes.length) {
+ writer.setStyle(VIEWPORT_WIDTH_PROPERTY, `${state.clientSize}px`, viewTable);
+ } else {
+ writer.removeStyle(VIEWPORT_WIDTH_PROPERTY, viewTable);
+ }
+ });
+ }
+
}
interface ContentOverflowChange {
@@ -171,6 +251,29 @@ interface ContentOverflowChange {
isOverflowing: boolean;
}
+interface TableFade {
+ /** The DOM figure that scrolls. */
+ figure: HTMLElement;
+ watch: ScrollFadeWatch;
+}
+
+/** The view `table` of the DOM `figure` of a table widget. */
+function getViewTable(view: EditingView, figure: HTMLElement) {
+ const viewFigure = view.domConverter.mapDomToView(figure);
+ /* v8 ignore next 3 -- defensive: a figure in an editable is always bound to a view element */
+ if (!viewFigure?.is("element")) {
+ return undefined;
+ }
+
+ for (const child of viewFigure.getChildren()) {
+ if (child.is("element", "table")) {
+ return child;
+ }
+ }
+ /* v8 ignore next -- defensive: the downcast always puts a table in the figure */
+ return undefined;
+}
+
/**
* 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.
diff --git a/packages/ckeditor5/src/plugins/table_scroll_read_only.spec.ts b/packages/ckeditor5/src/plugins/table_scroll_read_only.spec.ts
index beedd8a2a0..22f48ebfd4 100644
--- a/packages/ckeditor5/src/plugins/table_scroll_read_only.spec.ts
+++ b/packages/ckeditor5/src/plugins/table_scroll_read_only.spec.ts
@@ -1,8 +1,10 @@
+import "@triliumnext/commons/src/lib/scroll_fade.css";
import "../theme/table_scroll.css";
import editorStylesheetUrl from "ckeditor5/ckeditor5.css?url";
import { afterAll, beforeAll, describe, expect, it, onTestFinished } from "vitest";
+import { fadeClasses, scrollFigure } from "../../test/table-kit.js";
import { applyTableScroll } from "./table_scroll_read_only.js";
const TABLE = "<table><tbody><tr><td>a</td><td>b</td></tr></tbody></table>";
@@ -112,6 +114,55 @@ describe("applyTableScroll", () => {
.toBeCloseTo(figure.getBoundingClientRect().left, 0);
});
+ it("fades the edges that a scrolling table continues past", async () => {
+ const container = renderContent(tableFigure("width:150%;"), 600);
+ const figure = firstFigure(container);
+ expect(fadeClasses(figure))
+ .toEqual([ "scroll-fade", "scroll-fade-horizontal", "scroll-fade-end" ]);
+ expect(getComputedStyle(figure).maskImage).toContain("linear-gradient");
+ await expect.poll(() => getComputedStyle(figure).getPropertyValue("--scroll-fade-end"))
+ .toBe("2.5%");
+
+ // A second pass over the same content keeps one watcher, which writes the classes once.
+ applyTableScroll(container);
+ let classChanges = 0;
+ new MutationObserver((records) => {
+ classChanges += records.length;
+ }).observe(figure, { attributeFilter: [ "class" ] });
+ await scrollFigure(figure, 300);
+ expect(classChanges).toBe(2);
+ expect(fadeClasses(figure))
+ .toEqual([ "scroll-fade", "scroll-fade-horizontal", "scroll-fade-start" ]);
+
+ container.innerHTML = tableFigure("width:50%;");
+ applyTableScroll(container);
+ expect(fadeClasses(firstFigure(container))).toEqual([]);
+ });
+
+ it("fades towards the left in right-to-left content", () => {
+ const container = renderContent(tableFigure("width:150%;"), 600, "rtl");
+ const figure = firstFigure(container);
+ expect(fadeClasses(figure)).toEqual([
+ "scroll-fade", "scroll-fade-horizontal", "scroll-fade-end", "scroll-fade-rtl"
+ ]);
+ expect(getComputedStyle(figure).getPropertyValue("--scroll-fade-direction"))
+ .toBe("to left");
+ });
+
+ it("starts fading once detached content is attached", async () => {
+ const container = document.createElement("div");
+ container.className = "ck-content";
+ container.style.width = "600px";
+ container.innerHTML = tableFigure("width:150%;");
+ applyTableScroll(container);
+ const figure = firstFigure(container);
+ expect(fadeClasses(figure)).toEqual([]);
+
+ document.body.appendChild(container);
+ onTestFinished(() => container.remove());
+ await expect.poll(() => fadeClasses(figure)).toContain("scroll-fade-end");
+ });
+
it("leaves the tables of an editor alone", () => {
const container = renderContent(
`<figure class="table ck-widget" style="width:150%;">${TABLE}</figure>`,
@@ -127,9 +178,10 @@ function tableFigure(style: string) {
}
/** Renders saved HTML the way the read-only view does and applies the pass. */
-function renderContent(html: string, width: number) {
+function renderContent(html: string, width: number, dir: "ltr" | "rtl" = "ltr") {
const container = document.createElement("div");
container.className = "ck-content";
+ container.dir = dir;
container.style.width = `${width}px`;
container.innerHTML = html;
document.body.appendChild(container);
diff --git a/packages/ckeditor5/src/plugins/table_scroll_read_only.ts b/packages/ckeditor5/src/plugins/table_scroll_read_only.ts
index 89721ad1a8..217c635cc2 100644
--- a/packages/ckeditor5/src/plugins/table_scroll_read_only.ts
+++ b/packages/ckeditor5/src/plugins/table_scroll_read_only.ts
@@ -1,19 +1,47 @@
+import {
+ getScrollFadeClasses, SCROLL_FADE_CLASSES, type ScrollFadeState, watchScrollFade
+} from "@triliumnext/commons/src/lib/scroll_fade.js";
+
/**
* 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.
+ * on the figure, so a copied table keeps it. `scroll_fade.css` fades the edges that a scrolling
+ * table continues past.
*
* 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)");
+ const selector = "figure.table:not(.layout-table)";
+ const figures = [ ...container.querySelectorAll<HTMLElement>(selector) ]
+ .filter((figure) => isScrollable(figure, container));
for (const figure of figures) {
- if (isScrollable(figure, container)) {
- figure.style.setProperty("--table-width", toReferenceWidth(figure.style.width));
- }
+ figure.style.setProperty("--table-width", toReferenceWidth(figure.style.width));
+ }
+ // After every width is set, so that only the first measurement lays out the page.
+ for (const figure of figures) {
+ fadeEdges(figure);
+ }
+}
+
+/** The `scroll_fade.css` classes of a table in `state`, none while it fits. */
+export function getTableFadeClasses(state: ScrollFadeState) {
+ return state.overflow > 0 ? getScrollFadeClasses("horizontal", state) : [];
+}
+
+/** The figures whose edges fade, so that a second pass over the same content adds no watcher. */
+const fadedFigures = new WeakSet<HTMLElement>();
+
+function fadeEdges(figure: HTMLElement) {
+ if (fadedFigures.has(figure)) {
+ return;
}
+ fadedFigures.add(figure);
+ watchScrollFade(figure, (state) => {
+ figure.classList.remove(...SCROLL_FADE_CLASSES);
+ figure.classList.add(...getTableFadeClasses(state));
+ }, { direction: "horizontal" });
}
/**
diff --git a/packages/ckeditor5/src/theme/table_scroll.css b/packages/ckeditor5/src/theme/table_scroll.css
index 87f29a222e..3246002f4b 100644
--- a/packages/ckeditor5/src/theme/table_scroll.css
+++ b/packages/ckeditor5/src/theme/table_scroll.css
@@ -28,6 +28,17 @@
}
.ck.ck-editor__editable.ck-content figure.table.ck-widget.ck-table-overflowing {
+ /* `TriliumTableScroll` sets `--table-viewport-width`, CKEditor `--ck-table-scroll-offset`. */
+ > table.scroll-fade {
+ mask-size: var(--table-viewport-width) 100%;
+ mask-position: var(--ck-table-scroll-offset) 0;
+ mask-repeat: no-repeat;
+
+ &.scroll-fade-rtl {
+ mask-position: calc(100% + var(--ck-table-scroll-offset)) 0;
+ }
+ }
+
> figcaption {
position: sticky;
inset-inline-start: 0;
@@ -85,3 +96,14 @@
}
}
}
+
+.ck-content figure.table.scroll-fade,
+.ck-content figure.table > table.scroll-fade {
+ &.scroll-fade-start {
+ --scroll-fade-start: 2.5%;
+ }
+
+ &.scroll-fade-end {
+ --scroll-fade-end: 2.5%;
+ }
+}
diff --git a/packages/ckeditor5/test/table-kit.ts b/packages/ckeditor5/test/table-kit.ts
index fb5db4737f..0695862bd8 100644
--- a/packages/ckeditor5/test/table-kit.ts
+++ b/packages/ckeditor5/test/table-kit.ts
@@ -66,3 +66,17 @@ function cellMarkup(cell: CellSpec): string {
(spec.rowspan ? ` rowspan="${spec.rowspan}"` : "");
return `<tableCell${attributes}><paragraph>${spec.contents}</paragraph></tableCell>`;
}
+
+/** Scrolls `figure` sideways to `left` and waits for its `scroll` event. */
+export async function scrollFigure(figure: HTMLElement, left: number) {
+ const scrolled = new Promise((resolve) => {
+ figure.addEventListener("scroll", resolve, { once: true });
+ });
+ figure.scrollLeft = left;
+ await scrolled;
+}
+
+/** The `scroll_fade.css` classes of `element`. */
+export function fadeClasses(element: Element) {
+ return [ ...element.classList ].filter((name) => name.startsWith("scroll-fade"));
+}
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index cae1313b4c..89c15ba612 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -49,6 +49,7 @@ export * from "./lib/favicon_contrast.js";
export * from "./lib/mermaid_config.js";
export * from "./lib/link_embed.js";
export * from "./lib/link_embed_dom.js";
+export * from "./lib/scroll_fade.js";
export * from "./lib/link_embed_markup.js";
export * from "./lib/llm_api.js";
export * from "./lib/marked_extensions.js";
diff --git a/apps/client/src/widgets/react/scroll_fade.css b/packages/commons/src/lib/scroll_fade.css
similarity index 70%
rename from apps/client/src/widgets/react/scroll_fade.css
rename to packages/commons/src/lib/scroll_fade.css
index c46a6f7ed1..1931ee1548 100644
--- a/apps/client/src/widgets/react/scroll_fade.css
+++ b/packages/commons/src/lib/scroll_fade.css
@@ -1,16 +1,17 @@
/*
- * A custom property only animates once it is registered with a type, so both ends are declared as
- * lengths for the transition below to interpolate. Where `@property` is unsupported the fades snap,
- * and the `var()` fallbacks in the mask stand in for the initial values.
+ * A custom property animates only once it is registered with a type, so both ends are registered
+ * for the transition below. A percentage size is a share of the length of the gradient. Where
+ * `@property` is unsupported the fades snap, and the `var()` fallbacks in the mask stand in for the
+ * initial values.
*/
@property --scroll-fade-start {
- syntax: "<length>";
+ syntax: "<length-percentage>";
inherits: false;
initial-value: 0px;
}
@property --scroll-fade-end {
- syntax: "<length>";
+ syntax: "<length-percentage>";
inherits: false;
initial-value: 0px;
}
@@ -35,12 +36,12 @@
--scroll-fade-end var(--scroll-fade-duration, 300ms) ease;
}
-/* A gradient can only be given a physical direction, and the ends swap in a right-to-left page. */
+/* A gradient takes a physical direction, so the ends swap in a right-to-left container. */
.scroll-fade-horizontal {
--scroll-fade-direction: to right;
}
-body[dir=rtl] .scroll-fade-horizontal {
+.scroll-fade-horizontal.scroll-fade-rtl {
--scroll-fade-direction: to left;
}
diff --git a/packages/commons/src/lib/scroll_fade.spec.ts b/packages/commons/src/lib/scroll_fade.spec.ts
new file mode 100644
index 0000000000..9973556430
--- /dev/null
+++ b/packages/commons/src/lib/scroll_fade.spec.ts
@@ -0,0 +1,209 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ getScrollFadeClasses, type ScrollFadeState, type ScrollFadeWatch, type ScrollFadeWatchOptions,
+ watchScrollFade
+} from "./scroll_fade.js";
+
+describe("watchScrollFade", () => {
+ // happy-dom lays nothing out, so the container reports the sizes that a test sets.
+ let content: number;
+ let travelled: number;
+ let watch: ScrollFadeWatch | undefined;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ content = 1000;
+ travelled = 0;
+ });
+
+ afterEach(() => {
+ watch?.disconnect();
+ watch = undefined;
+ document.body.replaceChildren();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ });
+
+ it("reports the edges that content lies past as the container scrolls", () => {
+ const { element, onChange } = setup();
+ expect(onChange).toHaveBeenLastCalledWith({
+ isStartFaded: false, isEndFaded: true, overflow: 800, clientSize: 200, isRtl: false
+ });
+
+ scrollTo(element, 400);
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ isStartFaded: true, isEndFaded: true }));
+
+ scrollTo(element, 800);
+ expect(onChange).toHaveBeenLastCalledWith(
+ expect.objectContaining({ isStartFaded: true, isEndFaded: false }));
+
+ // A scroll that keeps the state reports nothing.
+ scrollTo(element, 800);
+ expect(onChange).toHaveBeenCalledTimes(3);
+ });
+
+ it("fades no edge while the content overflows by no more than the fade reaches", () => {
+ content = 150;
+ expect(lastState(setup().onChange)).toMatchObject({ isEndFaded: false, overflow: -50 });
+
+ content = 218;
+ expect(lastState(setup().onChange)).toMatchObject({ isEndFaded: false, overflow: 18 });
+ expect(lastState(setup({ options: { size: 10 } }).onChange).isEndFaded).toBe(true);
+
+ content = 205;
+ expect(lastState(setup({ options: { minOverflow: 1 } }).onChange).isEndFaded).toBe(true);
+ });
+
+ it("measures horizontally, and reports a right-to-left container", () => {
+ const horizontal = { direction: "horizontal" } as const;
+ travelled = -400;
+ expect(lastState(setup({ options: horizontal, rtl: true }).onChange)).toMatchObject({
+ isStartFaded: true, isEndFaded: true, isRtl: true
+ });
+ expect(lastState(setup({ options: horizontal }).onChange).isRtl).toBe(false);
+ expect(lastState(setup({ rtl: true }).onChange).isRtl).toBe(false);
+ });
+
+ it("measures once a frame after a resize or a change to the content", async () => {
+ const resizeObservers = stubResizeObserver();
+ const { element, onChange } = setup({ children: 1 });
+ const [ resizeObserver ] = resizeObservers;
+ expect(resizeObserver.observed).toEqual([ element, element.firstElementChild ]);
+ const requestFrame = vi.spyOn(globalThis, "requestAnimationFrame");
+
+ content = 150;
+ resizeObserver.callback();
+ resizeObserver.callback();
+ expect(requestFrame).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(20);
+ expect(lastState(onChange).isEndFaded).toBe(false);
+
+ content = 1000;
+ const added = document.createElement("div");
+ element.appendChild(added);
+ // The mutation observer delivers on a microtask.
+ await Promise.resolve();
+ expect(resizeObserver.observed).toContain(added);
+ vi.advanceTimersByTime(20);
+ expect(lastState(onChange).isEndFaded).toBe(true);
+ });
+
+ it("measures on request, for a change that nothing reports", () => {
+ const { onChange } = setup();
+ content = 150;
+ watch?.measure();
+ expect(lastState(onChange).isEndFaded).toBe(false);
+ });
+
+ it("stops watching once disconnected", async () => {
+ const resizeObservers = stubResizeObserver();
+ const { element, onChange } = setup();
+ const [ resizeObserver ] = resizeObservers;
+ const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame");
+
+ resizeObserver.callback();
+ watch?.disconnect();
+ expect(cancelFrame).toHaveBeenCalledTimes(1);
+ expect(resizeObserver.isDisconnected).toBe(true);
+
+ content = 150;
+ vi.advanceTimersByTime(20);
+ scrollTo(element, 400);
+ element.appendChild(document.createElement("div"));
+ await Promise.resolve();
+ vi.advanceTimersByTime(20);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
+ function setup({ options, rtl = false, children = 0 }: {
+ options?: ScrollFadeWatchOptions;
+ rtl?: boolean;
+ children?: number;
+ } = {}) {
+ const element = document.createElement("div");
+ element.style.direction = rtl ? "rtl" : "ltr";
+ for (let index = 0; index < children; index++) {
+ element.appendChild(document.createElement("div"));
+ }
+ const sizes: Record<string, () => number> = {
+ scrollHeight: () => content,
+ scrollWidth: () => content,
+ clientHeight: () => 200,
+ clientWidth: () => 200,
+ scrollTop: () => travelled,
+ scrollLeft: () => travelled
+ };
+ for (const [ name, get ] of Object.entries(sizes)) {
+ Object.defineProperty(element, name, { configurable: true, get });
+ }
+ document.body.appendChild(element);
+
+ watch?.disconnect();
+ const onChange = vi.fn<(state: ScrollFadeState) => void>();
+ watch = watchScrollFade(element, onChange, options);
+ return { element, onChange };
+ }
+
+ function scrollTo(element: HTMLElement, offset: number) {
+ travelled = offset;
+ element.dispatchEvent(new Event("scroll"));
+ }
+});
+
+describe("getScrollFadeClasses", () => {
+ it("names the axis, each faded edge and a right-to-left container", () => {
+ const state: ScrollFadeState = {
+ isStartFaded: false, isEndFaded: false, overflow: 0, clientSize: 0, isRtl: false
+ };
+ expect(getScrollFadeClasses("vertical", state))
+ .toEqual([ "scroll-fade", "scroll-fade-vertical" ]);
+ expect(getScrollFadeClasses("horizontal", {
+ ...state, isStartFaded: true, isEndFaded: true, isRtl: true
+ })).toEqual([
+ "scroll-fade", "scroll-fade-horizontal", "scroll-fade-start", "scroll-fade-end",
+ "scroll-fade-rtl"
+ ]);
+ });
+});
+
+function lastState(onChange: { mock: { lastCall?: [ScrollFadeState] } }) {
+ const state = onChange.mock.lastCall?.[0];
+ if (!state) {
+ throw new Error("No state was reported.");
+ }
+ return state;
+}
+
+interface FakeResizeObserver {
+ callback: () => void;
+ observed: Element[];
+ isDisconnected: boolean;
+}
+
+/** Replaces `ResizeObserver`, which happy-dom never calls back, with one a test calls back. */
+function stubResizeObserver() {
+ const instances: FakeResizeObserver[] = [];
+ vi.stubGlobal("ResizeObserver", class implements FakeResizeObserver {
+
+ observed: Element[] = [];
+ isDisconnected = false;
+
+ constructor(readonly callback: () => void) {
+ instances.push(this);
+ }
+
+ observe(element: Element) {
+ this.observed.push(element);
+ }
+
+ disconnect() {
+ this.isDisconnected = true;
+ }
+
+ });
+ return instances;
+}
diff --git a/packages/commons/src/lib/scroll_fade.ts b/packages/commons/src/lib/scroll_fade.ts
new file mode 100644
index 0000000000..7281f11edf
--- /dev/null
+++ b/packages/commons/src/lib/scroll_fade.ts
@@ -0,0 +1,152 @@
+/** Scroll offsets come at sub-pixel precision, so an edge is never tested exactly. */
+const EDGE_EPSILON = 1;
+
+/** How far a fade reaches from an edge when the caller names no size. Matches `scroll_fade.css`. */
+export const DEFAULT_FADE_SIZE = 20;
+
+/** Every class that {@link getScrollFadeClasses} can return. */
+export const SCROLL_FADE_CLASSES: readonly string[] = [
+ "scroll-fade",
+ "scroll-fade-horizontal",
+ "scroll-fade-vertical",
+ "scroll-fade-start",
+ "scroll-fade-end",
+ "scroll-fade-rtl"
+];
+
+export type ScrollFadeDirection = "horizontal" | "vertical";
+
+export interface ScrollFadeWatchOptions {
+ /** Which way the container scrolls. */
+ direction?: ScrollFadeDirection;
+ /** How far the fade reaches from each edge, in pixels. */
+ size?: number;
+ /**
+ * The least a container has to scroll for its edges to fade, in pixels. Defaults to the fade
+ * size. Lower it where a few hidden pixels still need a fade, such as text cut off by one
+ * character.
+ */
+ minOverflow?: number;
+}
+
+export interface ScrollFadeState {
+ /** Whether content lies past the start edge. */
+ isStartFaded: boolean;
+ /** Whether content lies past the end edge. */
+ isEndFaded: boolean;
+ /** How much of the content lies outside the box along the scrolling axis, in pixels. */
+ overflow: number;
+ /** The size of the box along the scrolling axis, in pixels. */
+ clientSize: number;
+ /** Whether a horizontal container lays out right to left, with its start edge on the right. */
+ isRtl: boolean;
+}
+
+/** The state of a container that has not been measured, or that fits its content. */
+export const NO_SCROLL_FADE: ScrollFadeState = {
+ isStartFaded: false,
+ isEndFaded: false,
+ overflow: 0,
+ clientSize: 0,
+ isRtl: false
+};
+
+export interface ScrollFadeWatch {
+ /** Measures again, for content that changes without a resize or a DOM mutation. */
+ measure(): void;
+ /** Stops watching the container. */
+ disconnect(): void;
+}
+
+/**
+ * Watches the scroll container `element` and reports which of its edges `scroll_fade.css` fades.
+ * Measures before it returns, then on every scroll, resize and content change. `onChange` runs
+ * only when the state differs from the last one.
+ */
+export function watchScrollFade(
+ element: HTMLElement,
+ onChange: (state: ScrollFadeState) => void,
+ options: ScrollFadeWatchOptions = {}
+): ScrollFadeWatch {
+ const { direction = "vertical", size, minOverflow = size ?? DEFAULT_FADE_SIZE } = options;
+ const isHorizontal = direction === "horizontal";
+ let state: ScrollFadeState | undefined;
+ let frame: number | undefined;
+
+ const measure = () => {
+ // A right-to-left container scrolls towards negative offsets.
+ const travelled = Math.abs(isHorizontal ? element.scrollLeft : element.scrollTop);
+ const clientSize = isHorizontal ? element.clientWidth : element.clientHeight;
+ const overflow = (isHorizontal ? element.scrollWidth : element.scrollHeight) - clientSize;
+ const isFaded = overflow > minOverflow;
+ const next: ScrollFadeState = {
+ isStartFaded: isFaded && travelled > EDGE_EPSILON,
+ isEndFaded: isFaded && travelled < overflow - EDGE_EPSILON,
+ overflow,
+ clientSize,
+ isRtl: isHorizontal && getComputedStyle(element).direction === "rtl"
+ };
+ if (!state || !isSameState(state, next)) {
+ state = next;
+ onChange(next);
+ }
+ };
+
+ // Observer callbacks share one measurement per frame. A scroll is measured at once.
+ const requestMeasure = () => {
+ frame ??= requestAnimationFrame(() => {
+ frame = undefined;
+ measure();
+ });
+ };
+
+ // The children as well, since one of them can grow while the box keeps its size.
+ const resizeObserver = new ResizeObserver(requestMeasure);
+ const observeChildren = () => {
+ for (const child of element.children) {
+ resizeObserver.observe(child);
+ }
+ };
+ const mutationObserver = new MutationObserver(() => {
+ observeChildren();
+ requestMeasure();
+ });
+
+ measure();
+ resizeObserver.observe(element);
+ observeChildren();
+ mutationObserver.observe(element, { childList: true, subtree: true, characterData: true });
+ element.addEventListener("scroll", measure, { passive: true });
+
+ return {
+ measure,
+ disconnect() {
+ resizeObserver.disconnect();
+ mutationObserver.disconnect();
+ element.removeEventListener("scroll", measure);
+ if (frame !== undefined) {
+ cancelAnimationFrame(frame);
+ frame = undefined;
+ }
+ }
+ };
+}
+
+/** The classes of `scroll_fade.css` for a container that scrolls in `direction`, in `state`. */
+export function getScrollFadeClasses(direction: ScrollFadeDirection, state: ScrollFadeState) {
+ const classes = [ "scroll-fade", `scroll-fade-${direction}` ];
+ if (state.isStartFaded) {
+ classes.push("scroll-fade-start");
+ }
+ if (state.isEndFaded) {
+ classes.push("scroll-fade-end");
+ }
+ if (state.isRtl) {
+ classes.push("scroll-fade-rtl");
+ }
+ return classes;
+}
+
+function isSameState(a: ScrollFadeState, b: ScrollFadeState) {
+ return (Object.keys(a) as (keyof ScrollFadeState)[]).every((key) => a[key] === b[key]);
+}
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index b85225effa..ae7405b1c1 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -29,6 +29,7 @@ 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 "@triliumnext/commons/src/lib/scroll_fade.css";
import { applyTableScroll } from "@triliumnext/ckeditor5/src/plugins/table_scroll_read_only.js";
import {