Skip to content

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

refactor: replace ActionIcon with native buttons, enable auto-save state for comment operations, and implement text selection menu. (#7661)

briosd6784b3962c1
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 2ca4a93a1d..358b1422d2 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -1876,6 +1876,7 @@ comment = "Comment"
comments = "Comments"
contents = "Text"
delete = "Delete"
+deleted = "Annotation deleted"
drawing = "Drawing"
editSelectDescription = "Click an existing annotation to edit its color, opacity, text, or size."
editText = "Edit"
@@ -1917,6 +1918,7 @@ textAlignment = "Text Alignment"
textMarkup = "Text Markup"
title = "Annotate"
underline = "Underline"
+undoDelete = "Undo"
width = "Width"
[app]
@@ -12550,6 +12552,7 @@ validUntrusted = "Valid, signer not verified"
cannotPreviewFile = "Cannot Preview File"
copyText = "Copy"
disableColorFilter = "Disable Color Filter"
+documentUpdated = "Document updated"
dualPageView = "Dual Page View"
enableDarkFilter = "Enable Dark Filter"
enableSepiaFilter = "Enable Sepia Filter"
diff --git a/frontend/editor/src/core/components/annotation/shared/ColorControl.tsx b/frontend/editor/src/core/components/annotation/shared/ColorControl.tsx
index 7cced260cd..21fb153443 100644
--- a/frontend/editor/src/core/components/annotation/shared/ColorControl.tsx
+++ b/frontend/editor/src/core/components/annotation/shared/ColorControl.tsx
@@ -64,17 +64,16 @@ export function ColorControl({
withinPortal
>
<Popover.Target>
- <Tooltip label={label}>
- <ActionIcon
- aria-label={label}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={label} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={() => setOpened(!opened)}
disabled={disabled}
+ aria-label={label}
>
<ColorSwatch color={localColor} size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
</Popover.Target>
<Popover.Dropdown>
diff --git a/frontend/editor/src/core/components/annotation/shared/OpacityControl.tsx b/frontend/editor/src/core/components/annotation/shared/OpacityControl.tsx
index dc710751f1..fb2fe032f3 100644
--- a/frontend/editor/src/core/components/annotation/shared/OpacityControl.tsx
+++ b/frontend/editor/src/core/components/annotation/shared/OpacityControl.tsx
@@ -2,7 +2,6 @@ import { Tooltip, Popover, Stack, Slider, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useState } from "react";
import { Icon } from "@app/ui/Icon";
-import { ActionIcon } from "@app/ui/ActionIcon";
interface OpacityControlProps {
value: number; // 0-100
@@ -21,17 +20,16 @@ export function OpacityControl({
return (
<Popover opened={opened} onChange={setOpened} position="top" withArrow>
<Popover.Target>
- <Tooltip label={t("annotation.opacity", "Opacity")}>
- <ActionIcon
- aria-label={t("annotation.opacity", "Opacity")}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={t("annotation.opacity", "Opacity")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={() => setOpened(!opened)}
disabled={disabled}
+ aria-label={t("annotation.opacity", "Opacity")}
>
<Icon name="droplet" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
</Popover.Target>
<Popover.Dropdown>
diff --git a/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx b/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx
index ead203adc1..3d8b0c3114 100644
--- a/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx
+++ b/frontend/editor/src/core/components/annotation/shared/PropertiesPopover.tsx
@@ -191,17 +191,16 @@ export function PropertiesPopover({
return (
<Popover opened={opened} onChange={setOpened} position="bottom" withArrow>
<Popover.Target>
- <Tooltip label={t("annotation.properties", "Properties")}>
- <ActionIcon
- aria-label={t("annotation.properties", "Properties")}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={t("annotation.properties", "Properties")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={() => setOpened(!opened)}
disabled={disabled}
+ aria-label={t("annotation.properties", "Properties")}
>
<Icon name="sliders-horizontal" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
</Popover.Target>
<Popover.Dropdown>
diff --git a/frontend/editor/src/core/components/annotation/shared/WidthControl.tsx b/frontend/editor/src/core/components/annotation/shared/WidthControl.tsx
index c860c2fda8..83840f1adc 100644
--- a/frontend/editor/src/core/components/annotation/shared/WidthControl.tsx
+++ b/frontend/editor/src/core/components/annotation/shared/WidthControl.tsx
@@ -2,7 +2,6 @@ import { Tooltip, Popover, Stack, Slider, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useState } from "react";
import { Icon } from "@app/ui/Icon";
-import { ActionIcon } from "@app/ui/ActionIcon";
interface WidthControlProps {
value: number;
@@ -25,17 +24,16 @@ export function WidthControl({
return (
<Popover opened={opened} onChange={setOpened} position="top" withArrow>
<Popover.Target>
- <Tooltip label={t("annotation.width", "Width")}>
- <ActionIcon
- aria-label={t("annotation.width", "Width")}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={t("annotation.width", "Width")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={() => setOpened(!opened)}
disabled={disabled}
+ aria-label={t("annotation.width", "Width")}
>
<Icon name="line-weight" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
</Popover.Target>
<Popover.Dropdown>
diff --git a/frontend/editor/src/core/components/shared/ViewerInlineControls.tsx b/frontend/editor/src/core/components/shared/ViewerInlineControls.tsx
index 29eb4d1419..16f9c3a4ba 100644
--- a/frontend/editor/src/core/components/shared/ViewerInlineControls.tsx
+++ b/frontend/editor/src/core/components/shared/ViewerInlineControls.tsx
@@ -13,17 +13,25 @@ export function ViewerInlineControls() {
const { workbench } = useNavigationState();
const viewer = useViewer();
- const [zoomPercent, setZoomPercent] = useState(100);
+ const [zoomPercent, setZoomPercent] = useState(
+ () => viewer.getZoomState().zoomPercent || 100,
+ );
useEffect(() => {
const zoomState = viewer.getZoomState();
setZoomPercent(zoomState.zoomPercent || 100);
const unregister = viewer.registerImmediateZoomUpdate((pct) => {
+ // A carried zoom's fit pass is intermediate; its settled tick re-syncs.
+ if (viewer.zoomRestorePendingRef.current) return;
setZoomPercent(pct);
});
return () => unregister?.();
- }, [viewer.registerImmediateZoomUpdate]);
+ }, [
+ viewer.registerImmediateZoomUpdate,
+ viewer.zoomRestorePendingRef,
+ viewer.zoomRestoreSettledTick,
+ ]);
if (workbench !== "viewer") return null;
diff --git a/frontend/editor/src/core/components/tools/redact/ManualRedactionControls.tsx b/frontend/editor/src/core/components/tools/redact/ManualRedactionControls.tsx
index 6b053065bc..39e2c87e69 100644
--- a/frontend/editor/src/core/components/tools/redact/ManualRedactionControls.tsx
+++ b/frontend/editor/src/core/components/tools/redact/ManualRedactionControls.tsx
@@ -44,7 +44,8 @@ export default function ManualRedactionControls({
const { signatureApiRef } = useSignature();
// Check if user is navigating away (modal shown) — don't fight the save/leave process
- const { showNavigationWarning } = useNavigationGuard();
+ const { showNavigationWarning, hasUnsavedChanges: navHasUnsavedChanges } =
+ useNavigationGuard();
const isLeavingRef = useRef(false);
const prevFileIndexRef = useRef(activeFileIndex);
@@ -134,8 +135,9 @@ export default function ManualRedactionControls({
}
}, [applyChanges]);
- // Check if there are unsaved changes to save (pending redactions OR applied redactions)
- const hasUnsavedChanges = pendingCount > 0 || redactionsApplied;
+ // Check if there are unsaved changes to save (pending redactions OR applied redactions OR unsaved changes)
+ const hasUnsavedChanges =
+ pendingCount > 0 || redactionsApplied || navHasUnsavedChanges;
const isApiReady = isBridgeReady;
diff --git a/frontend/editor/src/core/components/viewer/AnnotationAPIBridge.tsx b/frontend/editor/src/core/components/viewer/AnnotationAPIBridge.tsx
index 762d7584e0..e09647fda5 100644
--- a/frontend/editor/src/core/components/viewer/AnnotationAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/AnnotationAPIBridge.tsx
@@ -13,6 +13,7 @@ import type {
ClearDocumentAnnotationsResult,
} from "@app/components/viewer/viewerTypes";
import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";
+import { MARKUP_ANNOTATION_COLORS } from "@app/components/viewer/annotationDefaults";
type NoteIcon = NonNullable<AnnotationToolOptions["icon"]>;
@@ -154,10 +155,7 @@ const NOTE_ICON_MAP: Record<NoteIcon, PdfAnnotationIcon> = {
};
const DEFAULTS = {
- highlight: "#ffd54f",
- underline: "#ffb300",
- strikeout: "#e53935",
- squiggly: "#00acc1",
+ ...MARKUP_ANNOTATION_COLORS,
ink: "#1f2933",
inkHighlighter: "#ffd54f",
text: "#111111",
diff --git a/frontend/editor/src/core/components/viewer/AnnotationDeletedMenu.tsx b/frontend/editor/src/core/components/viewer/AnnotationDeletedMenu.tsx
new file mode 100644
index 0000000000..6090c533f4
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/AnnotationDeletedMenu.tsx
@@ -0,0 +1,91 @@
+import { useCallback, useEffect } from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import { useAnnotationCapability } from "@embedpdf/plugin-annotation/react";
+import { useHistoryCapability } from "@embedpdf/plugin-history/react";
+import { Icon } from "@app/ui/Icon";
+import type { AnnotationMenuAnchor } from "@app/components/viewer/viewerTypes";
+import "@app/components/viewer/TextSelectionMenu.css";
+
+interface AnnotationDeletedMenuProps {
+ anchor: AnnotationMenuAnchor | null;
+ onDismiss: () => void;
+}
+
+/** Undo affordance for a just-deleted annotation, shown where its menu sat. */
+export function AnnotationDeletedMenu({
+ anchor,
+ onDismiss,
+}: AnnotationDeletedMenuProps) {
+ const { t } = useTranslation();
+ const { provides: annotationApi } = useAnnotationCapability();
+ const { provides: historyApi } = useHistoryCapability();
+
+ useEffect(() => {
+ if (!anchor) return;
+ const handlePointerDown = (event: PointerEvent) => {
+ const target = event.target as HTMLElement;
+ if (target.closest("[data-annotation-deleted-menu]")) return;
+ onDismiss();
+ };
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") onDismiss();
+ };
+ document.addEventListener("pointerdown", handlePointerDown);
+ document.addEventListener("keydown", handleKeyDown);
+ return () => {
+ document.removeEventListener("pointerdown", handlePointerDown);
+ document.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [anchor, onDismiss]);
+
+ const handleUndo = useCallback(() => {
+ if (!anchor) return;
+ historyApi?.undo();
+ // The history replay is asynchronous, so wait for the annotation to exist
+ // again before re-selecting it and letting the normal menu take over.
+ let attempts = 0;
+ const selectRestored = () => {
+ if (annotationApi?.getAnnotationById(anchor.annotationId)) {
+ annotationApi.selectAnnotation(anchor.pageIndex, anchor.annotationId);
+ onDismiss();
+ return;
+ }
+ attempts += 1;
+ if (attempts < 20) {
+ setTimeout(selectRestored, 50);
+ } else {
+ onDismiss();
+ }
+ };
+ setTimeout(selectRestored, 50);
+ }, [anchor, annotationApi, historyApi, onDismiss]);
+
+ if (!anchor) return null;
+
+ return createPortal(
+ <div
+ data-annotation-deleted-menu
+ className="embedpdf-floating-menu"
+ style={{
+ position: "fixed",
+ top: `${anchor.top}px`,
+ left: `${anchor.left}px`,
+ transform: "translateX(-50%)",
+ pointerEvents: "auto",
+ zIndex: 10000,
+ }}
+ >
+ <span>{t("annotation.deleted", "Annotation deleted")}</span>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
+ onClick={handleUndo}
+ aria-label={t("annotation.undoDelete", "Undo")}
+ >
+ <Icon name="undo-2" size={18} />
+ </button>
+ </div>,
+ document.body,
+ );
+}
diff --git a/frontend/editor/src/core/components/viewer/AnnotationMenuButtons.tsx b/frontend/editor/src/core/components/viewer/AnnotationMenuButtons.tsx
index cb0a958f6f..b5b1d498c0 100644
--- a/frontend/editor/src/core/components/viewer/AnnotationMenuButtons.tsx
+++ b/frontend/editor/src/core/components/viewer/AnnotationMenuButtons.tsx
@@ -3,22 +3,21 @@ import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon } from "@app/ui/Icon";
import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
import type { FirstLinkTarget } from "@app/components/viewer/useAnnotationMenuHandlers";
+import "@app/components/viewer/TextSelectionMenu.css";
export function DeleteButton({ onDelete }: { onDelete: () => void }) {
const { t } = useTranslation();
return (
- <Tooltip label={t("annotation.delete", "Delete")}>
- <ActionIcon
- aria-label={t("annotation.delete", "Delete")}
- variant="secondary"
- accent="danger"
- size="md"
+ <Tooltip label={t("annotation.delete", "Delete")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn embedpdf-floating-btn-danger"
onClick={onDelete}
+ aria-label={t("annotation.delete", "Delete")}
>
<Icon name="trash" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
);
}
@@ -26,16 +25,15 @@ export function DeleteButton({ onDelete }: { onDelete: () => void }) {
export function EditTextButton({ onEdit }: { onEdit: () => void }) {
const { t } = useTranslation();
return (
- <Tooltip label={t("annotation.editText", "Edit Text")}>
- <ActionIcon
- aria-label={t("annotation.editText", "Edit Text")}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={t("annotation.editText", "Edit Text")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={onEdit}
+ aria-label={t("annotation.editText", "Edit Text")}
>
<Icon name="pencil" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
);
}
@@ -56,16 +54,15 @@ export function AttachCommentButton({
? t("viewer.comments.viewComment", "View comment")
: t("viewer.comments.addComment", "Add comment");
return (
- <Tooltip label={label}>
- <ActionIcon
- aria-label={label}
- variant={isInSidebar ? "primary" : "secondary"}
- accent={isInSidebar ? undefined : "neutral"}
- size="md"
+ <Tooltip label={label} withArrow>
+ <button
+ type="button"
+ className={`embedpdf-floating-btn ${isInSidebar ? "embedpdf-floating-btn-active" : ""}`}
onClick={isInSidebar ? onView : onAdd}
+ aria-label={label}
>
<Icon name="message-square-plus" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
);
}
@@ -81,16 +78,15 @@ export function CommentButton({ hasContent, onClick }: CommentButtonProps) {
? t("viewer.comments.viewComment", "View comment")
: t("viewer.comments.addComment", "Add comment");
return (
- <Tooltip label={label}>
- <ActionIcon
- aria-label={label}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={label} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={onClick}
+ aria-label={label}
>
<Icon name="message-square" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
);
}
@@ -112,33 +108,36 @@ export function LinkButton({
if (firstLinkTarget) {
return (
- <Tooltip label={t("viewer.comments.goToLink", "Go to link")}>
- <ActionIcon
- aria-label={t("viewer.comments.goToLink", "Go to link")}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={t("viewer.comments.goToLink", "Go to link")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={onGoToLink}
+ aria-label={t("viewer.comments.goToLink", "Go to link")}
>
<Icon name="external-link" size={18} />
- </ActionIcon>
+ </button>
</Tooltip>
);
}
return (
- <Popover opened={open} onClose={() => setOpen(false)} position="top">
+ <Popover
+ opened={open}
+ onClose={() => setOpen(false)}
+ position="top"
+ withArrow
+ >
<Popover.Target>
- <Tooltip label={t("viewer.comments.addLink", "Add link")}>
- <ActionIcon
- aria-label={t("viewer.comments.addLink", "Add link")}
- variant="secondary"
- accent="neutral"
- size="md"
+ <Tooltip label={t("viewer.comments.addLink", "Add link")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-floating-btn"
onClick={() => setOpen((o) => !o)}
+ aria-label={t("viewer.comments.addLink", "Add link")}
>
<Icon name="link" size="1.25rem" />
- </ActionIcon>
+ </button>
</Tooltip>
</Popover.Target>
<Popover.Dropdown>
diff --git a/frontend/editor/src/core/components/viewer/AnnotationMenuEvents.tsx b/frontend/editor/src/core/components/viewer/AnnotationMenuEvents.tsx
new file mode 100644
index 0000000000..4c57fd8b73
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/AnnotationMenuEvents.tsx
@@ -0,0 +1,43 @@
+import { useEffect } from "react";
+import { useAnnotationCapability } from "@embedpdf/plugin-annotation/react";
+import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
+import type { AnnotationMenuAnchor } from "@app/components/viewer/viewerTypes";
+
+interface AnnotationMenuEventsProps {
+ /** Last on-screen anchor for an annotation, even after it was deselected. */
+ getAnchor: (annotationId: string) => AnnotationMenuAnchor | null;
+ onDeleted: (anchor: AnnotationMenuAnchor) => void;
+}
+
+/** Opens the menu for a committed edit, or an undo menu for a committed delete. */
+export function AnnotationMenuEvents({
+ getAnchor,
+ onDeleted,
+}: AnnotationMenuEventsProps) {
+ const documentId = useActiveDocumentId();
+ const { provides } = useAnnotationCapability();
+
+ useEffect(() => {
+ if (!provides || !documentId) return;
+
+ return provides.onAnnotationEvent((event) => {
+ if (event.type === "loaded") return;
+ if (!event.committed) return;
+
+ if (event.type === "delete") {
+ const anchor = getAnchor(event.annotation.id);
+ if (anchor) {
+ onDeleted(anchor);
+ }
+ return;
+ }
+
+ if (event.type !== "update") return;
+ const selected = provides.getSelectedAnnotationIds?.() ?? [];
+ if (selected.includes(event.annotation.id)) return;
+ provides.selectAnnotation?.(event.pageIndex, event.annotation.id);
+ });
+ }, [provides, documentId, getAnchor, onDeleted]);
+
+ return null;
+}
diff --git a/frontend/editor/src/core/components/viewer/AnnotationSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/AnnotationSelectionMenu.tsx
index 97d697a467..4153c2091b 100644
--- a/frontend/editor/src/core/components/viewer/AnnotationSelectionMenu.tsx
+++ b/frontend/editor/src/core/components/viewer/AnnotationSelectionMenu.tsx
@@ -1,4 +1,3 @@
-import { Group } from "@mantine/core";
import { createPortal } from "react-dom";
import { useEffect, useState, useRef, useCallback, useMemo } from "react";
import { useAnnotation } from "@embedpdf/plugin-annotation/react";
@@ -7,11 +6,15 @@ import {
PdfAnnotationSubtype,
type PdfAnnotationObject,
} from "@embedpdf/models";
-import type { AnnotationObject } from "@app/components/viewer/viewerTypes";
+import type {
+ AnnotationMenuAnchor,
+ AnnotationObject,
+} from "@app/components/viewer/viewerTypes";
import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
import { useViewer } from "@app/contexts/ViewerContext";
import { useAnnotationMenuHandlers } from "@app/components/viewer/useAnnotationMenuHandlers";
import { AnnotationTypeButtons } from "@app/components/viewer/AnnotationTypeButtons";
+import "@app/components/viewer/TextSelectionMenu.css";
/**
* Props interface matching EmbedPDF's annotation selection menu pattern
@@ -29,6 +32,8 @@ export interface AnnotationSelectionMenuProps {
ref?: (node: HTMLDivElement | null) => void;
style?: React.CSSProperties;
};
+ /** Reports where the menu sits so a delete can leave an undo affordance there. */
+ onAnchor?: (anchor: AnnotationMenuAnchor | null) => void;
}
export function AnnotationSelectionMenu(props: AnnotationSelectionMenuProps) {
@@ -44,6 +49,7 @@ function AnnotationSelectionMenuInner({
context,
selected,
menuWrapperProps,
+ onAnchor,
}: AnnotationSelectionMenuProps & { documentId: string }) {
const annotation = context?.annotation;
const pageIndex = context?.pageIndex;
@@ -125,7 +131,12 @@ function AnnotationSelectionMenuInner({
if (!selected) return;
const handlePointerDown = (e: PointerEvent) => {
const target = e.target as HTMLElement;
- if (target.closest("[data-annotation-selection-menu]")) return;
+ if (
+ target.closest(
+ "[data-annotation-selection-menu],[data-text-selection-menu],[data-redaction-selection-menu]",
+ )
+ )
+ return;
if (target.closest("[data-no-interaction]")) return;
if (target.closest(".mantine-Popover-dropdown")) return;
provides?.deselectAnnotation?.();
@@ -143,10 +154,27 @@ function AnnotationSelectionMenuInner({
[menuWrapperProps],
);
+ // The anchor follows the wrapper so a delete from any path can keep an undo
+ // menu where the annotation was.
+ const updateAnchor = useCallback(
+ (position: { top: number; left: number }) => {
+ const id = (annotation?.object as AnnotationObject | undefined)?.id;
+ if (!onAnchor || !id || pageIndex === undefined) return;
+ onAnchor({
+ annotationId: id,
+ pageIndex,
+ top: position.top,
+ left: position.left,
+ });
+ },
+ [annotation, onAnchor, pageIndex],
+ );
+
// Track menu position via MutationObserver (handles drag repositioning)
useEffect(() => {
if (!selected || !annotation || !wrapperRef.current) {
setMenuPosition(null);
+ onAnchor?.(null);
return;
}
@@ -157,10 +185,12 @@ function AnnotationSelectionMenuInner({
return;
}
const rect = wrapper.getBoundingClientRect();
- setMenuPosition({
+ const position = {
top: rect.bottom + 8,
left: rect.left + rect.width / 2,
- });
+ };
+ setMenuPosition(position);
+ updateAnchor(position);
};
updatePosition();
@@ -178,13 +208,14 @@ function AnnotationSelectionMenuInner({
window.removeEventListener("scroll", updatePosition, true);
window.removeEventListener("resize", updatePosition);
};
- }, [selected]);
+ }, [selected, updateAnchor]);
if (!selected || !annotation) return null;
const menuContent = menuPosition ? (
<div
data-annotation-selection-menu
+ className="embedpdf-floating-menu"
style={{
position: "fixed",
top: `${menuPosition.top}px`,
@@ -192,26 +223,17 @@ function AnnotationSelectionMenuInner({
transform: "translateX(-50%)",
pointerEvents: "auto",
zIndex: 10000,
- backgroundColor: "var(--mantine-color-body)",
- borderRadius: 8,
- padding: "8px 12px",
- boxShadow: "0 2px 12px rgba(0, 0, 0, 0.25)",
- border: "1px solid var(--mantine-color-default-border)",
- fontSize: "14px",
- minWidth: `${handlers.menuWidth}px`,
- transition: "min-width 0.2s ease",
+ width: "max-content",
}}
>
- <Group gap="sm" wrap="nowrap" justify="center">
- <AnnotationTypeButtons
- {...handlers}
- isInSidebar={isInSidebar}
- annotation={annotation}
- documentId={documentId}
- pageIndex={pageIndex}
- annotationId={handlers.annotationId}
- />
- </Group>
+ <AnnotationTypeButtons
+ {...handlers}
+ isInSidebar={isInSidebar}
+ annotation={annotation}
+ documentId={documentId}
+ pageIndex={pageIndex}
+ annotationId={handlers.annotationId}
+ />
</div>
) : null;
diff --git a/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.stories.tsx b/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.stories.tsx
index 860f743a99..a38a6067f8 100644
--- a/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.stories.tsx
+++ b/frontend/editor/src/core/components/viewer/AnnotationTypeButtons.stories.tsx
@@ -14,7 +14,6 @@ const baseArgs = {
documentId: "doc-1",
pageIndex: 0,
annotationId: "annotation-1",
- menuWidth: 260,
obj: undefined,
firstLinkTarget: null,
hasCommentContent: false,
diff --git a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
index b5ac166a1f..b09eb1c58a 100644
--- a/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
+++ b/frontend/editor/src/core/components/viewer/CommentsSidebar.tsx
@@ -30,6 +30,7 @@ import { useCommentAuthor } from "@app/contexts/CommentAuthorContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useAnnotation as useAnnotationContext } from "@app/contexts/AnnotationContext";
+import { useNavigationActions } from "@app/contexts/NavigationContext";
import { compareEntriesByVisualOrder } from "@app/components/viewer/commentsSidebarOrder";
import { SidebarBase } from "@app/components/viewer/SidebarBase";
@@ -304,6 +305,7 @@ export function CommentsSidebar({
const scrollViewportRef = useRef<HTMLDivElement | null>(null);
const { state, provides } = useAnnotation(documentId);
const { handleToolSelectForced, readerMode } = useToolWorkflow();
+ const { actions: navActions } = useNavigationActions();
const {
activateAnnotationToolRef,
activeAnnotationToolId,
@@ -539,14 +541,16 @@ export function CommentsSidebar({
// post-reload linked annotations, so clearing it removes the annotation
// from the sidebar (contents is not visually rendered on ink/shape/markup types).
provides.updateAnnotation(pageIndex, id, getRemoveCommentPatch(ann));
+ navActions?.setHasUnsavedChanges(true);
setDeleteModal(null);
- }, [deleteModal, provides]);
+ }, [deleteModal, provides, navActions]);
const handleDeleteAnnotation = useCallback(() => {
if (!deleteModal) return;
provides?.deleteAnnotation?.(deleteModal.pageIndex, deleteModal.id);
+ navActions?.setHasUnsavedChanges(true);
setDeleteModal(null);
- }, [deleteModal, provides]);
+ }, [deleteModal, provides, navActions]);
const handleClearAllComments = useCallback(() => {
const annotationsToDelete: Array<{ pageIndex: number; id: string }> = [];
@@ -613,7 +617,8 @@ export function CommentsSidebar({
setEditingReplyKey(null);
setDeleteModal(null);
setClearAllModalOpen(false);
- }, [byPage, provides]);
+ navActions?.setHasUnsavedChanges(true);
+ }, [byPage, provides, navActions]);
const handleSendMainComment = useCallback(
(pageIndex: number, annotationId: string, value: string) => {
@@ -623,12 +628,13 @@ export function CommentsSidebar({
contents: trimmed,
author: displayName,
});
+ navActions?.setHasUnsavedChanges(true);
setDraftContents((prev) => ({
...prev,
[pageIndex + "_" + annotationId]: trimmed,
}));
},
- [provides, displayName],
+ [provides, displayName, navActions],
);
const handleSendReply = useCallback(
@@ -651,9 +657,10 @@ export function CommentsSidebar({
author: displayName,
};
provides.createAnnotation(pageIndex, reply);
+ navActions?.setHasUnsavedChanges(true);
setReplyDrafts((prev) => ({ ...prev, [key]: "" }));
},
- [provides, replyDrafts, displayName],
+ [provides, replyDrafts, displayName, navActions],
);
const handleSaveReplyEdit = useCallback(
@@ -664,6 +671,7 @@ export function CommentsSidebar({
contents: trimmed,
author: displayName,
});
+ navActions?.setHasUnsavedChanges(true);
setReplyEditDrafts((prev) => {
const next = { ...prev };
delete next[editKey];
@@ -671,7 +679,7 @@ export function CommentsSidebar({
});
setEditingReplyKey(null);
},
- [provides, displayName],
+ [provides, displayName, navActions],
);
const handleAddComment = useCallback(() => {
@@ -1002,15 +1010,32 @@ export function CommentsSidebar({
</Group>
{!hasMainContent || isEditingMain ? (
- <>
+ <Group gap="xs" wrap="nowrap" align="flex-end">
<Textarea
placeholder={t(
"viewer.comments.addCommentPlaceholder",
"Add comment...",
)}
- minRows={2}
+ size="sm"
autosize
+ minRows={1}
+ maxRows={6}
value={draft ?? ""}
+ onKeyDown={(e) => {
+ if (
+ e.key === "Enter" &&
+ !e.shiftKey &&
+ (draft ?? "").trim()
+ ) {
+ e.preventDefault();
+ handleSendMainComment(
+ pageIndex,
+ id,
+ draft ?? "",
+ );
+ setEditingMainKey(null);
+ }
+ }}
onChange={(e) => {
const v =
(e?.currentTarget ?? e?.target)?.value ??
@@ -1023,38 +1048,47 @@ export function CommentsSidebar({
handleContentsChange(pageIndex, id, v);
}
}}
- styles={{ root: { width: "100%" } }}
- mb="xs"
+ style={{ flex: 1, minWidth: 0 }}
+ styles={{
+ input: {
+ borderColor:
+ "var(--mantine-color-blue-3)",
+ },
+ }}
+ autoFocus
/>
- <Group gap={4} wrap="nowrap" justify="flex-end">
- <Tooltip
- label={t(
+ <Tooltip
+ label={t(
+ "viewer.comments.addComment",
+ "Add comment",
+ )}
+ >
+ <ActionIcon
+ variant="primary"
+ size="md"
+ aria-label={t(
"viewer.comments.addComment",
"Add comment",
)}
+ onClick={() => {
+ handleSendMainComment(
+ pageIndex,
+ id,
+ draft ?? "",
+ );
+ setEditingMainKey(null);
+ }}
+ disabled={!(draft ?? "").trim()}
+ style={{
+ height: "36px",
+ width: "36px",
+ flexShrink: 0,
+ }}
>
- <ActionIcon
- variant="primary"
- size="sm"
- aria-label={t(
- "viewer.comments.addComment",
- "Add comment",
- )}
- onClick={() => {
- handleSendMainComment(
- pageIndex,
- id,
- draft ?? "",
- );
- setEditingMainKey(null);
- }}
- disabled={!(draft ?? "").trim()}
- >
- <Icon name="check" size={18} />
- </ActionIcon>
- </Tooltip>
- </Group>
- </>
+ <Icon name="check" size={18} />
+ </ActionIcon>
+ </Tooltip>
+ </Group>
) : (
<>
<Text
@@ -1231,14 +1265,27 @@ export function CommentsSidebar({
</Stack>
) : null}
- <Group gap="xs" wrap="nowrap" align="flex-end">
+ <Group gap="xs" wrap="nowrap" align="center">
<TextInput
placeholder={t(
"viewer.comments.addReplyPlaceholder",
"Add reply...",
)}
- size="xs"
+ size="sm"
value={replyDraft}
+ onKeyDown={(e) => {
+ if (
+ e.key === "Enter" &&
+ replyDraft.trim()
+ ) {
+ e.preventDefault();
+ handleSendReply(
+ pageIndex,
+ id,
+ ann?.rect,
+ );
+ }
+ }}
onChange={(e) => {
const v =
(e?.currentTarget ?? e?.target)
@@ -1253,6 +1300,8 @@ export function CommentsSidebar({
input: {
borderColor:
"var(--mantine-color-blue-3)",
+ height: "36px",
+ minHeight: "36px",
},
}}
/>
@@ -1277,6 +1326,11 @@ export function CommentsSidebar({
)
}
disabled={!replyDraft.trim()}
+ style={{
+ height: "36px",
+ width: "36px",
+ flexShrink: 0,
+ }}
>
<Icon name="check" size={20} />
</ActionIcon>
diff --git a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
new file mode 100644
index 0000000000..53dd9812b6
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
@@ -0,0 +1,98 @@
+import { useEffect, useRef } from "react";
+import { useDocumentManagerCapability } from "@embedpdf/plugin-document-manager/react";
+
+interface PendingDocument {
+ buffer: ArrayBuffer;
+ name: string;
+}
+
+interface DocumentSwapBridgeProps {
+ pending: PendingDocument | null;
+ onSwapped: () => void;
+ onFailed: (error: unknown) => void;
+}
+
+/** Activates replacement bytes once loaded, so the mounted document keeps
+ * rendering through the swap; activate before closing, or the manager
+ * promotes whatever is left. A superseded open is closed without being shown. */
+export function DocumentSwapBridge({
+ pending,
+ onSwapped,
+ onFailed,
+}: DocumentSwapBridgeProps) {
+ const { provides: documentManager } = useDocumentManagerCapability();
+ const generationRef = useRef(0);
+
+ useEffect(() => {
+ if (!documentManager || !pending) return;
+ const generation = ++generationRef.current;
+ let cancelled = false;
+ const previousId = documentManager.getActiveDocumentId();
+
+ void documentManager
+ .openDocumentBuffer({
+ buffer: pending.buffer,
+ name: pending.name,
+ autoActivate: false,
+ })
+ .toPromise()
+ .then(async (response) => {
+ // The open task resolves with the loading task; the pages only render
+ // once the engine reports the document loaded.
+ try {
+ await response.task.toPromise();
+ } catch (error) {
+ void documentManager
+ .closeDocument(response.documentId)
+ .toPromise()
+ .catch(() => {});
+ if (!cancelled) onFailed(error);
+ return;
+ }
+ if (cancelled || generation !== generationRef.current) {
+ // Superseded or unmounted: the background document is never shown.
+ void documentManager
+ .closeDocument(response.documentId)
+ .toPromise()
+ .catch(() => {});
+ return;
+ }
+
+ try {
+ documentManager.setActiveDocument(response.documentId);
+ onSwapped();
+ if (previousId && previousId !== response.documentId) {
+ // A failed close only leaks a background document until unmount.
+ void documentManager
+ .closeDocument(previousId)
+ .toPromise()
+ .catch(() => {});
+ }
+ } catch (error) {
+ if (previousId) {
+ try {
+ documentManager.setActiveDocument(previousId);
+ } catch {
+ // Ignore rollback failure if previous document was destroyed.
+ }
+ }
+ void documentManager
+ .closeDocument(response.documentId)
+ .toPromise()
+ .catch(() => {});
+ if (!cancelled) onFailed(error);
+ }
+ })
+ .catch((error) => {
+ // A superseded open rejecting must not clear the newer pending
+ // document its replacement already queued.
+ if (!cancelled && generation === generationRef.current) onFailed(error);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [documentManager, pending, onSwapped, onFailed]);
+
+ return null;
+}
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index 70c011a6fb..c0f9b69afd 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -1,5 +1,13 @@
-import React, { useCallback, useEffect, useLayoutEffect, useRef } from "react";
+import React, {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import { useTranslation } from "react-i18next";
+import type { SpreadMode } from "@embedpdf/plugin-spread/react";
+import type { ZoomLevel } from "@embedpdf/plugin-zoom/react";
import { Box, Center, Text, Stack } from "@mantine/core";
import { Button } from "@app/ui/Button";
import { ActionIcon } from "@app/ui/ActionIcon";
@@ -78,6 +86,27 @@ export interface EmbedPdfViewerProps {
const documentCacheKey = (file: StirlingFile): string =>
`${file.fileId}|${file.quickKey}`;
+// Slow engines can take seconds to report the replacement's page count and
+// land the carried zoom; the hide lasts until then, not for a fixed flash.
+const SWAP_REVEAL_DEADLINE_MS = 5_000;
+// Re-checks how often the hide decides whether the carried zoom has landed.
+const SWAP_REVEAL_HIDE_RECHECK_MS = 250;
+
+const findScrollableAncestor = (el: HTMLElement | null): HTMLElement | null => {
+ let node = el?.parentElement ?? null;
+ while (node) {
+ const style = getComputedStyle(node);
+ if (
+ node.scrollHeight > node.clientHeight + 5 &&
+ /auto|scroll/.test(style.overflowY)
+ ) {
+ return node;
+ }
+ node = node.parentElement;
+ }
+ return null;
+};
+
const EmbedPdfViewerContent = ({
onClose,
previewFile,
@@ -110,7 +139,12 @@ const EmbedPdfViewerContent = ({
panActions: _panActions,
rotationActions,
getScrollState,
+ getSpreadState,
+ getZoomState,
getRotationState,
+ spreadActions,
+ zoomRestorePendingRef,
+ notifyZoomRestoreSettled,
setAnnotationMode,
isAnnotationsVisible,
exportActions,
@@ -154,8 +188,11 @@ const EmbedPdfViewerContent = ({
const hasAnnotationChangesRef = useRef(false);
// EmbedPDF can emit once from the saved undo stack before the saved file remounts.
// Ignore that stale update without suppressing future edits on the same instance.
- const savedAnnotationHistoryApiRef =
- useRef<typeof historyApiRef.current>(null);
+ // Save point for annotations: history edits before the last save stay
+ // undoable, but only edits after it make the document unsaved again.
+ const historyRevisionRef = useRef(0);
+ const savedHistoryRevisionRef = useRef(0);
+ const suppressHistoryDirtyRef = useRef(false);
// Scroll position preservation system
// We continuously track the last known good scroll position, so we always have it available
@@ -168,11 +205,327 @@ const EmbedPdfViewerContent = ({
const pendingRotationRestoreRef = useRef<number | null>(null);
const rotationRestoreAttemptsRef = useRef<number>(0);
+ // The zoom survives an in-place reload, mode or number: a replacement opens
+ // at the plugin default otherwise, which reads as the zoom changing.
+ const pendingZoomRestoreRef = useRef<ZoomLevel | null>(null);
+ // Spread mode is per document, so a replacement opens single-page unless it
+ // is carried over like the position.
+ const pendingSpreadRestoreRef = useRef<SpreadMode | null>(null);
+ const spreadRestoreAttemptsRef = useRef(0);
+ // The toolbar must not show the plugin's intermediate fit pass while a
+ // carried zoom lands, so the bridge publishes nothing until this settles.
+ const settleZoomRestore = useCallback(() => {
+ zoomRestorePendingRef.current = false;
+ notifyZoomRestoreSettled();
+ }, [zoomRestorePendingRef, notifyZoomRestoreSettled]);
+ const zoomRestoreAttemptsRef = useRef<number>(0);
+ // Reading position captured from the outgoing document: the page's node
+ // identifies the swap, the offsets restore the exact spot within the page.
+ const pendingScrollPositionRef = useRef<{
+ page: number;
+ offsetPx: number | null;
+ offsetFraction: number | null;
+ pageHeight: number | null;
+ element: HTMLElement | null;
+ scroller: HTMLElement | null;
+ expectSwap: boolean;
+ /** A fraction apply landed against the replacement's own geometry. */
+ fractionApplied: boolean;
+ } | null>(null);
+ const pendingScrollSwappedRef = useRef(false);
+ const pendingScrollReassertTimerRef = useRef<number | null>(null);
+ // Content key of a just-saved file whose visual state the live document
+ // already shows: skip the reopen so a save cannot move the view.
+ const skipReloadContentKeyRef = useRef<string | null>(null);
+ // Bumped when a replacement seeds the pending refs, so the restore effects
+ // run even when the page count does not change across the swap.
+ const [restoreTick, setRestoreTick] = useState(0);
+ // True only while a restore is in flight, so the per-page layout hook and
+ // the swap backstop cost nothing during ordinary scrolling.
+ const [restorePending, setRestorePending] = useState(false);
+ // A replacement renders at the wrong scale until its zoom lands, so the
+ // scroller hides for that window. The hide survives until the carried zoom
+ // lands (revealing early shows a wrong-scale frame), capped so a failed
+ // restore can never leave it hidden.
+ const swapRevealRef = useRef<{
+ scroller: HTMLElement | null;
+ timer: ReturnType<typeof setTimeout> | null;
+ deadline: number;
+ }>({ scroller: null, timer: null, deadline: 0 });
+ // Last scroll target the restore computed, used to reveal only once the
+ // layout has stopped moving the target around.
+ const swapTargetRef = useRef<number | null>(null);
+ // Layout signature (page height + content height) of the last apply, so the
+ // per-frame hold can skip when the page already sits at the target.
+ const swapLayoutRef = useRef<string | null>(null);
+ // The swap bridge activates replacements, and React can reuse the page
+ // nodes, so node identity alone cannot tell that a new document is mounted.
+ const documentSwappedRef = useRef(false);
+ const scrollIntentCleanupRef = useRef<(() => void) | null>(null);
+
+ const revealSwappedDocument = useCallback(() => {
+ const state = swapRevealRef.current;
+ if (state.timer !== null) {
+ clearTimeout(state.timer);
+ state.timer = null;
+ }
+ if (state.scroller) {
+ state.scroller.style.visibility = "";
+ state.scroller = null;
+ }
+ }, []);
+
+ const detachScrollIntentListeners = useCallback(() => {
+ scrollIntentCleanupRef.current?.();
+ scrollIntentCleanupRef.current = null;
+ }, []);
+
+ // Single release path: drop the target, stop the hold, stop listening for
+ // intent and show the content again.
+ const clearPendingScrollRestore = useCallback(() => {
+ pendingScrollPositionRef.current = null;
+ if (pendingScrollReassertTimerRef.current !== null) {
+ cancelAnimationFrame(pendingScrollReassertTimerRef.current);
+ pendingScrollReassertTimerRef.current = null;
+ }
+ detachScrollIntentListeners();
+ revealSwappedDocument();
+ setRestorePending(false);
+ }, [detachScrollIntentListeners, revealSwappedDocument]);
+
+ const attachScrollIntentListeners = useCallback(() => {
+ const scroller = pendingScrollPositionRef.current?.scroller;
+ if (!scroller || scrollIntentCleanupRef.current) return;
+ const release = () => clearPendingScrollRestore();
+ const events = ["wheel", "touchstart", "pointerdown", "keydown"];
+ for (const name of events) {
+ scroller.addEventListener(name, release, { passive: true });
+ }
+ scrollIntentCleanupRef.current = () => {
+ for (const name of events) {
+ scroller.removeEventListener(name, release);
+ }
+ };
+ }, [clearPendingScrollRestore]);
+
+ const hideUntilSettled = useCallback(
+ (scroller: HTMLElement | null) => {
+ if (!scroller) return;
+ swapRevealRef.current.scroller = scroller;
+ swapRevealRef.current.deadline =
+ performance.now() + SWAP_REVEAL_DEADLINE_MS;
+ scroller.style.visibility = "hidden";
+ const arm = () => {
+ if (swapRevealRef.current.timer !== null) {
+ clearTimeout(swapRevealRef.current.timer);
+ }
+ swapRevealRef.current.timer = setTimeout(() => {
+ // The carried zoom is the reason the scroller is hidden: a reveal
+ // before it lands paints the wrong scale on the next frame.
+ if (
+ pendingZoomRestoreRef.current !== null &&
+ performance.now() < swapRevealRef.current.deadline
+ ) {
+ arm();
+ return;
+ }
+ clearPendingScrollRestore();
+ }, SWAP_REVEAL_HIDE_RECHECK_MS);
+ };
+ arm();
+ },
+ [clearPendingScrollRestore],
+ );
+
+ const queueScrollRestore = useCallback((page: number, expectSwap = false) => {
+ pendingScrollRestoreRef.current = page;
+ scrollRestoreAttemptsRef.current = 0;
+ pendingScrollSwappedRef.current = false;
+
+ const element = document.querySelector<HTMLElement>(
+ `[data-page-index="${page - 1}"]`,
+ );
+ const scroller = findScrollableAncestor(element);
+ if (!element || !scroller) {
+ pendingScrollPositionRef.current = null;
+ swapTargetRef.current = null;
+ swapLayoutRef.current = null;
+ documentSwappedRef.current = false;
+ return;
+ }
+ const scrollerTop = scroller.getBoundingClientRect().top;
+ const pageTopInContent =
+ element.getBoundingClientRect().top - scrollerTop + scroller.scrollTop;
+ const offsetPx = scroller.scrollTop - pageTopInContent;
+ const offsetFraction =
+ element.clientHeight > 0 ? offsetPx / element.clientHeight : 0;
+ pendingScrollPositionRef.current = {
+ page,
+ offsetPx,
+ offsetFraction,
+ pageHeight: element.clientHeight,
+ element,
+ scroller,
+ expectSwap,
+ fractionApplied: false,
+ };
+ // Arm the pre-paint restore gates (the per-page layout hook and the swap
+ // layout effect); every completion path clears through
+ // clearPendingScrollRestore.
+ setRestorePending(true);
+ swapTargetRef.current = null;
+ swapLayoutRef.current = null;
+ documentSwappedRef.current = false;
+ }, []);
+
+ const applyScrollNow = useCallback(
+ (useFraction: boolean): boolean => {
+ const pending = pendingScrollPositionRef.current;
+ if (
+ !pending ||
+ pending.offsetPx === null ||
+ pending.offsetFraction === null
+ ) {
+ clearPendingScrollRestore();
+ return false;
+ }
+ const pageEl = document.querySelector<HTMLElement>(
+ `[data-page-index="${pending.page - 1}"]`,
+ );
+ // The scroller survives document swaps; walking ancestors on every frame
+ // of the hold is what made it expensive.
+ const scroller =
+ pending.scroller && pending.scroller.isConnected
+ ? pending.scroller
+ : findScrollableAncestor(pageEl);
+ if (!pageEl || !scroller) return false;
+ pending.scroller = scroller;
+
+ // The fraction only matters when the page geometry changed (a zoom
+ // restore); otherwise the captured pixel offset is exact.
+ const heightChanged =
+ pending.pageHeight !== null &&
+ Math.abs(pageEl.clientHeight - pending.pageHeight) > 1;
+ // A fraction apply means the replacement's geometry is settled even
+ // though it differs; a carried zoom keeps it unsettled until it lands.
+ const geometrySettled =
+ (!heightChanged || pending.fractionApplied) &&
+ pendingZoomRestoreRef.current === null;
+
+ // Nothing moved since the last apply: no rect reads needed, but the
+ // settled scale still has to reveal the content.
+ const layoutSignature = `${pageEl.clientHeight}|${scroller.scrollHeight}`;
+ const lastTarget = swapTargetRef.current;
+ if (
+ layoutSignature === swapLayoutRef.current &&
+ lastTarget !== null &&
+ Math.abs(scroller.scrollTop - lastTarget) <= 1
+ ) {
+ if (geometrySettled) {
+ revealSwappedDocument();
+ }
+ return true;
+ }
+ const offset =
+ useFraction && heightChanged
+ ? pending.offsetFraction * pageEl.clientHeight
+ : pending.offsetPx;
+ const scrollerTop = scroller.getBoundingClientRect().top;
+ const pageTopInContent =
+ pageEl.getBoundingClientRect().top - scrollerTop + scroller.scrollTop;
+ const target = Math.max(0, pageTopInContent + offset);
+ swapLayoutRef.current = layoutSignature;
+ scroller.scrollTop = target;
+ // Reveal once the scale settled and two frames agree on the target: a
+ // neighbour still moves it while the height already matches.
+ const stable =
+ geometrySettled &&
+ swapTargetRef.current !== null &&
+ Math.abs(swapTargetRef.current - target) <= 2;
+ swapTargetRef.current = target;
+ if (useFraction && heightChanged) {
+ // The fraction now maps to the replacement's own page height.
+ pending.fractionApplied = true;
+ }
+ if (stable) {
+ revealSwappedDocument();
+ }
+ return true;
+ },
+ [revealSwappedDocument],
+ );
+
+ // Re-apply the captured position to the swapped document. Returns false until
+ // the replacement page node exists and while no offset was captured.
+ const applyPendingScrollPosition = useCallback(
+ (options?: { useFraction?: boolean }): boolean => {
+ const pending = pendingScrollPositionRef.current;
+ if (!pending) return false;
+
+ const pageEl = document.querySelector<HTMLElement>(
+ `[data-page-index="${pending.page - 1}"]`,
+ );
+ if (!pendingScrollSwappedRef.current) {
+ const replaced =
+ !!pageEl && (pending.element ? pageEl !== pending.element : true);
+ // Same-document restores apply straight away; a byte replacement waits
+ // for the swap bridge or the new page node.
+ const sameDocument = !pending.expectSwap;
+ if (!replaced && !documentSwappedRef.current && !sameDocument) {
+ return false;
+ }
+ if (!pending.scroller?.isConnected) {
+ pending.scroller = findScrollableAncestor(pageEl);
+ }
+ if (!sameDocument) {
+ // First frame of the replacement: hide it until it settles so no
+ // wrong-scale or wrong-position frame can be seen.
+ hideUntilSettled(pending.scroller);
+ }
+ attachScrollIntentListeners();
+ }
+ if (!applyScrollNow(options?.useFraction ?? false)) return false;
+ pendingScrollSwappedRef.current = true;
+
+ // The replacement's own ready pass can still reset the scroll, so hold
+ // the position per frame for a short bounded window.
+ if (pendingScrollReassertTimerRef.current) {
+ cancelAnimationFrame(pendingScrollReassertTimerRef.current);
+ }
+ const useFraction = options?.useFraction ?? false;
+ const holdUntil = performance.now() + 1_500;
+ const reassert = () => {
+ if (!pendingScrollPositionRef.current) return;
+ if (performance.now() >= holdUntil) {
+ clearPendingScrollRestore();
+ return;
+ }
+ applyScrollNow(useFraction);
+ pendingScrollReassertTimerRef.current = requestAnimationFrame(reassert);
+ };
+ pendingScrollReassertTimerRef.current = requestAnimationFrame(reassert);
+
+ return true;
+ },
+ [
+ applyScrollNow,
+ clearPendingScrollRestore,
+ hideUntilSettled,
+ attachScrollIntentListeners,
+ revealSwappedDocument,
+ ],
+ );
+
const formApplyInProgressRef = useRef(false);
const applyChangesInFlightRef = useRef<Promise<void> | null>(null);
// Get redaction context
- const { redactionsApplied, setRedactionsApplied } = useRedaction();
+ const {
+ redactionsApplied,
+ setRedactionsApplied,
+ deactivateRedact,
+ setRedactionMode,
+ } = useRedaction();
// Ref for redaction pending tracker API
const redactionTrackerRef = useRef<RedactionPendingTrackerAPI>(null);
@@ -196,6 +549,13 @@ const EmbedPdfViewerContent = ({
const { selectedTool } = useNavigationState();
+ useEffect(() => {
+ if (selectedTool !== "redact") {
+ setRedactionMode(false);
+ deactivateRedact();
+ }
+ }, [selectedTool, setRedactionMode, deactivateRedact]);
+
// Form fill context
const { fetchFields: fetchFormFields, setProviderMode } = useFormFill();
@@ -204,13 +564,11 @@ const EmbedPdfViewerContent = ({
selectedTool === "addText" ||
selectedTool === "addImage" ||
selectedTool === "annotate";
- const isSignatureMode = isInAnnotationTool;
const isManualRedactMode = selectedTool === "redact";
- // Enable annotations when annotation tool is selected OR when annotations are visible
- // (so users can interact with existing comment annotations in reader/viewer mode)
- const shouldEnableAnnotations =
- selectedTool === "annotate" || isSignatureMode || isAnnotationsVisible;
+ // Live layer visibility is controlled via showBakedAnnotations CSS; unmounting
+ // AnnotationPlugin on visibility toggle destroys in-memory annotations.
+ const shouldEnableAnnotations = true;
// Enable redaction only when redaction tool is selected
const shouldEnableRedaction = selectedTool === "redact";
@@ -258,8 +616,7 @@ const EmbedPdfViewerContent = ({
const pageToRestore = pageFromState > 0 ? pageFromState : pageFromRef;
if (pageToRestore > 0) {
- pendingScrollRestoreRef.current = pageToRestore;
- scrollRestoreAttemptsRef.current = 0;
+ queueScrollRestore(pageToRestore);
}
prevEnableAnnotationsRef.current = shouldEnableAnnotations;
@@ -306,6 +663,19 @@ const EmbedPdfViewerContent = ({
currentFile && isStirlingFile(currentFile) ? currentFile.fileId : null;
const fileWithUrl = useFileWithUrl(currentFile, currentFileId);
+ // Lineage root of the open document: saves and tool outputs add a child record,
+ // so mounting on the root keeps the engine alive across reloads.
+ const currentFileRootId = React.useMemo(() => {
+ if (previewFile) {
+ return `preview-${previewFile.name}|${previewFile.size}|${previewFile.lastModified}`;
+ }
+ if (currentFile && isStirlingFile(currentFile)) {
+ const stub = selectors.getStirlingFileStub(currentFile.fileId);
+ return stub?.originalFileId ?? stub?.id ?? currentFile.fileId;
+ }
+ return currentFileId;
+ }, [previewFile, currentFile, currentFileId, selectors]);
+
// Determine the effective file to display
const effectiveFile = React.useMemo(() => {
if (previewFile) {
@@ -549,6 +919,8 @@ const EmbedPdfViewerContent = ({
if (!documentBytesReplaced(previous, current)) return;
hasAnnotationChangesRef.current = false;
+ historyRevisionRef.current = 0;
+ savedHistoryRevisionRef.current = 0;
setHasUnsavedChanges(false);
setRedactionsApplied(false);
}, [
@@ -568,15 +940,34 @@ const EmbedPdfViewerContent = ({
}
const updateHasChanges = () => {
- if (savedAnnotationHistoryApiRef.current === historyApi) {
- savedAnnotationHistoryApiRef.current = null;
+ const canUndo = historyApi.canUndo?.() ?? false;
+ if (!canUndo && savedHistoryRevisionRef.current === 0) {
+ historyRevisionRef.current = 0;
+ hasAnnotationChangesRef.current = false;
+ const hasPendingRedactions =
+ (redactionTrackerRef.current?.getPendingCount() ?? 0) > 0;
+ if (!hasPendingRedactions && !redactionsApplied) {
+ setHasUnsavedChanges(false);
+ }
return;
}
-
- const canUndo = historyApi.canUndo?.() ?? false;
- if (!hasAnnotationChangesRef.current && canUndo) {
- hasAnnotationChangesRef.current = true;
+ historyRevisionRef.current += 1;
+ if (suppressHistoryDirtyRef.current) return;
+ // A revision equal to the save point means the annotations match the
+ // exported bytes again (for example an undo that lands back on them).
+ const annotationDirty =
+ historyRevisionRef.current !== savedHistoryRevisionRef.current;
+ hasAnnotationChangesRef.current = annotationDirty;
+ if (annotationDirty) {
setHasUnsavedChanges(true);
+ return;
+ }
+ // Undo back to the saved state disarms the warning, but redactions keep
+ // their own claim on the flag.
+ const hasPendingRedactions =
+ (redactionTrackerRef.current?.getPendingCount() ?? 0) > 0;
+ if (!hasPendingRedactions && !redactionsApplied) {
+ setHasUnsavedChanges(false);
}
};
@@ -586,7 +977,12 @@ const EmbedPdfViewerContent = ({
unsubscribe();
}
};
- }, [historyApiRef.current, setHasUnsavedChanges]);
+ }, [
+ historyApiRef.current,
+ setHasUnsavedChanges,
+ redactionsApplied,
+ redactionTrackerRef,
+ ]);
// Register checker for unsaved changes (annotations only for now)
useEffect(() => {
@@ -637,12 +1033,6 @@ const EmbedPdfViewerContent = ({
"[Viewer] Applying changes - exporting PDF with annotations/redactions",
);
- // Use the continuously tracked scroll position - more reliable than reading at this moment
- const pageToRestore = lastKnownScrollPageRef.current;
-
- // Save the current rotation to restore after reload
- const currentRotation = rotationState.rotation ?? 0;
-
// Step 0: Commit any pending redactions before export
const hadPendingRedactions =
(redactionTrackerRef.current?.getPendingCount() ?? 0) > 0;
@@ -660,6 +1050,8 @@ const EmbedPdfViewerContent = ({
}
// Step 1: Export PDF with annotations using EmbedPDF
+ suppressHistoryDirtyRef.current = true;
+ const exportRevision = historyRevisionRef.current;
const arrayBuffer = await exportActions.saveAsCopy();
if (!arrayBuffer) {
throw new Error("Failed to export PDF");
@@ -684,13 +1076,13 @@ const EmbedPdfViewerContent = ({
selectedTool ?? "multiTool",
);
- // Store the page to restore after file replacement triggers re-render
- pendingScrollRestoreRef.current = pageToRestore;
- scrollRestoreAttemptsRef.current = 0;
+ // The live document already renders what was exported, and a reopen would
+ // reset the scroll, so the save must not reopen it.
+ const savedFile = stirlingFiles[0];
+ if (savedFile) {
+ skipReloadContentKeyRef.current = getFormFillFileId(savedFile);
+ }
- // Store the rotation to restore after file replacement
- pendingRotationRestoreRef.current = currentRotation;
- rotationRestoreAttemptsRef.current = 0;
// Track the new file ID so the viewer follows it after the list reorders
const newFileId = stubs[0]?.id;
if (newFileId) setActiveFileId(newFileId);
@@ -698,15 +1090,19 @@ const EmbedPdfViewerContent = ({
// Step 4: Consume only the current file (replace in context)
await actions.consumeFiles([currentFileId], stirlingFiles, stubs);
- // Mark annotations as saved so navigation away from the viewer is allowed.
- savedAnnotationHistoryApiRef.current = historyApiRef.current;
- hasAnnotationChangesRef.current = false;
- setHasUnsavedChanges(false);
+ // The exported bytes cover everything up to this revision; an edit that
+ // landed while the save was in flight stays unsaved.
+ savedHistoryRevisionRef.current = exportRevision;
+ hasAnnotationChangesRef.current =
+ historyRevisionRef.current !== exportRevision;
+ suppressHistoryDirtyRef.current = false;
+ setHasUnsavedChanges(hasAnnotationChangesRef.current);
setRedactionsApplied(false);
};
const savePromise = saveChanges()
.catch((error) => {
+ suppressHistoryDirtyRef.current = false;
console.error("Apply changes failed:", error);
alert({
title: t("viewer.saveChangesErrorTitle", "Could not save changes"),
@@ -779,8 +1175,7 @@ const EmbedPdfViewerContent = ({
);
// Store the page to restore after file replacement
- pendingScrollRestoreRef.current = pageToRestore;
- scrollRestoreAttemptsRef.current = 0;
+ queueScrollRestore(pageToRestore, true);
// Store the rotation to restore after file replacement
pendingRotationRestoreRef.current = currentRotation;
@@ -849,8 +1244,7 @@ const EmbedPdfViewerContent = ({
selectedTool ?? "multiTool",
);
- pendingScrollRestoreRef.current = pageToRestore;
- scrollRestoreAttemptsRef.current = 0;
+ queueScrollRestore(pageToRestore, true);
pendingRotationRestoreRef.current = currentRotation;
rotationRestoreAttemptsRef.current = 0;
@@ -918,8 +1312,7 @@ const EmbedPdfViewerContent = ({
);
// Store view state to restore after file replacement
- pendingScrollRestoreRef.current = pageToRestore;
- scrollRestoreAttemptsRef.current = 0;
+ queueScrollRestore(pageToRestore, true);
pendingRotationRestoreRef.current = currentRotation;
rotationRestoreAttemptsRef.current = 0;
@@ -932,8 +1325,6 @@ const EmbedPdfViewerContent = ({
// Clear flags
hasAnnotationChangesRef.current = false;
setRedactionsApplied(false);
-
- console.log("[Viewer] Applied redactions saved, pending marks discarded");
} catch (error) {
console.error("Failed to save applied redactions:", error);
}
@@ -966,6 +1357,8 @@ const EmbedPdfViewerContent = ({
}
}
hasAnnotationChangesRef.current = false;
+ historyRevisionRef.current = 0;
+ savedHistoryRevisionRef.current = 0;
},
});
return () => unregisterNavigationWarningHandlers();
@@ -977,11 +1370,241 @@ const EmbedPdfViewerContent = ({
unregisterNavigationWarningHandlers,
]);
+ // Veto the byte swap for a key whose visual state is already on screen.
+ const shouldSkipBytes = useCallback((stableKey: string) => {
+ const skipKey = skipReloadContentKeyRef.current;
+ if (skipKey && skipKey === stableKey) {
+ skipReloadContentKeyRef.current = null;
+ return true;
+ }
+ return false;
+ }, []);
+
+ // Carry the reading position across an in-place reload; a genuinely different
+ // document starts fresh.
+ const previousDocumentRef = useRef<{
+ root: string | null;
+ content: string | null;
+ encrypted: boolean;
+ } | null>(null);
+ useLayoutEffect(() => {
+ const root = currentFileRootId ?? null;
+ const content = currentFileId;
+ const encrypted = isCurrentFileEncrypted;
+ const previous = previousDocumentRef.current;
+ previousDocumentRef.current = { root, content, encrypted };
+
+ if (!previous || !root || !content) return;
+ if (previous.encrypted || encrypted) return;
+ if (previous.root !== root || previous.content === content) return;
+
+ const page = getScrollState().currentPage || lastKnownScrollPageRef.current;
+ if (page > 0) {
+ // Captures the within-page offset and waits for the replacement node, so
+ // the restore cannot apply to the outgoing document.
+ queueScrollRestore(page, true);
+ }
+
+ pendingRotationRestoreRef.current = getRotationState().rotation ?? 0;
+ rotationRestoreAttemptsRef.current = 0;
+
+ const zoom = getZoomState();
+ // Automatic re-evaluates against the unmounted shell; preserve the numeric scale.
+ const level =
+ zoom.level === ZoomMode.Automatic && typeof zoom.currentZoom === "number"
+ ? zoom.currentZoom
+ : (zoom.level ?? zoom.currentZoom);
+ if (level !== undefined && level !== null) {
+ pendingZoomRestoreRef.current = level;
+ zoomRestoreAttemptsRef.current = 0;
+ zoomRestorePendingRef.current = true;
+ }
+
+ pendingSpreadRestoreRef.current = getSpreadState().spreadMode ?? null;
+
+ setRestoreTick((tick) => tick + 1);
+ }, [
+ currentFileRootId,
+ currentFileId,
+ isCurrentFileEncrypted,
+ getScrollState,
+ getRotationState,
+ getZoomState,
+ getSpreadState,
+ queueScrollRestore,
+ ]);
// Restore scroll position after file replacement or tool switch
// Uses polling with retries to ensure the scroll succeeds
useEffect(() => {
if (pendingScrollRestoreRef.current === null) return;
+ const pageToRestore = pendingScrollRestoreRef.current;
+ // A tool output can take seconds to land, so retries are bounded by time,
+ // not a frame count.
+ const deadline = performance.now() + 30_000;
+ // The effect re-runs as the viewer's state settles; retire old chains so a
+ // stale fallback cannot clear the position the current chain just applied.
+ let cancelled = false;
+ // Frame-accurate retries: the replacement document paints its own top for
+ // as long as it takes to re-apply, so waiting whole intervals is visible.
+ const retry = () => {
+ if (cancelled) return;
+ scrollRestoreAttemptsRef.current++;
+ requestAnimationFrame(attemptScroll);
+ };
+
+ const finish = () => {
+ if (cancelled) return;
+ pendingScrollRestoreRef.current = null;
+ scrollRestoreAttemptsRef.current = 0;
+ swapTargetRef.current = null;
+ swapLayoutRef.current = null;
+ clearPendingScrollRestore();
+ };
+
+ const attemptScroll = () => {
+ if (cancelled) return;
+ const currentState = getScrollState();
+ const targetPage = Math.min(pageToRestore, currentState.totalPages);
+ const captured = pendingScrollPositionRef.current;
+ if (captured) {
+ // An exact capture never falls back to the page top; wait for the
+ // replacement (or apply straight away for a same-document restore).
+ if (
+ !applyPendingScrollPosition({
+ useFraction: pendingZoomRestoreRef.current !== null,
+ })
+ ) {
+ if (performance.now() < deadline) {
+ retry();
+ } else {
+ finish();
+ }
+ return;
+ }
+ pendingScrollRestoreRef.current = null;
+ scrollRestoreAttemptsRef.current = 0;
+ return;
+ }
+
+ // Only attempt if we have valid state (totalPages > 0 means PDF is loaded)
+ if (currentState.totalPages > 0 && targetPage > 0) {
+ scrollActions.scrollToPage(targetPage, "instant");
+
+ // Check if scroll succeeded after a brief delay
+ setTimeout(() => {
+ if (cancelled) return;
+ const afterState = getScrollState();
+ if (afterState.currentPage === targetPage) {
+ finish();
+ } else if (performance.now() < deadline) {
+ retry();
+ } else {
+ finish();
+ }
+ }, 50);
+ } else if (performance.now() < deadline) {
+ retry();
+ } else {
+ finish();
+ }
+ };
+
+ // Start on the next frame so the swapped document's DOM is favoured.
+ const timer = setTimeout(attemptScroll, 0);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [
+ restoreTick,
+ scrollState.totalPages,
+ scrollActions,
+ getScrollState,
+ applyPendingScrollPosition,
+ clearPendingScrollRestore,
+ ]);
+
+ // The swap bridge reports activation; reused page nodes need this layout-pass
+ // backstop to apply the position before paint.
+ const handleDocumentSwapped = useCallback(() => {
+ documentSwappedRef.current = true;
+ const zoomToRestore = pendingZoomRestoreRef.current;
+ if (zoomToRestore !== null) {
+ // The incoming document is still hidden, so a carried mode or level can
+ // land before anything is shown.
+ try {
+ const current = getZoomState();
+ const alreadyApplied =
+ current.level === zoomToRestore &&
+ (typeof zoomToRestore !== "number" ||
+ Math.abs((current.currentZoom ?? 0) - zoomToRestore) < 0.001);
+ if (!alreadyApplied) {
+ zoomActions.requestZoom(zoomToRestore);
+ }
+ } catch {
+ // Handled by retry effect
+ }
+ }
+ const spreadToRestore = pendingSpreadRestoreRef.current;
+ if (spreadToRestore !== null) {
+ try {
+ if (spreadActions.getSpreadMode() !== spreadToRestore) {
+ spreadActions.setSpreadMode(spreadToRestore);
+ }
+ } catch {
+ // Handled by retry effect
+ }
+ }
+ const rotationToRestore = pendingRotationRestoreRef.current;
+ if (rotationToRestore !== null && rotationToRestore !== 0) {
+ try {
+ if (rotationActions.getRotation() !== rotationToRestore) {
+ rotationActions.setRotation(rotationToRestore);
+ }
+ } catch {
+ // Handled by retry effect
+ }
+ }
+ if (pendingScrollRestoreRef.current === null) return;
+ if (!pendingScrollPositionRef.current) return;
+ if (pendingScrollSwappedRef.current) return;
+ applyPendingScrollPosition({
+ useFraction: pendingZoomRestoreRef.current !== null,
+ });
+ }, [applyPendingScrollPosition, zoomActions, spreadActions, rotationActions]);
+
+ const handleDocumentSwapFailed = useCallback(() => {
+ clearPendingScrollRestore();
+ }, [clearPendingScrollRestore]);
+ useLayoutEffect(() => {
+ if (!restorePending) return;
+ if (pendingScrollRestoreRef.current === null) return;
+ if (!pendingScrollPositionRef.current) return;
+ if (!documentSwappedRef.current) return;
+ if (pendingScrollSwappedRef.current) return;
+ applyPendingScrollPosition({
+ useFraction: pendingZoomRestoreRef.current !== null,
+ });
+ });
+
+ // Runs from the layout pass that mounts the replacement's pages, so the saved
+ // position lands before their first frame paints.
+ const handleViewerPageLayout = useCallback(() => {
+ if (pendingScrollRestoreRef.current === null) return;
+ if (!pendingScrollPositionRef.current) return;
+ if (pendingScrollSwappedRef.current) return;
+ applyPendingScrollPosition({
+ useFraction: pendingZoomRestoreRef.current !== null,
+ });
+ }, [applyPendingScrollPosition]);
+
+ // Never leave the viewer hidden or holding a scroll if this unmounts mid-swap.
+ useEffect(() => clearPendingScrollRestore, [clearPendingScrollRestore]);
+ // Uses polling with retries to ensure the scroll succeeds
+ useEffect(() => {
+ if (pendingScrollRestoreRef.current === null) return;
+
const pageToRestore = pendingScrollRestoreRef.current;
const maxAttempts = 10;
const attemptInterval = 100; // ms between attempts
@@ -990,6 +1613,10 @@ const EmbedPdfViewerContent = ({
const currentState = getScrollState();
const targetPage = Math.min(pageToRestore, currentState.totalPages);
+ // An exact-offset capture is restored by the layout attempt and held by
+ // the reassert chain; the page-level fallback would snap to the page top.
+ if (pendingScrollPositionRef.current) return;
+
// Only attempt if we have valid state (totalPages > 0 means PDF is loaded)
if (currentState.totalPages > 0 && targetPage > 0) {
scrollActions.scrollToPage(targetPage, "instant");
@@ -1015,7 +1642,7 @@ const EmbedPdfViewerContent = ({
scrollRestoreAttemptsRef.current = 0;
}
}
- }, 50);
+ }, 100);
} else if (scrollRestoreAttemptsRef.current < maxAttempts) {
// PDF not ready yet, retry
scrollRestoreAttemptsRef.current++;
@@ -1027,13 +1654,13 @@ const EmbedPdfViewerContent = ({
}
};
- // Start attempting after initial delay
- const timer = setTimeout(attemptScroll, 150);
+ // Start attempting after initial delay to let PDF start loading
+ const timer = setTimeout(attemptScroll, 200);
return () => clearTimeout(timer);
- }, [scrollState.totalPages, scrollActions, getScrollState]);
+ }, [restoreTick, scrollState.totalPages, scrollActions, getScrollState]);
// Restore rotation after file replacement or tool switch
- // Uses polling with retries to ensure the rotation succeeds
+ // Uses polling with retries to ensure rotation is applied
useEffect(() => {
if (pendingRotationRestoreRef.current === null) return;
@@ -1042,20 +1669,28 @@ const EmbedPdfViewerContent = ({
const attemptInterval = 100; // ms between attempts
const attemptRotation = () => {
- const currentState = getScrollState();
+ if (
+ pendingScrollPositionRef.current?.expectSwap &&
+ !documentSwappedRef.current
+ ) {
+ return;
+ }
+ if (getScrollState().totalPages > 0) {
+ // Check if rotation already matches
+ const currentRotation = rotationActions.getRotation();
+ if (currentRotation === rotationToRestore) {
+ pendingRotationRestoreRef.current = null;
+ rotationRestoreAttemptsRef.current = 0;
+ return;
+ }
- // Only attempt if PDF is loaded (totalPages > 0)
- if (currentState.totalPages > 0) {
+ // Apply rotation
rotationActions.setRotation(rotationToRestore);
- // Check if rotation succeeded after a brief delay
+ // Verify rotation succeeded after a brief delay
setTimeout(() => {
- const currentRotation = rotationActions.getRotation();
- if (
- currentRotation === rotationToRestore ||
- rotationRestoreAttemptsRef.current >= maxAttempts
- ) {
- // Success or max attempts reached - clear pending
+ const afterRotation = rotationActions.getRotation();
+ if (afterRotation === rotationToRestore) {
pendingRotationRestoreRef.current = null;
rotationRestoreAttemptsRef.current = 0;
} else {
@@ -1084,8 +1719,128 @@ const EmbedPdfViewerContent = ({
// Start attempting after initial delay
const timer = setTimeout(attemptRotation, 150);
return () => clearTimeout(timer);
- }, [scrollState.totalPages, rotationActions, getScrollState]);
+ }, [restoreTick, scrollState.totalPages, rotationActions, getScrollState]);
+
+ // A replacement starts single-page, so the spread lands before the reading
+ // position settles or the pages reflow under it.
+ useEffect(() => {
+ if (pendingSpreadRestoreRef.current === null) return;
+
+ const modeToRestore = pendingSpreadRestoreRef.current;
+ const maxAttempts = 10;
+ const attemptInterval = 100;
+
+ const attemptSpread = () => {
+ if (
+ pendingScrollPositionRef.current?.expectSwap &&
+ !documentSwappedRef.current
+ ) {
+ return;
+ }
+ if (getScrollState().totalPages > 0) {
+ pendingSpreadRestoreRef.current = null;
+ if (spreadActions.getSpreadMode() !== modeToRestore) {
+ spreadActions.setSpreadMode(modeToRestore);
+ // The spread reflows the pages, so any held position has to be
+ // recomputed against the new geometry.
+ swapLayoutRef.current = null;
+ swapTargetRef.current = null;
+ if (pendingScrollPositionRef.current) {
+ applyPendingScrollPosition({ useFraction: true });
+ }
+ }
+ return;
+ }
+ spreadRestoreAttemptsRef.current++;
+ if (spreadRestoreAttemptsRef.current < maxAttempts) {
+ setTimeout(attemptSpread, attemptInterval);
+ } else {
+ pendingSpreadRestoreRef.current = null;
+ spreadRestoreAttemptsRef.current = 0;
+ }
+ };
+
+ const timer = setTimeout(attemptSpread, 150);
+ return () => clearTimeout(timer);
+ }, [restoreTick, scrollState.totalPages, spreadActions, getScrollState]);
+ // Re-asserts the carried zoom until it sticks; the plugin's own fit pass can
+ // override the first request and zoomRestorePendingRef keeps the UI quiet.
+ useEffect(() => {
+ const levelToRestore = pendingZoomRestoreRef.current;
+ if (levelToRestore === null) return;
+
+ let cancelled = false;
+ // Matches the reveal cap: the scroller stays hidden until this loop either
+ // lands the zoom or runs out, so the two deadlines must not disagree.
+ const deadline = performance.now() + SWAP_REVEAL_DEADLINE_MS;
+
+ const matchesLevel = () => {
+ const current = getZoomState();
+ if (current.level !== levelToRestore) return false;
+ return (
+ typeof levelToRestore !== "number" ||
+ Math.abs((current.currentZoom ?? 0) - levelToRestore) < 0.001
+ );
+ };
+
+ const attemptZoom = () => {
+ if (cancelled) return;
+ // A byte replacement must land before this document's zoom can apply.
+ if (
+ pendingScrollPositionRef.current?.expectSwap &&
+ !documentSwappedRef.current
+ ) {
+ if (performance.now() < deadline) {
+ setTimeout(attemptZoom, 100);
+ }
+ return;
+ }
+ if (getScrollState().totalPages === 0) {
+ if (performance.now() < deadline) {
+ setTimeout(attemptZoom, 100);
+ } else {
+ pendingZoomRestoreRef.current = null;
+ settleZoomRestore();
+ }
+ return;
+ }
+ if (matchesLevel()) {
+ pendingZoomRestoreRef.current = null;
+ zoomRestoreAttemptsRef.current = 0;
+ settleZoomRestore();
+ return;
+ }
+
+ try {
+ zoomActions.requestZoom(levelToRestore);
+ } catch {
+ // Retried below while the deadline holds.
+ }
+ // The rescale moves the page geometry, so re-apply the reading offset.
+ applyPendingScrollPosition({ useFraction: true });
+ if (performance.now() < deadline) {
+ setTimeout(attemptZoom, 100);
+ } else {
+ pendingZoomRestoreRef.current = null;
+ settleZoomRestore();
+ }
+ };
+
+ const timer = setTimeout(attemptZoom, 0);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [
+ restoreTick,
+ scrollState.totalPages,
+ zoomActions,
+ getScrollState,
+ getZoomState,
+ applyPendingScrollPosition,
+ settleZoomRestore,
+ ]);
// Register applyChanges with ViewerContext so tools can access it directly
useEffect(() => {
setApplyChanges(applyChanges);
@@ -1256,7 +2011,12 @@ const EmbedPdfViewerContent = ({
}}
>
<LocalEmbedPDF
- key={currentFileId || "no-file"}
+ key={currentFileRootId || "no-file"}
+ shouldSkipBytes={shouldSkipBytes}
+ onPageLayout={handleViewerPageLayout}
+ onDocumentSwapped={handleDocumentSwapped}
+ onDocumentSwapFailed={handleDocumentSwapFailed}
+ restorePending={restorePending}
pdfRenderMode={pdfRenderMode}
file={effectiveFile.file}
url={effectiveFile.url}
diff --git a/frontend/editor/src/core/components/viewer/HistoryAPIBridge.tsx b/frontend/editor/src/core/components/viewer/HistoryAPIBridge.tsx
index 28a32cd067..7d5d9f7011 100644
--- a/frontend/editor/src/core/components/viewer/HistoryAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/HistoryAPIBridge.tsx
@@ -40,6 +40,7 @@ export const HistoryAPIBridge = forwardRef<HistoryAPI>(
const handleAnnotationEvent = (event: AnnotationEvent) => {
if (event.type === "loaded") return;
+
const annotation: SignatureAnnotation = event.annotation;
// Store image data for all STAMP annotations immediately when created or modified
@@ -174,14 +175,14 @@ export const HistoryAPIBridge = forwardRef<HistoryAPI>(
};
// Add the event listener
- annotationApi.onAnnotationEvent(handleAnnotationEvent);
+ const unsubscribe = annotationApi.onAnnotationEvent(
+ handleAnnotationEvent,
+ );
- // Cleanup function
return () => {
- // Note: EmbedPDF doesn't provide a way to remove event listeners
- // This is a limitation of the current API
+ unsubscribe();
};
- }, [annotationApi, getImageData, storeImageData]);
+ }, [annotationApi, documentReady, getImageData, storeImageData]);
useImperativeHandle(
ref,
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index 7d6b92d81d..f84f413744 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -2,11 +2,13 @@ import React, {
useCallback,
useEffect,
useImperativeHandle,
+ useLayoutEffect,
useMemo,
+ useRef,
useState,
} from "react";
-import { createPluginRegistration } from "@embedpdf/core";
-import type { PluginRegistry } from "@embedpdf/core";
+import { createPluginRegistration, type PluginRegistry } from "@embedpdf/core";
+import type { InitialDocumentOptions } from "@embedpdf/plugin-document-manager";
import { EmbedPDF, useDocumentState } from "@embedpdf/core/react";
import { usePdfiumEngine } from "@embedpdf/engines/react";
import { PrivateContent } from "@app/components/shared/PrivateContent";
@@ -75,6 +77,7 @@ import { HistoryAPIBridge } from "@app/components/viewer/HistoryAPIBridge";
import type {
SignatureAPI,
AnnotationAPI,
+ AnnotationMenuAnchor,
HistoryAPI,
SignaturePreview,
SignatureOverlayAPI,
@@ -90,6 +93,9 @@ 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 { AnnotationMenuEvents } from "@app/components/viewer/AnnotationMenuEvents";
+import { DocumentSwapBridge } from "@app/components/viewer/DocumentSwapBridge";
+import { AnnotationDeletedMenu } from "@app/components/viewer/AnnotationDeletedMenu";
import { TextSelectionMenu } from "@app/components/viewer/TextSelectionMenu";
import {
RedactionPendingTracker,
@@ -151,6 +157,16 @@ interface LocalEmbedPDFProps {
onSignaturePreviewsChange?: (previews: SignaturePreview[]) => void;
/** Imperative handle for reading/clearing/deleting signature previews. */
signatureOverlayApiRef?: React.RefObject<SignatureOverlayAPI | null>;
+ /** Veto for a swap the mounted document already shows; must be stable. */
+ shouldSkipBytes?: (stableKey: string) => boolean;
+ /** Fires from the layout pass that mounts a page, before it paints. */
+ onPageLayout?: () => void;
+ /** Fires when the swap bridge activates a replacement document. */
+ onDocumentSwapped?: () => void;
+ /** Fires when the swap bridge fails to open or activate a replacement document. */
+ onDocumentSwapFailed?: (error: unknown) => void;
+ /** True while a view restore is in flight; gates the per-page layout hook. */
+ restorePending?: boolean;
}
interface ViewerPageContainerProps {
@@ -159,6 +175,10 @@ interface ViewerPageContainerProps {
width: number;
height: number;
children: React.ReactNode;
+ /** Runs in the same layout pass that mounts a page, before it paints. */
+ onPageLayout?: () => void;
+ /** Gates the layout callback so steady-state scrolling pays nothing. */
+ restorePending?: boolean;
}
function normalizePageRotation(rotation: number | null | undefined): number {
@@ -173,12 +193,19 @@ function ViewerPageContainer({
width,
height,
children,
+ onPageLayout,
+ restorePending = false,
}: ViewerPageContainerProps) {
const documentState = useDocumentState(documentId);
const pageRotation = normalizePageRotation(
documentState?.document?.pages?.[pageIndex]?.rotation,
);
+ useLayoutEffect(() => {
+ if (!restorePending) return;
+ onPageLayout?.();
+ });
+
return (
<div
data-page-index={pageIndex}
@@ -233,6 +260,11 @@ export function LocalEmbedPDF({
signaturePlacementType,
onSignaturePreviewsChange,
signatureOverlayApiRef,
+ shouldSkipBytes,
+ onPageLayout,
+ onDocumentSwapped,
+ onDocumentSwapFailed,
+ restorePending = false,
}: LocalEmbedPDFProps) {
const { t } = useTranslation();
const { config } = useAppConfig();
@@ -310,77 +342,194 @@ export function LocalEmbedPDF({
// FileContext produces new File object references for the same file content.
const fileStableKey =
fileId ?? (file ? `${(file as File).name}-${file.size}` : null);
- useEffect(() => {
- if (url) {
- setPdfUrl(url);
- return;
- }
- if (file) {
- const objectUrl = URL.createObjectURL(file);
- setPdfUrl(objectUrl);
- return () => URL.revokeObjectURL(objectUrl);
- }
- // When file is present, use the stable key to avoid blob URL churn from FileContext
- // re-renders. When only url is provided, depend on url directly so changes are picked up.
- }, [url, file ? fileStableKey : null]);
- const [pdfBuffer, setPdfBuffer] = useState<ArrayBuffer | null>(null);
+ // Keyed by fileStableKey to avoid recomputing on every FileContext re-render.
+ const exportFileName = useMemo(() => {
+ if (fileName) return fileName;
+ if (file && "name" in file) return (file as File).name;
+ if (url) return url.split("/").pop()?.split("?")[0] || "document.pdf";
+ return "document.pdf";
+ }, [fileStableKey, fileName, url]);
+
+ // The first document goes through the registry; replacements open in the
+ // background and activate once ready, so the viewer never blanks.
+ const [initialDocument, setInitialDocument] = useState<{
+ buffer: ArrayBuffer;
+ name: string;
+ } | null>(null);
+ const [pendingDocument, setPendingDocument] = useState<{
+ buffer: ArrayBuffer;
+ name: string;
+ } | null>(null);
+ const initialDocumentOpenedRef = useRef(false);
+ const openedContentKeyRef = useRef<string | null>(null);
+ // Anchors survive deselection per annotation id, so a delete that happens
+ // while no menu is open (keyboard, sidebar) still has somewhere to appear.
+ const annotationAnchorsByIdRef = useRef<Map<string, AnnotationMenuAnchor>>(
+ new Map(),
+ );
+ const [deletedAnnotationMenu, setDeletedAnnotationMenu] =
+ useState<AnnotationMenuAnchor | null>(null);
+ const handleAnnotationMenuAnchor = useCallback(
+ (anchor: AnnotationMenuAnchor | null) => {
+ if (anchor) {
+ annotationAnchorsByIdRef.current.set(anchor.annotationId, anchor);
+ }
+ },
+ [],
+ );
+ const getAnnotationAnchor = useCallback(
+ (annotationId: string) =>
+ // Only the anchor keyed by this annotation: falling back to the
+ // last-open menu would pin a deletion to another annotation's spot.
+ annotationAnchorsByIdRef.current.get(annotationId) ?? null,
+ [],
+ );
+ const handleAnnotationDeleted = useCallback(
+ (anchor: AnnotationMenuAnchor) => setDeletedAnnotationMenu(anchor),
+ [],
+ );
+ const dismissDeletedAnnotationMenu = useCallback(
+ () => setDeletedAnnotationMenu(null),
+ [],
+ );
+ // The published blob URL is revoked by its replacement or on unmount, never
+ // by the effect run that decided to skip a swap.
+ const publishedObjectUrlRef = useRef<string | null>(null);
+ const revokeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- // Read file/url directly into an ArrayBuffer on the main thread so EmbedPDF's worker
- // receives the document data via buffer rather than failing to fetch partitioned blob URLs.
+ // Reads bytes on the main thread for the worker, and lands bytes plus URL in
+ // one commit so the registry rebuilds once per replacement.
useEffect(() => {
+ if (fileStableKey && shouldSkipBytes?.(fileStableKey)) {
+ // The live document already shows this save; swapping the bytes would
+ // reopen it and lose the scroll position for no visual gain.
+ return;
+ }
let cancelled = false;
- setPdfBuffer(null);
+ let objectUrl: string | null = null;
+ const openDocument = (
+ buffer: ArrayBuffer,
+ name: string,
+ contentKey: string | null,
+ ) => {
+ // A repeat run for the same content (a rename, a FileContext churn) must
+ // not reopen the document.
+ if (!contentKey || openedContentKeyRef.current === contentKey) return;
+ openedContentKeyRef.current = contentKey;
+ if (!initialDocumentOpenedRef.current) {
+ initialDocumentOpenedRef.current = true;
+ setInitialDocument({ buffer, name });
+ return;
+ }
+ setPendingDocument({ buffer, name });
+ };
+ const fail = (source: string) => (err: unknown) => {
+ console.error(
+ `[LocalEmbedPDF] Failed to read ${source} arrayBuffer:`,
+ err,
+ );
+ };
if (file && typeof (file as Blob).arrayBuffer === "function") {
(file as Blob)
.arrayBuffer()
.then((buf) => {
- if (!cancelled) setPdfBuffer(buf);
+ if (cancelled) return;
+ objectUrl = URL.createObjectURL(file);
+ const previous = publishedObjectUrlRef.current;
+ publishedObjectUrlRef.current = objectUrl;
+ openDocument(buf, exportFileName, fileStableKey);
+ setPdfUrl(objectUrl);
+ if (previous && previous !== objectUrl) {
+ URL.revokeObjectURL(previous);
+ }
})
- .catch((err) => {
- console.error(
- "[LocalEmbedPDF] Failed to read file arrayBuffer:",
- err,
- );
- });
- return () => {
- cancelled = true;
- };
- }
- if (url) {
+ .catch(fail("file"));
+ } else if (url) {
+ setPdfUrl(url);
fetch(url)
.then((r) => r.arrayBuffer())
.then((buf) => {
- if (!cancelled) setPdfBuffer(buf);
+ if (!cancelled) openDocument(buf, exportFileName, url);
})
- .catch((err) => {
- console.error(
- "[LocalEmbedPDF] Failed to fetch url arrayBuffer:",
- err,
- );
- });
- return () => {
- cancelled = true;
- };
+ .catch(fail("url"));
+ } else {
+ initialDocumentOpenedRef.current = false;
+ openedContentKeyRef.current = null;
+ setInitialDocument(null);
+ setPendingDocument(null);
+ setPdfUrl(null);
}
- setPdfBuffer(null);
- }, [file ? fileStableKey : null, url]);
+ return () => {
+ cancelled = true;
+ // Revokes only URLs that never reached state; the published one is
+ // replaced or revoked on real unmount below.
+ if (objectUrl && publishedObjectUrlRef.current !== objectUrl) {
+ URL.revokeObjectURL(objectUrl);
+ }
+ };
+ }, [file ? fileStableKey : null, url, shouldSkipBytes, exportFileName]);
- // Keyed by fileStableKey to avoid recomputing on every FileContext re-render.
- const exportFileName = useMemo(() => {
- if (fileName) return fileName;
- if (file && "name" in file) return (file as File).name;
- if (url) return url.split("/").pop()?.split("?")[0] || "document.pdf";
- return "document.pdf";
- }, [fileStableKey, fileName, url]);
+ useEffect(() => {
+ // A pending revocation belongs to a previous mount of this effect; cancel
+ // it so React's strict-mode simulated unmount cannot revoke the live URL.
+ if (revokeTimerRef.current !== null) {
+ clearTimeout(revokeTimerRef.current);
+ revokeTimerRef.current = null;
+ }
+ return () => {
+ revokeTimerRef.current = setTimeout(() => {
+ revokeTimerRef.current = null;
+ const urlToRevoke = publishedObjectUrlRef.current;
+ publishedObjectUrlRef.current = null;
+ if (urlToRevoke) URL.revokeObjectURL(urlToRevoke);
+ }, 0);
+ };
+ }, []);
+
+ const [swapAnnouncement, setSwapAnnouncement] = useState<string | null>(null);
+
+ const handleDocumentSwapped = useCallback(() => {
+ onDocumentSwapped?.();
+ setPendingDocument(null);
+ setSwapAnnouncement(t("viewer.documentUpdated", "Document updated"));
+ setTimeout(() => setSwapAnnouncement(null), 3000);
+ }, [onDocumentSwapped, t]);
+ const handleDocumentSwapFailed = useCallback(
+ (error: unknown) => {
+ // The outgoing document stays active; the replacement never landed.
+ console.warn(
+ "[LocalEmbedPDF] Replacement document failed to open:",
+ error,
+ );
+ onDocumentSwapFailed?.(error);
+ setPendingDocument(null);
+ },
+ [onDocumentSwapFailed],
+ );
+
+ useEffect(() => {
+ // A replacement document has no relation to the deleted annotation.
+ setDeletedAnnotationMenu(null);
+ annotationAnchorsByIdRef.current.clear();
+ }, [fileStableKey]);
+
+ // The registry is built from the viewer's first source; later bytes arrive
+ // through DocumentSwapBridge, so no replacement may change that identity.
+ const urlDocumentSource = file ? null : pdfUrl;
+ const urlPluginsSource = useMemo(() => {
+ if (file || !urlDocumentSource) return null;
+ return { url: urlDocumentSource, name: exportFileName };
+ }, [!!file, urlDocumentSource, exportFileName]);
// Create plugins configuration
const plugins = useMemo(() => {
- // When a File object is the source, we MUST wait for the buffer, the
- // worker cannot fetch partitioned blob: URLs. pdfUrl is still created
- // (for thumbnails etc.) but plugins must not start until the buffer lands.
- if (file && !pdfBuffer) return [];
- if (!pdfBuffer && !pdfUrl) return [];
+ const initialSource = initialDocument ?? urlPluginsSource;
+ if (!initialSource) return [];
+ const initialDocuments: InitialDocumentOptions[] =
+ "buffer" in initialSource
+ ? [{ buffer: initialSource.buffer, name: initialSource.name }]
+ : [{ url: initialSource.url, name: initialSource.name }];
// Calculate 3.5rem in pixels dynamically based on root font size
const rootFontSize = parseFloat(
@@ -390,21 +539,7 @@ export function LocalEmbedPDF({
return [
createPluginRegistration(DocumentManagerPluginPackage, {
- initialDocuments: pdfBuffer
- ? [
- {
- buffer: pdfBuffer,
- name: exportFileName,
- },
- ]
- : pdfUrl
- ? [
- {
- url: pdfUrl,
- name: exportFileName,
- },
- ]
- : [],
+ initialDocuments,
}),
createPluginRegistration(ViewportPluginPackage, {
viewportGap,
@@ -486,7 +621,7 @@ export function LocalEmbedPDF({
createPluginRegistration(PrintPluginPackage),
];
- }, [!!file, pdfBuffer, pdfUrl, enableAnnotations, exportFileName]);
+ }, [initialDocument, urlPluginsSource, enableAnnotations]);
const fontFallbackConfig = useMemo(() => getLocalFontFallbackConfig(), []);
@@ -550,7 +685,7 @@ export function LocalEmbedPDF({
}
const hasInput = Boolean(file || url);
- const isInputReady = Boolean(pdfBuffer || (!file && pdfUrl));
+ const isInputReady = Boolean(initialDocument || (!file && pdfUrl));
if (isLoading || !engine || (hasInput && !isInputReady)) {
return (
@@ -600,6 +735,7 @@ export function LocalEmbedPDF({
return (
<PrivateContent>
<div
+ aria-busy={pendingDocument !== null}
style={{
height: "100%",
width: "100%",
@@ -609,6 +745,9 @@ export function LocalEmbedPDF({
minWidth: 0,
}}
>
+ <span className="sr-only" aria-live="polite" aria-atomic="true">
+ {swapAnnouncement}
+ </span>
<EmbedPDF
engine={engine}
plugins={plugins}
@@ -621,7 +760,7 @@ export function LocalEmbedPDF({
if (!annotationApi) return;
if (enableAnnotations) {
- // LooseAnnotationTool bypasses strict Partial<T> defaults typing from the library —
+ // LooseAnnotationTool bypasses strict Partial<T> defaults typing from the library:
// EmbedPDF accepts extra runtime properties (borderWidth, textColor, finishOnDoubleClick,
// etc.) that aren't reflected in the TypeScript model types.
type LooseAnnotationTool = {
@@ -1100,6 +1239,11 @@ export function LocalEmbedPDF({
}
}}
>
+ <DocumentSwapBridge
+ pending={pendingDocument}
+ onSwapped={handleDocumentSwapped}
+ onFailed={handleDocumentSwapFailed}
+ />
<ZoomAPIBridge />
<ScrollAPIBridge />
<SelectionAPIBridge />
@@ -1112,6 +1256,18 @@ export function LocalEmbedPDF({
{(enableAnnotations || enableRedaction || isManualRedactionMode) && (
<HistoryAPIBridge ref={historyApiRef} />
)}
+ {(enableAnnotations || enableRedaction || isManualRedactionMode) && (
+ <>
+ <AnnotationMenuEvents
+ getAnchor={getAnnotationAnchor}
+ onDeleted={handleAnnotationDeleted}
+ />
+ <AnnotationDeletedMenu
+ anchor={deletedAnnotationMenu}
+ onDismiss={dismissDeletedAnnotationMenu}
+ />
+ </>
+ )}
{/* Always render RedactionAPIBridge when in manual redaction mode so buttons can switch from annotation mode */}
{(enableRedaction || isManualRedactionMode) && <RedactionAPIBridge />}
{/* Always render SignatureAPIBridge so annotation tools (draw) can be activated even when starting in redaction mode */}
@@ -1172,6 +1328,8 @@ export function LocalEmbedPDF({
pageIndex={pageIndex}
width={width}
height={height}
+ onPageLayout={onPageLayout}
+ restorePending={restorePending}
>
<div
style={{
@@ -1280,7 +1438,10 @@ export function LocalEmbedPDF({
pageIndex={pageIndex}
selectionOutline={{ color: "#007ACC" }}
selectionMenu={(props) => (
- <AnnotationSelectionMenu {...props} />
+ <AnnotationSelectionMenu
+ {...props}
+ onAnchor={handleAnnotationMenuAnchor}
+ />
)}
style={
!showBakedAnnotations
diff --git a/frontend/editor/src/core/components/viewer/PdfViewerToolbar.tsx b/frontend/editor/src/core/components/viewer/PdfViewerToolbar.tsx
index ec0af3ee72..0d12b11d17 100644
--- a/frontend/editor/src/core/components/viewer/PdfViewerToolbar.tsx
+++ b/frontend/editor/src/core/components/viewer/PdfViewerToolbar.tsx
@@ -38,6 +38,8 @@ export function PdfViewerToolbar({
scrollActions,
zoomActions,
spreadActions,
+ zoomRestorePendingRef,
+ zoomRestoreSettledTick,
registerImmediateZoomUpdate,
registerImmediateScrollUpdate,
registerImmediateSpreadUpdate,
@@ -52,7 +54,7 @@ export function PdfViewerToolbar({
scrollState.currentPage || currentPage,
);
const [displayZoomPercent, setDisplayZoomPercent] = useState(
- zoomState.zoomPercent || 140,
+ () => zoomState.zoomPercent || 100,
);
const [isDualPageActive, setIsDualPageActive] = useState(
spreadState.isDualPage,
@@ -71,14 +73,25 @@ export function PdfViewerToolbar({
};
}, [registerImmediateScrollUpdate, scrollState.currentPage]);
- // Register for immediate zoom updates and sync with actual zoom state
+ // A carried zoom's fit pass is intermediate, so the readout holds until its
+ // settled tick re-syncs from the live state.
useEffect(() => {
- const unregister = registerImmediateZoomUpdate(setDisplayZoomPercent);
- setDisplayZoomPercent(zoomState.zoomPercent || 140);
+ const unregister = registerImmediateZoomUpdate((percent) => {
+ if (zoomRestorePendingRef.current) return;
+ setDisplayZoomPercent(percent);
+ });
+ if (!zoomRestorePendingRef.current) {
+ setDisplayZoomPercent(zoomState.zoomPercent || 100);
+ }
return () => {
unregister?.();
};
- }, [registerImmediateZoomUpdate, zoomState.zoomPercent]);
+ }, [
+ registerImmediateZoomUpdate,
+ zoomState.zoomPercent,
+ zoomRestorePendingRef,
+ zoomRestoreSettledTick,
+ ]);
useEffect(() => {
const unregister = registerImmediateSpreadUpdate((_mode, isDual) => {
diff --git a/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx b/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx
index 11cddc4f4d..6c37f67c31 100644
--- a/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx
@@ -1,7 +1,8 @@
import { useEffect, useImperativeHandle } from "react";
import { useRedaction as useEmbedPdfRedaction } from "@embedpdf/plugin-redaction/react";
import { PdfAnnotationSubtype } from "@embedpdf/models";
-import { useRedaction } from "@app/contexts/RedactionContext";
+import { useRedaction, useRedactionMode } from "@app/contexts/RedactionContext";
+import { useNavigationState } from "@app/contexts/NavigationContext";
import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
import { useAnnotationCapability } from "@embedpdf/plugin-annotation/react";
import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";
@@ -27,6 +28,8 @@ function RedactionAPIBridgeInner({ documentId }: { documentId: string }) {
const { state, provides: redactionProvides } =
useEmbedPdfRedaction(documentId);
const { provides: annotationProvides } = useAnnotationCapability();
+ const { isRedactionModeActive } = useRedactionMode();
+ const { selectedTool } = useNavigationState();
const {
redactionApiRef,
setPendingCount,
@@ -36,13 +39,22 @@ function RedactionAPIBridgeInner({ documentId }: { documentId: string }) {
manualRedactColor,
} = useRedaction();
- // Mark bridge as ready on mount, not ready on unmount
+ // Ensure EmbedPDF exits redaction mode whenever we are not in redact tool mode
+ useEffect(() => {
+ if (selectedTool !== "redact") {
+ leaveRedactionMode(redactionProvides);
+ }
+ }, [selectedTool, isRedactionModeActive, redactionProvides]);
+
+ // Mark bridge as ready on mount, cleanup on unmount
useEffect(() => {
setBridgeReady(true);
return () => {
setBridgeReady(false);
+ // The scope can belong to a document that a swap already closed.
+ leaveRedactionMode(redactionProvides);
};
- }, [setBridgeReady]);
+ }, [setBridgeReady, redactionProvides]);
// The interaction mode is viewer-global, so a stranded redaction mode would block
// selection for the next document.
diff --git a/frontend/editor/src/core/components/viewer/RedactionSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/RedactionSelectionMenu.tsx
index 2c22fc7e1d..84f3b74191 100644
--- a/frontend/editor/src/core/components/viewer/RedactionSelectionMenu.tsx
+++ b/frontend/editor/src/core/components/viewer/RedactionSelectionMenu.tsx
@@ -2,15 +2,14 @@ import {
useRedaction as useEmbedPdfRedaction,
RedactionSelectionMenuProps,
} from "@embedpdf/plugin-redaction/react";
-import { Tooltip, Group } from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
+import { Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { createPortal } from "react-dom";
import { useEffect, useState, useRef, useCallback } from "react";
import { Icon } from "@app/ui/Icon";
import { useRedaction } from "@app/contexts/RedactionContext";
import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
+import "@app/components/viewer/TextSelectionMenu.css";
export type { RedactionSelectionMenuProps };
@@ -113,55 +112,50 @@ function RedactionSelectionMenuInner({
const menuContent = menuPosition ? (
<div
+ data-redaction-selection-menu
+ className="embedpdf-floating-menu"
style={{
position: "fixed",
top: `${menuPosition.top}px`,
left: `${menuPosition.left}px`,
transform: "translateX(-50%)",
pointerEvents: "auto",
- zIndex: 10000, // Very high z-index to appear above everything
- backgroundColor: "var(--mantine-color-body)",
- borderRadius: 8,
- padding: "8px 12px",
- boxShadow: "0 2px 12px rgba(0, 0, 0, 0.25)",
- border: "1px solid var(--mantine-color-default-border)",
- // Fixed size to prevent browser zoom affecting layout
- fontSize: "14px",
- minWidth: "180px",
+ zIndex: 10000,
}}
>
- <Group gap="sm" wrap="nowrap" justify="center">
- <Tooltip label={t("viewer.redaction.removeMark", "Remove this mark")}>
- <ActionIcon
- aria-label={t("viewer.redaction.removeMark", "Remove this mark")}
- variant="secondary"
- accent="neutral"
- size="md"
- onClick={handleRemove}
- >
- <Icon name="trash" size={18} />
- </ActionIcon>
- </Tooltip>
-
- <Tooltip
- label={t(
- "redact.manual.applyWarning",
- "⚠️ Permanent application, cannot be undone and the data underneath will be deleted",
- )}
- withArrow
- position="top"
+ <Tooltip
+ label={t("viewer.redaction.removeMark", "Remove this mark")}
+ withArrow
+ >
+ <button
+ type="button"
+ className="embedpdf-floating-btn embedpdf-floating-btn-danger"
+ onClick={handleRemove}
+ aria-label={t("viewer.redaction.removeMark", "Remove this mark")}
>
- <Button
- accent="danger"
- size="sm"
- onClick={handleApply}
- leftSection={<Icon name="circle-check" size={16} />}
- style={{ flexShrink: 0, whiteSpace: "nowrap" }}
- >
- Apply (permanent)
- </Button>
- </Tooltip>
- </Group>
+ <Icon name="trash" size={18} />
+ </button>
+ </Tooltip>
+
+ <div className="embedpdf-floating-divider" />
+
+ <Tooltip
+ label={t(
+ "redact.manual.applyWarning",
+ "⚠️ Permanent application, cannot be undone and the data underneath will be deleted",
+ )}
+ withArrow
+ position="top"
+ >
+ <button
+ type="button"
+ className="embedpdf-floating-badge-btn"
+ onClick={handleApply}
+ >
+ <Icon name="circle-check" size={16} />
+ <span>{t("redact.manual.apply", "Apply")}</span>
+ </button>
+ </Tooltip>
</div>
) : null;
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.css b/frontend/editor/src/core/components/viewer/TextSelectionMenu.css
new file mode 100644
index 0000000000..a9d53ae718
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.css
@@ -0,0 +1,121 @@
+.embedpdf-floating-menu,
+.embedpdf-text-selection-menu {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ width: max-content;
+ max-width: calc(100vw - 32px);
+ background: var(--c-floating-menu-bg);
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ border-radius: 10px;
+ padding: 6px 12px;
+ box-shadow:
+ 0 6px 24px rgba(0, 0, 0, 0.45),
+ 0 2px 8px rgba(0, 0, 0, 0.25);
+ color: var(--c-floating-menu-text);
+ user-select: none;
+ backdrop-filter: blur(8px);
+ font-size: 14px;
+ box-sizing: border-box;
+}
+
+.embedpdf-floating-btn,
+.embedpdf-text-selection-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 30px;
+ padding: 0;
+ border-radius: 6px;
+ border: none;
+ background: transparent;
+ color: var(--c-floating-menu-text);
+ cursor: pointer;
+ transition:
+ background-color 0.15s ease,
+ transform 0.1s ease,
+ color 0.15s ease;
+ outline: none;
+ flex-shrink: 0;
+}
+
+.embedpdf-floating-btn:hover:not(:disabled),
+.embedpdf-text-selection-btn:hover:not(:disabled) {
+ background-color: rgba(255, 255, 255, 0.12);
+ color: var(--c-text-on-primary);
+}
+
+.embedpdf-floating-btn:active:not(:disabled),
+.embedpdf-text-selection-btn:active:not(:disabled) {
+ transform: scale(0.92);
+ background-color: rgba(255, 255, 255, 0.18);
+}
+
+.embedpdf-floating-btn:disabled,
+.embedpdf-text-selection-btn:disabled,
+.embedpdf-floating-badge-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.embedpdf-floating-btn:focus-visible,
+.embedpdf-text-selection-btn:focus-visible {
+ box-shadow: 0 0 0 2px color-mix(in srgb, var(--c-primary) 60%, transparent);
+}
+
+.embedpdf-floating-btn-danger {
+ color: var(--c-floating-danger);
+}
+
+.embedpdf-floating-btn-danger:hover:not(:disabled) {
+ background-color: color-mix(
+ in srgb,
+ var(--c-floating-danger) 18%,
+ transparent
+ );
+ color: var(--c-floating-danger-hover);
+}
+
+.embedpdf-floating-btn-active {
+ background-color: rgba(255, 255, 255, 0.2);
+ color: var(--c-text-on-primary);
+}
+
+.embedpdf-floating-badge-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ height: 28px;
+ padding: 0 10px;
+ border-radius: 6px;
+ border: 1px solid
+ color-mix(in srgb, var(--c-floating-danger) 40%, transparent);
+ background: color-mix(in srgb, var(--c-floating-danger) 15%, transparent);
+ color: var(--c-floating-danger-hover);
+ font-size: 12px;
+ font-weight: 500;
+ cursor: pointer;
+ transition:
+ background-color 0.15s ease,
+ transform 0.1s ease,
+ border-color 0.15s ease;
+ white-space: nowrap;
+}
+
+.embedpdf-floating-badge-btn:hover:not(:disabled) {
+ background: color-mix(in srgb, var(--c-floating-danger) 25%, transparent);
+ border-color: color-mix(in srgb, var(--c-floating-danger) 60%, transparent);
+ color: var(--c-text-on-primary);
+}
+
+.embedpdf-floating-badge-btn:active:not(:disabled) {
+ transform: scale(0.95);
+}
+
+.embedpdf-floating-divider {
+ width: 1px;
+ height: 18px;
+ background-color: rgba(255, 255, 255, 0.15);
+ margin: 0 2px;
+}
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.stories.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.stories.tsx
index 1321fe7ea8..0fe80fd8c0 100644
--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.stories.tsx
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.stories.tsx
@@ -15,6 +15,10 @@ function baseProps(
};
}
+// TextSelectionMenu reads the active document from ActiveDocumentContext, which
+// defaults to `null` outside of a live EmbedPDF document-manager session (not something the
+// shared preview can stub). With no active document it short-circuits and renders nothing,
+// so this story only exercises that no-active-document mount path without throwing.
const meta = {
title: "Viewer/TextSelectionMenu",
component: TextSelectionMenu,
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx
new file mode 100644
index 0000000000..f341fb563f
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.test.tsx
@@ -0,0 +1,361 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { TextSelectionMenu } from "@app/components/viewer/TextSelectionMenu";
+import { PdfAnnotationSubtype } from "@embedpdf/models";
+
+// Mock i18next
+const mockT = vi.fn(
+ (key: string, fallback?: string) => fallback || `mock-${key}`,
+);
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: mockT }),
+}));
+
+// Mock EmbedPDF hooks
+const mockCopyToClipboard = vi.fn();
+const mockGetFormattedSelection = vi.fn();
+const mockGetSelectedText = vi.fn();
+const mockClearSelection = vi.fn();
+
+vi.mock("@embedpdf/plugin-selection/react", () => ({
+ useSelectionCapability: () => ({
+ provides: {
+ copyToClipboard: mockCopyToClipboard,
+ getFormattedSelection: mockGetFormattedSelection,
+ getSelectedText: mockGetSelectedText,
+ clear: mockClearSelection,
+ },
+ }),
+}));
+
+const mockCreateAnnotation = vi.fn();
+vi.mock("@embedpdf/plugin-annotation/react", () => ({
+ useAnnotation: () => ({
+ state: {},
+ provides: {
+ createAnnotation: mockCreateAnnotation,
+ },
+ }),
+}));
+
+const mockQueueCurrentSelectionAsPending = vi.fn();
+vi.mock("@embedpdf/plugin-redaction/react", () => ({
+ useRedaction: () => ({
+ state: {},
+ provides: {
+ queueCurrentSelectionAsPending: mockQueueCurrentSelectionAsPending,
+ },
+ }),
+}));
+
+vi.mock("@app/components/viewer/useActiveDocumentId", () => ({
+ useActiveDocumentId: () => "doc-1",
+}));
+
+const mockHandleToolSelectForced = vi.fn();
+const mockSetLeftPanelView = vi.fn();
+vi.mock("@app/contexts/ToolWorkflowContext", () => ({
+ useToolWorkflow: () => ({
+ handleToolSelectForced: mockHandleToolSelectForced,
+ setLeftPanelView: mockSetLeftPanelView,
+ }),
+}));
+
+const mockSetRedactionMode = vi.fn();
+const mockActivateRedact = vi.fn();
+const mockSetRedactionConfig = vi.fn();
+vi.mock("@app/contexts/RedactionContext", () => ({
+ useRedaction: () => ({
+ setRedactionMode: mockSetRedactionMode,
+ activateRedact: mockActivateRedact,
+ setRedactionConfig: mockSetRedactionConfig,
+ redactionApiRef: { current: null },
+ isBridgeReady: true,
+ manualRedactColor: "#000000",
+ }),
+}));
+
+const mockSetToolAndWorkbench = vi.fn();
+const mockSetHasUnsavedChanges = vi.fn();
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigationActions: () => ({
+ actions: {
+ setToolAndWorkbench: mockSetToolAndWorkbench,
+ setHasUnsavedChanges: mockSetHasUnsavedChanges,
+ },
+ }),
+}));
+
+const mockAlert = vi.fn();
+vi.mock("@app/components/toast", () => ({
+ alert: (options: unknown) => mockAlert(options),
+}));
+
+const TestWrapper = ({ children }: { children: React.ReactNode }) => (
+ <MantineProvider>{children}</MantineProvider>
+);
+
+describe("TextSelectionMenu", () => {
+ const defaultProps = {
+ rect: { origin: { x: 100, y: 100 }, size: { width: 80, height: 20 } },
+ menuWrapperProps: {
+ style: {},
+ ref: vi.fn(),
+ },
+ selected: true,
+ placement: {
+ pageIndex: 0,
+ rect: { origin: { x: 100, y: 100 }, size: { width: 80, height: 20 } },
+ spaceAbove: 100,
+ spaceBelow: 200,
+ suggestTop: true,
+ isVisible: true,
+ },
+ context: {
+ type: "selection" as const,
+ pageIndex: 0,
+ },
+ documentId: "doc-1",
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetFormattedSelection.mockReturnValue([
+ {
+ pageIndex: 0,
+ rect: { origin: { x: 100, y: 100 }, size: { width: 80, height: 20 } },
+ segmentRects: [
+ { origin: { x: 100, y: 100 }, size: { width: 80, height: 20 } },
+ ],
+ },
+ ]);
+ });
+
+ test("renders all 7 action buttons when selected", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ expect(screen.getByRole("button", { name: "Copy" })).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Highlight" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Strikeout" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Underline" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Squiggly" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Add link" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Redact" })).toBeInTheDocument();
+ });
+
+ test("does not render portal content when selected is false", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} selected={false} />
+ </TestWrapper>,
+ );
+
+ expect(
+ screen.queryByRole("button", { name: "Copy" }),
+ ).not.toBeInTheDocument();
+ });
+
+ test("calls copyToClipboard, clears selection, and triggers toast popup when Copy button is clicked", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ const copyBtn = screen.getByRole("button", { name: "Copy" });
+ fireEvent.click(copyBtn);
+
+ expect(mockCopyToClipboard).toHaveBeenCalledWith("doc-1");
+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");
+ expect(mockAlert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ alertType: "neutral",
+ title: "Copied to clipboard",
+ durationMs: 2000,
+ }),
+ );
+ });
+
+ test("creates HIGHLIGHT annotation, clears selection and opens Annotate UI when Highlight button is clicked", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ const highlightBtn = screen.getByRole("button", { name: "Highlight" });
+ fireEvent.click(highlightBtn);
+
+ expect(mockCreateAnnotation).toHaveBeenCalledWith(
+ 0,
+ expect.objectContaining({
+ type: PdfAnnotationSubtype.HIGHLIGHT,
+ color: "#ffd54f",
+ pageIndex: 0,
+ }),
+ );
+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");
+ expect(mockHandleToolSelectForced).toHaveBeenCalledWith("annotate");
+ });
+
+ test("refuses to create a LINK annotation for a javascript: URL", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Add link" }));
+ const input = screen.getByPlaceholderText("https://...");
+ fireEvent.change(input, { target: { value: "javascript:alert(1)" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ expect(mockCreateAnnotation).not.toHaveBeenCalled();
+ });
+
+ test("creates STRIKEOUT annotation, clears selection and opens Annotate UI when Strikeout button is clicked", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ const strikeoutBtn = screen.getByRole("button", { name: "Strikeout" });
+ fireEvent.click(strikeoutBtn);
+
+ expect(mockCreateAnnotation).toHaveBeenCalledWith(
+ 0,
+ expect.objectContaining({
+ type: PdfAnnotationSubtype.STRIKEOUT,
+ color: "#e53935",
+ pageIndex: 0,
+ }),
+ );
+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");
+ expect(mockHandleToolSelectForced).toHaveBeenCalledWith("annotate");
+ });
+
+ test("creates UNDERLINE annotation, clears selection and opens Annotate UI when Underline button is clicked", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ const underlineBtn = screen.getByRole("button", { name: "Underline" });
+ fireEvent.click(underlineBtn);
+
+ expect(mockCreateAnnotation).toHaveBeenCalledWith(
+ 0,
+ expect.objectContaining({
+ type: PdfAnnotationSubtype.UNDERLINE,
+ color: "#ffb300",
+ pageIndex: 0,
+ }),
+ );
+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");
+ expect(mockHandleToolSelectForced).toHaveBeenCalledWith("annotate");
+ });
+
+ test("creates SQUIGGLY annotation, clears selection and opens Annotate UI when Squiggly button is clicked", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ const squigglyBtn = screen.getByRole("button", { name: "Squiggly" });
+ fireEvent.click(squigglyBtn);
+
+ expect(mockCreateAnnotation).toHaveBeenCalledWith(
+ 0,
+ expect.objectContaining({
+ type: PdfAnnotationSubtype.SQUIGGLY,
+ color: "#00acc1",
+ pageIndex: 0,
+ }),
+ );
+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");
+ expect(mockHandleToolSelectForced).toHaveBeenCalledWith("annotate");
+ });
+
+ test("opens link popover and creates LINK annotation upon submit", () => {
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ const linkBtn = screen.getByRole("button", { name: "Add link" });
+ fireEvent.click(linkBtn);
+
+ const input = screen.getByPlaceholderText("https://...");
+ expect(input).toBeInTheDocument();
+
+ fireEvent.change(input, { target: { value: "https://example.com" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ expect(mockCreateAnnotation).toHaveBeenCalledWith(
+ 0,
+ expect.objectContaining({
+ type: PdfAnnotationSubtype.LINK,
+ target: {
+ type: "action",
+ action: { type: 3, uri: "https://example.com" },
+ },
+ }),
+ );
+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");
+ expect(mockHandleToolSelectForced).toHaveBeenCalledWith("annotate");
+ });
+
+ test("creates REDACT annotation, marks unsaved changes, and opens Redact UI when Redact button is clicked", () => {
+ mockGetFormattedSelection.mockReturnValue([
+ {
+ pageIndex: 0,
+ rect: { origin: { x: 10, y: 10 }, size: { width: 100, height: 20 } },
+ segmentRects: [],
+ },
+ ]);
+
+ render(
+ <TestWrapper>
+ <TextSelectionMenu {...defaultProps} />
+ </TestWrapper>,
+ );
+
+ const redactBtn = screen.getByRole("button", { name: "Redact" });
+ fireEvent.click(redactBtn);
+
+ expect(mockCreateAnnotation).toHaveBeenCalledWith(
+ 0,
+ expect.objectContaining({
+ type: PdfAnnotationSubtype.REDACT,
+ }),
+ );
+ expect(mockClearSelection).toHaveBeenCalledWith("doc-1");
+ expect(mockSetHasUnsavedChanges).toHaveBeenCalledWith(true);
+ expect(mockSetRedactionConfig).toHaveBeenCalledWith(
+ expect.objectContaining({ mode: "manual" }),
+ );
+ expect(mockSetToolAndWorkbench).toHaveBeenCalledWith("redact", "viewer");
+ expect(mockSetLeftPanelView).toHaveBeenCalledWith("toolContent");
+ expect(mockSetRedactionMode).toHaveBeenCalledWith(true);
+ expect(mockActivateRedact).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
index 383e7c6a54..94fe5525d4 100644
--- a/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
+++ b/frontend/editor/src/core/components/viewer/TextSelectionMenu.tsx
@@ -1,25 +1,89 @@
-import { Tooltip } from "@mantine/core";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { Icon } from "@app/ui/Icon";
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
+import { Tooltip, Popover, TextInput, Stack } from "@mantine/core";
+import { Button } from "@app/ui/Button";
+import { Icon } from "@app/ui/Icon";
import type { SelectionSelectionMenuProps } from "@embedpdf/plugin-selection/react";
import { useSelectionCapability } from "@embedpdf/plugin-selection/react";
+import { useAnnotation } from "@embedpdf/plugin-annotation/react";
+import { RedactionMode } from "@embedpdf/plugin-redaction";
+import {
+ PdfAnnotationSubtype,
+ PdfActionType,
+ PdfBlendMode,
+ uuidV4,
+} from "@embedpdf/models";
+import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
+import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
+import { useRedaction } from "@app/contexts/RedactionContext";
+import { useNavigationActions } from "@app/contexts/NavigationContext";
+import {
+ defaultParameters,
+ RedactParameters,
+} from "@app/hooks/tools/redact/useRedactParameters";
+import { MARKUP_ANNOTATION_COLORS } from "@app/components/viewer/annotationDefaults";
+import { alert } from "@app/components/toast";
+import { getExternalHref } from "@app/utils/externalUrl";
+import "@app/components/viewer/TextSelectionMenu.css";
+
+export type TextSelectionMenuProps = SelectionSelectionMenuProps & {
+ documentId?: string;
+};
-export function TextSelectionMenu({
+export function TextSelectionMenu(props: TextSelectionMenuProps) {
+ const contextDocId = useActiveDocumentId();
+ const documentId = props.documentId ?? contextDocId;
+
+ if (!documentId) {
+ return null;
+ }
+
+ return <TextSelectionMenuInner {...props} documentId={documentId} />;
+}
+
+function TextSelectionMenuInner({
selected,
menuWrapperProps,
placement,
-}: SelectionSelectionMenuProps) {
+ documentId,
+}: TextSelectionMenuProps & { documentId: string }) {
const { t } = useTranslation();
const { provides: selection } = useSelectionCapability();
+ const { provides: annotationProvides } = useAnnotation(documentId ?? "");
+
+ const { handleToolSelectForced, setLeftPanelView } = useToolWorkflow();
+ const {
+ setRedactionMode,
+ activateRedact,
+ setRedactionConfig,
+ redactionApiRef,
+ isBridgeReady,
+ manualRedactColor,
+ } = useRedaction();
+ const { actions: navActions } = useNavigationActions();
+
const wrapperRef = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState<{
top: number;
left: number;
} | null>(null);
+ const [linkPopoverOpen, setLinkPopoverOpen] = useState(false);
+ const [linkUrl, setLinkUrl] = useState("");
+ const [pendingRedactActivation, setPendingRedactActivation] = useState(false);
+
+ // The redact tool bridge mounts after its panel opens, so activation waits
+ // for bridge readiness instead of guessing a timeout.
+ useEffect(() => {
+ if (!pendingRedactActivation || !isBridgeReady) return;
+ setPendingRedactActivation(false);
+ const currentType = redactionApiRef?.current?.getActiveType?.();
+ if (currentType !== RedactionMode.Redact) {
+ activateRedact?.();
+ }
+ }, [pendingRedactActivation, isBridgeReady, redactionApiRef, activateRedact]);
+
const setRef = useCallback(
(node: HTMLDivElement | null) => {
wrapperRef.current = node;
@@ -54,13 +118,178 @@ export function TextSelectionMenu({
}, [selected, showAbove]);
const handleCopy = useCallback(() => {
- selection?.copyToClipboard();
- }, [selection]);
+ if (documentId) {
+ selection?.copyToClipboard(documentId);
+ selection?.clear(documentId);
+ alert({
+ alertType: "neutral",
+ title: t("common.copied", "Copied to clipboard"),
+ durationMs: 2000,
+ });
+ }
+ }, [selection, documentId, t]);
+
+ const openAnnotateUi = useCallback(() => {
+ handleToolSelectForced?.("annotate");
+ setLeftPanelView?.("toolContent");
+ }, [handleToolSelectForced, setLeftPanelView]);
+
+ const createMarkupAnnotation = useCallback(
+ (
+ subtype:
+ | PdfAnnotationSubtype.HIGHLIGHT
+ | PdfAnnotationSubtype.STRIKEOUT
+ | PdfAnnotationSubtype.UNDERLINE
+ | PdfAnnotationSubtype.SQUIGGLY,
+ color: string,
+ blendMode?: PdfBlendMode,
+ ) => {
+ if (!documentId) return;
+ const selections = selection?.getFormattedSelection(documentId) ?? [];
+ if (!selections.length) return;
+
+ const apply = (text?: string) => {
+ for (const sel of selections) {
+ annotationProvides?.createAnnotation(sel.pageIndex, {
+ type: subtype,
+ strokeColor: color,
+ color,
+ opacity: 1,
+ ...(blendMode !== undefined ? { blendMode } : {}),
+ rect: sel.rect,
+ segmentRects: sel.segmentRects,
+ pageIndex: sel.pageIndex,
+ created: new Date(),
+ id: uuidV4(),
+ ...(text ? { custom: { text } } : {}),
+ });
+ }
+ selection?.clear(documentId);
+ navActions?.setHasUnsavedChanges(true);
+ openAnnotateUi();
+ };
+
+ const selTask = selection?.getSelectedText(documentId);
+ if (selTask) {
+ selTask.wait(
+ (texts) => apply(texts.join("\n")),
+ () => apply(),
+ );
+ } else {
+ apply();
+ }
+ },
+ [documentId, selection, annotationProvides, navActions, openAnnotateUi],
+ );
+
+ const handleHighlight = useCallback(() => {
+ createMarkupAnnotation(
+ PdfAnnotationSubtype.HIGHLIGHT,
+ MARKUP_ANNOTATION_COLORS.highlight,
+ PdfBlendMode.Multiply,
+ );
+ }, [createMarkupAnnotation]);
+
+ const handleStrikeout = useCallback(() => {
+ createMarkupAnnotation(
+ PdfAnnotationSubtype.STRIKEOUT,
+ MARKUP_ANNOTATION_COLORS.strikeout,
+ );
+ }, [createMarkupAnnotation]);
+
+ const handleUnderline = useCallback(() => {
+ createMarkupAnnotation(
+ PdfAnnotationSubtype.UNDERLINE,
+ MARKUP_ANNOTATION_COLORS.underline,
+ );
+ }, [createMarkupAnnotation]);
+
+ const handleSquiggly = useCallback(() => {
+ createMarkupAnnotation(
+ PdfAnnotationSubtype.SQUIGGLY,
+ MARKUP_ANNOTATION_COLORS.squiggly,
+ );
+ }, [createMarkupAnnotation]);
+
+ const handleAddLink = useCallback(
+ (url: string) => {
+ const uri = url.trim();
+ if (!documentId || !uri) return;
+ // User input is untrusted: refuse URI schemes the viewer itself would
+ // not open, so javascript: and friends cannot ride out in the PDF. The
+ // original string is persisted verbatim once it passes the allowlist.
+ if (!getExternalHref(uri)) return;
+ const selections = selection?.getFormattedSelection(documentId) ?? [];
+ if (!selections.length) return;
+
+ for (const sel of selections) {
+ annotationProvides?.createAnnotation(sel.pageIndex, {
+ type: PdfAnnotationSubtype.LINK,
+ id: uuidV4(),
+ pageIndex: sel.pageIndex,
+ rect: sel.rect,
+ target: { type: "action", action: { type: PdfActionType.URI, uri } },
+ created: new Date(),
+ });
+ }
+ selection?.clear(documentId);
+ setLinkPopoverOpen(false);
+ setLinkUrl("");
+ navActions?.setHasUnsavedChanges(true);
+ openAnnotateUi();
+ },
+ [documentId, selection, annotationProvides, navActions, openAnnotateUi],
+ );
+
+ const handleRedact = useCallback(() => {
+ if (!documentId) return;
+ const selections = selection?.getFormattedSelection(documentId) ?? [];
+ for (const sel of selections) {
+ annotationProvides?.createAnnotation(sel.pageIndex, {
+ type: PdfAnnotationSubtype.REDACT,
+ strokeColor: manualRedactColor,
+ color: manualRedactColor,
+ overlayColor: manualRedactColor,
+ fillColor: manualRedactColor,
+ interiorColor: manualRedactColor,
+ backgroundColor: manualRedactColor,
+ opacity: 1,
+ rect: sel.rect,
+ segmentRects: sel.segmentRects,
+ pageIndex: sel.pageIndex,
+ created: new Date(),
+ id: uuidV4(),
+ });
+ }
+ selection?.clear(documentId);
+
+ // Bring the full Redact tool UI
+ const manualConfig: RedactParameters = {
+ ...defaultParameters,
+ mode: "manual",
+ };
+ setRedactionConfig?.(manualConfig);
+ setRedactionMode?.(true);
+ navActions?.setHasUnsavedChanges(true);
+ navActions?.setToolAndWorkbench("redact", "viewer");
+ setLeftPanelView?.("toolContent");
+ setPendingRedactActivation(true);
+ }, [
+ documentId,
+ selection,
+ annotationProvides,
+ manualRedactColor,
+ setRedactionConfig,
+ setRedactionMode,
+ navActions,
+ setLeftPanelView,
+ ]);
const portalContent =
position &&
createPortal(
<div
+ data-text-selection-menu
style={{
position: "fixed",
top: position.top,
@@ -71,20 +300,130 @@ export function TextSelectionMenu({
}}
onMouseDown={(e) => e.preventDefault()}
>
- <Tooltip label={t("viewer.copyText", "Copy")} withArrow>
- <ActionIcon
- variant="secondary"
- accent="neutral"
- size="md"
- onClick={handleCopy}
- aria-label={t("viewer.copyText", "Copy")}
- style={{
- boxShadow: "0 2px 12px rgba(0, 0, 0, 0.25)",
- }}
+ <div className="embedpdf-text-selection-menu">
+ <Tooltip label={t("viewer.copyText", "Copy")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleCopy}
+ aria-label={t("viewer.copyText", "Copy")}
+ >
+ <Icon name="copy" size={20} />
+ </button>
+ </Tooltip>
+
+ <Tooltip label={t("annotation.highlight", "Highlight")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleHighlight}
+ aria-label={t("annotation.highlight", "Highlight")}
+ >
+ <Icon name="highlighter" size={20} />
+ </button>
+ </Tooltip>
+
+ <Tooltip label={t("annotation.strikeout", "Strikeout")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleStrikeout}
+ aria-label={t("annotation.strikeout", "Strikeout")}
+ >
+ <Icon name="strikethrough" size={20} />
+ </button>
+ </Tooltip>
+
+ <Tooltip label={t("annotation.underline", "Underline")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleUnderline}
+ aria-label={t("annotation.underline", "Underline")}
+ >
+ <Icon name="underline" size={20} />
+ </button>
+ </Tooltip>
+
+ <Tooltip label={t("annotation.squiggly", "Squiggly")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleSquiggly}
+ aria-label={t("annotation.squiggly", "Squiggly")}
+ >
+ <Icon name="line-squiggle" size={20} />
+ </button>
+ </Tooltip>
+
+ <Popover
+ opened={linkPopoverOpen}
+ onChange={setLinkPopoverOpen}
+ position={showAbove ? "top" : "bottom"}
+ withArrow
+ shadow="md"
+ transitionProps={{ duration: 0 }}
>
- <Icon name="copy" size={18} />
- </ActionIcon>
- </Tooltip>
+ <Popover.Target>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={() => setLinkPopoverOpen((o) => !o)}
+ aria-label={t("viewer.comments.addLink", "Add link")}
+ >
+ <Tooltip
+ label={t("viewer.comments.addLink", "Add link")}
+ withArrow
+ disabled={linkPopoverOpen}
+ >
+ <span style={{ display: "inline-flex" }}>
+ <Icon name="link" size={20} />
+ </span>
+ </Tooltip>
+ </button>
+ </Popover.Target>
+ <Popover.Dropdown
+ onMouseDown={(e) => e.stopPropagation()}
+ style={{
+ backgroundColor: "var(--mantine-color-body)",
+ borderColor: "var(--mantine-color-default-border)",
+ }}
+ >
+ <Stack gap="xs" style={{ minWidth: 220 }}>
+ <TextInput
+ placeholder="https://..."
+ value={linkUrl}
+ onChange={(e) => setLinkUrl(e.currentTarget.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && linkUrl.trim()) {
+ handleAddLink(linkUrl);
+ }
+ }}
+ size="xs"
+ autoFocus
+ />
+ <Button
+ size="sm"
+ disabled={!linkUrl.trim()}
+ onClick={() => handleAddLink(linkUrl)}
+ >
+ {t("viewer.comments.addLink", "Add link")}
+ </Button>
+ </Stack>
+ </Popover.Dropdown>
+ </Popover>
+
+ <Tooltip label={t("workbenchBar.redact", "Redact")} withArrow>
+ <button
+ type="button"
+ className="embedpdf-text-selection-btn"
+ onClick={handleRedact}
+ aria-label={t("workbenchBar.redact", "Redact")}
+ >
+ <Icon name="file-x" size={20} />
+ </button>
+ </Tooltip>
+ </div>
</div>,
document.body,
);
diff --git a/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx b/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx
index 8d517577dc..8337bcc75d 100644
--- a/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx
+++ b/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx
@@ -55,11 +55,11 @@ export default function ViewerAnnotationControls({
// Get redaction pending state and navigation guard
const { isRedacting: _isRedacting } = useRedactionMode();
- const { requestNavigation, setHasUnsavedChanges, hasUnsavedChanges } =
- useNavigationGuard();
+ const { requestNavigation, setHasUnsavedChanges } = useNavigationGuard();
const {
setRedactionMode,
activateRedact,
+ deactivateRedact,
setRedactionConfig,
setRedactionsApplied,
redactionApiRef,
@@ -119,7 +119,14 @@ export default function ViewerAnnotationControls({
setLeftPanelView("toolPicker");
setRedactionMode(false);
setActiveType(null);
- }, [navActions, setLeftPanelView, setRedactionMode, setActiveType]);
+ deactivateRedact();
+ }, [
+ navActions,
+ setLeftPanelView,
+ setRedactionMode,
+ setActiveType,
+ deactivateRedact,
+ ]);
// Handle redaction mode toggle
const handleRedactionToggle = async () => {
@@ -159,12 +166,8 @@ export default function ViewerAnnotationControls({
};
const handleToggleAnnotationsVisibility = useCallback(() => {
- if (!annotationsHidden && hasUnsavedChanges) {
- requestNavigation(() => viewerContext?.toggleAnnotationsVisibility());
- } else {
- viewerContext?.toggleAnnotationsVisibility();
- }
- }, [annotationsHidden, hasUnsavedChanges, requestNavigation, viewerContext]);
+ viewerContext?.toggleAnnotationsVisibility();
+ }, [viewerContext]);
// NOTE: This early return is placed AFTER all hooks to satisfy React's rules of hooks
if (isSignMode) {
diff --git a/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx b/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx
index e9df5f0926..e13cc0e888 100644
--- a/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx
@@ -4,7 +4,7 @@ import { useSpread, SpreadMode } from "@embedpdf/plugin-spread/react";
import { useScroll } from "@embedpdf/plugin-scroll/react";
import { useViewer } from "@app/contexts/ViewerContext";
import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
-import { useAllFiles } from "@app/contexts/FileContext";
+import { useAllFiles, useFileSelection } from "@app/contexts/FileContext";
import {
determineAutoZoom,
DEFAULT_FALLBACK_ZOOM,
@@ -24,26 +24,48 @@ import {
export function ZoomAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
+ const lastAutoZoomedRootIdRef = useRef<string | null>(null);
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
return null;
}
- return <ZoomAPIBridgeInner documentId={activeDocumentId} />;
+ return (
+ <ZoomAPIBridgeInner
+ key={activeDocumentId}
+ documentId={activeDocumentId}
+ lastAutoZoomedRootIdRef={lastAutoZoomedRootIdRef}
+ />
+ );
}
-function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
+function ZoomAPIBridgeInner({
+ documentId,
+ lastAutoZoomedRootIdRef,
+}: {
+ documentId: string;
+ lastAutoZoomedRootIdRef: React.MutableRefObject<string | null>;
+}) {
const { provides: zoom, state: zoomState } = useZoom(documentId);
+ const liveZoomState = zoom?.getState() ?? zoomState;
const { provides: spread, spreadMode } = useSpread(documentId);
const { state: scrollState } = useScroll(documentId);
const totalPages = scrollState?.totalPages ?? 0;
const { registerBridge, triggerImmediateZoomUpdate } = useViewer();
const { fileStubs } = useAllFiles();
+ const { selectedFileIds } = useFileSelection();
- const hasSetInitialZoom = useRef(false);
+ const activeId = selectedFileIds?.[0];
+ const activeStub =
+ (activeId ? fileStubs.find((s) => s.id === activeId) : undefined) ??
+ fileStubs[0];
+ const activeFileRootId = activeStub?.originalFileId || activeStub?.id;
+
+ const hasSetInitialZoom = useRef(
+ !!activeFileRootId && activeFileRootId === lastAutoZoomedRootIdRef.current,
+ );
const lastSpreadMode = useRef(spreadMode ?? SpreadMode.None);
- const lastFileId = useRef<string | undefined>(undefined);
const lastAppliedZoom = useRef<number | null>(null);
const zoomRef = useRef(zoom);
const [autoZoomTick, setAutoZoomTick] = useState(0);
@@ -100,43 +122,34 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
}
}, [checkSpreadReady]);
- const stubs = fileStubs;
- const firstFileStub = stubs[0];
- const firstFileRootId = firstFileStub?.originalFileId || firstFileStub?.id;
-
- // Extract primitive values from zoomState for dependency arrays
- const zoomLevel = zoomState?.zoomLevel;
- const currentZoomLevel = zoomState?.currentZoomLevel;
+ // Extract primitive values from liveZoomState for dependency arrays
+ const zoomLevel = liveZoomState?.zoomLevel;
+ const currentZoomLevel = liveZoomState?.currentZoomLevel;
// Extract metadata aspect ratio as a primitive to avoid object reference issues
- const metadataAspectRatio = getFirstPageAspectRatioFromStub(firstFileStub);
+ const metadataAspectRatio = getFirstPageAspectRatioFromStub(activeStub);
useEffect(() => {
- if (!firstFileRootId) {
+ if (!activeFileRootId) {
hasSetInitialZoom.current = false;
- lastFileId.current = undefined;
+ lastAutoZoomedRootIdRef.current = null;
lastAppliedZoom.current = null;
return;
}
// Only reset zoom when opening a genuinely different document, not on version increments
- if (firstFileRootId !== lastFileId.current) {
- lastFileId.current = firstFileRootId;
+ if (activeFileRootId !== lastAutoZoomedRootIdRef.current) {
+ lastAutoZoomedRootIdRef.current = activeFileRootId;
scheduleAutoZoom();
}
- }, [firstFileRootId, scheduleAutoZoom]);
+ }, [activeFileRootId, scheduleAutoZoom]);
useEffect(() => {
const currentSpreadMode = spreadMode ?? SpreadMode.None;
if (currentSpreadMode !== lastSpreadMode.current) {
lastSpreadMode.current = currentSpreadMode;
- const hadTrackedAutoZoom = lastAppliedZoom.current !== null;
- if (
- zoomLevel === ZoomMode.FitWidth ||
- zoomLevel === ZoomMode.Automatic ||
- hadTrackedAutoZoom
- ) {
+ if (zoomLevel === ZoomMode.FitWidth || zoomLevel === ZoomMode.Automatic) {
requestFitWidth();
scheduleAutoZoom();
}
@@ -146,9 +159,7 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
const isManagedZoom =
checkSpreadReady() &&
!!zoom &&
- (zoomLevel === ZoomMode.FitWidth ||
- zoomLevel === ZoomMode.Automatic ||
- lastAppliedZoom.current !== null);
+ (zoomLevel === ZoomMode.FitWidth || zoomLevel === ZoomMode.Automatic);
useFitWidthResize({
isManaged: isManagedZoom,
@@ -161,7 +172,7 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
return;
}
- if (!firstFileRootId || !checkSpreadReady()) {
+ if (!activeFileRootId || !checkSpreadReady()) {
return;
}
@@ -170,7 +181,9 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
}
if (zoomLevel !== ZoomMode.FitWidth) {
- requestFitWidth();
+ if (zoomLevel === ZoomMode.Automatic) {
+ requestFitWidth();
+ }
return;
}
@@ -259,7 +272,7 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
zoom,
zoomLevel,
currentZoomLevel,
- firstFileRootId,
+ activeFileRootId,
checkSpreadReady,
spreadReadyTick,
metadataAspectRatio,
@@ -302,7 +315,7 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
}, [zoom, triggerImmediateZoomUpdate]);
// Extract primitive values to avoid dependency on object reference
- const zoomStateCurrentZoomLevel = zoomState?.currentZoomLevel;
+ const zoomStateCurrentZoomLevel = liveZoomState?.currentZoomLevel;
// Register bridge - only re-run when actual values change
useEffect(() => {
@@ -312,11 +325,12 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
}
const currentZoomLevel =
- lastAppliedZoom.current ?? zoomStateCurrentZoomLevel ?? 1;
+ zoomStateCurrentZoomLevel ?? lastAppliedZoom.current ?? 1;
const newState = {
currentZoom: currentZoomLevel,
zoomPercent: Math.round(currentZoomLevel * 100),
+ level: zoomLevel,
};
triggerImmediateZoomUpdate(newState.zoomPercent);
@@ -325,7 +339,12 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
state: newState,
api: currentZoom,
});
- }, [zoomStateCurrentZoomLevel, registerBridge, triggerImmediateZoomUpdate]);
+ }, [
+ zoomStateCurrentZoomLevel,
+ zoomLevel,
+ registerBridge,
+ triggerImmediateZoomUpdate,
+ ]);
return null;
}
diff --git a/frontend/editor/src/core/components/viewer/annotationDefaults.ts b/frontend/editor/src/core/components/viewer/annotationDefaults.ts
new file mode 100644
index 0000000000..13fe730f9c
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/annotationDefaults.ts
@@ -0,0 +1,7 @@
+/** Markup-annotation colours shared by the tool defaults and the menu. */
+export const MARKUP_ANNOTATION_COLORS = {
+ highlight: "#ffd54f",
+ underline: "#ffb300",
+ strikeout: "#e53935",
+ squiggly: "#00acc1",
+} as const;
diff --git a/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts b/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts
index 3e9e048aaf..a66a096d4c 100644
--- a/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts
+++ b/frontend/editor/src/core/components/viewer/useAnnotationMenuHandlers.ts
@@ -76,7 +76,6 @@ interface UseAnnotationMenuHandlersParams {
export interface AnnotationMenuState {
annotationType: AnnotationType;
- menuWidth: number;
obj: AnnotationObject | undefined;
annotationId: string | undefined;
firstLinkTarget: FirstLinkTarget | null;
@@ -195,23 +194,6 @@ export function useAnnotationMenuHandlers({
return "unknown";
}, [annotation]);
- const menuWidth = useMemo((): number => {
- switch (annotationType) {
- case "stamp":
- return 80;
- case "inkHighlighter":
- case "comment":
- case "textMarkup":
- case "text":
- case "note":
- return 280;
- case "shape":
- return 200;
- default:
- return 260;
- }
- }, [annotationType]);
-
const hasCommentContent = (obj?.contents ?? "").trim().length > 0;
const isInSidebar =
(obj?.customData as Record<string, unknown> | undefined)?.isComment ===
@@ -456,7 +438,6 @@ export function useAnnotationMenuHandlers({
return {
annotationType,
- menuWidth,
obj,
annotationId,
firstLinkTarget,
diff --git a/frontend/editor/src/core/components/viewer/viewerTypes.ts b/frontend/editor/src/core/components/viewer/viewerTypes.ts
index f779635263..75c0c4cb2b 100644
--- a/frontend/editor/src/core/components/viewer/viewerTypes.ts
+++ b/frontend/editor/src/core/components/viewer/viewerTypes.ts
@@ -223,3 +223,11 @@ export interface AnnotationToolOptions {
| "toggleNoView"
)[];
}
+
+/** Screen anchor of the selection menu, retained by a delete so an undo menu can sit in its place. */
+export interface AnnotationMenuAnchor {
+ annotationId: string;
+ pageIndex: number;
+ top: number;
+ left: number;
+}
diff --git a/frontend/editor/src/core/contexts/RedactionContext.tsx b/frontend/editor/src/core/contexts/RedactionContext.tsx
index 8afda027c5..80f2610c6f 100644
--- a/frontend/editor/src/core/contexts/RedactionContext.tsx
+++ b/frontend/editor/src/core/contexts/RedactionContext.tsx
@@ -10,6 +10,7 @@ import React, {
import { RedactParameters } from "@app/hooks/tools/redact/useRedactParameters";
import { useNavigationGuard } from "@app/contexts/NavigationContext";
import { RedactionMode } from "@embedpdf/plugin-redaction";
+import { leaveRedactionMode } from "@app/components/viewer/leaveRedactionMode";
/**
* API interface that the EmbedPDF bridge will implement
@@ -166,14 +167,15 @@ export const RedactionProvider: React.FC<{ children: ReactNode }> = ({
}));
}, []);
- // Keep navigation guard aware of pending or applied redactions so we block navigation
- // Also clear the flag when all redactions have been saved
+ // Cleared only when redaction armed the flag, so manual mode cannot drop a
+ // dirty state owned by annotations, comments or form fill.
+ const redactionDirtyRef = useRef(false);
useEffect(() => {
if (state.pendingCount > 0 || state.redactionsApplied) {
+ redactionDirtyRef.current = true;
setHasUnsavedChanges(true);
- } else if (state.isRedactionMode) {
- // Only clear if we're in redaction mode - this avoids interfering with annotation changes
- // When there are no pending redactions and nothing has been applied, we're "clean"
+ } else if (state.isRedactionMode && redactionDirtyRef.current) {
+ redactionDirtyRef.current = false;
setHasUnsavedChanges(false);
}
}, [
@@ -191,9 +193,7 @@ export const RedactionProvider: React.FC<{ children: ReactNode }> = ({
}, []);
const deactivateRedact = useCallback(() => {
- if (redactionApiRef.current) {
- redactionApiRef.current.endRedact();
- }
+ leaveRedactionMode(redactionApiRef.current);
}, []);
const commitAllPending = useCallback(async () => {
diff --git a/frontend/editor/src/core/contexts/ViewerContext.tsx b/frontend/editor/src/core/contexts/ViewerContext.tsx
index 78535b41ac..3bb8d01320 100644
--- a/frontend/editor/src/core/contexts/ViewerContext.tsx
+++ b/frontend/editor/src/core/contexts/ViewerContext.tsx
@@ -180,6 +180,13 @@ export interface ViewerContextType {
callback: (rotation: number) => void,
) => () => void;
+ // True while a carried zoom lands after a swap; zoom percent updates in that
+ // window are intermediate and must not reach the toolbar.
+ zoomRestorePendingRef: React.MutableRefObject<boolean>;
+ /** Bumped when the carried zoom settles so bridges can re-publish the state. */
+ zoomRestoreSettledTick: number;
+ notifyZoomRestoreSettled: () => void;
+
// Internal - for bridges to trigger immediate updates
triggerImmediateScrollUpdate: (
currentPage: number,
@@ -596,6 +603,12 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
[printWithPolicy],
);
+ const zoomRestorePendingRef = useRef(false);
+ const [zoomRestoreSettledTick, setZoomRestoreSettledTick] = useState(0);
+ const notifyZoomRestoreSettled = useCallback(() => {
+ setZoomRestoreSettledTick((tick) => tick + 1);
+ }, []);
+
const value: ViewerContextType = {
// UI state
isThumbnailSidebarVisible,
@@ -657,6 +670,9 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {
triggerImmediateScrollUpdate,
triggerImmediateZoomUpdate,
triggerImmediateSpreadUpdate,
+ zoomRestorePendingRef,
+ zoomRestoreSettledTick,
+ notifyZoomRestoreSettled,
triggerImmediatePanUpdate,
triggerImmediateRotationUpdate,
diff --git a/frontend/editor/src/core/contexts/viewer/viewerBridges.ts b/frontend/editor/src/core/contexts/viewer/viewerBridges.ts
index e77018a837..2cf5a67e63 100644
--- a/frontend/editor/src/core/contexts/viewer/viewerBridges.ts
+++ b/frontend/editor/src/core/contexts/viewer/viewerBridges.ts
@@ -130,6 +130,8 @@ export interface ScrollState {
export interface ZoomState {
currentZoom: number;
zoomPercent: number;
+ /** Active zoom as the plugin reports it: a mode or a numeric user level. */
+ level?: ZoomLevel;
}
export interface PanState {
diff --git a/frontend/editor/src/core/icons/icons.ts b/frontend/editor/src/core/icons/icons.ts
index 1bcce2fceb..bf0558419d 100644
--- a/frontend/editor/src/core/icons/icons.ts
+++ b/frontend/editor/src/core/icons/icons.ts
@@ -165,6 +165,7 @@ import LayoutGrid from "lucide-static/icons/layout-grid.svg?react";
import Leaf from "lucide-static/icons/leaf.svg?react";
import Library from "lucide-static/icons/library.svg?react";
import Lightbulb from "lucide-static/icons/lightbulb.svg?react";
+import LineSquiggle from "lucide-static/icons/line-squiggle.svg?react";
import Link from "lucide-static/icons/link.svg?react";
import List from "lucide-static/icons/list.svg?react";
import ListChecks from "lucide-static/icons/list-checks.svg?react";
@@ -556,6 +557,7 @@ export const ICONS = {
leaf: { Component: Leaf, kind: "lucide" },
library: { Component: Library, kind: "lucide" },
lightbulb: { Component: Lightbulb, kind: "lucide" },
+ "line-squiggle": { Component: LineSquiggle, kind: "lucide" },
link: { Component: Link, kind: "lucide" },
list: { Component: List, kind: "lucide" },
"list-checks": { Component: ListChecks, kind: "lucide" },
diff --git a/frontend/editor/src/core/tests/stubbed/floating-menu-controls.spec.ts b/frontend/editor/src/core/tests/stubbed/floating-menu-controls.spec.ts
new file mode 100644
index 0000000000..ddf5d44bc9
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/floating-menu-controls.spec.ts
@@ -0,0 +1,76 @@
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+
+/** The floating menus use native buttons and one stylesheet, so a disabled
+ * control must not read as interactive: no pointer cursor, no hover fill. */
+test("disabled floating buttons do not look interactive", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.goto("/editor");
+ await page.locator('input[type="file"]').first().setInputFiles(SAMPLE_PDF);
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.waitForTimeout(2_000);
+
+ const styles = await page.evaluate(() => {
+ const host = document.createElement("div");
+ host.style.position = "fixed";
+ host.style.top = "0px";
+ host.style.right = "0px";
+ host.style.zIndex = "999999";
+ host.innerHTML = `
+ <button id="disabled-btn" type="button" class="embedpdf-floating-btn" disabled>
+ <span id="disabled-child" style="display:block;width:18px;height:18px"></span>
+ </button>
+ <button id="enabled-btn" type="button" class="embedpdf-floating-btn">
+ <span id="enabled-child" style="display:block;width:18px;height:18px"></span>
+ </button>
+ `;
+ document.body.appendChild(host);
+
+ const read = (id: string) => {
+ const el = document.getElementById(id) as HTMLElement;
+ const style = getComputedStyle(el);
+ return {
+ cursor: style.cursor,
+ opacity: style.opacity,
+ background: style.backgroundColor,
+ };
+ };
+
+ return {
+ disabled: read("disabled-btn"),
+ enabled: read("enabled-btn"),
+ disabledChildCursor: getComputedStyle(
+ document.getElementById("disabled-child") as HTMLElement,
+ ).cursor,
+ };
+ });
+
+ expect(styles.disabled.cursor).toBe("not-allowed");
+ expect(styles.disabled.opacity).toBe("0.45");
+ expect(styles.disabledChildCursor).toBe("not-allowed");
+ expect(styles.enabled.cursor).toBe("pointer");
+
+ await page.hover("#disabled-btn");
+ const disabledBgAfter = await page.evaluate(
+ () =>
+ getComputedStyle(document.getElementById("disabled-btn") as HTMLElement)
+ .backgroundColor,
+ );
+ expect(disabledBgAfter).toBe(styles.disabled.background);
+
+ await page.hover("#enabled-btn");
+ await page.waitForTimeout(400);
+ const enabledBgAfter = await page.evaluate(
+ () =>
+ getComputedStyle(document.getElementById("enabled-btn") as HTMLElement)
+ .backgroundColor,
+ );
+ expect(enabledBgAfter).not.toBe(styles.enabled.background);
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-annotation-delete-persistence.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-annotation-delete-persistence.spec.ts
new file mode 100644
index 0000000000..632043c0d9
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-annotation-delete-persistence.spec.ts
@@ -0,0 +1,82 @@
+import fs from "node:fs";
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
+const SAMPLE_PDF = path.join(FIXTURES, "sample.pdf");
+
+async function annotationCounts(
+ page: import("@playwright/test").Page,
+ label: string,
+) {
+ const downloadPromise = page.waitForEvent("download", { timeout: 20_000 });
+ await page
+ .getByRole("button", { name: /download|export/i })
+ .first()
+ .click();
+ const download = await downloadPromise;
+ const target = path.join("/tmp", `stirling-delete-${label}.pdf`);
+ await download.saveAs(target);
+ const { PDFDocument } = await import("@cantoo/pdf-lib");
+ const exported = await PDFDocument.load(fs.readFileSync(target));
+ await page.waitForTimeout(600);
+ return exported.getPages().map((entry) => entry.node.Annots()?.size() ?? 0);
+}
+
+async function createHighlight(page: import("@playwright/test").Page) {
+ await page.goto("/editor");
+ 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 });
+ await page.waitForTimeout(2_000);
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Sample page has no bounding box");
+ const y = box.y + box.height * 0.105;
+ 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();
+
+ const highlight = page
+ .locator('[data-text-selection-menu] button[aria-label="Highlight"]')
+ .first();
+ await expect(highlight).toBeVisible({ timeout: 5_000 });
+ await highlight.click();
+ await page.waitForTimeout(1_500);
+}
+
+test("a deleted annotation is not in the exported PDF", async ({ page }) => {
+ test.setTimeout(180_000);
+ await createHighlight(page);
+
+ const menu = page.locator("[data-annotation-selection-menu]").first();
+ await expect(menu).toBeVisible({ timeout: 10_000 });
+ await menu.getByRole("button", { name: "Delete" }).click();
+ await expect(
+ page.locator("[data-annotation-deleted-menu]").first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ const counts = await annotationCounts(page, "deleted");
+ expect(counts.every((count) => count === 0)).toBe(true);
+});
+
+test("a save after a delete keeps the deletion", async ({ page }) => {
+ test.setTimeout(180_000);
+ await createHighlight(page);
+
+ const menu = page.locator("[data-annotation-selection-menu]").first();
+ await expect(menu).toBeVisible({ timeout: 10_000 });
+ await menu.getByRole("button", { name: "Delete" }).click();
+ await expect(
+ page.locator("[data-annotation-deleted-menu]").first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await expect(save).toBeEnabled({ timeout: 15_000 });
+ await save.click();
+ await expect(save).toBeDisabled({ timeout: 20_000 });
+
+ const counts = await annotationCounts(page, "deleted-then-saved");
+ expect(counts.every((count) => count === 0)).toBe(true);
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-annotation-menu-after-edits.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-annotation-menu-after-edits.spec.ts
new file mode 100644
index 0000000000..bf7326ad8b
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-annotation-menu-after-edits.spec.ts
@@ -0,0 +1,128 @@
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
+const SAMPLE_PDF = path.join(FIXTURES, "sample.pdf");
+
+async function loadViewerWithHighlight(page: import("@playwright/test").Page) {
+ await page.goto("/editor");
+ 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 });
+ await page.waitForTimeout(2_000);
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Sample page has no bounding box");
+ const y = box.y + box.height * 0.105;
+ 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();
+
+ const highlight = page
+ .locator('[data-text-selection-menu] button[aria-label="Highlight"]')
+ .first();
+ await expect(highlight).toBeVisible({ timeout: 5_000 });
+ await highlight.click();
+ await page.waitForTimeout(1_500);
+ return firstPage;
+}
+
+test("changing a colour keeps the annotation menu open", async ({ page }) => {
+ test.setTimeout(180_000);
+ await loadViewerWithHighlight(page);
+
+ const menu = page.locator("[data-annotation-selection-menu]").first();
+ await expect(menu).toBeVisible({ timeout: 10_000 });
+
+ await page
+ .getByRole("button", { name: /^Change Colou?r$/ })
+ .first()
+ .click();
+ await page.locator(".mantine-ColorPicker-swatch").nth(2).click();
+
+ await expect(menu).toBeVisible({ timeout: 10_000 });
+ await expect(menu.getByRole("button", { name: "Delete" })).toBeVisible();
+});
+
+test("deleting an annotation leaves an undo menu that restores it", async ({
+ page,
+}) => {
+ test.setTimeout(180_000);
+ await loadViewerWithHighlight(page);
+
+ const menu = page.locator("[data-annotation-selection-menu]").first();
+ const deletedMenu = page.locator("[data-annotation-deleted-menu]").first();
+ await expect(menu).toBeVisible({ timeout: 10_000 });
+ await expect(deletedMenu).not.toBeVisible();
+
+ await menu.getByRole("button", { name: "Delete" }).click();
+
+ // The annotation is gone, so its selection menu gives way to the undo menu
+ // anchored where the annotation was.
+ await expect(menu).not.toBeVisible({ timeout: 10_000 });
+ await expect(deletedMenu).toBeVisible({ timeout: 10_000 });
+ await expect(deletedMenu).toContainText(/Annotation deleted/i);
+
+ await deletedMenu.getByRole("button", { name: "Undo" }).click();
+
+ // Undo restores the annotation and hands the anchor back to the normal menu.
+ await expect(menu).toBeVisible({ timeout: 10_000 });
+ await expect(deletedMenu).not.toBeVisible();
+ await expect(menu.getByRole("button", { name: "Delete" })).toBeVisible();
+});
+
+test("dismissing the undo menu leaves the selection menu closed", async ({
+ page,
+}) => {
+ test.setTimeout(180_000);
+ const firstPage = await loadViewerWithHighlight(page);
+
+ const menu = page.locator("[data-annotation-selection-menu]").first();
+ const deletedMenu = page.locator("[data-annotation-deleted-menu]").first();
+ await menu.getByRole("button", { name: "Delete" }).click();
+ await expect(deletedMenu).toBeVisible({ timeout: 10_000 });
+
+ // Clicking away dismisses the undo menu without reopening the selection
+ // menu, so a dismissed delete reads as a plain delete.
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Sample page has no bounding box");
+ await page.mouse.click(box.x + 16, box.y + box.height - 16);
+ await expect(deletedMenu).not.toBeVisible({ timeout: 5_000 });
+ await expect(menu).not.toBeVisible();
+
+ // The delete is still recoverable from the toolbar Undo.
+ await expect(page.getByRole("button", { name: "Undo" }).first()).toBeEnabled({
+ timeout: 10_000,
+ });
+});
+
+test("editing a comment from the sidebar reopens its menu", async ({
+ page,
+}) => {
+ test.setTimeout(180_000);
+ const firstPage = await loadViewerWithHighlight(page);
+
+ const menu = page.locator("[data-annotation-selection-menu]").first();
+ await menu.getByRole("button", { name: "Add comment" }).click();
+ await expect(page.locator(".comments-sidebar").first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ // Deselect so the sidebar edit is the only thing dirtying the annotation.
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Sample page has no bounding box");
+ await page.mouse.click(box.x + 16, box.y + box.height - 16);
+ await expect(menu).not.toBeVisible({ timeout: 10_000 });
+
+ // The sidebar header has its own "More actions" menu; the comment row's one
+ // is the second button carrying that label.
+ await page.getByRole("button", { name: "More actions" }).nth(1).click();
+ await page.getByRole("menuitem", { name: /Edit/ }).click();
+ const draft = page.locator(".comments-sidebar textarea").first();
+ await draft.fill("Updated from the sidebar");
+ await draft.press("Enter");
+
+ // A committed update opens the menu for the annotation that changed.
+ await expect(menu).toBeVisible({ timeout: 10_000 });
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-annotation-unsaved-changes.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-annotation-unsaved-changes.spec.ts
new file mode 100644
index 0000000000..b32825fe64
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-annotation-unsaved-changes.spec.ts
@@ -0,0 +1,104 @@
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const SAMPLE_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/sample.pdf",
+);
+
+async function loadViewer(page: import("@playwright/test").Page) {
+ await page.goto("/editor");
+ 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 });
+ await expect(firstPage.locator(".pdf-selection-layer")).toBeAttached({
+ timeout: 15_000,
+ });
+ await page.waitForTimeout(2_000);
+ return firstPage;
+}
+
+async function highlightSomeText(
+ 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.105;
+ 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();
+
+ const highlight = page.getByRole("button", { name: "Highlight" }).first();
+ await expect(highlight).toBeVisible({ timeout: 5_000 });
+ await highlight.click();
+ await page.waitForTimeout(1_000);
+}
+
+/** Form Editor goes through the tool switch guard, unlike plain tool-panel nav. */
+async function switchToFormEditor(page: import("@playwright/test").Page) {
+ await page.getByRole("button", { name: "Form Editor" }).first().click();
+ await page.waitForTimeout(700);
+}
+
+function viewerCursor(page: import("@playwright/test").Page) {
+ return page.evaluate(() => {
+ const pageEl = document.querySelector<HTMLElement>('[data-page-index="0"]');
+ return pageEl?.parentElement
+ ? getComputedStyle(pageEl.parentElement).cursor
+ : null;
+ });
+}
+
+test("highlighting text arms the unsaved-changes warning", async ({ page }) => {
+ test.setTimeout(120_000);
+ const firstPage = await loadViewer(page);
+ await highlightSomeText(page, firstPage);
+ await switchToFormEditor(page);
+ await expect(page.getByText("Unsaved changes").first()).toBeVisible({
+ timeout: 5_000,
+ });
+});
+
+test("undoing the only annotation disarms the unsaved-changes warning", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const firstPage = await loadViewer(page);
+ await highlightSomeText(page, firstPage);
+
+ const undo = page.getByRole("button", { name: "Undo" }).first();
+ await expect(undo).toBeEnabled({ timeout: 5_000 });
+ await undo.click();
+ await page.waitForTimeout(1_000);
+
+ await switchToFormEditor(page);
+ await expect(page.getByText("Unsaved changes").first()).not.toBeVisible();
+});
+
+test("entering manual redact mode keeps annotation work saveable", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const firstPage = await loadViewer(page);
+ await highlightSomeText(page, firstPage);
+
+ // Back to the picker first: switching tools while still on Annotate would
+ // trip the unsaved-changes guard.
+ await page.getByRole("button", { name: "Back to all tools" }).first().click();
+ await page.waitForTimeout(700);
+ await page.getByRole("link", { name: "Redact" }).first().click();
+ await page.waitForTimeout(700);
+ await page.getByText("Manual", { exact: true }).first().click();
+
+ await expect
+ .poll(() => viewerCursor(page), { timeout: 15_000 })
+ .toBe("crosshair");
+
+ // Manual redaction mode used to clear the shared dirty flag, disabling this
+ // button while the annotation history was still unsaved.
+ await expect(
+ page.getByRole("button", { name: "Save Changes" }).first(),
+ ).toBeEnabled({ timeout: 10_000 });
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts
new file mode 100644
index 0000000000..b97b3107d8
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts
@@ -0,0 +1,519 @@
+import fs from "node:fs";
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+interface SteadyZoomSamplerState {
+ stop: boolean;
+ widths: number[];
+ indicators: string[];
+}
+
+declare global {
+ interface Window {
+ __steadySampler?: SteadyZoomSamplerState;
+ }
+}
+
+const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
+const MULTIPAGE_PDF = path.join(FIXTURES, "annotations_out_of_order.pdf");
+const ROTATED_TEXT_PDF = path.join(FIXTURES, "rotated-text-sample.pdf");
+const ROTATED_PAGES_PDF = path.join(FIXTURES, "rotated-pages.pdf");
+const FORM_PDF = path.join(FIXTURES, "form-fields-sample.pdf");
+
+async function loadFixture(
+ page: import("@playwright/test").Page,
+ fixture: string,
+ pages = 1,
+) {
+ await page.goto("/editor");
+ await page.locator('input[type="file"]').first().setInputFiles(fixture);
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 30_000 })
+ .toBeGreaterThanOrEqual(pages);
+ await page.waitForTimeout(2_000);
+}
+
+function pageTopOf(
+ page: import("@playwright/test").Page,
+ index: number,
+): Promise<number> {
+ return page
+ .locator(`[data-page-index="${index}"]`)
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().top));
+}
+
+async function highlightAllText(page: import("@playwright/test").Page) {
+ const point = await page.evaluate(() => {
+ let best: { x: number; y: number; area: number } | null = null;
+ for (const el of document.querySelectorAll<HTMLElement>(
+ "[data-page-index]",
+ )) {
+ const rect = el.getBoundingClientRect();
+ const left = Math.max(0, Math.min(rect.left, window.innerWidth));
+ const top = Math.max(0, Math.min(rect.top, window.innerHeight));
+ const right = Math.max(0, Math.min(rect.right, window.innerWidth));
+ const bottom = Math.max(0, Math.min(rect.bottom, window.innerHeight));
+ const area = Math.max(0, right - left) * Math.max(0, bottom - top);
+ if (!best || area > best.area) {
+ best = { x: (left + right) / 2, y: (top + bottom) / 2, area };
+ }
+ }
+ return best && best.area > 0 ? { x: best.x, y: best.y } : null;
+ });
+ if (!point) throw new Error("No visible page to hover");
+ await page.mouse.move(point.x, point.y);
+ await page.waitForTimeout(150);
+ await page.keyboard.press("Control+A");
+ await page.waitForTimeout(600);
+ const highlight = page
+ .locator('[data-text-selection-menu] button[aria-label="Highlight"]')
+ .first();
+ await expect(highlight).toBeVisible({ timeout: 5_000 });
+ await highlight.click();
+ await page.waitForTimeout(1_500);
+}
+
+async function saveChanges(page: import("@playwright/test").Page) {
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await expect(save).toBeEnabled({ timeout: 15_000 });
+ await save.click();
+ await expect(save).toBeDisabled({ timeout: 20_000 });
+}
+
+async function mockCompress(
+ page: import("@playwright/test").Page,
+ fixture: string,
+) {
+ await page.route("**/api/v1/misc/compress-pdf", async (route) => {
+ const bytes = await fs.promises.readFile(fixture);
+ await route.fulfill({
+ status: 200,
+ contentType: "application/pdf",
+ body: bytes,
+ headers: {
+ "Content-Disposition": 'attachment; filename="compressed.pdf"',
+ },
+ });
+ });
+}
+
+/** Opens the Compress tool page without running it, so the caller can capture
+ * the position the tool output has to preserve. */
+async function openCompressPanel(page: import("@playwright/test").Page) {
+ await page
+ .getByRole("button", { name: "Redact", exact: true })
+ .first()
+ .click();
+ await page.waitForTimeout(800);
+ await page.getByRole("button", { name: "Back to all tools" }).first().click();
+ await page.waitForTimeout(800);
+ await page
+ .getByRole("link", { name: "Compress", exact: true })
+ .first()
+ .click();
+ await page.waitForTimeout(1_500);
+}
+
+async function applyCompress(page: import("@playwright/test").Page) {
+ await page
+ .getByRole("button", { name: "Compress", exact: true })
+ .first()
+ .click();
+}
+
+test("a rotated document saves annotations without reopening", async ({
+ page,
+}) => {
+ test.setTimeout(240_000);
+ await loadFixture(page, ROTATED_TEXT_PDF);
+ await highlightAllText(page);
+
+ await page.evaluate(() => {
+ for (const el of document.querySelectorAll("[data-page-index]")) {
+ el.setAttribute("data-matrix-page-probe", "1");
+ }
+ });
+ const pageCount = await page.locator("[data-page-index]").count();
+
+ await saveChanges(page);
+
+ // The live document survives, so no page node may be replaced.
+ expect(
+ await page.evaluate(
+ () =>
+ document.querySelectorAll('[data-matrix-page-probe="1"]').length ===
+ document.querySelectorAll("[data-page-index]").length,
+ ),
+ ).toBe(true);
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 15_000 })
+ .toBe(pageCount);
+});
+
+test("rotated and landscape pages reload a tool output in place", async ({
+ page,
+}) => {
+ test.setTimeout(240_000);
+ await loadFixture(page, ROTATED_PAGES_PDF, 4);
+ await page.getByRole("button", { name: "Next Page" }).first().click();
+ await page.waitForTimeout(600);
+ await page.getByRole("button", { name: "Zoom In" }).first().click();
+ await page.waitForTimeout(500);
+ await page.mouse.wheel(0, 200);
+ await page.waitForTimeout(500);
+
+ const pageInput = page.getByRole("textbox").first();
+ const pageBefore = await pageInput.inputValue();
+ await mockCompress(page, ROTATED_PAGES_PDF);
+ await openCompressPanel(page);
+ const zoomBefore = await page.getByText(/%$/).first().textContent();
+ await applyCompress(page);
+
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 60_000 })
+ .toBe(4);
+ // The reload keeps the reader on the same page at the same zoom; the tool
+ // panel itself can reset the pixel offset, which predates this work.
+ await expect
+ .poll(async () => pageInput.inputValue(), { timeout: 15_000 })
+ .toBe(pageBefore);
+ await expect
+ .poll(async () => page.getByText(/%$/).first().textContent(), {
+ timeout: 15_000,
+ })
+ .toBe(zoomBefore);
+});
+
+test("dual page view survives a save and a tool output", async ({ page }) => {
+ test.setTimeout(300_000);
+ await loadFixture(page, MULTIPAGE_PDF, 3);
+
+ await page.getByRole("button", { name: "Dual Page View" }).first().click();
+ await expect(
+ page.getByRole("button", { name: "Single Page View" }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ await highlightAllText(page);
+ await saveChanges(page);
+ await expect(
+ page.getByRole("button", { name: "Single Page View" }).first(),
+ ).toBeVisible({ timeout: 15_000 });
+
+ await mockCompress(page, MULTIPAGE_PDF);
+ await openCompressPanel(page);
+ const pageInput = page.getByRole("textbox").first();
+ await applyCompress(page);
+
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 60_000 })
+ .toBe(3);
+ // Dual mode holds across the byte swap, and the reader stays on page one.
+ await expect(
+ page.getByRole("button", { name: "Single Page View" }).first(),
+ ).toBeVisible({ timeout: 15_000 });
+ await expect
+ .poll(async () => pageInput.inputValue(), { timeout: 15_000 })
+ .toBe("1");
+});
+
+test("a tool output keeps the page width and zoom readout steady", async ({
+ page,
+}) => {
+ test.setTimeout(300_000);
+ await loadFixture(page, MULTIPAGE_PDF, 3);
+ const widthBefore = await page
+ .locator('[data-page-index="0"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().width));
+
+ await mockCompress(page, MULTIPAGE_PDF);
+ await openCompressPanel(page);
+ await page.evaluate(() => {
+ const state: SteadyZoomSamplerState = {
+ stop: false,
+ widths: [],
+ indicators: [],
+ };
+ window.__steadySampler = state;
+ const isRendered = (el: HTMLElement): boolean => {
+ try {
+ return el.checkVisibility({ checkVisibilityCSS: true });
+ } catch {
+ return el.getBoundingClientRect().width > 0;
+ }
+ };
+ const tick = () => {
+ if (state.stop) return;
+ const pageEl = document.querySelector<HTMLElement>(
+ '[data-page-index="0"]',
+ );
+ // Only painted frames count: the swap hides the scroller while the
+ // carried zoom lands, and hidden layout is not a visible flash.
+ if (pageEl && isRendered(pageEl))
+ state.widths.push(Math.round(pageEl.getBoundingClientRect().width));
+ const indicator = Array.from(
+ document.querySelectorAll<HTMLElement>("span,div,input"),
+ ).find((el) =>
+ /^\d+%$/.test(
+ (el.textContent ?? el.getAttribute("value") ?? "").trim(),
+ ),
+ );
+ if (indicator) {
+ state.indicators.push(
+ (
+ indicator.textContent ??
+ indicator.getAttribute("value") ??
+ ""
+ ).trim(),
+ );
+ }
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ });
+
+ await applyCompress(page);
+ await page.waitForTimeout(4_000);
+
+ const sampled = await page.evaluate(() => {
+ const state = window.__steadySampler;
+ if (!state) return { widths: [], indicators: [] };
+ state.stop = true;
+ return { widths: state.widths, indicators: state.indicators };
+ });
+
+ // The swap resolves the carried zoom while the scroller is hidden, so no
+ // frame may render a different page width and the readout must not move.
+ const widths = sampled.widths.filter((width) => width > 0);
+ expect(widths.length).toBeGreaterThan(0);
+ expect(Math.max(...widths) - Math.min(...widths)).toBeLessThanOrEqual(4);
+ expect(new Set(sampled.indicators).size).toBeLessThanOrEqual(1);
+ await expect
+ .poll(
+ async () =>
+ Math.abs(
+ widthBefore -
+ (await page
+ .locator('[data-page-index="0"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().width))),
+ ) <= 4,
+ { timeout: 10_000 },
+ )
+ .toBe(true);
+});
+
+test("a manual zoom survives a save and a tool output", async ({ page }) => {
+ test.setTimeout(300_000);
+ await loadFixture(page, MULTIPAGE_PDF, 3);
+ await highlightAllText(page);
+
+ await page.getByRole("button", { name: "Next Page" }).first().click();
+ await page.waitForTimeout(600);
+ await page.getByRole("button", { name: "Zoom In" }).first().click();
+ await page.waitForTimeout(400);
+ const zoomBefore = await page.getByText(/%$/).first().textContent();
+ await page.mouse.wheel(0, 160);
+ await page.waitForTimeout(400);
+
+ await saveChanges(page);
+ await expect
+ .poll(async () => page.getByText(/%$/).first().textContent(), {
+ timeout: 15_000,
+ })
+ .toBe(zoomBefore);
+
+ await mockCompress(page, MULTIPAGE_PDF);
+ await openCompressPanel(page);
+ await applyCompress(page);
+
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 60_000 })
+ .toBe(3);
+ // The manual zoom is carried across the reload. The page the tool panel
+ // leaves the viewer on is not asserted here; the rotated case covers that.
+ await expect
+ .poll(async () => page.getByText(/%$/).first().textContent(), {
+ timeout: 15_000,
+ })
+ .toBe(zoomBefore);
+});
+
+test("a form apply keeps a fit-page zoom", async ({ page }) => {
+ test.setTimeout(300_000);
+ await page.addInitScript(() => {
+ localStorage.setItem(
+ "stirlingpdf_preferences",
+ JSON.stringify({ defaultViewerZoom: "fitPage" }),
+ );
+ });
+ const fieldValue = "value 1";
+ await page.route("**/api/v1/form/fields-with-coordinates", (route) =>
+ route.fulfill({
+ json: [
+ {
+ name: "name_1",
+ label: "Name 1",
+ type: "text",
+ value: fieldValue,
+ options: null,
+ displayOptions: null,
+ required: false,
+ readOnly: false,
+ multiSelect: false,
+ multiline: false,
+ tooltip: null,
+ widgets: [
+ {
+ pageIndex: 0,
+ x: 48,
+ y: 120,
+ width: 300,
+ height: 24,
+ fontSize: 12,
+ cropBoxHeight: 792,
+ },
+ ],
+ },
+ ],
+ }),
+ );
+
+ await loadFixture(page, FORM_PDF, 2);
+
+ const pageWidth = () =>
+ page
+ .locator('[data-page-index="0"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().width));
+ const pageTop = () =>
+ page
+ .locator('[data-page-index="0"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().top));
+
+ // The preference-driven zoom lands a beat after the document renders.
+ const stable = async (read: () => Promise<number>) => {
+ let previous = Number.NaN;
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const current = await read();
+ if (Math.abs(current - previous) <= 1) return current;
+ previous = current;
+ await page.waitForTimeout(100);
+ }
+ return previous;
+ };
+ const field = page
+ .locator('[data-page-index="0"] input[type="text"]')
+ .first();
+ await expect(field).toBeVisible({ timeout: 20_000 });
+ await field.fill("updated value");
+ await page.keyboard.press("Tab");
+
+ // Filling can scroll the field into view, so the baseline is read once the
+ // edit is done, right before the apply.
+ const widthBefore = await stable(pageWidth);
+ const topBefore = await stable(pageTop);
+ await page.getByRole("button", { name: "Apply Changes" }).first().click();
+
+ // A replacement used to open at the plugin's fit-width default while the
+ // preference was fit page, which read as the zoom changing after apply.
+ await expect
+ .poll(async () => Math.abs((await pageWidth()) - widthBefore), {
+ timeout: 15_000,
+ })
+ .toBeLessThanOrEqual(3);
+ await expect
+ .poll(async () => Math.abs((await pageTop()) - topBefore), {
+ timeout: 15_000,
+ })
+ .toBeLessThanOrEqual(3);
+});
+
+test("a form apply reloads the new value and keeps the position", async ({
+ page,
+}) => {
+ test.setTimeout(300_000);
+ let fieldValue = "value 1";
+ await page.route("**/api/v1/form/fields-with-coordinates", (route) =>
+ route.fulfill({
+ json: [
+ {
+ name: "name_1",
+ label: "Name 1",
+ type: "text",
+ value: fieldValue,
+ options: null,
+ displayOptions: null,
+ required: false,
+ readOnly: false,
+ multiSelect: false,
+ multiline: false,
+ tooltip: null,
+ widgets: [
+ {
+ pageIndex: 0,
+ x: 48,
+ y: 120,
+ width: 300,
+ height: 24,
+ fontSize: 12,
+ cropBoxHeight: 792,
+ },
+ ],
+ },
+ ],
+ }),
+ );
+ await page.route("**/api/v1/form/edit-fields**", async (route) => {
+ fieldValue = "updated value";
+ const bytes = await fs.promises.readFile(FORM_PDF);
+ await route.fulfill({
+ status: 200,
+ contentType: "application/pdf",
+ body: bytes,
+ headers: { "Content-Disposition": 'attachment; filename="form.pdf"' },
+ });
+ });
+
+ // The normal viewer shows form overlays; the save bar only exists outside
+ // the form tool, which is the path users hit when filling a downloaded form.
+ await loadFixture(page, FORM_PDF, 2);
+ await page.getByRole("button", { name: "Zoom In" }).first().click();
+ await page.waitForTimeout(400);
+ await page.mouse.wheel(0, 240);
+ await page.waitForTimeout(400);
+ const field = page
+ .locator('[data-page-index="0"] input[type="text"]')
+ .first();
+ await expect(field).toBeVisible({ timeout: 20_000 });
+ await field.fill("updated value");
+ await page.keyboard.press("Tab");
+
+ // Filling can scroll the field into view, so the baseline is read once the
+ // edit is done, right before the apply.
+ const zoomBefore = await page.getByText(/%$/).first().textContent();
+ const pageTopBefore = await pageTopOf(page, 0);
+ await page.getByRole("button", { name: "Apply Changes" }).first().click();
+
+ // The reloaded document carries the value the round trip produced, and the
+ // apply does not rescale the page or move the reader.
+ await expect(field).toHaveValue("updated value", { timeout: 20_000 });
+ await expect
+ .poll(async () => page.getByText(/%$/).first().textContent(), {
+ timeout: 15_000,
+ })
+ .toBe(zoomBefore);
+ await expect
+ .poll(async () => Math.abs((await pageTopOf(page, 0)) - pageTopBefore), {
+ timeout: 15_000,
+ })
+ .toBeLessThanOrEqual(3);
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 15_000 })
+ .toBe(2);
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-in-place-reload.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-in-place-reload.spec.ts
new file mode 100644
index 0000000000..08bf075abe
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-in-place-reload.spec.ts
@@ -0,0 +1,624 @@
+import fs from "node:fs";
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+interface SwapSamplerState {
+ swapMs: number;
+ swapAt: number;
+ abs: number[];
+ samples: number[];
+ pageTops: number[];
+ visible: boolean[];
+ hidden: boolean[];
+ liveCounts: number[];
+ stop: boolean;
+}
+
+declare global {
+ interface Window {
+ __swapSampler?: SwapSamplerState;
+ __revokedObjectUrls?: string[];
+ }
+}
+
+const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
+const MULTIPAGE_PDF = path.join(FIXTURES, "annotations_out_of_order.pdf");
+const SAMPLE_PDF = path.join(FIXTURES, "sample.pdf");
+
+async function loadViewer(
+ page: import("@playwright/test").Page,
+ fixture: string = MULTIPAGE_PDF,
+ pages = 3,
+) {
+ await page.goto("/editor");
+ await page.locator('input[type="file"]').first().setInputFiles(fixture);
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 30_000 })
+ .toBe(pages);
+ await page.waitForTimeout(2_000);
+ return firstPage;
+}
+
+async function hoverVisiblePage(page: import("@playwright/test").Page) {
+ const point = await page.evaluate(() => {
+ let best: { x: number; y: number; area: number } | null = null;
+ for (const el of document.querySelectorAll<HTMLElement>(
+ "[data-page-index]",
+ )) {
+ const rect = el.getBoundingClientRect();
+ const left = Math.max(0, Math.min(rect.left, window.innerWidth));
+ const top = Math.max(0, Math.min(rect.top, window.innerHeight));
+ const right = Math.max(0, Math.min(rect.right, window.innerWidth));
+ const bottom = Math.max(0, Math.min(rect.bottom, window.innerHeight));
+ const area = Math.max(0, right - left) * Math.max(0, bottom - top);
+ if (!best || area > best.area) {
+ best = { x: (left + right) / 2, y: (top + bottom) / 2, area };
+ }
+ }
+ return best && best.area > 0 ? { x: best.x, y: best.y } : null;
+ });
+ if (point) {
+ await page.mouse.move(point.x, point.y);
+ await page.waitForTimeout(150);
+ }
+}
+
+async function highlightAllText(page: import("@playwright/test").Page) {
+ // Ctrl+A is handled only while the viewer is hovered.
+ await hoverVisiblePage(page);
+ await page.keyboard.press("Control+A");
+ await page.waitForTimeout(600);
+ const highlight = page
+ .locator('[data-text-selection-menu] button[aria-label="Highlight"]')
+ .first();
+ await expect(highlight).toBeVisible({ timeout: 5_000 });
+ await highlight.click();
+ await page.waitForTimeout(1_500);
+}
+
+async function saveDocument(page: import("@playwright/test").Page) {
+ // The panel button only enables while the viewer has unsaved changes, so it
+ // also asserts that the edit landed before the save.
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await expect(save).toBeEnabled({ timeout: 10_000 });
+ await save.click();
+}
+
+function tagViewerWrapper(page: import("@playwright/test").Page) {
+ return page.evaluate(() => {
+ const span = document.querySelector<HTMLElement>(
+ ".ph-no-capture:has([data-page-index])",
+ );
+ span?.setAttribute("data-reload-probe", "1");
+ });
+}
+
+function viewerWrapperSurvived(page: import("@playwright/test").Page) {
+ return page.evaluate(
+ () => document.querySelector('[data-reload-probe="1"]') !== null,
+ );
+}
+
+// Samples the scroller from the frame the outgoing pages are replaced, tracking
+// mounted pages so the first rendered frame's position can be asserted.
+async function startSwapSampler(page: import("@playwright/test").Page) {
+ await page.evaluate(() => {
+ const outgoing = document.querySelector<HTMLElement>(
+ '[data-page-index="0"]',
+ );
+ const outgoingAll = Array.from(
+ document.querySelectorAll<HTMLElement>("[data-page-index]"),
+ );
+ // The viewer can unmount and remount while a tool page is open, so the
+ // scroller is resolved per frame instead of captured once.
+ const findScroller = () => {
+ const pageEl = document.querySelector<HTMLElement>(
+ '[data-page-index="0"]',
+ );
+ let scroller: HTMLElement | null = pageEl?.parentElement ?? null;
+ while (scroller) {
+ const style = getComputedStyle(scroller);
+ if (
+ /(auto|scroll)/.test(style.overflowY) &&
+ scroller.scrollHeight > scroller.clientHeight
+ )
+ return scroller;
+ scroller = scroller.parentElement;
+ }
+ return null;
+ };
+ const state: SwapSamplerState = {
+ swapMs: -1,
+ swapAt: -1,
+ abs: [],
+ samples: [],
+ pageTops: [],
+ visible: [],
+ hidden: [],
+ liveCounts: [],
+ stop: false,
+ };
+ window.__swapSampler = state;
+ let t0 = 0;
+ const tick = () => {
+ if (state.stop) return;
+ const scroller = findScroller();
+ const live = Array.from(
+ document.querySelectorAll<HTMLElement>("[data-page-index]"),
+ ).filter((el) => !outgoingAll.includes(el));
+ if (!scroller || !outgoing || outgoing.isConnected || live.length === 0) {
+ requestAnimationFrame(tick);
+ return;
+ }
+ const rect = scroller.getBoundingClientRect();
+ const viewerVisible = rect.width > 0 && rect.height > 0;
+ if (state.swapMs < 0) {
+ state.swapMs = performance.now();
+ state.swapAt = Math.round(state.swapMs);
+ t0 = state.swapMs;
+ }
+ const scrolledPage = document.querySelector<HTMLElement>(
+ '[data-page-index="1"]',
+ );
+ state.abs.push(Math.round(performance.now()));
+ state.hidden.push(getComputedStyle(scroller).visibility === "hidden");
+ state.pageTops.push(
+ scrolledPage
+ ? Math.round(scrolledPage.getBoundingClientRect().top)
+ : Number.NaN,
+ );
+ state.liveCounts.push(live.length);
+ // Only frames the user can actually see count as flash.
+ state.samples.push(Math.round(scroller.scrollTop));
+ state.visible.push(viewerVisible);
+ state.swapMs = Math.round(performance.now() - t0);
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ });
+}
+
+function sampleVisibleFramesOffTarget(
+ pageTops: number[],
+ liveCounts: number[],
+ hidden: boolean[],
+ fromIndex: number,
+ baseline: number,
+) {
+ const offTarget: { index: number; top: number }[] = [];
+ for (let index = fromIndex; index < pageTops.length; index++) {
+ if (liveCounts[index] === 0 || hidden[index]) continue;
+ const top = pageTops[index];
+ if (!Number.isFinite(top)) continue;
+ if (Math.abs(top - baseline) > 20) offTarget.push({ index, top });
+ }
+ return offTarget;
+}
+
+async function readSwapSampler(page: import("@playwright/test").Page) {
+ return page.evaluate(() => {
+ const state = window.__swapSampler;
+ if (!state) return null;
+ state.stop = true;
+ return state;
+ });
+}
+
+// The reveal waits for the carried zoom, which slow engines can take seconds
+// to land; sampling before it would read only hidden frames.
+async function waitForRevealedFrame(page: import("@playwright/test").Page) {
+ await expect
+ .poll(
+ () =>
+ page.evaluate(() => {
+ const state = window.__swapSampler;
+ if (!state) return -1;
+ return state.liveCounts.findIndex(
+ (count, index) => count > 0 && state.hidden[index] !== true,
+ );
+ }),
+ { timeout: 15_000 },
+ )
+ .toBeGreaterThanOrEqual(0);
+}
+test("saving annotations keeps the live document mounted", async ({ page }) => {
+ test.setTimeout(180_000);
+ await loadViewer(page);
+ await highlightAllText(page);
+
+ const undo = page.getByRole("button", { name: "Undo" }).first();
+ await expect(undo).toBeEnabled({ timeout: 5_000 });
+
+ // Give the reload a position and a manual zoom worth carrying over.
+ await page.getByRole("button", { name: "Next Page" }).first().click();
+ await page.waitForTimeout(800);
+ await page.getByRole("button", { name: "Zoom In" }).first().click();
+ await page.waitForTimeout(500);
+ const zoomBefore = await page.getByText(/%$/).first().textContent();
+ await page.mouse.wheel(0, 320);
+ await page.waitForTimeout(400);
+ const pageTop = (index: number) =>
+ page
+ .locator(`[data-page-index="${index}"]`)
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().top));
+ const pageTopBefore = await pageTop(1);
+ const pageInput = page.getByRole("textbox").first();
+ expect(await pageInput.inputValue()).toBe("2");
+
+ // Tag the viewer wrapper: it lives above the document subtree, so it
+ // survives an in-place reload and is replaced by a remount.
+ await tagViewerWrapper(page);
+ // Tag the page nodes themselves: the viewer save keeps the live document,
+ // so the very same nodes must still be mounted after the save.
+ await page.evaluate(() => {
+ for (const el of document.querySelectorAll("[data-page-index]")) {
+ el.setAttribute("data-reload-page-probe", "1");
+ }
+ });
+ // Other hooks may replace their own URLs; only LocalEmbedPDF's revocations
+ // matter, because its published URL feeds PrintAPIBridge.
+ await page.evaluate(() => {
+ const revoked: string[] = [];
+ window.__revokedObjectUrls = revoked;
+ const original = URL.revokeObjectURL.bind(URL);
+ URL.revokeObjectURL = (url: string) => {
+ revoked.push(`${url}\n${new Error("revoke").stack ?? ""}`);
+ return original(url);
+ };
+ });
+ await saveDocument(page);
+
+ // The save replaces the workbench record and clears the unsaved state.
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await expect(save).toBeDisabled({ timeout: 15_000 });
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 15_000 })
+ .toBe(3);
+
+ // The mount and the surrounding viewer survive the byte replacement...
+ expect(await viewerWrapperSurvived(page)).toBe(true);
+ // ...and the document itself is not reopened: the page nodes are the same.
+ expect(
+ await page.evaluate(
+ () =>
+ document.querySelectorAll('[data-reload-page-probe="1"]').length === 3,
+ ),
+ ).toBe(true);
+ const viewerRevokedBlobUrls = await page.evaluate(() =>
+ (window.__revokedObjectUrls ?? []).filter((entry) =>
+ entry.includes("LocalEmbedPDF"),
+ ),
+ );
+ expect(viewerRevokedBlobUrls).toEqual([]);
+ // The within-page offset must hold across the save: snapping to the page top
+ // reads as a jump.
+ await expect
+ .poll(async () => pageInput.inputValue(), { timeout: 10_000 })
+ .toBe("2");
+ await expect
+ .poll(async () => Math.abs((await pageTop(1)) - pageTopBefore) <= 2, {
+ timeout: 15_000,
+ })
+ .toBe(true);
+ await expect
+ .poll(async () => page.getByText(/%$/).first().textContent(), {
+ timeout: 10_000,
+ })
+ .toBe(zoomBefore);
+});
+
+test("consecutive saves each keep the live document", async ({ page }) => {
+ test.setTimeout(180_000);
+ await loadViewer(page);
+ const undo = page.getByRole("button", { name: "Undo" }).first();
+
+ await highlightAllText(page);
+ await tagViewerWrapper(page);
+
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ for (const round of [1, 2]) {
+ await saveDocument(page);
+ await expect(save).toBeDisabled({ timeout: 15_000 });
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), {
+ timeout: 15_000,
+ })
+ .toBe(3);
+ expect(await viewerWrapperSurvived(page)).toBe(true);
+
+ if (round === 1) {
+ // Dirty the surviving document again on the same page.
+ await highlightAllText(page);
+ await expect(undo).toBeEnabled({ timeout: 5_000 });
+ }
+ }
+});
+
+test("a reload keeps other open viewer surfaces", async ({ page }) => {
+ test.setTimeout(180_000);
+ await loadViewer(page);
+
+ const comments = page.getByRole("button", { name: "Comments" }).first();
+ await comments.click();
+ await expect(page.locator(".comments-sidebar").first()).toBeVisible({
+ timeout: 5_000,
+ });
+
+ await highlightAllText(page);
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await saveDocument(page);
+ await expect(save).toBeDisabled({ timeout: 15_000 });
+
+ await expect(page.locator(".comments-sidebar").first()).toBeVisible();
+});
+
+test("text selection and undo survive a reload", async ({ page }) => {
+ test.setTimeout(180_000);
+ const firstPage = await loadViewer(page, SAMPLE_PDF, 1);
+ const selectionRects = firstPage.locator(
+ ".pdf-selection-layer > div:first-child > div",
+ );
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Sample page has no bounding box");
+ const y = box.y + box.height * 0.105;
+ const dragSelect = async () => {
+ 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();
+ };
+
+ await dragSelect();
+ const highlight = page
+ .locator('[data-text-selection-menu] button[aria-label="Highlight"]')
+ .first();
+ await expect(highlight).toBeVisible({ timeout: 5_000 });
+ await highlight.click();
+ await page.waitForTimeout(1_200);
+
+ const undo = page.getByRole("button", { name: "Undo" }).first();
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await expect(undo).toBeEnabled({ timeout: 5_000 });
+ await saveDocument(page);
+ await expect(save).toBeDisabled({ timeout: 15_000 });
+
+ // Text selection still produces rects after the save, so retry until the
+ // selection layer is hit-testable again.
+ await expect
+ .poll(
+ async () => {
+ await dragSelect();
+ await page.waitForTimeout(300);
+ return selectionRects.count();
+ },
+ { timeout: 20_000 },
+ )
+ .toBeGreaterThan(0);
+
+ // History keeps working after a save, and undoing past the saved state makes
+ // the document dirty again rather than being silently purged.
+ await highlightAllText(page);
+ await expect(undo).toBeEnabled({ timeout: 5_000 });
+ await undo.click();
+ // Undoing past the saved state makes the document dirty again, which is the
+ // point: a save no longer throws the user's history away.
+ await expect(save).toBeEnabled({ timeout: 5_000 });
+});
+
+test("a different document remounts and shows its own bytes", async ({
+ page,
+}) => {
+ test.setTimeout(240_000);
+ await loadViewer(page);
+ await tagViewerWrapper(page);
+
+ // A different lineage root cannot share the mount: the viewer remounts.
+ await page.locator('input[type="file"]').first().setInputFiles(SAMPLE_PDF);
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 30_000 })
+ .toBe(1);
+ expect(await viewerWrapperSurvived(page)).toBe(false);
+});
+
+test("tool output reloads the document in place", async ({ page }) => {
+ test.setTimeout(240_000);
+ await loadViewer(page);
+ await tagViewerWrapper(page);
+
+ // Reach the tool picker without leaving the viewer: a viewer tool, then
+ // back to the picker. The workbench stays on "viewer" throughout.
+ await page
+ .getByRole("button", { name: "Redact", exact: true })
+ .first()
+ .click();
+ await page.waitForTimeout(800);
+ await page.getByRole("button", { name: "Back to all tools" }).first().click();
+ await page.waitForTimeout(800);
+ await page.getByRole("link", { name: "Crop PDF" }).first().click();
+ await page.waitForTimeout(1_200);
+
+ // Answer the crop with a different, valid PDF so the reload is observable.
+ await page.route("**/api/v1/general/crop", async (route) => {
+ const bytes = await fs.promises.readFile(SAMPLE_PDF);
+ await route.fulfill({
+ status: 200,
+ contentType: "application/pdf",
+ body: bytes,
+ headers: { "content-disposition": 'attachment; filename="cropped.pdf"' },
+ });
+ });
+ await page.getByRole("button", { name: "Apply Crop" }).first().click();
+
+ // The output replaces the open record under the surviving mount.
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 30_000 })
+ .toBe(1);
+ expect(await viewerWrapperSurvived(page)).toBe(true);
+});
+
+test("a tool output reload shows the saved position in its first frame", async ({
+ page,
+}) => {
+ test.setTimeout(240_000);
+ await loadViewer(page);
+ await page.getByRole("button", { name: "Next Page" }).first().click();
+ await page.waitForTimeout(800);
+ // A manual zoom makes the restore use the fraction path, whose reveal used
+ // to wait for the deadline because the page height legitimately changed.
+ await page.getByRole("button", { name: "Zoom In" }).first().click();
+ await page.waitForTimeout(400);
+ await page.mouse.wheel(0, 260);
+ await page.waitForTimeout(500);
+
+ // Same bytes back, so the captured offset is exactly reproducible.
+ await page.route("**/api/v1/misc/compress-pdf", async (route) => {
+ const bytes = await fs.promises.readFile(MULTIPAGE_PDF);
+ await route.fulfill({
+ status: 200,
+ contentType: "application/pdf",
+ body: bytes,
+ headers: {
+ "Content-Disposition": 'attachment; filename="compressed.pdf"',
+ },
+ });
+ });
+
+ await page
+ .getByRole("button", { name: "Redact", exact: true })
+ .first()
+ .click();
+ await page.waitForTimeout(800);
+ await page.getByRole("button", { name: "Back to all tools" }).first().click();
+ await page.waitForTimeout(800);
+ await page
+ .getByRole("link", { name: "Compress", exact: true })
+ .first()
+ .click();
+ await page.waitForTimeout(1_200);
+
+ // Read the baseline once the panel has settled; the tool page can otherwise
+ // contribute its own preview pages to the sample stream.
+ const pageTopBefore = await page
+ .locator('[data-page-index="1"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().top));
+ await startSwapSampler(page);
+ await page
+ .getByRole("button", { name: "Compress", exact: true })
+ .first()
+ .click();
+
+ // The reload replaces the bytes; no frame may show the top of the document.
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 60_000 })
+ .toBe(3);
+ await waitForRevealedFrame(page);
+ const swap = await readSwapSampler(page);
+ const samples = swap?.samples ?? [];
+ const pageTops = swap?.pageTops ?? [];
+ const hidden = swap?.hidden ?? [];
+ const liveCounts = swap?.liveCounts ?? [];
+ if (samples.length === 0) {
+ // React reused the mounted page nodes across the swap, so nothing could
+ // have jumped; the page must still sit where it was.
+ await expect
+ .poll(
+ async () =>
+ pageTopBefore -
+ (await page
+ .locator('[data-page-index="1"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().top))),
+ { timeout: 10_000 },
+ )
+ .toBeLessThanOrEqual(2);
+ return;
+ }
+
+ // The replacement is hidden while it settles, so the first visible frame must
+ // already show the page where it was and every later one must hold it.
+ const firstVisibleRendered = samples.findIndex(
+ (_, index) => liveCounts[index] > 0 && hidden[index] !== true,
+ );
+ expect(firstVisibleRendered).toBeGreaterThanOrEqual(0);
+ const offTarget = sampleVisibleFramesOffTarget(
+ pageTops,
+ liveCounts,
+ hidden,
+ firstVisibleRendered,
+ pageTopBefore,
+ );
+ expect(offTarget).toEqual([]);
+
+ // The replacement must be revealed as soon as its geometry settles, not at
+ // the deadline. Twelve frames is about 200 ms of slack.
+ const hiddenAfterFirstRender = samples.filter(
+ (_, index) => index > firstVisibleRendered && hidden[index] === true,
+ ).length;
+ expect(hiddenAfterFirstRender).toBeLessThanOrEqual(12);
+});
+
+test("rotation carries over an in-place reload", async ({ page }) => {
+ test.setTimeout(180_000);
+ const firstPage = await loadViewer(page, SAMPLE_PDF, 1);
+
+ const dims = async () => {
+ const box = await firstPage.boundingBox();
+ return box
+ ? { width: Math.round(box.width), height: Math.round(box.height) }
+ : null;
+ };
+ const before = await dims();
+ if (!before) throw new Error("Sample page has no bounding box");
+
+ await page.getByRole("button", { name: "Rotate Left" }).first().click();
+ await expect
+ .poll(
+ async () => {
+ const now = await dims();
+ return now ? now.width > now.height : false;
+ },
+ { timeout: 10_000 },
+ )
+ .toBe(true);
+ const rotated = await dims();
+ expect(rotated?.width).toBe(before.height);
+
+ await highlightAllText(page);
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await saveDocument(page);
+ await expect(save).toBeDisabled({ timeout: 15_000 });
+
+ // The page element is momentarily detached during the swap, so tolerate a
+ // missing box while polling.
+ await expect
+ .poll(
+ async () => {
+ const now = await dims();
+ return now ? now.width > now.height : false;
+ },
+ { timeout: 10_000 },
+ )
+ .toBe(true);
+});
+
+test("a save clears the unsaved state so tools stay reachable", async ({
+ page,
+}) => {
+ test.setTimeout(180_000);
+ await loadViewer(page);
+ await highlightAllText(page);
+ await saveDocument(page);
+
+ // Navigating away must not raise the unsaved-changes dialog after a save.
+ await page
+ .getByRole("button", { name: "Redact", exact: true })
+ .first()
+ .click();
+ await expect(
+ page.getByRole("button", { name: "Back to all tools" }).first(),
+ ).toBeVisible({ timeout: 15_000 });
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-mobile-hot-reload.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-mobile-hot-reload.spec.ts
new file mode 100644
index 0000000000..21ffd3935f
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-mobile-hot-reload.spec.ts
@@ -0,0 +1,117 @@
+import path from "path";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+
+const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
+const MULTIPAGE_PDF = path.join(FIXTURES, "annotations_out_of_order.pdf");
+
+test.use({ viewport: { width: 390, height: 844 }, hasTouch: true });
+
+test.beforeEach(async ({ page }) => {
+ await page.addInitScript(() => {
+ Object.defineProperty(navigator, "maxTouchPoints", {
+ get: () => 10,
+ configurable: true,
+ });
+ });
+});
+
+async function loadViewer(page: import("@playwright/test").Page, pages = 3) {
+ await page.goto("/editor");
+ await page.locator('input[type="file"]').first().setInputFiles(MULTIPAGE_PDF);
+
+ // Narrow viewports put the viewer behind the Workspace tab.
+ const workspaceTab = page.getByRole("tab", { name: "Workspace" });
+ if (await workspaceTab.isVisible().catch(() => false)) {
+ await workspaceTab.click();
+ }
+
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 30_000 })
+ .toBe(pages);
+ await page.waitForTimeout(2_000);
+ return firstPage;
+}
+
+test("phone: a save keeps the live document and the page in place", async ({
+ page,
+}) => {
+ test.setTimeout(240_000);
+ await loadViewer(page);
+
+ if (
+ await page.getByRole("button", { name: "Next Page" }).first().isVisible()
+ ) {
+ await page.getByRole("button", { name: "Next Page" }).first().click();
+ await page.waitForTimeout(600);
+ }
+ const pageTopBefore = await page
+ .locator('[data-page-index="1"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().top));
+
+ // Tag the page nodes: a save must keep the live document on a phone too.
+ await page.evaluate(() => {
+ for (const el of document.querySelectorAll("[data-page-index]")) {
+ el.setAttribute("data-phone-page-probe", "1");
+ }
+ });
+ await page.keyboard.press("Control+s");
+ await page.waitForTimeout(2_500);
+
+ expect(
+ await page.evaluate(
+ () =>
+ document.querySelectorAll('[data-phone-page-probe="1"]').length ===
+ document.querySelectorAll("[data-page-index]").length,
+ ),
+ ).toBe(true);
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 15_000 })
+ .toBe(3);
+ await expect
+ .poll(
+ async () =>
+ Math.abs(
+ pageTopBefore -
+ (await page
+ .locator('[data-page-index="1"]')
+ .first()
+ .evaluate((el) => Math.round(el.getBoundingClientRect().top))),
+ ) <= 3,
+ { timeout: 15_000 },
+ )
+ .toBe(true);
+});
+
+test("phone: rotating the viewport keeps the document and does not crash", async ({
+ page,
+}) => {
+ test.setTimeout(240_000);
+ const errors: string[] = [];
+ page.on("pageerror", (error) => {
+ const message = String(error);
+ // WebKit surfaces the benign ResizeObserver-loop warning as a page error;
+ // reproduced on a clean upstream checkout, so only real errors fail here.
+ if (/ResizeObserver loop (completed|limit exceeded)/.test(message)) return;
+ errors.push(message);
+ });
+ await loadViewer(page);
+ await page.getByRole("button", { name: "Next Page" }).first().click();
+ await page.waitForTimeout(600);
+
+ await page.setViewportSize({ width: 844, height: 390 });
+ await page.waitForTimeout(1_500);
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 15_000 })
+ .toBe(3);
+
+ await page.setViewportSize({ width: 390, height: 844 });
+ await page.waitForTimeout(1_500);
+ await expect
+ .poll(() => page.locator("[data-page-index]").count(), { timeout: 15_000 })
+ .toBe(3);
+
+ expect(errors).toEqual([]);
+});
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-redaction-exit-restores-selection.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-redaction-exit-restores-selection.spec.ts
index f7d72ef1f1..eb3b8713f9 100644
--- a/frontend/editor/src/core/tests/stubbed/viewer-redaction-exit-restores-selection.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/viewer-redaction-exit-restores-selection.spec.ts
@@ -37,6 +37,15 @@ function viewerMode(page: import("@playwright/test").Page) {
});
}
+function grabCursorCount(page: import("@playwright/test").Page) {
+ return page.evaluate(
+ () =>
+ Array.from(document.querySelectorAll<HTMLElement>("div")).filter(
+ (el) => el.style.cursor === "grab",
+ ).length,
+ );
+}
+
test("exiting redaction restores text selection", async ({ page }) => {
test.setTimeout(120_000);
const firstPage = await loadViewer(page);
@@ -87,3 +96,131 @@ test("exiting redaction restores text selection", async ({ page }) => {
timeout: 5_000,
});
});
+
+test("switching to the reader leaves an active pan mode alone", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await loadViewer(page);
+
+ const panButton = page.getByRole("button", { name: "Pan Mode" }).first();
+ await expect(panButton).toBeVisible({ timeout: 10_000 });
+ await panButton.click();
+ await expect
+ .poll(() => grabCursorCount(page), { timeout: 10_000 })
+ .toBeGreaterThan(0);
+
+ // Pan is a manual interaction mode and must survive a tool switch (#7678);
+ // asserted on a switch that does not touch redaction.
+ await page
+ .getByRole("navigation", { name: "Quick navigation" })
+ .getByRole("button", { name: "Reader" })
+ .click();
+
+ await expect
+ .poll(() => grabCursorCount(page), { timeout: 10_000 })
+ .toBeGreaterThan(0);
+});
+
+test("switching the redact tool back to automatic leaves redaction mode", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await loadViewer(page);
+
+ const redactButton = page.getByRole("button", { name: /redact/i }).first();
+ await expect(redactButton).toBeVisible({ timeout: 10_000 });
+ await redactButton.click();
+
+ await expect
+ .poll(async () => (await viewerMode(page)).cursor, { timeout: 15_000 })
+ .toBe("crosshair");
+
+ // The panel is lazy: the mode selector appears once the tool has loaded.
+ const automatic = page.getByText("Automatic", { exact: true }).first();
+ await expect(automatic).toBeVisible({ timeout: 20_000 });
+ await automatic.click();
+
+ await expect
+ .poll(async () => (await viewerMode(page)).touchScroll, { timeout: 10_000 })
+ .toBe("on");
+});
+
+test("redacting from the text selection menu queues a pending redaction", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const firstPage = await loadViewer(page);
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Page wrapper has no bounding box");
+ const y = box.y + box.height * 0.105;
+ 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();
+
+ const redactInMenu = page
+ .locator('[data-text-selection-menu] button[aria-label="Redact"]')
+ .first();
+ await expect(redactInMenu).toBeVisible({ timeout: 5_000 });
+ await redactInMenu.click();
+
+ // The plugin mirrors REDACT annotations into its pending state, so the mark
+ // is immediately actionable rather than only drawable.
+ await expect(page.getByText(/Apply Redactions/).first()).toBeVisible({
+ timeout: 10_000,
+ });
+});
+
+test("saving redactions keeps the live document mounted", async ({ page }) => {
+ test.setTimeout(180_000);
+ const firstPage = await loadViewer(page);
+
+ await page.evaluate(() => {
+ const span = document.querySelector<HTMLElement>(
+ ".ph-no-capture:has([data-page-index])",
+ );
+ span?.setAttribute("data-reload-probe", "1");
+ for (const el of document.querySelectorAll("[data-page-index]")) {
+ el.setAttribute("data-reload-page-probe", "1");
+ }
+ });
+
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Page wrapper has no bounding box");
+ const y = box.y + box.height * 0.105;
+ 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();
+ const redactInMenu = page
+ .locator('[data-text-selection-menu] button[aria-label="Redact"]')
+ .first();
+ await expect(redactInMenu).toBeVisible({ timeout: 5_000 });
+ await redactInMenu.click();
+
+ const save = page.getByRole("button", { name: "Save Changes" }).first();
+ await expect(save).toBeEnabled({ timeout: 15_000 });
+ await expect(page.getByText(/Apply Redactions/).first()).toBeVisible({
+ timeout: 10_000,
+ });
+ await save.click();
+
+ // The committed save clears the pending set and keeps the redacted live
+ // document: the same page nodes stay mounted, so the view cannot move.
+ await expect(page.getByText(/Apply Redactions/).first()).not.toBeVisible({
+ timeout: 30_000,
+ });
+ expect(
+ await page.evaluate(
+ () => document.querySelector('[data-reload-probe="1"]') !== null,
+ ),
+ ).toBe(true);
+ expect(
+ await page.evaluate(
+ () =>
+ document.querySelectorAll('[data-reload-page-probe="1"]').length > 0,
+ ),
+ ).toBe(true);
+});
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
index a43dde7182..3af7a2320f 100644
--- a/frontend/editor/src/core/tests/stubbed/viewer-text-selection.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/viewer-text-selection.spec.ts
@@ -120,7 +120,8 @@ test("Ctrl+C copies selected text to the clipboard", async ({
await dragSelectAcrossPage(page, firstPage);
await page.waitForTimeout(500);
- await page.keyboard.press("Control+C");
+ const isMac = process.platform === "darwin";
+ await page.keyboard.press(isMac ? "Meta+c" : "Control+c");
await page.waitForTimeout(500);
// If keyboard event didn't trigger clipboard write due to container focus, trigger via copy menu
diff --git a/frontend/editor/src/core/tests/test-fixtures/form-fields-sample.pdf b/frontend/editor/src/core/tests/test-fixtures/form-fields-sample.pdf
new file mode 100644
index 0000000000..ccaab491d5
Binary files /dev/null and b/frontend/editor/src/core/tests/test-fixtures/form-fields-sample.pdf differ
diff --git a/frontend/editor/src/core/tests/test-fixtures/generate-form-fields-sample.mjs b/frontend/editor/src/core/tests/test-fixtures/generate-form-fields-sample.mjs
new file mode 100644
index 0000000000..327e76cce9
--- /dev/null
+++ b/frontend/editor/src/core/tests/test-fixtures/generate-form-fields-sample.mjs
@@ -0,0 +1,38 @@
+// One-off script: generate `form-fields-sample.pdf`, a small two-page
+// AcroForm fixture with one text field and one checkbox per page, so the
+// viewer's form-apply reload path can be tested without a large fixture.
+//
+// Run with: node generate-form-fields-sample.mjs
+import { writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { PDFDocument, StandardFonts, rgb } from "@cantoo/pdf-lib";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+const doc = await PDFDocument.create();
+const font = await doc.embedFont(StandardFonts.Helvetica);
+const form = doc.getForm();
+
+for (let index = 0; index < 2; index++) {
+ const page = doc.addPage([612, 792]);
+ page.drawText(`Form page ${index + 1}`, {
+ x: 48,
+ y: 700,
+ size: 18,
+ font,
+ color: rgb(0, 0, 0),
+ });
+
+ const text = form.createTextField(`name_${index + 1}`);
+ text.setText(`value ${index + 1}`);
+ text.addToPage(page, { x: 48, y: 640, width: 300, height: 24 });
+
+ const check = form.createCheckBox(`agree_${index + 1}`);
+ check.addToPage(page, { x: 48, y: 600, width: 18, height: 18 });
+}
+
+const bytes = await doc.save();
+const out = join(here, "form-fields-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`${out}: ${(bytes.length / 1024).toFixed(1)} KB`);
diff --git a/frontend/editor/src/core/theme/colors.css b/frontend/editor/src/core/theme/colors.css
index 0f6f5461a2..df4c5b3812 100644
--- a/frontend/editor/src/core/theme/colors.css
+++ b/frontend/editor/src/core/theme/colors.css
@@ -114,6 +114,12 @@ html[data-app-theme="light"] {
--c-hero-dark: var(--p-zinc-950);
--c-hero-dark-cta-text: var(--p-navy-700);
+ /* Always-dark floating PDF context/selection toolbars. Same in both themes. */
+ --c-floating-menu-bg: var(--p-c-181c24);
+ --c-floating-menu-text: var(--p-gray-250);
+ --c-floating-danger: var(--p-red-500);
+ --c-floating-danger-hover: var(--p-red-400);
+
/* Neutral solid badge fill (grey pill). */
--c-neutral-fill: var(--p-gray-500);
diff --git a/frontend/editor/src/core/theme/primitives.css b/frontend/editor/src/core/theme/primitives.css
index ee8f0225e8..9e3fba3fa1 100644
--- a/frontend/editor/src/core/theme/primitives.css
+++ b/frontend/editor/src/core/theme/primitives.css
@@ -38,6 +38,7 @@
--p-zinc-200: #a1a1aa;
--p-zinc-100: #f4f4f5;
--p-c-141416: #141416;
+ --p-c-181c24: #181c24;
--p-c-1a1a1d: #1a1a1d;
--p-c-100f0e: #100f0e;
--p-c-28282d: #28282d;
diff --git a/frontend/editor/src/core/tools/Redact.tsx b/frontend/editor/src/core/tools/Redact.tsx
index f172a2bc23..5a6c35fc61 100644
--- a/frontend/editor/src/core/tools/Redact.tsx
+++ b/frontend/editor/src/core/tools/Redact.tsx
@@ -35,8 +35,12 @@ const Redact = (props: BaseToolProps) => {
// Navigation and redaction context
const { actions: navActions } = useNavigationActions();
- const { setRedactionConfig, setRedactionMode, redactionConfig } =
- useRedaction();
+ const {
+ setRedactionConfig,
+ setRedactionMode,
+ deactivateRedact,
+ redactionConfig,
+ } = useRedaction();
const { workbench } = useNavigationState();
const hasOpenedViewer = useRef(false);
@@ -47,6 +51,14 @@ const Redact = (props: BaseToolProps) => {
props,
);
+ // Clean up redaction mode when tool unmounts
+ useEffect(() => {
+ return () => {
+ setRedactionMode(false);
+ deactivateRedact();
+ };
+ }, [setRedactionMode, deactivateRedact]);
+
// Get total file count from context (any files in workbench, not just selected)
const { state: fileState } = useFileState();
const hasAnyFiles = fileState.files.ids.length > 0;
@@ -82,10 +94,14 @@ const Redact = (props: BaseToolProps) => {
if (mode === "manual" && hasAnyFiles) {
// Set redaction config and navigate to viewer
- setRedactionConfig(base.params.parameters);
+ setRedactionConfig({ ...base.params.parameters, mode: "manual" });
setRedactionMode(true);
navActions.setWorkbench("viewer");
hasOpenedViewer.current = true;
+ } else if (mode === "automatic") {
+ // Leave the manual-entry config behind, or the reset effect below reads
+ // it as "still manual" and the viewer stays in redaction mode.
+ setRedactionConfig(null);
}
};
@@ -112,11 +128,20 @@ const Redact = (props: BaseToolProps) => {
// Reset viewer flag when mode changes back to automatic
useEffect(() => {
- if (base.params.parameters.mode === "automatic") {
+ if (
+ base.params.parameters.mode === "automatic" &&
+ redactionConfig?.mode !== "manual"
+ ) {
hasOpenedViewer.current = false;
setRedactionMode(false);
+ deactivateRedact();
}
- }, [base.params.parameters.mode, setRedactionMode]);
+ }, [
+ base.params.parameters.mode,
+ redactionConfig?.mode,
+ setRedactionMode,
+ deactivateRedact,
+ ]);
const isExecuteDisabled = () => {
if (base.params.parameters.mode === "manual") {
diff --git a/frontend/editor/src/core/tools/formFill/FormSaveBar.tsx b/frontend/editor/src/core/tools/formFill/FormSaveBar.tsx
index 6f9eb9913d..907540b4f0 100644
--- a/frontend/editor/src/core/tools/formFill/FormSaveBar.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormSaveBar.tsx
@@ -17,6 +17,7 @@ import { useTranslation } from "react-i18next";
import { Icon } from "@app/ui/Icon";
import { useFormFill } from "@app/tools/formFill/FormFillContext";
import { downloadFileWithPolicy } from "@app/services/exportWithPolicy";
+import { getFormFillFileId } from "@app/types/fileContext";
interface FormSaveBarProps {
/** The current file being viewed */
@@ -42,10 +43,13 @@ export function FormSaveBar({
const [applying, setApplying] = useState(false);
const [dismissed, setDismissed] = useState(false);
- // Reset dismissed state when file changes
- const [prevFile, setPrevFile] = useState<File | Blob | null>(null);
- if (file !== prevFile) {
- setPrevFile(file);
+ // Reset the dismissed state only when genuinely different bytes open: the
+ // key folds the content identity (quickKey) in, so a disk reload under an
+ // unchanged record id still brings the bar back.
+ const fileRootKey = getFormFillFileId(file);
+ const [prevFileRootKey, setPrevFileRootKey] = useState<unknown>(fileRootKey);
+ if (fileRootKey !== prevFileRootKey) {
+ setPrevFileRootKey(fileRootKey);
setDismissed(false);
}