Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
17 changes: 10 additions & 7 deletions specs/reference-library/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -583,14 +583,17 @@ memory and makes citation aliases compete with stable source identity.
and the annotation overview persistent. Contents, scrolling and page-display
controls move behind a labelled View menu; reference inspection and PDF file
actions move behind a separate labelled action menu. Menu items keep visible
text while persistent rail controls keep accessible names and tooltips. A
horizontal swipe begun on the fitted page or its surround changes page,
except when it begins on an interactive PDF link or saved annotation. A
text while persistent rail controls keep accessible names and tooltips. The
View menu stays open when stepping zoom in or out. A horizontal swipe begun
on the fitted page or its surround changes page, except when it begins on an
interactive PDF link or saved annotation. A
two-finger gesture zooms the PDF rather than the application, anchored at the
pinch midpoint; trackpad zoom is anchored at the pointer. The reader preserves
its scrollbar-free fitted width across buffered zoom renders and remeasures it
only after document or layout changes, so returning to fitted zoom cannot
leave the page narrower. Live ink updates one draft path between saves.
pinch midpoint. Trackpad zoom is anchored at the pointer in single-page,
continuous, and spread layouts, including when Select is active. The reader
preserves its scrollbar-free fitted width across buffered zoom renders and
remeasures it only after document or layout changes, so returning to fitted
zoom cannot leave the page narrower. Live ink updates one draft path between
saves.
- The active PDF page exposes standard PDF link annotations. Internal
destinations stay in the reader and restore the destination page and
position; external URLs open in a protected new tab.
Expand Down
23 changes: 19 additions & 4 deletions src/client/app/action-menu-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ActionMenuController } from "./action-menu-controller";

class FakeTarget {
constructor(readonly action = false) {}
constructor(
readonly action = false,
readonly keepOpen = false,
) {}

closest(): FakeTarget | null {
return this.action ? this : null;
}

hasAttribute(name: string): boolean {
return name === "data-action-menu-keep-open" && this.keepOpen;
}
}

