Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/tables: improve sticky header positioning on Firefox while scrolling

Adorian Doran28e6ee42be54
diff --git a/packages/ckeditor5/src/plugins/table_sticky_header.spec.ts b/packages/ckeditor5/src/plugins/table_sticky_header.spec.ts
index 7f5a9c97fb..d4dfd634fd 100644
--- a/packages/ckeditor5/src/plugins/table_sticky_header.spec.ts
+++ b/packages/ckeditor5/src/plugins/table_sticky_header.spec.ts
@@ -48,7 +48,7 @@ describe("TableStickyHeader", () => {
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);
+ .toBeCloseTo(tableBottom - newHead.getBoundingClientRect().bottom - 1, 1);
expect(parseFloat(newHead.style.getPropertyValue(TRAVEL_PROPERTY))).toBeLessThan(travel);
});
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
index 203589a9a6..7bb74623e6 100644
--- a/packages/ckeditor5/src/plugins/table_sticky_header_read_only.spec.ts
+++ b/packages/ckeditor5/src/plugins/table_sticky_header_read_only.spec.ts
@@ -6,7 +6,7 @@ import { afterAll, beforeAll, describe, expect, it, onTestFinished, vi } from "v
import { applyTableScroll } from "./table_scroll_read_only.js";
import {
- applyStickyTableHeaders, START_PROPERTY, StickyTableHeaders, TRAVEL_PROPERTY
+ applyStickyTableHeaders, EASING_PROPERTY, START_PROPERTY, StickyTableHeaders, TRAVEL_PROPERTY
} from "./table_sticky_header_read_only.js";
const SCROLLER_HEIGHT = 200;
@@ -37,7 +37,9 @@ describe("applyStickyTableHeaders", () => {
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(lengthOf(thead, TRAVEL_PROPERTY))
+ .toBeCloseTo(tableBox.bottom - header.bottom - 1, 1);
+ expect(thead.style.getPropertyValue(EASING_PROPERTY)).toBe("");
expect(bordersOf(thead)).toBe("none");
await scrollTo(scroller, offsetIn(scroller, thead) + 150);
@@ -118,6 +120,52 @@ describe("applyStickyTableHeaders", () => {
expect(topIn(scroller, thead)).toBeCloseTo(30, 0);
});
+ it("moves the header rows by device pixels where scroll offsets are rounded", async () => {
+ snapScrollOffsets();
+ const { scroller, content, spacer } = renderContent(tableFigure(1, 20));
+ scroller.style.scrollPaddingTop = "10px";
+ spacer.style.height = "100.4px";
+ applyStickyTableHeaders(content);
+ await settle();
+
+ const { figure, thead } = parts(content);
+ const steps = lengthOf(thead, TRAVEL_PROPERTY) * SCALE;
+ expect(steps).toBeCloseTo(Math.round(steps), 1);
+ expect(thead.style.getPropertyValue(EASING_PROPERTY)).toBe(`steps(${Math.round(steps)})`);
+ expect(stickOffsetOf(scroller, figure, 10) * SCALE % 1).toBeCloseTo(0.5, 1);
+
+ for (const offset of [ 120, 121, 122 ]) {
+ await scrollTo(scroller, offset);
+ const shift = shiftOf(thead) * SCALE;
+ expect(shift).toBeGreaterThan(0);
+ expect(shift).toBeCloseTo(Math.round(shift), 1);
+ expect(topIn(scroller, thead)).toBeCloseTo(10, 0);
+ }
+ });
+
+ it("aligns the header rows again as their scroll container starts to scroll", async () => {
+ snapScrollOffsets();
+ const { scroller, content, spacer } = renderContent(tableFigure(1, 20));
+ const dispose = applyStickyTableHeaders(content);
+ await settle();
+
+ const { figure, thead } = parts(content);
+ const start = thead.style.getPropertyValue(START_PROPERTY);
+ spacer.style.height = "100.4px";
+ await settle();
+ expect(thead.style.getPropertyValue(START_PROPERTY)).toBe(start);
+
+ await scrollTo(scroller, 120);
+ expect(thead.style.getPropertyValue(START_PROPERTY)).not.toBe(start);
+ expect(stickOffsetOf(scroller, figure, 0) * SCALE % 1).toBeCloseTo(0.5, 1);
+
+ dispose();
+ const aligned = thead.style.getPropertyValue(START_PROPERTY);
+ spacer.style.height = "100px";
+ await scrollTo(scroller, 0);
+ expect(thead.style.getPropertyValue(START_PROPERTY)).toBe(aligned);
+ });
+
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);
@@ -182,6 +230,18 @@ describe("applyStickyTableHeaders", () => {
});
});
+const SCALE = 1.5;
+
+/** Measures as Firefox needs, at a device pixel ratio of `SCALE`. */
+function snapScrollOffsets() {
+ vi.spyOn(CSS, "supports").mockReturnValue(true);
+ vi.stubGlobal("devicePixelRatio", SCALE);
+ onTestFinished(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+}
+
/** 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}>`
@@ -201,12 +261,14 @@ function renderContent(html: string) {
+ `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>`;
+ const spacer = document.createElement("div");
+ spacer.style.height = "100px";
+ content.innerHTML = `${html}<div style="height:${SCROLLER_HEIGHT * 2}px"></div>`;
+ content.prepend(spacer);
scroller.appendChild(content);
document.body.appendChild(scroller);
onTestFinished(() => scroller.remove());
- return { scroller, content };
+ return { scroller, content, spacer };
}
function parts(container: Element) {
@@ -237,6 +299,15 @@ function offsetIn(scroller: HTMLElement, element: HTMLElement) {
+ scroller.scrollTop;
}
+/** The scroll offset at which the header rows of `figure` start to move. */
+function stickOffsetOf(scroller: HTMLElement, figure: HTMLElement, padding: number) {
+ return offsetIn(scroller, figure) - padding + lengthOf(parts(figure).thead, START_PROPERTY);
+}
+
+function shiftOf(element: HTMLElement) {
+ return parseFloat(getComputedStyle(element).translate.split(" ")[1] ?? "0");
+}
+
/** 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;
diff --git a/packages/ckeditor5/src/plugins/table_sticky_header_read_only.ts b/packages/ckeditor5/src/plugins/table_sticky_header_read_only.ts
index 8c68c698ba..c3398b0e47 100644
--- a/packages/ckeditor5/src/plugins/table_sticky_header_read_only.ts
+++ b/packages/ckeditor5/src/plugins/table_sticky_header_read_only.ts
@@ -8,9 +8,18 @@
/** 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. */
+/** The distance that the header rows move while they stick, set on the `thead`. */
export const TRAVEL_PROPERTY = "--table-header-travel";
+/** The timing function of the header rows, set on the `thead` where `snapsScrollOffsets()`. */
+export const EASING_PROPERTY = "--table-header-easing";
+
+/**
+ * In device pixels; wider than the rounding of the lengths to 0.01px and of Gecko's 1/60px layout
+ * unit together, up to a device pixel ratio of 2.
+ */
+const TIE_MARGIN = 1 / 32;
+
/**
* Keeps the header rows of the tables in `container` in view while it scrolls. Returns a function
* that stops measuring them.
@@ -21,7 +30,10 @@ export function applyStickyTableHeaders(container: Element) {
return () => headers.disconnect();
}
-/** Measures header rows again whenever their figure or the rows themselves change size. */
+/**
+ * Measures header rows again whenever their figure or the rows themselves change size, and, where
+ * `snapsScrollOffsets()`, whenever their scroll container starts to scroll.
+ */
export class StickyTableHeaders {
private observer: ResizeObserver | undefined;
@@ -29,7 +41,10 @@ export class StickyTableHeaders {
private readonly observed = new Set<Element>();
/** The figures to measure in the next animation frame. */
- private readonly resized = new Set<Element>();
+ private readonly pending = new Set<Element>();
+
+ /** The scroll containers between their first `scroll` event and their `scrollend` event. */
+ private readonly scrolling = new Set<EventTarget>();
private frame: number | undefined;
@@ -57,38 +72,70 @@ export class StickyTableHeaders {
disconnect() {
this.observer?.disconnect();
+ this.observer = undefined;
+ document.removeEventListener("scroll", this.onScroll, { capture: true });
+ document.removeEventListener("scrollend", this.onScrollEnd, { capture: true });
this.observed.clear();
- this.resized.clear();
+ this.pending.clear();
+ this.scrolling.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);
+ if (this.observed.has(element)) {
+ return;
}
+
+ if (!this.observer) {
+ this.observer = new ResizeObserver((entries) => {
+ this.schedule(entries.map(({ target }) => target));
+ });
+ if (snapsScrollOffsets()) {
+ const options = { capture: true, passive: true };
+ document.addEventListener("scroll", this.onScroll, options);
+ document.addEventListener("scrollend", this.onScrollEnd, options);
+ }
+ }
+ this.observer.observe(element);
+ this.observed.add(element);
}
- private onResize(entries: ResizeObserverEntry[]) {
- for (const { target } of entries) {
- const figure = target.closest("figure");
+ /** `measure()` aligns the steps to where the table sits, which can change without a resize. */
+ private readonly onScroll = ({ target }: Event) => {
+ if (target instanceof Node && !this.scrolling.has(target)) {
+ this.scrolling.add(target);
+ this.schedule([ ...this.observed ].filter((element) => target.contains(element)));
+ }
+ };
+
+ private readonly onScrollEnd = ({ target }: Event) => {
+ if (target) {
+ this.scrolling.delete(target);
+ }
+ };
+
+ /** Measures the figures of `elements` in the next animation frame. */
+ private schedule(elements: Element[]) {
+ for (const element of elements) {
+ const figure = element.closest("figure");
if (figure) {
- this.resized.add(figure);
+ this.pending.add(figure);
}
}
// Chromium drops a range change made in the frame that creates the animation.
- this.frame ??= requestAnimationFrame(() => this.measureResized());
+ if (this.pending.size) {
+ this.frame ??= requestAnimationFrame(() => this.measurePending());
+ }
}
- private measureResized() {
+ private measurePending() {
this.frame = undefined;
- for (const figure of this.resized) {
+ for (const figure of this.pending) {
if (figure.isConnected) {
measure(figure);
}
}
- this.resized.clear();
+ this.pending.clear();
}
}
@@ -102,7 +149,10 @@ export function getStuckHeaderBottom(table: Element) {
return thead && getShift(thead) > 0 ? thead.getBoundingClientRect().bottom : null;
}
-/** Sets the start and the travel of the header rows, measured without the shift of sticking. */
+/**
+ * Sets the start, the travel and, where `snapsScrollOffsets()`, the steps 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");
@@ -112,10 +162,59 @@ function measure(figure: Element) {
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);
+ const top = header.top - shift;
+ let start = top - figure.getBoundingClientRect().top;
+ // Leaves room for the 1px that the borders of `th::before` reach past the cells.
+ let travel = table.getBoundingClientRect().bottom - (header.bottom - shift) - 1;
+ if (snapsScrollOffsets()) {
+ // Steps where WebRender's rounded scroll offset changes, half a device pixel past a whole
+ // one, less `TIE_MARGIN` so that an offset right on the half rounds up in both.
+ const scale = devicePixelRatio;
+ const offset = getStickOffset(figure, top);
+ start += (Math.round(offset * scale) - 0.5 - TIE_MARGIN) / scale - offset;
+ const steps = Math.floor(travel * scale);
+ travel = steps / scale;
+ setValue(thead, EASING_PROPERTY, `steps(${Math.max(steps, 1)})`);
+ }
+ setValue(thead, START_PROPERTY, toPixels(start));
+ setValue(thead, TRAVEL_PROPERTY, toPixels(travel));
+}
+
+/**
+ * Whether the browser rounds scroll offsets to device pixels but moves a scroll-driven `translate`
+ * by the exact offset, as WebRender does, so the header rows must move by whole device pixels.
+ */
+function snapsScrollOffsets() {
+ return CSS.supports("-moz-appearance", "none");
+}
+
+/**
+ * The scroll offset at which `top`, a position in the viewport, reaches the scroll padding of the
+ * scroll container of `figure`, which is where `view-timeline-inset: auto` puts the timeline.
+ */
+function getStickOffset(figure: Element, top: number) {
+ const scroller = getScrollContainer(figure);
+ const style = getComputedStyle(scroller ?? document.documentElement);
+ const padding = parseFloat(style.scrollPaddingTop) || 0;
+ if (!scroller) {
+ return window.scrollY + top - padding;
+ }
+
+ const scrollport = scroller.getBoundingClientRect().top + scroller.clientTop;
+ return scroller.scrollTop + top - scrollport - padding;
+}
+
+/** The nearest ancestor of `element` that is a scroll container, or `null` for the viewport. */
+function getScrollContainer(element: Element) {
+ let parent = element.parentElement;
+ while (parent && parent !== document.body) {
+ const { overflowY } = getComputedStyle(parent);
+ if (overflowY !== "visible" && overflowY !== "clip") {
+ return parent;
+ }
+ parent = parent.parentElement;
+ }
+ return null;
}
/** The vertical `translate` that the running animation gives `element`. */
@@ -124,9 +223,12 @@ function getShift(element: HTMLElement) {
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`;
+function toPixels(length: number) {
+ return `${Math.round(length * 100) / 100}px`;
+}
+
+/** Sets a custom property, leaving the style alone when the value is the same. */
+function setValue(element: HTMLElement, property: string, value: string) {
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
index 517e384c94..55f074e3c8 100644
--- a/packages/ckeditor5/src/theme/table_sticky_header.css
+++ b/packages/ckeditor5/src/theme/table_sticky_header.css
@@ -12,20 +12,19 @@
animation-range: exit-crossing 0% exit-crossing 100%;
}
- /* `StickyTableHeaders` sets `--table-header-start` and `--table-header-travel`. */
+ /* `StickyTableHeaders` sets `--table-header-start`, `--table-header-travel` and, in
+ Firefox, `--table-header-easing`. */
> 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-timing-function: var(--table-header-easing, 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));
+ exit-crossing
+ calc(var(--table-header-start, 0px) + var(--table-header-travel, 0px));
> tr > th {
position: relative;
@@ -57,7 +56,7 @@
}
to {
- translate: 0 var(--table-header-end);
+ translate: 0 var(--table-header-travel, 0px);
}
}