Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(e2e): catch layout thrashing while scrolling a text note
Elian Doran014ee71ce76c
diff --git a/packages/trilium-e2e/src/note_types/text_scrolling.spec.ts b/packages/trilium-e2e/src/note_types/text_scrolling.spec.tsnew file mode 100644index 0000000000..56dc10aecb--- /dev/null+++ b/packages/trilium-e2e/src/note_types/text_scrolling.spec.ts@@ -0,0 +1,117 @@+import { expect, type Page, test } from "@playwright/test";++import App from "../support/app";+import {+ findThrashingFrames, summarizeThrashing, type TraceEvent+} from "../support/layout_thrashing";++const TRACE_CATEGORIES = [+ "toplevel",+ "devtools.timeline",+ "disabled-by-default-devtools.timeline",+ "disabled-by-default-devtools.timeline.frame",+ "disabled-by-default-devtools.timeline.stack"+];++/**+ * CKEditor's `PoweredBy` balloon stays pinned to the editable while `style.css` hides it, and+ * `BalloonPanelView.attachTo()` measures it on every scroll, which makes a few frames thrash.+ */+const MAX_THRASHING_SHARE = 0.1;++test.describe("Scrolling a text note", () => {+ let previousEditorType: string | undefined;++ test.afterEach(async ({ page, context }) => {+ if (!previousEditorType) return;+ await new App(page, context).setOption("textNoteEditorType", previousEditorType);+ });++ test("computes style and layout once a frame", async ({ page, context, browserName }) => {+ test.skip(browserName !== "chromium", "Tracing needs Chromium.");++ const app = new App(page, context);+ await app.goto();+ // The block drag handle exists only with the fixed toolbar.+ previousEditorType = await getOption(page, "textNoteEditorType");+ await app.setOption("textNoteEditorType", "ckeditor-classic");+ await app.goto();++ const title = `Long note ${Date.now().toString(36)}`;+ await createLongTextNote(page, title);+ await app.goToNoteInNewTab(title);++ // With the caret in the first paragraph, the editor follows that block on every scroll.+ const editor = app.currentNoteSplit.locator(".note-detail-editable-text-editor");+ await editor.locator("p").first().click({ position: { x: 2, y: 2 } });+ const scrollingContainer = app.currentNoteSplit.locator(".scrolling-container");+ const box = await scrollingContainer.boundingBox();+ expect(box).not.toBeNull();+ await page.mouse.move(+ (box?.x ?? 0) + (box?.width ?? 0) / 2,+ (box?.y ?? 0) + (box?.height ?? 0) / 2+ );++ const browser = context.browser();+ expect(browser).not.toBeNull();+ await browser?.startTracing(page, { categories: TRACE_CATEGORIES });+ for (let step = 0; step < 40; step++) {+ await page.mouse.wheel(0, 120);+ await page.waitForTimeout(30);+ }+ const trace = await browser?.stopTracing();+ const scrollTop = await scrollingContainer.evaluate((element) => element.scrollTop);+ expect(scrollTop).toBeGreaterThan(0);++ const { traceEvents } = JSON.parse(trace?.toString() ?? "{}") as {+ traceEvents: TraceEvent[];+ };+ const report = findThrashingFrames(traceEvents);+ expect(report.frameCount).toBeGreaterThan(0);+ expect(report.thrashing.length, summarizeThrashing(report))+ .toBeLessThanOrEqual(report.frameCount * MAX_THRASHING_SHARE);+ });+});++/**+ * Creates a text note long enough to scroll, with inline formatting as in a real note, that opens+ * editable whatever its size.+ */+async function createLongTextNote(page: Page, title: string) {+ const paragraph = "<p>Some <strong>bold</strong> text, a "+ + "<a href=\"https://triliumnotes.org\">link</a>, "+ + "<em>italics</em> and <code>code</code>, long enough to wrap onto a second line in "+ + "the note pane at the width of the test browser window.</p>";+ const content = Array.from({ length: 100 }, (_, index) => (index % 10 === 0+ ? `<h2>Section ${index / 10 + 1}</h2>`+ : paragraph)).join("");++ await page.evaluate(async ({ title, content }) => {+ const headers = {+ "content-type": "application/json",+ "x-csrf-token": (window as any).glob.csrfToken+ };+ const response = await fetch("/api/notes/root/children?target=into", {+ method: "POST",+ headers,+ body: JSON.stringify({ title, content, type: "text" })+ });+ if (!response.ok) throw new Error(`Creating the note failed (status=${response.status})`);++ const { note } = await response.json();+ await fetch(`/api/notes/${note.noteId}/attributes`, {+ method: "POST",+ headers,+ body: JSON.stringify({ type: "label", name: "autoReadOnlyDisabled", value: "" })+ });+ }, { title, content });+}++async function getOption(page: Page, name: string): Promise<string | undefined> {+ return page.evaluate(async (name) => {+ const response = await fetch("/api/options");+ const options = await response.json() as Record<string, string>;+ return options[name];+ }, name);+}+diff --git a/packages/trilium-e2e/src/support/layout_thrashing.ts b/packages/trilium-e2e/src/support/layout_thrashing.tsnew file mode 100644index 0000000000..491955ea7a--- /dev/null+++ b/packages/trilium-e2e/src/support/layout_thrashing.ts@@ -0,0 +1,141 @@+/**+ * Finds the frames of a Chromium trace in which a script forced style or layout and the frame+ * computed it more than once. A frame needs at most one pass of each: a script that reads the+ * layout after another one wrote to the DOM only moves that pass earlier, and only a write after+ * the read makes the frame do it again. Frames whose extra pass no script forced, such as one after+ * a `ResizeObserver` callback, don't count.+ */+export function findThrashingFrames(traceEvents: TraceEvent[]): FrameReport {+ const threads = new Map<string, TraceEvent[]>();+ const rendererMainThreads = new Set(traceEvents+ .filter((event) => event.ph === "M" && event.name === "thread_name"+ && event.args?.name === "CrRendererMain")+ .map(threadKey));+ for (const event of traceEvents) {+ if (event.ph !== "X" && event.ph !== "I" && event.ph !== "i") continue;+ const key = threadKey(event);+ if (!rendererMainThreads.has(key)) continue;+ let events = threads.get(key);+ if (!events) threads.set(key, events = []);+ events.push(event);+ }++ let frameCount = 0;+ const thrashing: ThrashingFrame[] = [];+ for (const events of threads.values()) {+ events.sort((a, b) => a.ts - b.ts);+ for (const task of events.filter((event) => event.name === "RunTask" && event.dur)) {+ const end = task.ts + (task.dur ?? 0);+ const inside = events.slice(+ findFirstAtOrAfter(events, task.ts),+ findFirstAtOrAfter(events, end + 1)+ );+ if (!inside.some((event) => event.name === "BeginMainThreadFrame")) continue;+ frameCount++;++ const passes = inside.filter(isPassWithWork).map(describePass);+ const styleCount = passes.filter((pass) => pass.name === "UpdateLayoutTree").length;+ const layoutCount = passes.length - styleCount;+ const isForced = passes.some((pass) => pass.forcedBy);+ if (isForced && (styleCount > 1 || layoutCount > 1)) {+ thrashing.push({ durationMs: (task.dur ?? 0) / 1000, passes });+ }+ }+ }++ return { frameCount, thrashing };+}++/** Lists each script that forced a pass in a thrashing frame, the most frequent first. */+export function summarizeThrashing({ frameCount, thrashing }: FrameReport) {+ const forcers = new Map<string, number>();+ for (const frame of thrashing) {+ for (const pass of frame.passes) {+ if (pass.forcedBy) forcers.set(pass.forcedBy, (forcers.get(pass.forcedBy) ?? 0) + 1);+ }+ }++ const lines = [ ...forcers ]+ .sort((a, b) => b[1] - a[1])+ .map(([ forcedBy, count ]) => ` ${count}× ${forcedBy}`);+ return [+ `${thrashing.length} of ${frameCount} frames computed style or layout more than once.`,+ "Passes forced by:",+ ...lines+ ].join("\n");+}++export interface TraceEvent {+ name: string;+ ph: string;+ pid: number;+ tid: number;+ ts: number;+ dur?: number;+ args?: {+ name?: string;+ elementCount?: number;+ beginData?: {+ dirtyObjects?: number;+ stackTrace?: StackFrame[];+ };+ };+}++export interface FrameReport {+ frameCount: number;+ thrashing: ThrashingFrame[];+}++export interface ThrashingFrame {+ durationMs: number;+ passes: Pass[];+}++interface Pass {+ name: string;+ /** The innermost script frame that forced the pass, or nothing for the frame's own pass. */+ forcedBy?: string;+}++interface StackFrame {+ functionName: string;+ url: string;+ lineNumber: number;+}++function threadKey(event: TraceEvent) {+ return `${event.pid}:${event.tid}`;+}++function findFirstAtOrAfter(events: TraceEvent[], ts: number) {+ let low = 0;+ let high = events.length;+ while (low < high) {+ const middle = (low + high) >> 1;+ if (events[middle].ts < ts) low = middle + 1;+ else high = middle;+ }+ return low;+}++/** Style passes that restyle no element and layout passes with nothing dirty cost nothing. */+function isPassWithWork(event: TraceEvent) {+ if (event.ph !== "X") return false;+ if (event.name === "UpdateLayoutTree") return (event.args?.elementCount ?? 1) > 0;+ if (event.name === "Layout") return (event.args?.beginData?.dirtyObjects ?? 1) > 0;+ return false;+}++function describePass(event: TraceEvent): Pass {+ const stack = event.args?.beginData?.stackTrace;+ if (!stack?.length) return { name: event.name };++ return { name: event.name, forcedBy: stack.slice(0, 3).map(describeStackFrame).join(" < ") };+}++function describeStackFrame({ functionName, url, lineNumber }: StackFrame) {+ const file = url.split("/").pop()?.split("?")[0] ?? url;+ // Trace line numbers start at 0.+ return `${functionName || "(anonymous)"} (${file}:${lineNumber + 1})`;+}