Skip to content

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

fix(viewer): exit annotation mode when the toolbar button is clicked again (#8590)

brios85b7e2f6e30a
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 148dc50864..cd0a91ed6f 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -14064,6 +14064,7 @@ closeAll = "Close All Files"
closePdf = "Close PDF"
deselectAll = "Deselect All"
downloadAll = "Download All"
+exitAnnotations = "Exit annotation mode"
exitRedaction = "Exit Redaction Mode"
formFill = "Form Editor"
hideToolbar = "Hide toolbar"
diff --git a/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx b/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx
index 3d6bfca343..5d0eeedd1d 100644
--- a/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx
+++ b/frontend/editor/src/core/components/viewer/useViewerWorkbenchBarButtons.tsx
@@ -19,7 +19,6 @@ import {
useNavigationState,
useNavigationGuard,
} from "@app/contexts/NavigationContext";
-import { stripBasePath, withBasePath } from "@app/constants/app";
import { useRedaction, useRedactionMode } from "@app/contexts/RedactionContext";
import { useViewerReadAloud } from "@app/components/viewer/useViewerReadAloud";
import { RulerScaleSettingsButton } from "@app/components/viewer/RulerScaleSettingsButton";
@@ -78,30 +77,9 @@ export function useViewerWorkbenchBarButtons(
});
}, [registerImmediatePanUpdate]);
- const isAnnotationsPath = useCallback(() => {
- const cleanPath = stripBasePath(window.location.pathname).toLowerCase();
- return cleanPath === "/annotations" || cleanPath.endsWith("/annotations");
- }, []);
-
- const [isAnnotationsActive, setIsAnnotationsActive] = useState<boolean>(() =>
- isAnnotationsPath(),
- );
-
- useEffect(() => {
- if (selectedTool === "annotate") {
- setIsAnnotationsActive(true);
- } else if (selectedTool) {
- setIsAnnotationsActive(false);
- } else {
- setIsAnnotationsActive(isAnnotationsPath());
- }
- }, [selectedTool, isAnnotationsPath]);
-
- useEffect(() => {
- const handlePopState = () => setIsAnnotationsActive(isAnnotationsPath());
- window.addEventListener("popstate", handlePopState);
- return () => window.removeEventListener("popstate", handlePopState);
- }, [isAnnotationsPath]);
+ // The tool the URL resolves to is the single source of truth: a separate
+ // mirror drifts the moment the address changes without a popstate.
+ const isAnnotationsActive = selectedTool === "annotate";
const searchLabel = t("workbenchBar.search", "Search PDF");
const panLabel = t("workbenchBar.panMode", "Pan Mode");
@@ -123,6 +101,10 @@ export function useViewerWorkbenchBarButtons(
const layersLabel = t("workbenchBar.toggleLayers", "Toggle Layers");
const commentsLabel = t("workbenchBar.toggleComments", "Comments");
const annotationsLabel = t("workbenchBar.annotations", "Annotations");
+ const exitAnnotationsLabel = t(
+ "workbenchBar.exitAnnotations",
+ "Exit annotation mode",
+ );
const formFillLabel = t("workbenchBar.formFill", "Form Editor");
const rulerLabel = t("workbenchBar.ruler", "Ruler / Measure");
const rulerSettingsLabel = t("workbenchBar.rulerSettings", "Scale Settings");
@@ -479,7 +461,9 @@ export function useViewerWorkbenchBarButtons(
active: isAnnotationsActive,
render: ({ disabled }) => (
<Tooltip
- content={annotationsLabel}
+ content={
+ isAnnotationsActive ? exitAnnotationsLabel : annotationsLabel
+ }
position={tooltipPosition}
offset={12}
arrow
@@ -489,31 +473,27 @@ export function useViewerWorkbenchBarButtons(
variant={isAnnotationsActive ? "primary" : "tertiary"}
className="workbench-bar-action-icon"
onClick={() => {
- if (disabled || isAnnotationsActive) return;
-
- const hasRedactionChanges =
- pendingCount > 0 || redactionsApplied;
-
- const switchToAnnotations = () => {
- const targetPath = withBasePath("/annotations");
- if (window.location.pathname !== targetPath) {
- window.history.pushState(null, "", targetPath);
- }
- setIsAnnotationsActive(true);
- // Use handleToolSelectForced to bypass the unsaved-changes guard —
- // the navigation warning modal already handled that check.
- handleToolSelectForced("annotate");
- };
-
- if (hasRedactionChanges) {
- requestNavigation(switchToAnnotations);
+ if (disabled) return;
+ if (isAnnotationsActive) {
+ // The tool's own exit path, so pending annotations get the
+ // same save warning Form Editor has always shown.
+ handleBackToTools();
+ return;
+ }
+ if (pendingCount > 0 || redactionsApplied) {
+ // The redaction warning answers the save question, so the
+ // forced selection here avoids a second modal.
+ requestNavigation(() => handleToolSelectForced("annotate"));
} else {
- switchToAnnotations();
+ handleToolSelect("annotate");
}
}}
disabled={disabled}
aria-pressed={isAnnotationsActive}
- aria-label={annotationsLabel}
+ aria-label={
+ isAnnotationsActive ? exitAnnotationsLabel : annotationsLabel
+ }
+ data-testid="annotations-toggle"
>
<Icon name="pencil" size="1rem" />
</ActionIcon>
@@ -587,8 +567,13 @@ export function useViewerWorkbenchBarButtons(
layersLabel,
tooltipPosition,
annotationsLabel,
+ exitAnnotationsLabel,
isAnnotationsActive,
handleToolSelect,
+ handleToolSelectForced,
+ handleBackToTools,
+ requestNavigation,
+ redactionsApplied,
pendingCount,
redactionActiveType,
formFillLabel,
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-annotation-mode-toggle.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-annotation-mode-toggle.spec.ts
new file mode 100644
index 0000000000..5ad9da712b
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/viewer-annotation-mode-toggle.spec.ts
@@ -0,0 +1,168 @@
+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,
+ });
+ return firstPage;
+}
+
+test("the annotations button leaves annotation mode when clicked again", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await loadViewer(page);
+
+ const toggle = page.getByTestId("annotations-toggle");
+ await expect(toggle).toBeVisible({ timeout: 10_000 });
+ await expect(toggle).toHaveAttribute("aria-pressed", "false");
+
+ await toggle.click();
+ await expect(toggle).toHaveAttribute("aria-pressed", "true", {
+ timeout: 15_000,
+ });
+ await expect(page).toHaveURL(/\/annotate/);
+ const highlightTool = page.getByRole("button", {
+ name: "Highlight",
+ exact: true,
+ });
+ await expect(highlightTool).toBeVisible({ timeout: 20_000 });
+
+ await toggle.click();
+ await expect(toggle).toHaveAttribute("aria-pressed", "false", {
+ timeout: 15_000,
+ });
+ await expect(highlightTool).not.toBeVisible();
+ await expect(page).not.toHaveURL(/\/annotate/);
+
+ // Leaving the tool is a mode change, not a document change: the page stays
+ // mounted and selectable.
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible();
+ await expect(firstPage.locator(".pdf-selection-layer")).toBeAttached();
+});
+
+test("exiting with pending annotations asks before leaving", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ const firstPage = await loadViewer(page);
+
+ const toggle = page.getByTestId("annotations-toggle");
+ await toggle.click();
+ await expect(toggle).toHaveAttribute("aria-pressed", "true", {
+ timeout: 15_000,
+ });
+ await expect(
+ page.getByRole("button", { name: "Highlight", exact: true }),
+ ).toBeVisible({ timeout: 20_000 });
+
+ 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
+ .locator('[data-text-selection-menu] button[aria-label="Highlight"]')
+ .first();
+ await expect(highlight).toBeVisible({ timeout: 5_000 });
+ await highlight.click();
+ await expect(
+ page.getByRole("button", { name: "Save Changes" }).first(),
+ ).toBeEnabled({ timeout: 10_000 });
+
+ await toggle.click();
+ const guard = page.getByRole("dialog", {
+ name: "Unsaved Changes",
+ exact: true,
+ });
+ await expect(guard).toBeVisible();
+ await guard
+ .getByRole("button", { name: "Keep Working", exact: true })
+ .click();
+ await expect(toggle).toHaveAttribute("aria-pressed", "true");
+
+ await toggle.click();
+ await expect(guard).toBeVisible();
+ await guard
+ .getByRole("button", { name: "Save & Leave", exact: true })
+ .click();
+ await expect(toggle).toHaveAttribute("aria-pressed", "false", {
+ timeout: 15_000,
+ });
+ await expect(page).not.toHaveURL(/\/annotate/);
+});
+
+const FORM_FIELDS = [
+ {
+ name: "firstName",
+ label: "First name",
+ type: "text",
+ value: "",
+ options: null,
+ displayOptions: null,
+ required: false,
+ readOnly: false,
+ multiSelect: false,
+ multiline: false,
+ tooltip: null,
+ widgets: [
+ {
+ pageIndex: 0,
+ x: 100,
+ y: 100,
+ width: 180,
+ height: 20,
+ fontSize: 12,
+ cropBoxHeight: 792,
+ },
+ ],
+ },
+];
+
+test("entering annotation mode from Form Editor keeps the save warning", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await page.route("**/api/v1/form/fields-with-coordinates", (route) =>
+ route.fulfill({ json: FORM_FIELDS }),
+ );
+ await loadViewer(page);
+
+ await page.getByRole("button", { name: "Form Editor" }).first().click();
+ const field = page.getByRole("textbox", {
+ name: "First name",
+ exact: true,
+ });
+ await expect(field).toBeVisible({ timeout: 30_000 });
+ await field.fill("Unsaved answer");
+ await page.keyboard.press("Tab");
+ await expect(
+ page.getByRole("button", { name: "Save", exact: true }),
+ ).toBeEnabled({ timeout: 5_000 });
+
+ const toggle = page.getByTestId("annotations-toggle");
+ await toggle.click();
+ const guard = page.getByRole("dialog", {
+ name: "Unsaved Changes",
+ exact: true,
+ });
+ await expect(guard).toBeVisible({ timeout: 10_000 });
+ await guard
+ .getByRole("button", { name: "Keep Working", exact: true })
+ .click();
+ await expect(toggle).toHaveAttribute("aria-pressed", "false");
+ await expect(field).toHaveValue("Unsaved answer");
+});