class FakeSummary {
Expand Down Expand Up @@ -78,17 +85,25 @@ describe("action menu controller", () => {
beforeEach(() => vi.stubGlobal("Element", FakeTarget));
afterEach(() => vi.unstubAllGlobals());

it("closes action menus outside or after choosing an action", () => {
it("keeps the owning menu open for an opted-in action and closes other open menus", () => {
const root = new FakeMenuDocument();
const menu = new FakeMenu();
const otherMenu = new FakeMenu();
const inside = new FakeTarget();
const keepOpen = new FakeTarget(true, true);
const close = new FakeTarget(true);
menu.inside.add(inside);
root.actionMenus = [menu];
menu.inside.add(keepOpen);
menu.inside.add(close);
root.actionMenus = [menu, otherMenu];
const controller = new TestActionMenuController(root);

controller.dispatchClick(keepOpen);
expect(menu.open).toBe(true);
expect(otherMenu.open).toBe(false);
controller.dispatchClick(inside);
expect(menu.open).toBe(true);
controller.dispatchClick(new FakeTarget(true));
controller.dispatchClick(close);
expect(menu.open).toBe(false);
expect(controller.renderForTest()).toBeDefined();
expect(controller.rootForTest()).toBe(controller);
Expand Down
3 changes: 2 additions & 1 deletion src/client/app/action-menu-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ export class ActionMenuController extends LightDomHost {

protected readonly closeFromClick = (event: MouseEvent): void => {
if (!(event.target instanceof Element)) return;
const action = event.target.closest("button, a");
for (const menu of this.menuDocument.querySelectorAll<HTMLDetailsElement>("details[data-action-menu][open]")) {
if (!menu.contains(event.target) || event.target.closest("button, a")) menu.open = false;
if (!menu.contains(event.target) || (action && !action.hasAttribute("data-action-menu-keep-open"))) menu.open = false;
}
const settings = this.menuDocument.querySelector<HTMLDetailsElement>("details[data-settings-menu][open]");
if (settings && !settings.contains(event.target)) settings.open = false;
Expand Down
61 changes: 61 additions & 0 deletions src/client/library/library-pdf-layout.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,67 @@ async function openPaper(page: Page, draft: PdfDraftResult): Promise<void> {
await expect(page.locator("#paper-text-layer")).toContainText("Knowledge grows through inspectable evidence.");
}

test.describe("PDF pinch zoom", () => {
test.use({ hasTouch: true });

test("zooms in and out in Select mode in continuous view", async ({ page, context, baseURL }) => {
if (!baseURL) throw new Error("Expected browser test origin");
const draft = await uploadPaper(context, baseURL);
await openPaper(page, draft);
await page.getByRole("button", { name: "Select", exact: true }).click();
await page.locator("#library-pdf-view-options").click();
await page.locator("#toggle-library-paper-continuous").click();

const canvas = page.locator('.pdf-continuous-page[data-pdf-page="1"] canvas');
const canvasWidth = async () => Number(await canvas.getAttribute("width"));
await expect.poll(canvasWidth).toBeGreaterThan(0);
const fittedWidth = await canvasWidth();
const reader = page.locator("#paper-reader");
const bounds = await reader.boundingBox();
if (!bounds) throw new Error("Expected a visible PDF reader");
const x = Math.round(bounds.x + bounds.width / 2);
const y = Math.round(bounds.y + bounds.height / 3);
const input = await context.newCDPSession(page);

await input.send("Input.synthesizePinchGesture", { x, y, scaleFactor: 1.5, gestureSourceType: "touch" });
await expect.poll(canvasWidth).toBeGreaterThan(fittedWidth);

const zoomedWidth = await canvasWidth();
await input.send("Input.synthesizePinchGesture", { x, y, scaleFactor: 0.8, gestureSourceType: "mouse" });
await expect
.poll(async () => {
const width = await canvasWidth();
return width > fittedWidth && width < zoomedWidth;
})
.toBe(true);
await expect(reader).toHaveAttribute("data-display-mode", "continuous");
await expect(page.getByRole("button", { name: "Select", exact: true })).toHaveAttribute("aria-pressed", "true");
});
});

test("keeps PDF view options open while stepping zoom", async ({ page, context, baseURL }) => {
if (!baseURL) throw new Error("Expected browser test origin");
const draft = await uploadPaper(context, baseURL);
await openPaper(page, draft);

const canvas = page.locator("#paper-canvas");
const canvasWidth = async () => Number(await canvas.getAttribute("width"));
const fittedWidth = await canvasWidth();
const viewOptions = page.getByRole("button", { name: "View options", exact: true });
const panel = page.getByRole("group", { name: "PDF view options" });
await viewOptions.click();
await panel.getByRole("button", { name: "Zoom in", exact: true }).click();
await expect.poll(canvasWidth).toBeGreaterThan(fittedWidth);
await expect(panel).toBeVisible();
await panel.getByRole("button", { name: "Zoom out", exact: true }).click();
await expect.poll(canvasWidth).toBe(fittedWidth);
await expect(panel).toBeVisible();

await page.keyboard.press("Escape");
await expect(panel).toBeHidden();
await expect(viewOptions).toBeFocused();
});

for (const viewport of [
{ width: 1440, height: 900 },
{ width: 1024, height: 640 },
Expand Down
36 changes: 34 additions & 2 deletions src/client/pdf/pdf-reading-controls.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,21 +138,53 @@ beforeEach(() => {
vi.stubGlobal("HTMLElement", FakeElement);
vi.stubGlobal("Node", FakeElement);
vi.stubGlobal("window", {
clearTimeout,
clearTimeout: (timer: number | undefined) => clearTimeout(timer),
devicePixelRatio: 1,
getComputedStyle: () => ({ paddingLeft: "0", paddingRight: "0" }),
getSelection: () => null,
localStorage: { getItem: () => null, setItem: setStoredDisplayMode },
setTimeout,
setTimeout: (callback: () => void, delay: number) => setTimeout(callback, delay),
});
});

afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});

describe("PDF reading controls", () => {
it.each([
{ mode: "continuous", width: 1_350 },
{ mode: "spread", width: 663 },
] as const)("debounces trackpad zoom in $mode view and keeps the current page", async ({ mode, width }) => {
vi.useFakeTimers();
const elements = viewerElements();
const viewer = new PdfEvidenceViewer(elements as never, vi.fn(), vi.fn());
const documentModel = pdfDocument(3);
pdfjs.getDocument.mockReturnValue({ destroy: vi.fn(), promise: Promise.resolve(documentModel) });
const openFlow = vi.spyOn(PdfContinuousView.prototype, "open").mockResolvedValue();

await viewer.open({ annotations: [], page: 2, url: "/paper.pdf" });
await viewer.setDisplayMode(mode);
const preventDefault = vi.fn();
const wheel = { clientX: 100, clientY: 200, ctrlKey: true, deltaY: -50 * Math.log(1.5), preventDefault };
elements.reader.dispatch("wheel", wheel);
await vi.advanceTimersByTimeAsync(100);
elements.reader.dispatch("wheel", wheel);
await vi.advanceTimersByTimeAsync(100);

expect(preventDefault).toHaveBeenCalledTimes(2);
expect(elements.continuousPages.style.transform).toMatch(/^scale\(/u);
expect(openFlow).toHaveBeenCalledOnce();

await vi.advanceTimersByTimeAsync(40);

expect(openFlow).toHaveBeenCalledTimes(2);
expect(openFlow).toHaveBeenLastCalledWith(documentModel, pdfjs, 2, expect.closeTo(width), 0, false);
expect(elements.continuousPages.style.transform).toBe("");
});

it.each(["continuous", "spread"] as const)("manually pans a %s Draw surface under one-finger touch", async (mode) => {
const reader = new FakeElement();
reader.scrollLeft = 40;
Expand Down
60 changes: 38 additions & 22 deletions src/client/pdf/pdf-viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ export class PdfEvidenceViewer {
? this.#elements.page.hidden && !this.#elements.continuousPages.hidden
: !this.#elements.page.hidden && this.#elements.continuousPages.hidden;
if (mode === this.#displayMode && alreadyPresented) return;
this.#cancelPendingWheelZoom();
const flowRenderGeneration = ++this.#flowRenderGeneration;
this.#pinchGeneration += 1;
this.#displayMode = mode;
Expand Down Expand Up @@ -265,13 +266,15 @@ export class PdfEvidenceViewer {
}

async adjustZoom(delta: number): Promise<void> {
this.#cancelPendingWheelZoom();
this.#zoom = adjustPdfZoom(this.#zoom, delta);
this.#elements.reader.dataset.zoomed = String(Math.abs(this.#zoom - 1) > 0.01);
if (this.#displayMode === "single") await this.#renderPage();
else await this.#rerenderFlow();
}

async cycleFitMode(): Promise<void> {
this.#cancelPendingWheelZoom();
this.#fitMode = nextPdfFitMode(this.#fitMode);
this.#zoom = 1;
this.#fittedWidth = null;
Expand All @@ -281,6 +284,7 @@ export class PdfEvidenceViewer {
}

async rotateClockwise(): Promise<void> {
this.#cancelPendingWheelZoom();
this.#rotation = nextPdfRotation(this.#rotation);
this.#fittedWidth = null;
if (this.#displayMode === "single") await this.#renderPage();
Expand All @@ -307,7 +311,7 @@ export class PdfEvidenceViewer {
this.#renderedZoom = renderedZoom;
this.#presentContinuousReady();
if (pinchGeneration !== undefined && pinchGeneration !== this.#pinchGeneration) {
if (this.#pinchStart?.surface === this.#elements.continuousPages) {
if (this.#pinchStart?.surface === this.#elements.continuousPages || this.#wheelZoomRenderTimer !== undefined) {
this.#elements.continuousPages.style.transform = `scale(${this.#flowPreviewScale(this.#zoom)})`;
}
return false;
Expand All @@ -316,6 +320,7 @@ export class PdfEvidenceViewer {
}

async open(options: OpenPdfOptions): Promise<boolean> {
this.#cancelPendingWheelZoom();
this.#flowRenderGeneration += 1;
this.#pinchGeneration += 1;
this.#lifecycle.send({ type: "OPEN" });
Expand All @@ -338,8 +343,6 @@ export class PdfEvidenceViewer {
this.#privateHighlights = options.privateHighlights ?? [];
this.#focusedAnnotationId = options.focusAnnotationId;
window.clearTimeout(this.#selectionCaptureTimer);
window.clearTimeout(this.#wheelZoomRenderTimer);
this.#wheelZoomRenderTimer = undefined;
this.#clearNativeSelection();
this.#draftSelection = null;
this.#mode = options.mode ?? "evidence";
Expand Down Expand Up @@ -520,8 +523,7 @@ export class PdfEvidenceViewer {
}

async resize(): Promise<void> {
window.clearTimeout(this.#wheelZoomRenderTimer);
this.#wheelZoomRenderTimer = undefined;
this.#cancelPendingWheelZoom();
this.#fittedWidth = null;
if (this.#displayMode !== "single") await this.#rerenderFlow();
else await this.#renderPage();
Expand Down Expand Up @@ -557,14 +559,12 @@ export class PdfEvidenceViewer {
}

#handleWheel(event: WheelEvent): void {
if (this.#displayMode !== "single") {
if (event.ctrlKey) event.preventDefault();
return;
}
if (event.ctrlKey) {
this.#zoomFromWheel(event);
event.preventDefault();
if (this.#document && !this.#pinchStart) this.#zoomFromWheel(event);
return;
}
if (this.#displayMode !== "single") return;
if (!this.#document || !this.#wheelCanTurnPage(event.deltaX)) {
this.#wheelPagingState = initialPdfWheelPagingState();
return;
Expand All @@ -588,16 +588,25 @@ export class PdfEvidenceViewer {
}

#zoomFromWheel(event: WheelEvent): void {
event.preventDefault();
this.#lifecycle.send({ type: "CANCEL_RENDER" });
this.#previewZoom(clamp(this.#zoom * Math.exp(-event.deltaY * 0.01), 0.75, 4), event.clientX, event.clientY);
const surface = this.#zoomPreviewSurface();
const generation = ++this.#pinchGeneration;
this.#previewZoom(clamp(this.#zoom * Math.exp(-event.deltaY * 0.01), 0.75, 4), event.clientX, event.clientY, surface);
window.clearTimeout(this.#wheelZoomRenderTimer);
this.#wheelZoomRenderTimer = window.setTimeout(() => {
this.#wheelZoomRenderTimer = undefined;
void this.#renderPage();
void this.#commitZoom(surface, generation);
}, 140);
}

#cancelPendingWheelZoom(): void {
if (this.#wheelZoomRenderTimer === undefined) return;
window.clearTimeout(this.#wheelZoomRenderTimer);
this.#wheelZoomRenderTimer = undefined;
this.#clearZoomPreview(this.#zoomPreviewSurface());
this.#zoomAnchor = null;
}

async #renderPage(): Promise<void> {
const documentModel = this.#document;
const runtime = this.#runtime;
Expand Down Expand Up @@ -1022,12 +1031,7 @@ export class PdfEvidenceViewer {
const pinchStart = this.#pinchStart;
if (pinchStart && event.touches.length < 2) {
this.#pinchStart = null;
if (this.#displayMode === "single") await this.#renderPage();
else {
const zoomAnchor = this.#takeZoomAnchor();
this.#clearZoomPreview(pinchStart.surface);
if (await this.#rerenderFlow(pinchStart.generation)) this.#restoreZoomAnchor(pinchStart.surface, zoomAnchor);
}
await this.#commitZoom(pinchStart.surface, pinchStart.generation);
return;
}
const start = this.#swipeStart;
Expand Down Expand Up @@ -1069,6 +1073,17 @@ export class PdfEvidenceViewer {
return this.#displayMode === "single" ? this.#elements.page : this.#elements.continuousPages;
}

async #commitZoom(surface: HTMLElement, generation: number): Promise<void> {
if (generation !== this.#pinchGeneration) return;
if (this.#displayMode === "single") {
await this.#renderPage();
return;
}
const anchor = this.#takeZoomAnchor();
this.#clearZoomPreview(surface);
if (await this.#rerenderFlow(generation)) this.#restoreZoomAnchor(surface, anchor);
}

#setZoomAnchor(clientX: number, clientY: number, surface: HTMLElement = this.#elements.page): void {
const anchor = pdfZoomAnchor(surface.getBoundingClientRect(), { x: clientX, y: clientY });
this.#zoomAnchor = anchor;
Expand Down Expand Up @@ -1178,12 +1193,13 @@ export class PdfEvidenceViewer {
this.#focusedAnnotationId = undefined;
this.#draftSelection = null;
this.#zoomAnchor = null;
window.clearTimeout(this.#wheelZoomRenderTimer);
this.#wheelZoomRenderTimer = undefined;
if (this.#displayMode !== "single") {
this.#continuousView.scrollToPage(next);
this.#presentContinuousPage(next);
} else await this.#renderPage();
} else {
this.#cancelPendingWheelZoom();
await this.#renderPage();
}
}

#scrollToPdfDestination(destination: readonly unknown[]): void {
Expand Down
4 changes: 2 additions & 2 deletions src/views/home-pdf-components.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ export function renderLibraryPdfRail(): string {
</button>
<p class="library-pdf-menu-heading">Display</p>
<div class="library-pdf-menu-stepper" role="group" aria-label="PDF zoom">
<button id="library-pdf-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">${renderIcon("zoomOut")}</button>
<button id="library-pdf-zoom-out" type="button" aria-label="Zoom out" title="Zoom out" data-action-menu-keep-open>${renderIcon("zoomOut")}</button>
<button id="library-pdf-fit-mode" type="button" aria-label="Change PDF fit mode" title="Fit width">${renderIcon("fit")}<span data-pdf-fit-label>Fit width</span></button>
<button id="library-pdf-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">${renderIcon("zoomIn")}</button>
<button id="library-pdf-zoom-in" type="button" aria-label="Zoom in" title="Zoom in" data-action-menu-keep-open>${renderIcon("zoomIn")}</button>
</div>
<button class="library-pdf-menu-action" id="library-pdf-rotate" type="button">${renderIcon("rotate")}<span>Rotate clockwise</span></button>
<button class="library-pdf-menu-action" id="library-pdf-spread" type="button" aria-pressed="false">${renderIcon("spread")}<span>Two-page view</span></button>
Expand Down
Loading