Skip to content

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

fix(viewer): wire Ctrl+A to select all text in the PDF (#6517)

Anthony Stirlingc3795c1a3ca1
diff --git a/.gitleaksignore b/.gitleaksignore
index cf676687ec..43f9db5957 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -1,4 +1,4 @@
-# PostHog project-level key — phc_ prefix keys are public/client-side by design
+# PostHog project-level key - phc_ prefix keys are public/client-side by design
# (PostHog client-side tracking embeds them in the browser bundle). Committed
# intentionally in #6150 so engine/.env has a working default, with real
# credentials overridden via engine/.env.local.
@@ -12,6 +12,10 @@ app/proprietary/src/test/java/stirling/software/proprietary/mcp/security/McpApiK
testing/compose/docker-compose-keycloak-mcp.yml:generic-api-key:25
testing/compose/validate-mcp-apikey.sh:curl-auth-header:73
testing/compose/validate-mcp-test.sh:curl-auth-header:92
+testing/compose/validate-mcp-test.sh:curl-auth-header:116
+
+# Storybook example showing curl with a fake Bearer token placeholder (sk_live_a3f8...).
+frontend/shared/components/CodeBlock.stories.tsx:curl-auth-header:4
# Truncated placeholder API key in portal docs example (sk_live_8f2c...e10) - not a real secret.
frontend/portal/src/components/docs/GettingStartedSection.tsx:generic-api-key:31
diff --git a/frontend/editor/public/locales/en-GB/translation.toml b/frontend/editor/public/locales/en-GB/translation.toml
index 607dfa4e5d..4b81665480 100644
--- a/frontend/editor/public/locales/en-GB/translation.toml
+++ b/frontend/editor/public/locales/en-GB/translation.toml
@@ -7917,6 +7917,7 @@ valid = "Valid"
[viewer]
cannotPreviewFile = "Cannot Preview File"
+copyText = "Copy"
disableColorFilter = "Disable Colour Filter"
dualPageView = "Dual Page View"
enableDarkFilter = "Enable Dark Filter"
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 5133ff6ce6..46dd123b3f 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7890,6 +7890,7 @@ valid = "Valid"
[viewer]
cannotPreviewFile = "Cannot Preview File"
+copyText = "Copy"
disableColorFilter = "Disable Color Filter"
dualPageView = "Dual Page View"
enableDarkFilter = "Enable Dark Filter"
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index 75b893cb38..0d2a78dee8 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -173,6 +173,7 @@ const EmbedPdfViewerContent = ({
isAnnotationsVisible,
exportActions,
printActions,
+ selectionActions,
setApplyChanges,
applyChanges: viewerApplyChanges,
pdfRenderMode,
@@ -442,6 +443,17 @@ const EmbedPdfViewerContent = ({
event.preventDefault();
printActions.print();
return;
+ case "a":
+ case "A":
+ // Intercept unconditionally so the browser can't blanket-select the surrounding UI chrome.
+ event.preventDefault();
+ {
+ const totalPages = getScrollState().totalPages;
+ if (totalPages > 0) {
+ void selectionActions.selectAll(totalPages);
+ }
+ }
+ return;
case "=":
case "+":
event.preventDefault();
@@ -469,11 +481,6 @@ const EmbedPdfViewerContent = ({
// Modifier key shortcuts (Ctrl/Cmd + key)
if (mod) {
switch (event.key) {
- case "a":
- case "A":
- // Ctrl+A: Prevent browser from selecting all UI text
- event.preventDefault();
- return;
case "f":
case "F":
event.preventDefault();
@@ -558,6 +565,8 @@ const EmbedPdfViewerContent = ({
viewerApplyChanges,
cyclePdfRenderMode,
viewerKeyCommand,
+ selectionActions,
+ getScrollState,
]);
// Watch the annotation history API to detect when the document becomes "dirty".
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index 66af74fb67..d9dedb4005 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -81,6 +81,7 @@ import { LinkLayer } from "@app/components/viewer/LinkLayer";
import { TextSelectionHandler } from "@app/components/viewer/TextSelectionHandler";
import { RedactionSelectionMenu } from "@app/components/viewer/RedactionSelectionMenu";
import { AnnotationSelectionMenu } from "@app/components/viewer/AnnotationSelectionMenu";
+import { TextSelectionMenu } from "@app/components/viewer/TextSelectionMenu";
import {
RedactionPendingTracker,
RedactionPendingTrackerAPI,
@@ -995,6 +996,9 @@ export function LocalEmbedPDF({
documentId={documentId}
pageIndex={pageIndex}
background="var(--pdf-selection-bg)"
+ selectionMenu={(props) => (
+ <TextSelectionMenu {...props} />
+ )}
/>
</div>
<TextSelectionHandler
diff --git a/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx
index ced28e3417..36d0c59cf7 100644
--- a/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/SelectionAPIBridge.tsx
@@ -1,15 +1,27 @@
import { useEffect, useRef } from "react";
-import { useSelectionCapability } from "@embedpdf/plugin-selection/react";
+import {
+ useSelectionCapability,
+ useSelectionPlugin,
+ glyphAt,
+} from "@embedpdf/plugin-selection/react";
+import { useDocumentState } from "@embedpdf/core/react";
import { useViewer } from "@app/contexts/ViewerContext";
import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";
+import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
/**
* Connects the PDF selection plugin to the shared ViewerContext.
*/
export function SelectionAPIBridge() {
const { provides: selection } = useSelectionCapability();
+ const { plugin: selectionPlugin } = useSelectionPlugin();
const { registerBridge } = useViewer();
const documentReady = useDocumentReady();
+ const activeDocumentId = useActiveDocumentId();
+ const documentState = useDocumentState(activeDocumentId ?? "");
+ const scaleRef = useRef(1);
+ scaleRef.current =
+ (documentState as { scale?: number } | undefined)?.scale ?? 1;
const hasSelectionRef = useRef(false);
const selectedTextRef = useRef("");
@@ -17,10 +29,107 @@ export function SelectionAPIBridge() {
useEffect(() => {
if (!selection || !documentReady) return;
+ // begin/update/end + getOrLoadGeometry are runtime-public but typed private;
+ // matches the TextSelectionHandler word/line cast.
+ type SelectionPluginInternals = {
+ clearSelection: (id: string) => void;
+ beginSelection: (id: string, page: number, glyph: number) => void;
+ updateSelection: (id: string, page: number, glyph: number) => void;
+ endSelection: (id: string) => void;
+ getOrLoadGeometry: (
+ id: string,
+ pageIdx: number,
+ ) => { toPromise: () => Promise<unknown> };
+ };
+
+ const lastGlyphOnPage = (geo: {
+ runs: { charStart: number; glyphs: unknown[] }[];
+ }): number => {
+ let last = 0;
+ for (const run of geo.runs) {
+ const end = run.charStart + run.glyphs.length - 1;
+ if (end > last) last = end;
+ }
+ return last;
+ };
+
+ const selectAllInDocument = async (
+ documentId: string,
+ totalPages: number,
+ ) => {
+ const plugin = selectionPlugin as unknown as SelectionPluginInternals;
+ if (totalPages <= 0) return false;
+
+ // Pre-load geometry for every page so updateRectsAndSlices has data to
+ // emit rects for, and getSelectedText has slices for, every page.
+ try {
+ await Promise.all(
+ Array.from({ length: totalPages }, (_, p) =>
+ plugin.getOrLoadGeometry(documentId, p).toPromise(),
+ ),
+ );
+ } catch {
+ // Continue with whatever geometry did load
+ }
+
+ const state = selection.getState(documentId);
+ let firstPage = -1;
+ let lastPage = -1;
+ let lastGlyph = 0;
+ for (let p = 0; p < totalPages; p++) {
+ const geo = state.geometry[p];
+ if (!geo || geo.runs.length === 0) continue;
+ if (firstPage === -1) firstPage = p;
+ lastPage = p;
+ lastGlyph = lastGlyphOnPage(geo);
+ }
+
+ if (firstPage === -1 || lastPage === -1) return false;
+
+ plugin.clearSelection(documentId);
+ plugin.beginSelection(documentId, firstPage, 0);
+ plugin.updateSelection(documentId, lastPage, lastGlyph);
+ plugin.endSelection(documentId);
+ return true;
+ };
+
+ const selectWordAt = (
+ documentId: string,
+ pageIndex: number,
+ x: number,
+ y: number,
+ ) => {
+ const plugin = selectionPlugin as unknown as {
+ selectWord: (
+ id: string,
+ page: number,
+ glyph: number,
+ modeId: string,
+ ) => void;
+ };
+ const state = selection.getState(documentId);
+ const geo = state.geometry[pageIndex];
+ if (!geo) return false;
+ const g = glyphAt(geo, { x, y }, 3);
+ if (g === -1) return false;
+ plugin.selectWord(documentId, pageIndex, g, "pointerMode");
+ return true;
+ };
+
const buildApi = () => ({
copyToClipboard: () => selection.copyToClipboard(),
getSelectedText: () => selection.getSelectedText(),
getFormattedSelection: () => selection.getFormattedSelection(),
+ selectAll: async (totalPages: number) => {
+ const docId = activeDocumentId;
+ if (!docId || !selectionPlugin) return false;
+ return selectAllInDocument(docId, totalPages);
+ },
+ selectWordAt: (pageIndex: number, x: number, y: number) => {
+ const docId = activeDocumentId;
+ if (!docId || !selectionPlugin) return false;
+ return selectWordAt(docId, pageIndex, x, y);
+ },
});
registerBridge("selection", {
@@ -83,17 +192,47 @@ export function SelectionAPIBridge() {
}
};
+ // Right-click anywhere inside a PDF page: suppress the browser's "Copy
+ // image" menu, and if nothing is currently selected, auto-select the
+ // word under the cursor so the floating Copy menu appears in place.
+ const handleContextMenu = (event: MouseEvent) => {
+ let el = event.target as HTMLElement | null;
+ while (el && !el.dataset?.pageIndex) {
+ el = el.parentElement;
+ }
+ if (!el) return;
+ event.preventDefault();
+ if (hasSelectionRef.current) return;
+ const docId = activeDocumentId;
+ if (!docId || !selectionPlugin) return;
+ const pageIndex = Number(el.dataset.pageIndex);
+ if (Number.isNaN(pageIndex)) return;
+ const rect = el.getBoundingClientRect();
+ const scale = scaleRef.current || 1;
+ const x = (event.clientX - rect.left) / scale;
+ const y = (event.clientY - rect.top) / scale;
+ selectWordAt(docId, pageIndex, x, y);
+ };
+
document.addEventListener("copy", handleCopy);
document.addEventListener("keydown", handleKeyDown);
+ document.addEventListener("contextmenu", handleContextMenu);
return () => {
unsubChange?.();
unsubCopy?.();
document.removeEventListener("copy", handleCopy);
document.removeEventListener("keydown", handleKeyDown);
+ document.removeEventListener("contextmenu", handleContextMenu);
registerBridge("selection", null);
};
- }, [selection, documentReady, registerBridge]);
+ }, [
+ selection,
+ selectionPlugin,
+ activeDocumentId,
+ documentReady,
+ registerBridge,
+ ]);
return null;
}
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
new file mode 100644
index 0000000000..af3399e38d
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
@@ -0,0 +1,99 @@
+import { ActionIcon, Tooltip } from "@mantine/core";
+import ContentCopyIcon from "@mui/icons-material/ContentCopy";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import type { SelectionSelectionMenuProps } from "@embedpdf/plugin-selection/react";
+import { useSelectionCapability } from "@embedpdf/plugin-selection/react";
+
+export function TextSelectionMenu({
+ selected,
+ menuWrapperProps,
+ placement,
+}: SelectionSelectionMenuProps) {
+ const { t } = useTranslation();
+ const { provides: selection } = useSelectionCapability();
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const [position, setPosition] = useState<{
+ top: number;
+ left: number;
+ } | null>(null);
+
+ const setRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ wrapperRef.current = node;
+ menuWrapperProps?.ref?.(node);
+ },
+ [menuWrapperProps],
+ );
+
+ const showAbove = placement?.suggestTop ?? true;
+
+ useEffect(() => {
+ if (!selected || !wrapperRef.current) {
+ setPosition(null);
+ return;
+ }
+ const update = () => {
+ const wrapper = wrapperRef.current;
+ if (!wrapper) return;
+ const r = wrapper.getBoundingClientRect();
+ setPosition({
+ top: showAbove ? r.top - 8 : r.bottom + 8,
+ left: r.left + r.width / 2,
+ });
+ };
+ update();
+ window.addEventListener("scroll", update, true);
+ window.addEventListener("resize", update);
+ return () => {
+ window.removeEventListener("scroll", update, true);
+ window.removeEventListener("resize", update);
+ };
+ }, [selected, showAbove]);
+
+ const handleCopy = useCallback(() => {
+ selection?.copyToClipboard();
+ }, [selection]);
+
+ const portalContent =
+ position &&
+ createPortal(
+ <div
+ style={{
+ position: "fixed",
+ top: position.top,
+ left: position.left,
+ transform: `translate(-50%, ${showAbove ? "-100%" : "0"})`,
+ zIndex: 10000,
+ pointerEvents: "auto",
+ }}
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ <Tooltip label={t("viewer.copyText", "Copy")} withArrow>
+ <ActionIcon
+ variant="filled"
+ size="md"
+ onClick={handleCopy}
+ aria-label={t("viewer.copyText", "Copy")}
+ style={{
+ backgroundColor: "var(--mantine-color-body)",
+ border: "1px solid var(--mantine-color-default-border)",
+ color: "var(--text-primary)",
+ boxShadow: "0 2px 12px rgba(0, 0, 0, 0.25)",
+ }}
+ >
+ <ContentCopyIcon style={{ fontSize: 18 }} />
+ </ActionIcon>
+ </Tooltip>
+ </div>,
+ document.body,
+ );
+
+ return (
+ <>
+ <div ref={setRef} style={menuWrapperProps?.style} />
+ {portalContent}
+ </>
+ );
+}
diff --git a/frontend/editor/src/core/contexts/viewer/viewerActions.ts b/frontend/editor/src/core/contexts/viewer/viewerActions.ts
index 04e9dbce33..2e0231d766 100644
--- a/frontend/editor/src/core/contexts/viewer/viewerActions.ts
+++ b/frontend/editor/src/core/contexts/viewer/viewerActions.ts
@@ -33,6 +33,8 @@ export interface SelectionActions {
copyToClipboard: () => void;
getSelectedText: () => string;
getFormattedSelection: () => any;
+ selectAll: (totalPages: number) => Promise<boolean>;
+ selectWordAt: (pageIndex: number, x: number, y: number) => boolean;
}
export interface SpreadActions {
@@ -269,6 +271,20 @@ export function createViewerActions({
}
return null;
},
+ selectAll: async (totalPages: number) => {
+ const api = registry.current.selection?.api;
+ if (api?.selectAll) {
+ return api.selectAll(totalPages);
+ }
+ return false;
+ },
+ selectWordAt: (pageIndex: number, x: number, y: number) => {
+ const api = registry.current.selection?.api;
+ if (api?.selectWordAt) {
+ return api.selectWordAt(pageIndex, x, y);
+ }
+ return false;
+ },
};
const spreadActions: SpreadActions = {
diff --git a/frontend/editor/src/core/contexts/viewer/viewerBridges.ts b/frontend/editor/src/core/contexts/viewer/viewerBridges.ts
index 85739cccfd..c003013cb3 100644
--- a/frontend/editor/src/core/contexts/viewer/viewerBridges.ts
+++ b/frontend/editor/src/core/contexts/viewer/viewerBridges.ts
@@ -60,6 +60,8 @@ export interface SelectionAPIWrapper {
copyToClipboard: () => void;
getSelectedText: () => string | any;
getFormattedSelection: () => any;
+ selectAll: (totalPages: number) => Promise<boolean>;
+ selectWordAt: (pageIndex: number, x: number, y: number) => boolean;
}
export interface SpreadAPIWrapper {
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-text-selection.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-text-selection.spec.ts
new file mode 100644
index 0000000000..573789aca3
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-text-selection.spec.ts
@@ -0,0 +1,329 @@
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const FIXTURES_DIR = path.join(__dirname, "../test-fixtures");
+const SAMPLE_PDF = path.join(FIXTURES_DIR, "sample.pdf");
+const MULTIPAGE_PDF = path.join(FIXTURES_DIR, "annotations_out_of_order.pdf");
+
+async function loadSampleAndOpenViewer(page: import("@playwright/test").Page) {
+ await page.locator('input[type="file"]').first().setInputFiles(SAMPLE_PDF);
+
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+
+ const selectionLayer = firstPage.locator(".pdf-selection-layer");
+ await expect(selectionLayer).toBeAttached({ timeout: 15_000 });
+
+ // Geometry must be loaded before hit-testing.
+ await page.waitForTimeout(2_000);
+
+ return firstPage;
+}
+
+async function dragSelectAcrossPage(
+ page: import("@playwright/test").Page,
+ firstPage: import("@playwright/test").Locator,
+) {
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Page wrapper has no bounding box");
+
+ const y = box.y + box.height * 0.18;
+ await page.mouse.move(box.x + box.width * 0.15, y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * 0.6, y, { steps: 15 });
+ await page.mouse.up();
+}
+
+test("drag-selecting text in the viewer produces selection rects", async ({
+ page,
+}) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+ await dragSelectAcrossPage(page, firstPage);
+
+ const selectionRects = firstPage.locator(
+ ".pdf-selection-layer > div:first-child > div",
+ );
+ await expect(selectionRects.first()).toBeAttached({ timeout: 5_000 });
+ expect(await selectionRects.count()).toBeGreaterThan(0);
+});
+
+test("double-clicking a word produces a word-sized selection", async ({
+ page,
+}) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Page wrapper has no bounding box");
+
+ // sample.pdf has "Test document for word documents" at ~11% from top.
+ await page.mouse.dblclick(
+ box.x + box.width * 0.21,
+ box.y + box.height * 0.105,
+ );
+ await page.waitForTimeout(500);
+
+ const selectionRects = firstPage.locator(
+ ".pdf-selection-layer > div:first-child > div",
+ );
+ await expect(selectionRects.first()).toBeAttached({ timeout: 5_000 });
+});
+
+test("hovering over text changes the cursor to an I-beam", async ({ page }) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Page wrapper has no bounding box");
+
+ const targetX = box.x + box.width * 0.21;
+ const targetY = box.y + box.height * 0.105;
+ // Two-hop move so pointermove fires.
+ await page.mouse.move(box.x + 5, box.y + 5);
+ await page.waitForTimeout(100);
+ await page.mouse.move(targetX, targetY, { steps: 5 });
+ await page.waitForTimeout(500);
+
+ const cursor = await firstPage.evaluate((el) => {
+ const parent = (el as HTMLElement).parentElement;
+ return parent ? getComputedStyle(parent).cursor : "no-parent";
+ });
+
+ expect(cursor).toMatch(/^(text|vertical-text)$/);
+});
+
+test("Ctrl+C copies selected text to the clipboard", async ({
+ page,
+ context,
+}) => {
+ test.setTimeout(60_000);
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ const firstPage = await loadSampleAndOpenViewer(page);
+ await dragSelectAcrossPage(page, firstPage);
+ await page.waitForTimeout(500);
+
+ await page.keyboard.press("Control+C");
+ await page.waitForTimeout(500);
+
+ const clipboardText = await page.evaluate(() =>
+ navigator.clipboard.readText(),
+ );
+ expect(clipboardText.trim().length).toBeGreaterThan(0);
+});
+
+test("right-click on a word auto-selects it and reveals the Copy menu", async ({
+ page,
+}) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("no box");
+
+ // Right-click on a word in the top paragraph "Test document for word documents".
+ await page.mouse.click(box.x + box.width * 0.21, box.y + box.height * 0.105, {
+ button: "right",
+ });
+ await page.waitForTimeout(400);
+
+ const selectionRects = firstPage.locator(
+ ".pdf-selection-layer > div:first-child > div",
+ );
+ await expect(selectionRects.first()).toBeAttached({ timeout: 5_000 });
+
+ const copyButton = page.getByRole("button", { name: "Copy" }).first();
+ await expect(copyButton).toBeVisible({ timeout: 5_000 });
+});
+
+test("right-click on the page does not surface the browser context menu", async ({
+ page,
+}) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("no box");
+
+ // Track whether the browser would have opened a context menu (defaultPrevented stays false).
+ const prevented = await page.evaluate(
+ ([x, y]) =>
+ new Promise<boolean>((resolve) => {
+ const target = document.elementFromPoint(x, y);
+ if (!target) {
+ resolve(false);
+ return;
+ }
+ const evt = new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ clientX: x,
+ clientY: y,
+ });
+ target.dispatchEvent(evt);
+ resolve(evt.defaultPrevented);
+ }),
+ [box.x + box.width * 0.21, box.y + box.height * 0.105],
+ );
+ expect(prevented).toBe(true);
+});
+
+test("floating Copy menu appears after drag-select and copies", async ({
+ page,
+ context,
+}) => {
+ test.setTimeout(60_000);
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ const firstPage = await loadSampleAndOpenViewer(page);
+ await dragSelectAcrossPage(page, firstPage);
+ await page.waitForTimeout(500);
+
+ const copyButton = page.getByRole("button", { name: "Copy" }).first();
+ await expect(copyButton).toBeVisible({ timeout: 5_000 });
+
+ await copyButton.click();
+ await page.waitForTimeout(300);
+
+ const clipboardText = await page.evaluate(() =>
+ navigator.clipboard.readText(),
+ );
+ expect(clipboardText.trim().length).toBeGreaterThan(0);
+});
+
+test("selection highlight is actually rendered on screen", async ({ page }) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("no box");
+
+ const y = box.y + box.height * 0.105;
+ await page.mouse.move(box.x + box.width * 0.13, y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * 0.45, y, { steps: 15 });
+ await page.mouse.up();
+ await page.waitForTimeout(300);
+
+ const selectionWrapper = firstPage.locator(
+ ".pdf-selection-layer > div:first-child",
+ );
+ await expect(selectionWrapper).toBeAttached();
+
+ const rect = firstPage
+ .locator(".pdf-selection-layer > div:first-child > div")
+ .first();
+ await expect(rect).toBeAttached();
+ const dims = await rect.evaluate((el) => {
+ const r = (el as HTMLElement).getBoundingClientRect();
+ const cs = getComputedStyle(el as HTMLElement);
+ return { w: r.width, h: r.height, bg: cs.backgroundColor };
+ });
+ expect(dims.w).toBeGreaterThan(2);
+ expect(dims.h).toBeGreaterThan(2);
+ expect(dims.bg).not.toBe("rgba(0, 0, 0, 0)");
+});
+
+test("Ctrl+A selects all text in the document", async ({ page }) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("no box");
+ await page.mouse.move(0, 0);
+ await page.waitForTimeout(50);
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.waitForTimeout(300);
+
+ await page.keyboard.press("Control+A");
+ await page.waitForTimeout(500);
+
+ const selectionRects = firstPage.locator(
+ ".pdf-selection-layer > div:first-child > div",
+ );
+ await expect(selectionRects.first()).toBeAttached({ timeout: 5_000 });
+ expect(await selectionRects.count()).toBeGreaterThan(0);
+});
+
+test("Ctrl+A selects text on every page of a multi-page document", async ({
+ page,
+}) => {
+ test.setTimeout(60_000);
+ await page.locator('input[type="file"]').first().setInputFiles(MULTIPAGE_PDF);
+
+ // Wait until all 3 pages have rendered (the viewer pulls them in as the
+ // scroll plugin reports them).
+ const pageWrappers = page.locator("[data-page-index]");
+ await expect.poll(() => pageWrappers.count(), { timeout: 30_000 }).toBe(3);
+ // Geometry must be loaded before begin/update/end can produce rects.
+ await page.waitForTimeout(2_000);
+
+ await page.keyboard.press("Control+A");
+
+ // After Ctrl+A, at least two pages should carry selection rects. That's
+ // the multi-page invariant: single-page select-all would only ever paint
+ // the page currently in view.
+ await expect
+ .poll(
+ async () =>
+ await page.evaluate(() => {
+ const wrappers = Array.from(
+ document.querySelectorAll<HTMLElement>("[data-page-index]"),
+ );
+ return wrappers.filter(
+ (w) =>
+ w.querySelectorAll(".pdf-selection-layer > div:first-child > div")
+ .length > 0,
+ ).length;
+ }),
+ { timeout: 10_000 },
+ )
+ .toBeGreaterThanOrEqual(2);
+});
+
+test("Ctrl+A works without first hovering the viewer", async ({ page }) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+
+ // Park cursor far from the viewer so isViewerHovered is false.
+ await page.mouse.move(0, 0);
+ await page.waitForTimeout(200);
+
+ await page.keyboard.press("Control+A");
+ await page.waitForTimeout(500);
+
+ const selectionRects = firstPage.locator(
+ ".pdf-selection-layer > div:first-child > div",
+ );
+ await expect(selectionRects.first()).toBeAttached({ timeout: 5_000 });
+ expect(await selectionRects.count()).toBeGreaterThan(0);
+
+ // Browser must not have ranged the surrounding UI chrome.
+ const nativeSelectionLength = await page.evaluate(() => {
+ const sel = window.getSelection();
+ return sel ? sel.toString().length : 0;
+ });
+ expect(nativeSelectionLength).toBe(0);
+});
+
+test("text selection still works after toggling the pan tool off again", async ({
+ page,
+}) => {
+ test.setTimeout(60_000);
+ const firstPage = await loadSampleAndOpenViewer(page);
+
+ // Toggling pan on then off should return the active mode to pointerMode.
+ const panButton = page
+ .locator('[aria-label="Pan"], [aria-label*="and tool" i]')
+ .first();
+ if (await panButton.count()) {
+ await panButton.click();
+ await page.waitForTimeout(200);
+ await panButton.click();
+ await page.waitForTimeout(200);
+ }
+
+ await dragSelectAcrossPage(page, firstPage);
+
+ const selectionRects = firstPage.locator(
+ ".pdf-selection-layer > div:first-child > div",
+ );
+ await expect(selectionRects.first()).toBeAttached({ timeout: 5_000 });
+});