Skip to content

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

perf(viewer): stop the annotation layer rendering per-link hit boxes (#8233)

brios6d1574dc83a2
diff --git a/frontend/editor/src/core/components/viewer/LinkLayer.tsx b/frontend/editor/src/core/components/viewer/LinkLayer.tsx
index 4c8271f08e..0a2eba501b 100644
--- a/frontend/editor/src/core/components/viewer/LinkLayer.tsx
+++ b/frontend/editor/src/core/components/viewer/LinkLayer.tsx
@@ -200,11 +200,15 @@ LinkToolbar.displayName = "LinkToolbar";
interface LinkLayerProps {
documentId: string;
pageIndex: number;
+ /** While annotation editing is active, a click selects the link's
+ * annotation instead of following it. */
+ selectionActive?: boolean;
}
export const LinkLayer: React.FC<LinkLayerProps> = ({
documentId,
pageIndex,
+ selectionActive = false,
}) => {
const { t } = useTranslation();
const { provides: scroll } = useScroll(documentId);
@@ -479,6 +483,14 @@ export const LinkLayer: React.FC<LinkLayerProps> = ({
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
+ if (selectionActive) {
+ if (scope) {
+ scope.selectAnnotation(pageIndex, annotationLink.id);
+ }
+ setHoveredLinkId(null);
+ setToolbarPlacement(null);
+ return;
+ }
handleNavigate(annotationLink);
}}
onMouseDown={(e) => e.stopPropagation()}
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index 1094eb2e10..ddaf292100 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -53,6 +53,11 @@ import {
AnnotationPluginPackage,
} from "@embedpdf/plugin-annotation/react";
import type { AnnotationEvent } from "@embedpdf/plugin-annotation";
+import type { BoxedAnnotationRenderer } from "@embedpdf/plugin-annotation/react";
+import {
+ PdfAnnotationBorderStyle,
+ PdfAnnotationSubtype,
+} from "@embedpdf/models";
import type { PdfAnnotationObject, Rect } from "@embedpdf/models";
import { registerAnnotationTools } from "@app/components/viewer/annotationTools";
import {
@@ -121,6 +126,7 @@ import { ButtonAppearanceOverlay } from "@app/tools/formFill/ButtonAppearanceOve
import SignatureFieldOverlay from "@app/components/viewer/SignatureFieldOverlay";
import { CommentsSidebar } from "@app/components/viewer/CommentsSidebar";
import { CommentAuthorProvider } from "@app/contexts/CommentAuthorContext";
+import { useViewer } from "@app/contexts/ViewerContext";
import { accountService } from "@app/services/accountService";
interface LocalEmbedPDFProps {
@@ -197,6 +203,130 @@ function normalizePageRotation(rotation: number | null | undefined): number {
return ((Math.round(value) % 4) + 4) % 4;
}
+// LinkLayer owns link hit-testing, so this draws the underline or border and
+// nothing else: adding the built-in renderer's transparent rect back would
+// double every link's clickable overlay.
+function LinkStyling({
+ rect,
+ scale,
+ strokeColor = "#0000FF",
+ strokeWidth = 2,
+ strokeStyle = PdfAnnotationBorderStyle.UNDERLINE,
+ strokeDashArray,
+}: {
+ rect: Rect;
+ scale: number;
+ strokeColor?: string;
+ strokeWidth?: number;
+ strokeStyle?: PdfAnnotationBorderStyle;
+ strokeDashArray?: number[];
+}) {
+ const { width, height } = rect.size;
+ const svgWidth = width * scale;
+ const svgHeight = height * scale;
+ const dashArray =
+ strokeStyle === PdfAnnotationBorderStyle.DASHED
+ ? (strokeDashArray?.join(",") ?? `${strokeWidth * 3},${strokeWidth}`)
+ : undefined;
+ const isUnderline = strokeStyle === PdfAnnotationBorderStyle.UNDERLINE;
+ return (
+ // icon-lint-allow: runtime-generated-svg -- each link's box is measured from the annotation rect
+ <svg
+ style={{
+ position: "absolute",
+ width: svgWidth,
+ height: svgHeight,
+ pointerEvents: "none",
+ zIndex: 2,
+ }}
+ width={svgWidth}
+ height={svgHeight}
+ viewBox={`0 0 ${width} ${height}`}
+ >
+ {isUnderline ? (
+ <line
+ x1={1}
+ y1={height - 1}
+ x2={width - 1}
+ y2={height - 1}
+ stroke={strokeColor}
+ strokeWidth={strokeWidth}
+ strokeDasharray={dashArray}
+ style={{ pointerEvents: "none" }}
+ />
+ ) : (
+ <rect
+ x={strokeWidth / 2}
+ y={strokeWidth / 2}
+ width={Math.max(width - strokeWidth, 0)}
+ height={Math.max(height - strokeWidth, 0)}
+ fill="transparent"
+ stroke={strokeColor}
+ strokeWidth={strokeWidth}
+ strokeDasharray={dashArray}
+ style={{ pointerEvents: "none" }}
+ />
+ )}
+ </svg>
+ );
+}
+
+// Replaces the built-in link renderer, so every field it drops is a decision:
+// no selectOverride, because the default selects a threaded reply link itself
+// rather than its parent, and no renderLocked, because a locked link needs no
+// hit target of its own.
+const LINK_RENDERERS: BoxedAnnotationRenderer[] = [
+ {
+ id: "link",
+ matches: (annotation) => annotation.type === PdfAnnotationSubtype.LINK,
+ matchesPreview: (preview) => preview.type === PdfAnnotationSubtype.LINK,
+ render: ({ currentObject, scale }) => {
+ if (currentObject.type !== PdfAnnotationSubtype.LINK) return <></>;
+ const { rect, strokeColor, strokeWidth, strokeStyle, strokeDashArray } =
+ currentObject;
+ return (
+ <LinkStyling
+ rect={rect}
+ scale={scale}
+ strokeColor={strokeColor}
+ strokeWidth={strokeWidth}
+ strokeStyle={strokeStyle}
+ strokeDashArray={strokeDashArray}
+ />
+ );
+ },
+ renderPreview: ({ data, bounds, scale }) => {
+ // BoxedAnnotationRenderer erases the preview data type, so `data` arrives
+ // as unknown.
+ const { strokeWidth, strokeColor } = data as {
+ strokeWidth: number;
+ strokeColor: string;
+ };
+ return (
+ <div
+ style={{
+ position: "absolute",
+ left: 0,
+ top: 0,
+ width: bounds.size.width * scale,
+ height: bounds.size.height * scale,
+ borderBottom: `${strokeWidth * scale}px solid ${strokeColor}`,
+ backgroundColor: "rgba(0, 0, 255, 0.05)",
+ boxSizing: "border-box",
+ }}
+ />
+ );
+ },
+ interactionDefaults: {
+ isDraggable: true,
+ isResizable: true,
+ isRotatable: false,
+ },
+ useAppearanceStream: false,
+ hideSelectionMenu: (annotation) => !!annotation.inReplyToId,
+ },
+];
+
function ViewerPageContainer({
documentId,
pageIndex,
@@ -421,6 +551,7 @@ function AnnotationEditingLayers({
<AnnotationLayer
documentId={documentId}
pageIndex={pageIndex}
+ annotationRenderers={LINK_RENDERERS}
selectionOutline={{ color: "#007ACC" }}
selectionMenu={(props) => (
<AnnotationSelectionMenu
@@ -465,6 +596,7 @@ function PageLayers({
signatureOverlay,
readOnlySignaturePreviews,
}: PageGeometry & PageLayerOptions) {
+ const { isAnnotationMode } = useViewer();
return (
<>
<PageTiles
@@ -503,7 +635,11 @@ function PageLayers({
onAnnotationMenuAnchor={onAnnotationMenuAnchor}
/>
{/* LinkLayer: uses EmbedPDF annotation state for link rendering */}
- <LinkLayer documentId={documentId} pageIndex={pageIndex} />
+ <LinkLayer
+ documentId={documentId}
+ pageIndex={pageIndex}
+ selectionActive={isAnnotationMode}
+ />
{readOnlySignaturePreviews && (
<SignaturePreviewLayer
pageIndex={pageIndex}
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-link-annotations.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-link-annotations.spec.ts
new file mode 100644
index 0000000000..7b835014a7
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-link-annotations.spec.ts
@@ -0,0 +1,72 @@
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const LINK_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/link-annotations-sample.pdf",
+);
+const LINKS_PER_PAGE = 4;
+
+async function loadViewer(page: import("@playwright/test").Page) {
+ await page.goto("/editor");
+ await page.locator('input[type="file"]').first().setInputFiles(LINK_PDF);
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ await expect(firstPage.locator(".pdf-selection-layer")).toBeAttached({
+ timeout: 15_000,
+ });
+ return firstPage;
+}
+
+test("link annotations render as overlays with no annotation-layer hit boxes", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const firstPage = await loadViewer(page);
+
+ await expect(firstPage.locator(".pdf-link-overlay")).toHaveCount(
+ LINKS_PER_PAGE,
+ { timeout: 15_000 },
+ );
+
+ await expect(firstPage.locator("svg")).toHaveCount(LINKS_PER_PAGE);
+ await expect(firstPage.locator("svg rect:not([stroke])")).toHaveCount(0);
+});
+
+test("hovering a link overlay still opens the link toolbar", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const firstPage = await loadViewer(page);
+
+ const overlay = firstPage.locator(".pdf-link-overlay").first();
+ await expect(overlay).toBeAttached({ timeout: 15_000 });
+ await overlay.hover();
+
+ const toolbar = page.locator(".pdf-link-toolbar").first();
+ await expect(toolbar).toBeVisible({ timeout: 5_000 });
+ await expect(toolbar.locator(".pdf-link-toolbar-btn--delete")).toBeVisible();
+ await expect(toolbar.locator(".pdf-link-toolbar-btn--go")).toBeVisible();
+});
+
+test("annotation editing selects a link instead of navigating", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const popups: string[] = [];
+ page.on("popup", (popup) => popups.push(popup.url()));
+
+ await page.goto("/annotate");
+ await page.locator('input[type="file"]').first().setInputFiles(LINK_PDF);
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+
+ const overlay = firstPage.locator(".pdf-link-overlay").first();
+ await expect(overlay).toBeAttached({ timeout: 15_000 });
+ await overlay.click();
+
+ await expect(
+ page.locator("[data-annotation-selection-menu]").first(),
+ ).toBeVisible({ timeout: 10_000 });
+ expect(popups).toHaveLength(0);
+});
diff --git a/frontend/editor/src/core/tests/test-fixtures/generate-link-annotations-sample.mjs b/frontend/editor/src/core/tests/test-fixtures/generate-link-annotations-sample.mjs
new file mode 100644
index 0000000000..32af8c3665
--- /dev/null
+++ b/frontend/editor/src/core/tests/test-fixtures/generate-link-annotations-sample.mjs
@@ -0,0 +1,59 @@
+// One-off script: generate `link-annotations-sample.pdf`, two pages that carry
+// four borderless URI link annotations each. Borderless so the renderer takes
+// its underline branch, four per page so a page that grows or loses an overlay
+// is a count mismatch rather than a visual guess.
+//
+// Run with: node generate-link-annotations-sample.mjs
+import { PDFDocument, StandardFonts, PDFName } from "@cantoo/pdf-lib";
+import { writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const PAGES = 2;
+const LINKS_PER_PAGE = 4;
+
+async function main() {
+ const doc = await PDFDocument.create();
+ const font = await doc.embedFont(StandardFonts.Helvetica);
+
+ for (let pageIndex = 0; pageIndex < PAGES; pageIndex += 1) {
+ const page = doc.addPage([595, 842]);
+ page.drawText(`Link fixture page ${pageIndex + 1} of ${PAGES}`, {
+ x: 40,
+ y: 800,
+ size: 14,
+ font,
+ });
+
+ const annots = [];
+ for (let link = 0; link < LINKS_PER_PAGE; link += 1) {
+ const y = 740 - link * 60;
+ page.drawText(`Link ${link + 1}`, {
+ x: 40,
+ y: y + 16,
+ size: 11,
+ font,
+ });
+ const annot = doc.context.obj({
+ Type: "Annot",
+ Subtype: "Link",
+ Rect: [40, y, 240, y + 14],
+ Border: [0, 0, 0],
+ A: {
+ Type: "Action",
+ S: "URI",
+ URI: `https://example.com/page/${pageIndex + 1}/link/${link + 1}`,
+ },
+ });
+ annots.push(doc.context.register(annot));
+ }
+ page.node.set(PDFName.of("Annots"), doc.context.obj(annots));
+ }
+
+ const bytes = await doc.save();
+ writeFileSync(join(__dirname, "link-annotations-sample.pdf"), bytes);
+ console.log(`wrote link-annotations-sample.pdf (${bytes.length} B)`);
+}
+
+await main();
diff --git a/frontend/editor/src/core/tests/test-fixtures/link-annotations-sample.pdf b/frontend/editor/src/core/tests/test-fixtures/link-annotations-sample.pdf
new file mode 100644
index 0000000000..59509fcf5b
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/link-annotations-sample.pdf differ