Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 148 additions & 11 deletions apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2334,19 +2334,20 @@ it("toggles a Mermaid attachment between diagram and source through the lazy pre
expect(screen.container.querySelector('[role="alert"]')).toBeNull();
});

it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {
function planningPdf(
titles = ["Quarterly outlook", "Delivery milestones", "Budget and risks"],
firstHeight = 140,
pageHeight = 792,
) {
const objects = [
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Count 3 /Kids [3 0 R 5 0 R 7 0 R] >>",
`<< /Type /Pages /Count ${titles.length} /Kids [${titles.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] >>`,
];
for (const [index, title] of [
"Quarterly outlook",
"Delivery milestones",
"Budget and risks",
].entries()) {
const font = 3 + titles.length * 2;
for (const [index, title] of titles.entries()) {
const text = `/GS1 gs BT /F1 24 Tf 30 ${index === 0 ? 70 : 700} Td ${index === 0 ? "(Quarter) Tj /F2 24 Tf (ly outlook) Tj" : `(${title}) Tj`} ET`;
objects.push(
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? 140 : 792}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 9 0 R /F2 10 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`,
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? firstHeight : pageHeight}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 ${font} 0 R /F2 ${font + 1} 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`,
`<< /Length ${text.length} >>\nstream\n${text}\nendstream`,
);
}
Expand All @@ -2359,11 +2360,147 @@ it("navigates, searches, zooms, and selects mixed-height PDF pages", async () =>
source += `${index + 1} 0 obj\n${object}\nendobj\n`;
}
const xref = source.length;
source += `xref\n0 11\n0000000000 65535 f \n${offsets
source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets
.slice(1)
.map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)
.join("")}trailer\n<< /Size 11 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
const file = new Blob([source], { type: "application/pdf" });
.join("")}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
return new Blob([source], { type: "application/pdf" });
}

it("keeps workspace PDF scroll and zoom after reloads and clamps them when the document shrinks", async () => {
assetUrlState.mockReset();
const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel");
using _native = vi.spyOn(navigator, "pdfViewerEnabled", "get").mockReturnValue(false);
using urls = (() => {
const original = URL.createObjectURL(planningPdf());
const updated = URL.createObjectURL(
planningPdf(["Quarterly outlook", "Delivery milestones", "Updated budget"], 500),
);
const shorter = URL.createObjectURL(planningPdf(["Quarterly outlook", "Updated milestones"]));
const shrunk = URL.createObjectURL(
planningPdf(["Quarterly outlook", "Small page", "Budget and risks"], 500, 200),
);
const single = URL.createObjectURL(planningPdf(["Quarterly outlook"]));
return {
original,
updated,
shorter,
shrunk,
single,
[Symbol.dispose]: () =>
[original, updated, shorter, shrunk, single].forEach(URL.revokeObjectURL),
};
})();
const preview = (src: string, mutation: string, path = "/repo/planning.pdf") => {
assetUrlState.mockReturnValue({
_tag: "Success",
url: `${src}#preview`,
expiresAt: Date.now() + 3_600_000,
});
return (
<div style={{ display: "flex", height: 600, width: 320 }}>
<WorkspaceBrowserPreview
environmentId={EnvironmentId.make("test")}
threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }}
draft={false}
absolutePath={path}
workspaceRoot="/repo"
title="Planning PDF"
workspaceMutationId={mutation}
/>
</div>
);
};
await using screen = await render(preview(urls.original, "one"));
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"), {
timeout: 15_000,
});
await screen.getByRole("button", { name: "Next page", exact: true }).click();
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
await screen.getByRole("button", { name: "Next page", exact: true }).click();
await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
for (let index = 0; index < 4; index++) {
await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
}
const region = () => screen.container.querySelector<HTMLElement>('[role="region"]')!;
const canvas = (page: number) =>
region().querySelector<HTMLCanvasElement>(`canvas[aria-label="Page ${page}"]`)!;
const offset = (page: number) =>
region().getBoundingClientRect().top - canvas(page).getBoundingClientRect().top;
const scrollTo = (options: ScrollToOptions) =>
act(async () => {
const node = region();
const scrolled = new Promise<void>((resolve) =>
node.addEventListener("scroll", () => resolve(), { once: true }),
);
node.scrollTo(options);
await scrolled;
});
const zoom = screen.container.textContent!.match(/\d+%/)![0];
const top = region().scrollTop;
await scrollTo({ top: top + 100, left: 80 });
await vi.waitFor(() => {
expect(region().scrollTop).toBeCloseTo(top + 100, 0);
expect(region().scrollLeft).toBe(80);
});
const savedOffset = offset(3);
await screen.rerender(preview(urls.updated, "two"));
await vi.waitFor(() => {
expect(screen.container.textContent).toContain("3 / 3 pages");
expect(screen.container.querySelector('[role="region"]')?.textContent).toContain(
"Updated budget",
);
expect(screen.container.textContent).toContain(zoom);
expect(region().scrollLeft).toBe(80);
expect(offset(3)).toBeCloseTo(savedOffset, 0);
});
await screen.getByRole("button", { name: "Previous page", exact: true }).click();
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
const secondPageTop = region().scrollTop;
await scrollTo({ top: secondPageTop + 600 });
await vi.waitFor(() => expect(region().scrollTop).toBeCloseTo(secondPageTop + 600, 0));
await screen.rerender(preview(urls.shrunk, "smaller-page"));
await vi.waitFor(() => {
expect(screen.container.textContent).toContain("2 / 3 pages");
expect(screen.container.textContent).toContain(zoom);
expect(region().scrollLeft).toBe(80);
expect(offset(2)).toBeGreaterThan(0);
expect(offset(2)).toBeLessThan(canvas(2).getBoundingClientRect().height);
});
await screen.rerender(preview(urls.shorter, "three"));
await vi.waitFor(() => {
expect(screen.container.textContent).toContain("2 / 2 pages");
expect(screen.container.querySelector('[role="region"]')?.textContent).toContain(
"Updated milestones",
);
});
await screen.rerender(preview(urls.single, "four"));
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 1 pages"));
await screen.rerender(preview(urls.original, "five"));
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));
await screen.getByRole("button", { name: "Fit width", exact: true }).click();
await screen.rerender(preview(urls.original, "six"));
await vi.waitFor(() => {
expect(screen.container.textContent).toContain("Fit width");
expect(region().scrollLeft).toBe(0);
});
await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
const firstPageZoom = screen.container.textContent!.match(/\d+%/)![0];
await screen.rerender(preview(urls.original, "seven"));
await vi.waitFor(() => expect(screen.container.textContent).toContain(firstPageZoom));
await screen.getByRole("button", { name: "Next page", exact: true }).click();
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
await screen.rerender(preview(urls.original, "one", "/repo/another.pdf"));
await vi.waitFor(() => {
expect(screen.container.textContent).toContain("1 / 3 pages");
expect(screen.container.textContent).toContain("Fit width");
expect(region().scrollTop).toBe(0);
expect(region().scrollLeft).toBe(0);
});
});

