Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix flaky WebKit text editor e2e tests (#8427)

Anthony Stirling6a573a3776c7
diff --git a/AGENTS.md b/AGENTS.md
index 5520ec4ffc..c44ab85847 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -464,6 +464,9 @@ The frontend is organized with a clear separation of concerns:
- **Docker Testing**: `test.sh` validates all Docker variants
- **Manual Testing**: No unit tests currently - relies on UI and API testing
+#### No fixed waits in tests
+Never sleep in tests (`page.waitForTimeout`, `Thread.sleep`, etc.) - it causes flakes. Wait for the actual condition instead (`expect(...)`, `expect.poll`, `waitForFunction`, `vi.waitFor`), or use fake timers for time-based behaviour.
+
## Development Workflow
1. **Local Development** (using Taskfile):
diff --git a/frontend/editor/src/core/tests/stubbed/editorReady.ts b/frontend/editor/src/core/tests/stubbed/editorReady.ts
new file mode 100644
index 0000000000..97f6b59e64
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/editorReady.ts
@@ -0,0 +1,20 @@
+import type { Page } from "@playwright/test";
+
+interface ReadyWindow {
+ __editor_store?: { state: { loading: boolean; firstPageRendered: boolean } };
+}
+
+/** Wait until the editor has finished loading and painted page 0. */
+export async function waitForEditorReady(
+ page: Page,
+ timeout = 30_000,
+): Promise<void> {
+ await page.waitForFunction(
+ () => {
+ const state = (window as unknown as ReadyWindow).__editor_store?.state;
+ return !!state && state.firstPageRendered && !state.loading;
+ },
+ undefined,
+ { timeout },
+ );
+}
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
index 9652349689..85e489ad9a 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@app/tests/stubbed/editorTestTypes";
+import { waitForEditorReady } from "@app/tests/stubbed/editorReady";
import { downloadBytes, saveAndDownload } from "@app/tests/stubbed/saveHelpers";
// REGRESSION suite for the 12 issues found by the QA sweep of the PDF text
@@ -26,7 +27,7 @@ async function open(page: Page, file: string, firstPage = 0): Promise<void> {
await expect(page.getByTestId(`pdf-editor-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
- await page.waitForTimeout(900);
+ await waitForEditorReady(page);
}
async function findId(
page: Page,
@@ -368,11 +369,11 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
mimeType: "image/png",
buffer: png,
});
- await page.waitForTimeout(1800);
- const after = await countImages();
- expect(after, "image insert must add an image to the page").toBeGreaterThan(
- before,
- );
+ await expect
+ .poll(countImages, {
+ message: "image insert must add an image to the page",
+ })
+ .toBeGreaterThan(before);
});
// ISSUE: injecting several consecutive spaces into a multi-line paragraph
@@ -502,14 +503,14 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
.setInputFiles(
path.join(import.meta.dirname, "../test-fixtures/encrypted.pdf"),
);
- await page.waitForTimeout(2500);
- const loaded = await page.getByTestId("pdf-editor-page-0").count();
- const error = await page.getByTestId("pdf-editor-error").count();
- const prompt = await page.getByTestId("pdf-editor-password-modal").count();
- expect(
- loaded > 0 || error > 0 || prompt > 0,
+ await expect(
+ page
+ .getByTestId("pdf-editor-page-0")
+ .or(page.getByTestId("pdf-editor-error"))
+ .or(page.getByTestId("pdf-editor-password-modal"))
+ .first(),
"an encrypted PDF must either open or tell the user why it can't",
- ).toBe(true);
+ ).toBeAttached();
});
// ISSUE: opening a CORRUPTED PDF fails silently - same "No document loaded"
@@ -524,12 +525,12 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
.setInputFiles(
path.join(import.meta.dirname, "../test-fixtures/corrupted.pdf"),
);
- await page.waitForTimeout(2500);
- const loaded = await page.getByTestId("pdf-editor-page-0").count();
- const error = await page.getByTestId("pdf-editor-error").count();
- expect(
- loaded > 0 || error > 0,
+ await expect(
+ page
+ .getByTestId("pdf-editor-page-0")
+ .or(page.getByTestId("pdf-editor-error"))
+ .first(),
"a corrupted PDF must surface an error instead of failing silently",
- ).toBe(true);
+ ).toBeAttached();
});
});
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts
index 5c0d8d0106..c3a5cbe7b9 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-menu-layout.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@app/tests/stubbed/editorTestTypes";
+import { waitForEditorReady } from "@app/tests/stubbed/editorReady";
/**
* Layout coverage for the properties-inspector panel.
@@ -26,7 +27,7 @@ async function open(page: Page, firstPage = 0): Promise<void> {
await expect(page.getByTestId(`pdf-editor-page-${firstPage}`)).toBeVisible({
timeout: 30_000,
});
- await page.waitForTimeout(900);
+ await waitForEditorReady(page);
}
async function runId(
@@ -55,7 +56,6 @@ async function selectOne(page: Page, id: string): Promise<void> {
).__editor_store.selection.selectOne(rid),
id,
);
- await page.waitForTimeout(150);
}
/** Switch to the Document tab, which owns the document-level preferences. */
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts
index bffebf823b..847338c796 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-mobile-layout.spec.ts
@@ -1,5 +1,5 @@
import { test, expect } from "@app/tests/helpers/stub-test-base";
-import type { Page } from "@playwright/test";
+import type { Locator, Page } from "@playwright/test";
import fs from "fs";
import path from "path";
@@ -35,6 +35,21 @@ async function openEditor(page: Page, fileName?: string): Promise<void> {
});
}
+// Close the open sheet once it has finished sliding in, then wait for it to go.
+async function closeSheet(page: Page, content: Locator): Promise<void> {
+ const sheet = page
+ .locator(".mantine-Drawer-content")
+ .filter({ has: content });
+ await expect
+ .poll(() =>
+ sheet.evaluate((el) => el.getAnimations({ subtree: true }).length),
+ )
+ .toBe(0);
+ await sheet.locator(".mantine-Drawer-close").click();
+ // A sheet still sliding out swallows taps meant for the action bar.
+ await expect(content).toBeHidden();
+}
+
test.describe("PDF text editor - phone layout", () => {
test("opens on the canvas, fitted to width, with one header", async ({
page,
@@ -123,13 +138,13 @@ test.describe("PDF text editor - phone layout", () => {
await page.getByTestId("pdf-editor-mobile-style").tap();
await expect(page.getByTestId("pdf-editor-font-size")).toBeVisible();
- await page.locator(".mantine-Drawer-close:visible").first().click();
+ await closeSheet(page, page.getByTestId("pdf-editor-font-size"));
await page.getByTestId("pdf-editor-mobile-details").tap();
await expect(
page.getByTestId("pdf-editor-selection-inspector"),
).toBeVisible();
- await page.locator(".mantine-Drawer-close:visible").first().click();
+ await closeSheet(page, page.getByTestId("pdf-editor-selection-inspector"));
await page.getByTestId("pdf-editor-mobile-done").tap();
await expect(bar).toHaveAttribute("data-context", "idle");
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
index f829bff74f..aaa02f0bac 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import { readFile } from "node:fs/promises";
+import { waitForEditorReady } from "@app/tests/stubbed/editorReady";
import {
downloadBytes,
saveAndDownload,
@@ -111,27 +112,40 @@ async function inkRight(page: Page, name: string, box: Box): Promise<number> {
);
}
-// Wait until the page bitmap stops changing between two polls.
-async function settle(page: Page): Promise<void> {
+// A cheap hash of the page bitmap; "" until the canvas has painted.
+async function bitmapSig(page: Page): Promise<string> {
+ return page.evaluate((tid) => {
+ const c = Array.from(
+ document.querySelectorAll<HTMLCanvasElement>(
+ `[data-testid="${tid}"] canvas`,
+ ),
+ ).find((x) => x.width > 0 && x.height > 0);
+ if (!c) return "";
+ const d = c.getContext("2d")!.getImageData(0, 0, c.width, c.height).data;
+ let h = 0;
+ for (let k = 0; k < d.length; k += 16) h = (h * 31 + d[k]) | 0;
+ return `${c.width}x${c.height}:${h}`;
+ }, PAGE_TESTID);
+}
+
+// Wait until the bitmap differs from `from` (when given), then holds still.
+async function settle(page: Page, from?: string): Promise<void> {
let prev = "";
- for (let i = 0; i < 60; i++) {
- const sig = await page.evaluate((tid) => {
- const c = Array.from(
- document.querySelectorAll<HTMLCanvasElement>(
- `[data-testid="${tid}"] canvas`,
- ),
- ).find((x) => x.width > 0 && x.height > 0);
- if (!c) return "";
- const d = c.getContext("2d")!.getImageData(0, 0, c.width, c.height).data;
- let h = 0;
- for (let k = 0; k < d.length; k += 16) h = (h * 31 + d[k]) | 0;
- return `${c.width}x${c.height}:${h}`;
- }, PAGE_TESTID);
- if (sig && sig === prev) return;
- prev = sig;
- await page.waitForTimeout(400);
- }
- throw new Error("page bitmap never settled");
+ await expect
+ .poll(
+ async () => {
+ const sig = await bitmapSig(page);
+ const stable = !!sig && sig !== from && sig === prev;
+ prev = sig;
+ return stable;
+ },
+ {
+ message: "page bitmap never settled",
+ timeout: 30_000,
+ intervals: [400],
+ },
+ )
+ .toBe(true);
}
async function runs(page: Page): Promise<RunState[]> {
@@ -141,7 +155,8 @@ async function runs(page: Page): Promise<RunState[]> {
__editor_store: { state: { pages: { runs: RunState[] }[] } };
}
).__editor_store;
- return s.state.pages[0].runs.map((r) => ({
+ // Empty while a reload swaps the document in.
+ return (s.state.pages[0]?.runs ?? []).map((r) => ({
id: r.id,
text: r.text,
renderMode: r.renderMode ?? 0,
@@ -158,7 +173,7 @@ async function open(page: Page, file: string | Buffer): Promise<void> {
: { name: "reopened.pdf", mimeType: "application/pdf", buffer: file },
);
await expect(page.getByTestId(PAGE_TESTID)).toBeVisible({ timeout: 60_000 });
- await page.waitForTimeout(800);
+ await waitForEditorReady(page, 60_000);
await settle(page);
}
@@ -189,6 +204,7 @@ async function lineBox(page: Page, runId: string): Promise<Box> {
}
async function replaceRunText(page: Page, runId: string, text: string) {
+ const from = await bitmapSig(page);
await page.evaluate(
({ id, t }) => {
const el = document.querySelector<HTMLElement>(
@@ -205,8 +221,7 @@ async function replaceRunText(page: Page, runId: string, text: string) {
},
{ id: runId, t: text },
);
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, from);
}
for (const fixture of ["scanned-ocr-hocr.pdf", "scanned-ocr-sandwich.pdf"]) {
@@ -260,9 +275,9 @@ for (const fixture of ["scanned-ocr-hocr.pdf", "scanned-ocr-sandwich.pdf"]) {
"the edit disturbed the lines below it",
).toBe(0);
+ const editedSig = await bitmapSig(page);
await page.getByTestId("pdf-editor-undo").click();
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, editedSig);
await snap(page, "undone");
const undone = (await runs(page)).find((r) => r.id === target!.id)!;
expect(undone.text).toBe("Customer: Jane Example");
@@ -284,6 +299,7 @@ for (const fixture of ["scanned-ocr-hocr.pdf", "scanned-ocr-sandwich.pdf"]) {
await snap(page, "loaded");
// Keystrokes coalesce into several commands; only the first sees Tr 3.
+ const loadedSig = await bitmapSig(page);
await page.getByTestId(`pdf-editor-run-${target.id}`).click();
await page.keyboard.press("End");
await page.keyboard.type(" PAID", { delay: 60 });
@@ -292,8 +308,7 @@ for (const fixture of ["scanned-ocr-hocr.pdf", "scanned-ocr-sandwich.pdf"]) {
.querySelector<HTMLElement>(`[data-testid="pdf-editor-run-${id}"]`)
?.blur();
}, target.id);
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, loadedSig);
await snap(page, "edited");
const edited = (await runs(page)).find((r) => r.id === target.id)!;
expect(edited.text).toMatch(/EUR PAID$/);
@@ -529,10 +544,10 @@ test("Enter in a scanned block moves later text down a line, Backspace rejoins i
const addr = (await runs(page)).find((r) => r.text.startsWith("12-4"))!;
await snap(page, "loaded");
+ const loadedSig = await bitmapSig(page);
await caretAfter(page, addr.id, "ROAD,");
await page.keyboard.press("Enter");
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, loadedSig);
await snap(page, "split");
const split = (await runs(page)).find((r) => r.id === addr.id)!;
expect(split.text.split("\n")).toHaveLength(3);
@@ -557,9 +572,9 @@ test("Enter in a scanned block moves later text down a line, Backspace rejoins i
"nothing was pushed down into the next row",
).toBeGreaterThan(50);
+ const splitSig = await bitmapSig(page);
await page.keyboard.press("Backspace");
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, splitSig);
await snap(page, "joined");
expect((await runs(page)).find((r) => r.id === addr.id)!.text).toBe(
addr.text,
@@ -592,9 +607,9 @@ test("deleting a scanned line hides it, and undo brings the scan back", async ({
await page.evaluate(() =>
(document.activeElement as HTMLElement | null)?.blur(),
);
+ const loadedSig = await bitmapSig(page);
await page.keyboard.press("Delete");
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, loadedSig);
await snap(page, "deleted");
expect(await runs(page)).toHaveLength(all.length - 1);
expect(
@@ -608,9 +623,9 @@ test("deleting a scanned line hides it, and undo brings the scan back", async ({
"the deleted line still shows on the scan",
).toBeGreaterThan(200);
+ const deletedSig = await bitmapSig(page);
await page.getByTestId("pdf-editor-undo").click();
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, deletedSig);
await snap(page, "undone");
expect(await runs(page)).toHaveLength(all.length);
expect(await diff(page, "loaded", "undone")).toBeLessThan(20);
@@ -628,12 +643,12 @@ test("dragging a scanned block moves its text off the scan", async ({
const box = (await page
.getByTestId(`pdf-editor-run-${north.id}`)
.boundingBox())!;
+ const loadedSig = await bitmapSig(page);
await page.mouse.move(box.x + box.width / 2, box.y + 2);
await page.mouse.down();
await page.mouse.move(box.x + box.width / 2 + 120, box.y + 2, { steps: 8 });
await page.mouse.up();
- await page.waitForTimeout(800);
- await settle(page);
+ await settle(page, loadedSig);
await snap(page, "moved");
const before = await ptBox(page, FORM, 40, 51, 160, 59);
expect(
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
index bf9fd8b041..c5a1b7e56c 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
@@ -159,7 +159,8 @@ for (const file of [fixture, ...corpus]) {
}, testInfo) => {
test.setTimeout(180_000);
const errors: string[] = [];
- page.on("pageerror", (error) => errors.push(error.message));
+ const onPageError = (error: Error) => errors.push(error.message);
+ page.on("pageerror", onPageError);
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("pdf-editor-root")).toBeVisible();
await page.getByTestId("pdf-editor-file-input").setInputFiles(file);
@@ -247,7 +248,10 @@ for (const file of [fixture, ...corpus]) {
path: saved,
contentType: "application/pdf",
});
+ // WebKit reports the old page's blob reads cut off by the reload as errors.
+ page.off("pageerror", onPageError);
await page.reload({ waitUntil: "domcontentloaded" });
+ page.on("pageerror", onPageError);
await page.getByTestId("pdf-editor-file-input").setInputFiles(saved);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
index 99180e588e..8161a2144c 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-unicode-fallback.spec.ts
@@ -2,7 +2,13 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page, Route } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@app/tests/stubbed/editorTestTypes";
-import { downloadBytes, saveAndDownload } from "@app/tests/stubbed/saveHelpers";
+import {
+ downloadBytes,
+ saveAndDownload,
+ stashCurrentDocument,
+ waitForReopenedPage,
+} from "@app/tests/stubbed/saveHelpers";
+import { waitForEditorReady } from "@app/tests/stubbed/editorReady";
/** Client-side Unicode fallback font (Noto Sans, embedded on demand). */
@@ -41,6 +47,24 @@ async function gotoEditor(page: Page): Promise<Promise<unknown>> {
return fontLoaded;
}
+function runText(page: Page, rid: string): Promise<string> {
+ return page.evaluate((id: string) => {
+ const s = (window as unknown as EditorTestWindow).__editor_store;
+ return s.doc.page(0).runs.find((r) => r.id === id)?.text ?? "";
+ }, rid);
+}
+
+// Reopen saved bytes and wait for that document, not the one still on screen.
+async function reopen(page: Page, name: string, saved: Buffer) {
+ await stashCurrentDocument(page);
+ await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
+ name,
+ mimeType: "application/pdf",
+ buffer: saved,
+ });
+ await waitForReopenedPage(page, 0);
+}
+
// Load SAMPLE, append `text` to the first run, blur, save, and reopen the
// produced bytes.
async function appendSaveReopen(
@@ -59,7 +83,7 @@ async function appendSaveReopen(
timeout: 30_000,
});
await fontLoaded; // bytes cached before we edit
- await page.waitForTimeout(400);
+ await waitForEditorReady(page);
// Append the sample text to the first run and commit (blur).
const id = await page.evaluate(() => {
@@ -84,26 +108,17 @@ async function appendSaveReopen(
},
{ rid: id, txt: text },
);
- await page.waitForTimeout(200);
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="pdf-editor-run-${rid}"]`)
?.blur();
}, id);
- await page.waitForTimeout(1000);
+ await expect.poll(() => runText(page, id)).toContain(text);
// Save, then reopen the produced bytes.
const saved = await downloadBytes(await saveAndDownload(page, expectRisk));
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
- name: "round-trip.pdf",
- mimeType: "application/pdf",
- buffer: saved,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ await reopen(page, "round-trip.pdf", saved);
const reopened = await page.evaluate(() => {
const s = (window as unknown as EditorTestWindow).__editor_store;
@@ -175,7 +190,7 @@ for (const { name, text } of RTL_SAMPLES) {
timeout: 30_000,
});
await fontLoaded;
- await page.waitForTimeout(400);
+ await waitForEditorReady(page);
const id = await page.evaluate(() => {
const s = (window as unknown as EditorTestWindow).__editor_store;
@@ -199,20 +214,14 @@ for (const { name, text } of RTL_SAMPLES) {
},
{ rid: id, txt: text },
);
- await page.waitForTimeout(200);
await page.evaluate((rid: string) => {
document
.querySelector<HTMLElement>(`[data-testid="pdf-editor-run-${rid}"]`)
?.blur();
}, id);
- await page.waitForTimeout(1000);
// (a) model text carries the inserted RTL string.
- const model = await page.evaluate((rid: string) => {
- const s = (window as unknown as EditorTestWindow).__editor_store;
- return s.doc.page(0).runs.find((r) => r.id === rid)?.text ?? "";
- }, id);
- expect(model).toContain(text);
+ await expect.poll(() => runText(page, id)).toContain(text);
// (b) the edited run stays within page bounds after the edit.
const fits = await page.evaluate((rid: string) => {
@@ -230,15 +239,7 @@ for (const { name, text } of RTL_SAMPLES) {
// these are always dropped and the save-risk modal always gates the save.
const saved = await downloadBytes(await saveAndDownload(page, true));
- await page.locator('[data-testid="pdf-editor-file-input"]').setInputFiles({
- name: "rtl-round-trip.pdf",
- mimeType: "application/pdf",
- buffer: saved,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ await reopen(page, "rtl-round-trip.pdf", saved);
const reopened = await page.evaluate(() => {
const s = (window as unknown as EditorTestWindow).__editor_store;
diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts
index 9987d0bd1e..f566c3c1c8 100644
--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor-upgrades-walkthrough.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";
import type { Page } from "@playwright/test";
import path from "path";
import type { EditorTestWindow } from "@app/tests/stubbed/editorTestTypes";
+import { waitForEditorReady } from "@app/tests/stubbed/editorReady";
/** Drives the real UI control by control; the screenshots are the record. */
const SAMPLE = path.join(
@@ -25,7 +26,7 @@ async function openEditor(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 45_000,
});
- await page.waitForTimeout(900);
+ await waitForEditorReady(page, 45_000);
}
/** Select the first editable run through the page, as a user would. */
@@ -37,7 +38,6 @@ async function selectFirstRun(page: Page): Promise<string> {
return run?.id ?? "";
});
expect(id).toBeTruthy();
- await page.waitForTimeout(200);
return id;
}
@@ -79,31 +79,20 @@ test("giving a run an outline changes it, and undo takes it back", async ({
await page.getByTestId("pdf-editor-colour-advanced").click();
await page.getByTestId("pdf-editor-outline-width").fill("2");
await page.getByTestId("pdf-editor-outline-width").press("Enter");
- await page.waitForTimeout(400);
- const after = await page.evaluate((id: string) => {
- const store = (window as unknown as EditorTestWindow).__editor_store;
- const run = store.doc.page(0).runs.find((r) => r.id === id);
- return {
- stroke: run?.stroke ?? null,
- width: run?.strokeWidth ?? 0,
- renderMode: run?.renderMode ?? 0,
- };
- }, runId);
- expect(after.width).toBeGreaterThan(0);
+ const outline = () =>
+ page.evaluate((id: string) => {
+ const store = (window as unknown as EditorTestWindow).__editor_store;
+ const run = store.doc.page(0).runs.find((r) => r.id === id);
+ return { width: run?.strokeWidth ?? 0, renderMode: run?.renderMode ?? 0 };
+ }, runId);
// Width alone is invisible; the run must also move to a stroking mode.
- expect(after.renderMode).toBe(2);
+ await expect.poll(async () => (await outline()).renderMode).toBe(2);
+ expect((await outline()).width).toBeGreaterThan(0);
await page.screenshot({ path: path.join(SHOTS, "02-outline-applied.png") });
await page.getByTestId("pdf-editor-undo").click();
- await page.waitForTimeout(400);
- const reverted = await page.evaluate((id: string) => {
- const store = (window as unknown as EditorTestWindow).__editor_store;
- const run = store.doc.page(0).runs.find((r) => r.id === id);
- return { width: run?.strokeWidth ?? 0, renderMode: run?.renderMode ?? 0 };
- }, runId);
- expect(reverted.width).toBe(0);
- expect(reverted.renderMode).toBe(0);
+ await expect.poll(outline).toEqual({ width: 0, renderMode: 0 });
});
test("rulers and guides can be switched on from the sidebar", async ({
@@ -118,7 +107,6 @@ test("rulers and guides can be switched on from the sidebar", async ({
const toggle = page.getByTestId("pdf-editor-toggle-rulers");
await expect(toggle).toBeVisible();
await toggle.click();
- await page.waitForTimeout(500);
const rulers = page.getByTestId("pdf-editor-rulers-0");
await expect(rulers).toBeVisible();
@@ -127,7 +115,6 @@ test("rulers and guides can be switched on from the sidebar", async ({
await page.screenshot({ path: path.join(SHOTS, "03-rulers.png") });
await toggle.click();
- await page.waitForTimeout(300);
await expect(rulers).toHaveCount(0);
});
@@ -140,7 +127,6 @@ test("find offers the new matching options", async ({
await openEditor(page);
await page.keyboard.press("Control+f");
- await page.waitForTimeout(400);
await expect(page.getByTestId("pdf-editor-find-match-case")).toBeVisible();
await expect(page.getByTestId("pdf-editor-find-whole-word")).toBeVisible();
await expect(
@@ -183,7 +169,14 @@ test("a save still produces a readable PDF after the new passes run", async ({
}, runId);
await page.keyboard.type("X");
await page.keyboard.press("Tab");
- await page.waitForTimeout(600);
+ await expect
+ .poll(() =>
+ page.evaluate((id: string) => {
+ const store = (window as unknown as EditorTestWindow).__editor_store;
+ return store.doc.page(0).runs.find((r) => r.id === id)?.text ?? "";
+ }, runId),
+ )
+ .toContain("X");
const download = page.waitForEvent("download", { timeout: 60_000 });
await page.getByTestId("pdf-editor-download").click();
diff --git a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
index 2f30a9ea48..042f1265b8 100644
--- a/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/editor/src/core/tools/pdfTextEditor/components/PageView.tsx
@@ -124,8 +124,9 @@ export function PageView({
// Raw-PDF -> display (CropBox/rotation) transform for this page. Identity for
// normal pages, so every overlay/click computation below is unchanged there.
const transform = DisplayTransform.fromData(page.display);
- const visibleFiredRef = useRef(false);
- const firstRenderFiredRef = useRef(false);
+ // Per document: a newly opened file reuses this view for its page of the same index.
+ const visibleDocRef = useRef<typeof document | null>(null);
+ const firstRenderedDocRef = useRef<typeof document | null>(null);
const [rendering, setRendering] = useState(false);
const [paintedRevision, setPaintedRevision] = useState(-1);
const [renderError, setRenderError] = useState<string | null>(null);
@@ -137,12 +138,12 @@ export function PageView({
useEffect(() => {
const el = containerRef.current;
if (!el || !onFirstVisible) return;
- if (visibleFiredRef.current) return;
+ if (visibleDocRef.current === document) return;
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
- if (entry.isIntersecting && !visibleFiredRef.current) {
- visibleFiredRef.current = true;
+ if (entry.isIntersecting && visibleDocRef.current !== document) {
+ visibleDocRef.current = document;
onFirstVisible(page.pageIndex);
observer.disconnect();
}
@@ -152,7 +153,7 @@ export function PageView({
);
observer.observe(el);
return () => observer.disconnect();
- }, [page.pageIndex, onFirstVisible]);
+ }, [document, page.pageIndex, onFirstVisible]);
// Near-viewport observer drives rendering with a wide rootMargin so the
// bitmap is ready just before the page scrolls in.
@@ -198,8 +199,8 @@ export function PageView({
if (ctx) ctx.putImageData(image, 0, 0);
setRendering(false);
setPaintedRevision(page.revision);
- if (!firstRenderFiredRef.current) {
- firstRenderFiredRef.current = true;
+ if (firstRenderedDocRef.current !== document) {
+ firstRenderedDocRef.current = document;
onFirstRendered?.(page.pageIndex);
}
})
@@ -212,8 +213,8 @@ export function PageView({
setRenderError(msg);
// Flip the first-rendered flag on error too, so the loading
// overlay dismisses instead of leaving the user on a spinner.
- if (!firstRenderFiredRef.current) {
- firstRenderFiredRef.current = true;
+ if (firstRenderedDocRef.current !== document) {
+ firstRenderedDocRef.current = document;
onFirstRendered?.(page.pageIndex);
}
});