#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Fix flaky Page Editor tests (#8867)
James Brunton2af1964c636e
diff --git a/frontend/src/editor/core/components/shared/FileSidebar.tsx b/frontend/src/editor/core/components/shared/FileSidebar.tsxindex 578f251b69..69760d54e3 100644--- a/frontend/src/editor/core/components/shared/FileSidebar.tsx+++ b/frontend/src/editor/core/components/shared/FileSidebar.tsx@@ -540,6 +540,15 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([],);const [stubsLoaded, setStubsLoaded] = useState(false);+ const [ingestsInFlight, setIngestsInFlight] = useState(0);+ const trackIngest = useCallback(async (ingest: () => Promise<void>) => {+ setIngestsInFlight((n) => n + 1);+ try {+ await ingest();+ } finally {+ setIngestsInFlight((n) => n - 1);+ }+ }, []);const [saveToServerTarget, setSaveToServerTarget] = useState<StirlingFileStub[] | null>(null);@@ -830,17 +839,20 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(if (!isGoogleDriveEnabled) return;const files = await openGoogleDrivePicker({ multiple: true });if (files.length === 0) return;- if (onPickGoogleDriveFiles) {- await onPickGoogleDriveFiles(files);- return;- }- await addFiles(files);- if (!staysOnAdd) {- navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");- }+ await trackIngest(async () => {+ if (onPickGoogleDriveFiles) {+ await onPickGoogleDriveFiles(files);+ return;+ }+ await addFiles(files);+ if (!staysOnAdd) {+ navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");+ }+ });}, [isGoogleDriveEnabled,openGoogleDrivePicker,+ trackIngest,addFiles,navActions,staysOnAdd,@@ -984,9 +996,11 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(const ingestFiles = useCallback(async (files: File[]) => {if (files.length === 0) return;- if (onUploadFiles) {- await onUploadFiles(files);- } else {+ await trackIngest(async () => {+ if (onUploadFiles) {+ await onUploadFiles(files);+ return;+ }await addFiles(files);// A tool that pinned its own workbench surface owns it - switching to// the viewer here strands the upload outside the tool being used.@@ -995,9 +1009,16 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(files.length === 1 ? "viewer" : "fileEditor",);}- }+ });},- [addFiles, navActions, staysOnAdd, onUploadFiles, currentWorkbench],+ [+ trackIngest,+ addFiles,+ navActions,+ staysOnAdd,+ onUploadFiles,+ currentWorkbench,+ ],);const handleNativeFilePick = useCallback(@@ -1174,7 +1195,10 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(</NavSurface><NavSurface className="file-sidebar-files-box">- <div className="file-sidebar-scroll">+ <div+ className="file-sidebar-scroll"+ aria-busy={ingestsInFlight > 0}+ >{currentWorkbench === "myFiles" ? (<FolderTreeSection />) : (diff --git a/frontend/src/editor/core/tests/helpers/ui-helpers.ts b/frontend/src/editor/core/tests/helpers/ui-helpers.tsindex 6cf76cb9ea..406fcd05ee 100644--- a/frontend/src/editor/core/tests/helpers/ui-helpers.ts+++ b/frontend/src/editor/core/tests/helpers/ui-helpers.ts@@ -44,62 +44,50 @@ export async function waitForModalClose(});}-/** Uploads through the sidebar and waits for IndexedDB persistence before callers navigate. */+/**+ * Uploads through the sidebar and returns once the app has finished with it:+ * every file stored, and the view switched to wherever an upload lands. Not for+ * encrypted PDFs, whose upload stays open until the unlock prompt is answered.+ */export async function uploadFiles(page: Page,filePaths: string | string[],): Promise<void> {const paths = Array.isArray(filePaths) ? filePaths : [filePaths];- const names = paths.map((p) => p.split(/[\\/]/).pop() ?? p);await page.getByTestId("files-button").click();await page.locator('[data-testid="file-input"]').setInputFiles(paths);- await expect(page.locator(".file-sidebar-file-item").first()).toBeVisible({- timeout: 10_000,- });- await waitForStoredFiles(page, names);+ // The pick marks the list busy inside the change event, before setInputFiles+ // returns, so this cannot read the idle state from before the upload. No+ // timeout of its own: under load an upload is slow, not stuck, and the test+ // timeout still ends a real hang.+ await expect(page.locator(".file-sidebar-scroll")).toHaveAttribute(+ "aria-busy",+ "false",+ { timeout: 0 },+ );}-/** Polls an existing database without creating or upgrading it, so setup cannot race the app. */-async function waitForStoredFiles(page: Page, names: string[]): Promise<void> {- await page.waitForFunction(- (expected) =>- new Promise<boolean>((resolve) => {- const open = indexedDB.open("stirling-pdf-files");- open.onupgradeneeded = () => {- open.transaction?.abort();- resolve(false);- };- open.onsuccess = () => {- const db = open.result;- if (!db.objectStoreNames.contains("files")) {- db.close();- resolve(false);- return;- }- const request = db- .transaction("files", "readonly")- .objectStore("files")- .getAll();- request.onsuccess = () => {- const stored = new Set(- (request.result as Array<{ name?: string }>).map((r) => r.name),- );- db.close();- resolve(expected.every((name) => stored.has(name)));- };- request.onerror = () => {- db.close();- resolve(false);- };- };- open.onerror = () => resolve(false);- open.onblocked = () => resolve(false);- }),- names,- // The IndexedDB write can lag the upload on WebKit under parallel CI load;- // it lands, just not always within 10s, so give the commit room to finish.- { timeout: 30_000, polling: 100 },- );+/**+ * Switches workbench view by clicking the label of its segment, since the radio+ * itself is visually hidden. The selected view's label opens a beat after the+ * selection changes and slides the other segments sideways, so this first waits+ * for that to finish: mid-slide, the click lands on the neighbouring segment.+ */+export async function switchView(page: Page, label: string): Promise<void> {+ const switcher = page.locator('[data-tour="view-switcher"]').first();+ await expect(+ switcher.locator(+ ".mantine-SegmentedControl-control:has(input:checked) .workbench-bar-view-label.is-open",+ ),+ ).toHaveCount(1);+ await expect+ .poll(() =>+ switcher.evaluate((el) => el.getAnimations({ subtree: true }).length),+ )+ .toBe(0);+ await switcher+ .locator(".mantine-SegmentedControl-label", { hasText: label })+ .click();}/** Leaves upload-induced viewer mode when present, so tool controls can enable. */diff --git a/frontend/src/editor/core/tests/stubbed/page-editor-duplicate.spec.ts b/frontend/src/editor/core/tests/stubbed/page-editor-duplicate.spec.tsindex ef1bc925a7..71a3dde197 100644--- a/frontend/src/editor/core/tests/stubbed/page-editor-duplicate.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/page-editor-duplicate.spec.ts@@ -4,6 +4,7 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";import {uploadFiles,dismissTourTooltip,+ switchView,} from "@editor/tests/helpers/ui-helpers";/**@@ -35,17 +36,6 @@ function tile(return track(page, name).locator("[data-page-id]").nth(index);}-async function switchView(- page: import("@playwright/test").Page,- label: string,-) {- await page- .locator('[data-tour="view-switcher"]')- .first()- .locator(".mantine-SegmentedControl-label", { hasText: label })- .click();-}-/** Intrinsic rotations as the editor shows them, in track order. */async function readRotations(lane: import("@playwright/test").Locator,diff --git a/frontend/src/editor/core/tests/stubbed/page-tracks.spec.ts b/frontend/src/editor/core/tests/stubbed/page-tracks.spec.tsindex e5c4554655..02f8b597af 100644--- a/frontend/src/editor/core/tests/stubbed/page-tracks.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/page-tracks.spec.ts@@ -8,6 +8,7 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";import {uploadFiles,dismissTourTooltip,+ switchView,} from "@editor/tests/helpers/ui-helpers";// 4 portrait pages whose intrinsic /Rotate is 0, 90, 270, 180.@@ -27,23 +28,6 @@ function track(page: import("@playwright/test").Page, name: string) {return page.locator(`section[aria-label="${name}"]`);}-/**- * Switches workbench view. The switcher is a Mantine SegmentedControl whose- * radio input is visually hidden, so the click goes through the label. Only the- * active segment shows its text (the rest are icon-only), so the label is found- * by its text content and clicked as a whole rather than clicking the text node.- */-async function switchView(- page: import("@playwright/test").Page,- label: string,-) {- await page- .locator('[data-tour="view-switcher"]')- .first()- .locator(".mantine-SegmentedControl-label", { hasText: label })- .click();-}-/*** Rotations as the editor is displaying them. Thumbnails load lazily, so this* waits for the images before reading: an empty list means "not loaded yet",@@ -104,6 +88,12 @@ function dropTarget(page: import("@playwright/test").Page) {return page.locator("[data-page-id][data-drop-before]");}+/**+ * Releases once the insertion line shows the drop landing beside `to`: the drop+ * resolves against dnd-kit's hovered target, which can trail the last pointer+ * move, so releasing at once can land a slot short. Past the midpoint, `to` must+ * be the last page of its track.+ */async function dragPageOnto(page: import("@playwright/test").Page,from: import("@playwright/test").Locator,@@ -111,6 +101,10 @@ async function dragPageOnto(fractionAcross = 0.25,) {await dragPageOver(page, from, to, fractionAcross);+ await expect(to).toHaveAttribute(+ fractionAcross < 0.5 ? "data-drop-before" : "data-drop-after-last",+ "true",+ );await page.mouse.up();}@@ -140,6 +134,7 @@ async function dragPageIntoGap({ steps: 8 },);}+ await expect(rightTile).toHaveAttribute("data-drop-before", "true");await page.mouse.up();}@@ -185,6 +180,13 @@ async function dragTrackOnto(await page.mouse.up();}+function viewOption(page: import("@playwright/test").Page, label: string) {+ return page+ .locator('[data-tour="view-switcher"]')+ .first()+ .getByRole("radio", { name: label });+}+async function openPageEditor(page: import("@playwright/test").Page) {await page.goto("/editor", {waitUntil: "domcontentloaded",@@ -196,6 +198,15 @@ async function openPageEditor(page: import("@playwright/test").Page) {await expect(page.getByTestId("page-tracks")).toBeVisible({timeout: 30_000,});+ // Each file's pages load separately, and select-all or typed page numbers+ // reach only the pages already there.+ await expect(+ track(page, "rotated-pages.pdf").locator("[data-page-id]"),+ ).toHaveCount(4, { timeout: 30_000 });+ await expect(track(page, "sample.pdf").locator("[data-page-id]")).toHaveCount(+ 1,+ { timeout: 30_000 },+ );}test.describe("Page Editor tracks", () => {@@ -358,6 +369,11 @@ test.describe("Page Editor tracks", () => {page.getByRole("heading", { name: "Unsaved Changes" }),).toBeVisible();await page.getByRole("button", { name: "Save & Leave" }).click();+ // The prompt closes a render before the leave lands, and a click on the+ // still-selected Page Editor in that gap changes nothing.+ await expect(viewOption(page, "Active Files")).toBeChecked({+ timeout: 90_000,+ });// Back in the editor, the delete is now version 2 rather than pending.await switchView(page, "Page Editor");