it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {
const file = planningPdf();
const { default: PdfViewer } = await import("./PdfViewer");
const url = URL.createObjectURL(file);
try {
Expand Down
45 changes: 42 additions & 3 deletions apps/web/src/components/files/BrowserDocumentFrame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
} from "react";
import { isElectron } from "~/env";
import { FileSurfaceLoading } from "./fileSurfaceChrome";
import type { PdfViewState } from "./PdfViewer";

import { useOpenLink } from "~/browser/useOpenLink";
import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
Expand Down Expand Up @@ -73,7 +74,33 @@ export const isPdfPreviewFile = (path: string): boolean =>

const PdfViewer = lazy(() => import("./PdfViewer"));

function PdfDocument(props: { src: string; title: string }) {
/**
* documentKey includes the file's revision and remounts the viewer when it changes.
* A stable documentId keeps this component mounted to track the page, scroll, and zoom across reloads.
*/
function PdfDocument(props: { src: string; title: string; documentKey: string }) {
const [view, setView] = useState<PdfViewState>({ page: 0, offset: 0, zoom: null, left: 0 });
return (
<PdfDocumentRevision
key={props.documentKey}
src={props.src}
title={props.title}
initialView={view}
onViewChange={setView}
/>
);
}

/**
* File URLs expire and are refreshed even when the PDF hasn't changed.
* Keep the initial URL so those refreshes don't reload the viewer.
*/
function PdfDocumentRevision(props: {
src: string;
title: string;
initialView: PdfViewState;
onViewChange: (view: PdfViewState) => void;
}) {
const [src] = useState(props.src);
// The Electron shell does not enable PDF plugins. WebKit embeds on iOS
// expose only the first page, even when pdfViewerEnabled reports support.
Expand All @@ -91,7 +118,12 @@ function PdfDocument(props: { src: string; title: string }) {
/>
) : (
<Suspense fallback={<FileSurfaceLoading />}>
<PdfViewer src={src} title={props.title} />
<PdfViewer
src={src}
title={props.title}
initialView={props.initialView}
onViewChange={props.onViewChange}
/>
</Suspense>
);
}
Expand All @@ -108,10 +140,17 @@ export function BrowserDocumentFrame(props: {
readonly threadRef?: ScopedThreadRef | undefined;
/** Stable resource identity and revision; defaults to src for callers that reload on URL changes. */
readonly documentKey?: string | undefined;
/** Resource identity without its revision, so PDF reloads can retain the reading position. */
readonly documentId?: string | undefined;
}) {
const key = props.documentKey ?? props.src;
return props.pdf ? (
<PdfDocument key={key} src={props.src} title={props.title} />
<PdfDocument
key={props.documentId ?? key}
documentKey={key}
src={props.src}
title={props.title}
/>
) : props.htmlRender ? (
<HtmlRenderDocument
key={key}
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/components/files/FilePreviewPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ function WorkspaceImagePreview(props: {
);
}

function WorkspaceBrowserPreview(props: {
export function WorkspaceBrowserPreview(props: {
readonly environmentId: EnvironmentId;
readonly threadRef: ScopedThreadRef;
readonly draft: boolean;
Expand Down Expand Up @@ -257,6 +257,7 @@ function WorkspaceBrowserPreview(props: {
<BrowserDocumentFrame
src={`${assetUrl.url}${revisionSuffix}`}
documentKey={`${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}:${props.workspaceMutationId}`}
documentId={`${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}`}
title={props.title}
pdf={isPdfPreviewFile(props.absolutePath)}
/>
Expand Down
Loading
Loading