Skip to content

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

Fix Sign navigation crash and apply signatures before leaving (#8456)

ConnorYohdb5287dd5f4a
diff --git a/frontend/editor/src/core/components/tools/sign/wallet/useSignaturePlacement.ts b/frontend/editor/src/core/components/tools/sign/wallet/useSignaturePlacement.ts
index 945033f3b1..017d523dce 100644
--- a/frontend/editor/src/core/components/tools/sign/wallet/useSignaturePlacement.ts
+++ b/frontend/editor/src/core/components/tools/sign/wallet/useSignaturePlacement.ts
@@ -101,7 +101,7 @@ export function useSignaturePlacement({
onActivate,
onDeactivate,
}: SignaturePlacementOptions) {
- const { isPlacementMode } = useSignature();
+ const { isPlacementMode, isApplyingSignatures } = useSignature();
const [armedKey, setArmedKey] = useState<string | null>(null);
const activation = useRetriedActivation(onActivate, isPlacementMode);
@@ -125,6 +125,10 @@ export function useSignaturePlacement({
onParameterChange("signatureData", undefined);
}, [activation, onDeactivate, onParameterChange]);
+ useEffect(() => {
+ if (isApplyingSignatures && armedKey !== null) stop();
+ }, [isApplyingSignatures, armedKey, stop]);
+
useEscapeKey(armedKey !== null, stop);
useRearmOnFileSwitch(armedKey !== null, onActivate);
useActivateWhenViewerReady(armedKey !== null, onActivate);
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index 4b0ed257a1..9ef171cdf8 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -181,6 +181,7 @@ const EmbedPdfViewerContent = ({
// Get signature and annotation contexts
const {
+ applySignaturesRef,
signatureApiRef,
annotationApiRef,
historyApiRef,
@@ -491,6 +492,12 @@ const EmbedPdfViewerContent = ({
setRedactionMode,
} = useRedaction();
+ // Resubscribing to history emits its current state as though an edit occurred.
+ const redactionsAppliedRef = useRef(redactionsApplied);
+ useLayoutEffect(() => {
+ redactionsAppliedRef.current = redactionsApplied;
+ }, [redactionsApplied]);
+
// Ref for redaction pending tracker API
const redactionTrackerRef = useRef<RedactionPendingTrackerAPI>(null);
@@ -941,7 +948,7 @@ const EmbedPdfViewerContent = ({
hasAnnotationChangesRef.current = false;
const hasPendingRedactions =
(redactionTrackerRef.current?.getPendingCount() ?? 0) > 0;
- if (!hasPendingRedactions && !redactionsApplied) {
+ if (!hasPendingRedactions && !redactionsAppliedRef.current) {
setHasUnsavedChanges(false);
}
return;
@@ -961,7 +968,7 @@ const EmbedPdfViewerContent = ({
// their own claim on the flag.
const hasPendingRedactions =
(redactionTrackerRef.current?.getPendingCount() ?? 0) > 0;
- if (!hasPendingRedactions && !redactionsApplied) {
+ if (!hasPendingRedactions && !redactionsAppliedRef.current) {
setHasUnsavedChanges(false);
}
};
@@ -972,12 +979,7 @@ const EmbedPdfViewerContent = ({
unsubscribe();
}
};
- }, [
- historyApiRef.current,
- setHasUnsavedChanges,
- redactionsApplied,
- redactionTrackerRef,
- ]);
+ }, [historyApiRef.current, setHasUnsavedChanges, redactionTrackerRef]);
// Register checker for unsaved changes (annotations only for now)
useEffect(() => {
@@ -1022,6 +1024,7 @@ const EmbedPdfViewerContent = ({
}
if (!currentFile || activeFileIds.length === 0) return;
+ const applySignatures = applySignaturesRef.current;
const saveChanges = async () => {
console.log(
@@ -1040,8 +1043,16 @@ const EmbedPdfViewerContent = ({
if (hadPendingRedactions) {
console.log("[Viewer] Committing pending redactions before export");
- redactionTrackerRef.current?.commitAllPending();
- await new Promise((resolve) => setTimeout(resolve, 100));
+ await redactionTrackerRef.current?.commitAllPending();
+ }
+
+ if (applySignatures) {
+ await applySignatures();
+ savedHistoryRevisionRef.current = historyRevisionRef.current;
+ hasAnnotationChangesRef.current = false;
+ setHasUnsavedChanges(false);
+ setRedactionsApplied(false);
+ return;
}
// Step 1: Export PDF with annotations using EmbedPDF
@@ -1122,6 +1133,7 @@ const EmbedPdfViewerContent = ({
currentFile,
activeFiles,
exportActions,
+ applySignaturesRef,
actions,
selectors,
historyApiRef,
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index 4e29a21039..784cee9f01 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -806,7 +806,8 @@ function EditingBridges({
{redactionActive && <RedactionAPIBridge />}
{/* Always render SignatureAPIBridge so annotation tools (draw) can be activated even when starting in redaction mode */}
<SignatureAPIBridge ref={signatureApiRef} isSignMode={isSignMode} />
- {redactionActive && <RedactionPendingTracker ref={redactionTrackerRef} />}
+ {/* Pending redactions must remain available to Save & Leave in other editing tools. */}
+ <RedactionPendingTracker ref={redactionTrackerRef} />
{enableAnnotations && <AnnotationAPIBridge ref={annotationApiRef} />}
</>
);
diff --git a/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx b/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx
index 6c37f67c31..a5f7796658 100644
--- a/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/RedactionAPIBridge.tsx
@@ -32,7 +32,6 @@ function RedactionAPIBridgeInner({ documentId }: { documentId: string }) {
const { selectedTool } = useNavigationState();
const {
redactionApiRef,
- setPendingCount,
setActiveType,
setIsRedacting,
setBridgeReady,
@@ -67,11 +66,10 @@ function RedactionAPIBridgeInner({ documentId }: { documentId: string }) {
// Sync EmbedPDF state to our context
useEffect(() => {
if (state) {
- setPendingCount(state.pendingCount ?? 0);
setActiveType(state.activeType ?? null);
setIsRedacting(state.isRedacting ?? false);
}
- }, [state, setPendingCount, setActiveType, setIsRedacting]);
+ }, [state, setActiveType, setIsRedacting]);
// Synchronize manual redaction color with EmbedPDF
// Manual redaction uses the 'redact' annotation tool internally
diff --git a/frontend/editor/src/core/components/viewer/RedactionPendingTracker.test.tsx b/frontend/editor/src/core/components/viewer/RedactionPendingTracker.test.tsx
new file mode 100644
index 0000000000..c2adfc38ad
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/RedactionPendingTracker.test.tsx
@@ -0,0 +1,60 @@
+import { createRef } from "react";
+import { render } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import {
+ RedactionPendingTracker,
+ type RedactionPendingTrackerAPI,
+} from "@app/components/viewer/RedactionPendingTracker";
+
+const h = vi.hoisted(() => ({
+ commit: vi.fn<() => Promise<boolean>>(),
+ setPendingCount: vi.fn(),
+}));
+
+vi.mock("@app/contexts/RedactionContext", () => ({
+ useRedaction: () => ({ setPendingCount: h.setPendingCount }),
+}));
+
+vi.mock("@app/components/viewer/useActiveDocumentId", () => ({
+ useActiveDocumentId: () => "document",
+}));
+vi.mock("@embedpdf/plugin-redaction/react", () => ({
+ useRedaction: () => ({
+ state: { pendingCount: 1 },
+ provides: { commitAllPending: () => ({ toPromise: h.commit }) },
+ }),
+}));
+
+beforeEach(() => {
+ h.commit.mockReset();
+});
+
+it("keeps save pending until the redaction task finishes", async () => {
+ let finish!: (value: boolean) => void;
+ h.commit.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const ref = createRef<RedactionPendingTrackerAPI>();
+ render(<RedactionPendingTracker ref={ref} />);
+ expect(ref.current?.getPendingCount()).toBe(1);
+ let saved = false;
+ const saving = ref.current!.commitAllPending().then(() => {
+ saved = true;
+ });
+ await Promise.resolve();
+ expect(saved).toBe(false);
+ finish(true);
+ await saving;
+ expect(saved).toBe(true);
+});
+
+it("propagates failed redactions so Save & Leave can stop navigation", async () => {
+ h.commit.mockRejectedValue(new Error("Could not redact document"));
+ const ref = createRef<RedactionPendingTrackerAPI>();
+ render(<RedactionPendingTracker ref={ref} />);
+ await expect(ref.current!.commitAllPending()).rejects.toThrow(
+ "Could not redact document",
+ );
+});
diff --git a/frontend/editor/src/core/components/viewer/RedactionPendingTracker.tsx b/frontend/editor/src/core/components/viewer/RedactionPendingTracker.tsx
index bcd8b950ad..b49fd8fe0e 100644
--- a/frontend/editor/src/core/components/viewer/RedactionPendingTracker.tsx
+++ b/frontend/editor/src/core/components/viewer/RedactionPendingTracker.tsx
@@ -1,9 +1,11 @@
import { useEffect, useRef, useImperativeHandle, forwardRef } from "react";
import { useRedaction as useEmbedPdfRedaction } from "@embedpdf/plugin-redaction/react";
import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
+import { useRedaction } from "@app/contexts/RedactionContext";
export interface RedactionPendingTrackerAPI {
- commitAllPending: () => void;
+ /** Resolves after the document is redacted; rejects if it cannot be committed. */
+ commitAllPending: () => Promise<void>;
getPendingCount: () => number;
}
@@ -27,6 +29,7 @@ const RedactionPendingTrackerInner = forwardRef<
{ documentId: string }
>(function RedactionPendingTrackerInner({ documentId }, ref) {
const { state, provides } = useEmbedPdfRedaction(documentId);
+ const { setPendingCount } = useRedaction();
const pendingCountRef = useRef(0);
@@ -34,20 +37,19 @@ const RedactionPendingTrackerInner = forwardRef<
useImperativeHandle(
ref,
() => ({
- commitAllPending: () => {
- if (provides?.commitAllPending) {
- provides.commitAllPending();
- }
+ commitAllPending: async () => {
+ if (!provides) throw new Error("Redaction API unavailable");
+ await provides.commitAllPending().toPromise();
},
getPendingCount: () => pendingCountRef.current,
}),
[provides],
);
- // Update ref when pending count changes
useEffect(() => {
pendingCountRef.current = state?.pendingCount ?? 0;
- }, [state?.pendingCount]);
+ setPendingCount(pendingCountRef.current);
+ }, [state?.pendingCount, setPendingCount]);
return null;
});
diff --git a/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
index b05031e17f..63c303b235 100644
--- a/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/SignatureAPIBridge.tsx
@@ -597,6 +597,7 @@ export const SignatureAPIBridge = forwardRef<
}
const annotation = event.annotation as StampAnnotation;
+ if (annotation.type !== PdfAnnotationSubtype.STAMP) return;
const annotationId: string | undefined = annotation?.id;
if (!annotationId) {
return;
diff --git a/frontend/editor/src/core/contexts/SignatureContext.tsx b/frontend/editor/src/core/contexts/SignatureContext.tsx
index bbe4bbf3e7..41584a560a 100644
--- a/frontend/editor/src/core/contexts/SignatureContext.tsx
+++ b/frontend/editor/src/core/contexts/SignatureContext.tsx
@@ -59,6 +59,8 @@ interface SignatureActions {
// Combined context interface
interface SignatureContextValue extends SignatureState, SignatureActions {
+ /** The mounted Sign tool's Apply action; rejects when navigation must wait. */
+ applySignaturesRef: React.RefObject<(() => Promise<void>) | null>;
signatureApiRef: React.RefObject<SignatureAPI | null>;
annotationApiRef: React.RefObject<AnnotationAPI | null>;
historyApiRef: React.RefObject<HistoryAPI | null>;
@@ -85,6 +87,7 @@ export const SignatureProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
const [state, setState] = useState<SignatureState>(initialState);
+ const applySignaturesRef = useRef<(() => Promise<void>) | null>(null);
const signatureApiRef = useRef<SignatureAPI>(null);
const annotationApiRef = useRef<AnnotationAPI>(null);
const historyApiRef = useRef<HistoryAPI>(null);
@@ -115,8 +118,8 @@ export const SignatureProvider: React.FC<{ children: ReactNode }> = ({
const deactivateDrawMode = useCallback(() => {
if (signatureApiRef.current) {
signatureApiRef.current.deactivateTools();
- setPlacementMode(false);
}
+ setPlacementMode(false);
}, [setPlacementMode]);
const activateSignaturePlacementMode = useCallback(() => {
@@ -210,6 +213,7 @@ export const SignatureProvider: React.FC<{ children: ReactNode }> = ({
const contextValue: SignatureContextValue = {
...state,
+ applySignaturesRef,
signatureApiRef,
annotationApiRef,
historyApiRef,
diff --git a/frontend/editor/src/core/hooks/useUrlSync.transitions.test.tsx b/frontend/editor/src/core/hooks/useUrlSync.transitions.test.tsx
new file mode 100644
index 0000000000..c8405787b2
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useUrlSync.transitions.test.tsx
@@ -0,0 +1,107 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import type { Location } from "react-router-dom";
+import type { ToolRegistry } from "@app/data/toolsTaxonomy";
+import type { ToolId } from "@app/types/toolId";
+import { useNavigationUrlSync } from "@app/hooks/useUrlSync";
+import { EDITOR_BASENAME } from "@app/routes/editorBasename";
+
+const h = vi.hoisted(() => ({
+ location: {
+ pathname: "/scale-pages",
+ search: "",
+ hash: "",
+ state: null,
+ key: "scale",
+ } as Location,
+ navigate: vi.fn(),
+}));
+
+vi.mock("react-router-dom", () => ({
+ useLocation: () => h.location,
+ useNavigate: () => h.navigate,
+}));
+vi.mock("@app/utils/scarfTracking", () => ({ firePixel: vi.fn() }));
+vi.mock("@app/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { premiumEnabled: true } }),
+}));
+
+const registry = {
+ sign: { name: "Sign", workbench: "viewer" },
+ scalePages: { name: "Adjust page size and scale" },
+} as ToolRegistry;
+
+describe("useNavigationUrlSync router transitions", () => {
+ beforeEach(() => {
+ h.navigate.mockClear();
+ h.location = { ...h.location, pathname: "/scale-pages", key: "scale" };
+ });
+
+ it("requests a guarded history navigation only once per visit", () => {
+ const selectTool = vi.fn();
+ const clearTool = vi.fn();
+ const { rerender } = renderHook(() =>
+ useNavigationUrlSync(
+ "scalePages",
+ (tool) => selectTool(tool),
+ clearTool,
+ registry,
+ ),
+ );
+
+ h.location = { ...h.location, pathname: "/sign", key: "sign" };
+ rerender();
+ expect(selectTool).toHaveBeenCalledExactlyOnceWith("sign");
+
+ // Opening the warning changes the callback without accepting the selection.
+ rerender();
+ rerender();
+ expect(selectTool).toHaveBeenCalledTimes(1);
+
+ h.location = { ...h.location, pathname: "/scale-pages", key: "scale" };
+ rerender();
+ h.location = { ...h.location, pathname: "/sign", key: "sign" };
+ rerender();
+ expect(selectTool).toHaveBeenCalledTimes(2);
+ expect(clearTool).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { selection: "sign" as ToolId | null, target: "/sign" },
+ { selection: null, target: EDITOR_BASENAME },
+ ])(
+ "keeps the selection while $target is pending",
+ ({ selection, target }) => {
+ const selectTool = vi.fn();
+ const clearTool = vi.fn();
+ const { rerender } = renderHook(
+ ({ selectedTool }: { selectedTool: ToolId | null }) =>
+ useNavigationUrlSync(
+ selectedTool,
+ (tool) => selectTool(tool),
+ clearTool,
+ registry,
+ ),
+ { initialProps: { selectedTool: "scalePages" as ToolId | null } },
+ );
+
+ rerender({ selectedTool: selection });
+ expect(h.navigate).toHaveBeenLastCalledWith(target);
+
+ // A dirty-state update changes the guard callback before the router commits.
+ rerender({ selectedTool: selection });
+ rerender({ selectedTool: selection });
+ expect(selectTool).not.toHaveBeenCalled();
+ expect(clearTool).not.toHaveBeenCalled();
+
+ h.location = { ...h.location, pathname: target, key: "destination" };
+ rerender({ selectedTool: selection });
+ expect(selectTool).not.toHaveBeenCalled();
+ expect(clearTool).not.toHaveBeenCalled();
+
+ h.location = { ...h.location, pathname: "/scale-pages", key: "scale" };
+ rerender({ selectedTool: selection });
+ expect(selectTool).toHaveBeenCalledExactlyOnceWith("scalePages");
+ },
+ );
+});
diff --git a/frontend/editor/src/core/hooks/useUrlSync.ts b/frontend/editor/src/core/hooks/useUrlSync.ts
index ae56a31909..054fc9a5aa 100644
--- a/frontend/editor/src/core/hooks/useUrlSync.ts
+++ b/frontend/editor/src/core/hooks/useUrlSync.ts
@@ -36,16 +36,20 @@ export function useNavigationUrlSync(
const { config } = useAppConfig();
const premiumEnabled = config?.premiumEnabled;
const navigate = useNavigate();
- const { pathname, search } = useLocation();
+ const location = useLocation();
+ const { pathname } = location;
const hasInitialized = useRef(false);
const prevSelectedTool = useRef<ToolId | null>(null);
+ const lastReadLocation = useRef<typeof location | null>(null);
// A pixel is a move, not a render.
const countedPath = useRef<string | null>(null);
// Held in a ref so neither pass below depends on it: a write that re-ran on
// every address change would answer a Back by returning to the tool it left.
- const here = useRef({ pathname, search });
- here.current = { pathname, search };
+ const here = useRef(location);
+ useEffect(() => {
+ here.current = location;
+ }, [location]);
// Check if tool requires premium and redirect if needed
const checkPremiumAndSelect = useCallback(
@@ -73,6 +77,7 @@ export function useNavigationUrlSync(
// Fire pixel for initial page load
firePixel(window.location.pathname);
+ lastReadLocation.current = here.current;
const route = parseToolRoute(registry, here.current);
if (route.toolId) {
// URL specifies a tool — navigate to it (URL takes precedence over startup view preference)
@@ -100,17 +105,19 @@ export function useNavigationUrlSync(
useEffect(() => {
if (!enableSync) return;
if (!hasInitialized.current) return;
+ // A guard may keep the old selection while its warning is open. Replaying
+ // that visit would replace the pending navigation and trigger another render.
+ if (lastReadLocation.current === location) return;
// A selection the pass below has not pushed yet is in flight, not stale:
// reconciling it against the address it is leaving would cancel the move.
if (prevSelectedTool.current !== selectedTool) return;
+ lastReadLocation.current = location;
if (countedPath.current !== pathname) {
countedPath.current = pathname;
firePixel(window.location.pathname);
}
- // Disagreement is the trigger, not arrival: a Back can land on the address a
- // tool was picked from, where the path is unchanged but the selection is not.
const route = parseToolRoute(registry, here.current);
if (route.toolId === selectedTool) return;
if (route.toolId) {
@@ -119,7 +126,7 @@ export function useNavigationUrlSync(
clearToolSelection();
}
}, [
- pathname,
+ location,
selectedTool,
clearToolSelection,
registry,
@@ -147,7 +154,7 @@ export function useNavigationUrlSync(
// selection moves off it (cleared below).
if (startupTool !== selectedTool) {
const target = toolRoute(selectedTool, registry, here.current);
- if (target) navigate(target); // Pushed: picking a tool is a navigation
+ if (target) navigate(target);
}
} else if (previous !== null) {
// Only a tool's own address is this hook's to clear: the library and the
diff --git a/frontend/editor/src/core/tests/stubbed/sign-wallet.spec.ts b/frontend/editor/src/core/tests/stubbed/sign-wallet.spec.ts
index 0740ec6b95..d5711f36de 100644
--- a/frontend/editor/src/core/tests/stubbed/sign-wallet.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/sign-wallet.spec.ts
@@ -2,6 +2,8 @@ import { test, expect } from "@app/tests/helpers/stub-test-base";
import { uploadFiles } from "@app/tests/helpers/ui-helpers";
import type { Page, Route } from "@playwright/test";
import path from "path";
+import { readFile } from "node:fs/promises";
+import { PDFDocument, PDFDict, PDFName, PDFNumber } from "@cantoo/pdf-lib";
const SAMPLE_PDF = path.join(
import.meta.dirname,
@@ -68,6 +70,33 @@ async function createTypedSignature(page: Page, name: string) {
await page.getByTestId("signature-type-name").fill(name);
}
+async function expectSavedSignatures(page: Page, count: number) {
+ const row = page.locator(".file-sidebar-file-item").first();
+ await row.hover();
+ await row.locator(".file-sidebar-kebab-btn").click();
+ const downloadPromise = page.waitForEvent("download");
+ await page.getByRole("menuitem", { name: "Download", exact: true }).click();
+ const downloadPath = await (await downloadPromise).path();
+ if (!downloadPath) throw new Error("Signed PDF was not downloaded");
+ const bytes = new Uint8Array(await readFile(downloadPath));
+ const pdf = await PDFDocument.load(bytes);
+ const stamps = pdf.getPages().flatMap((pdfPage) => {
+ const annotations = pdfPage.node.Annots();
+ return Array.from({ length: annotations?.size() ?? 0 }, (_, index) =>
+ annotations!.lookup(index, PDFDict),
+ ).filter(
+ (annotation) =>
+ annotation.get(PDFName.of("Subtype")) === PDFName.of("Stamp"),
+ );
+ });
+ expect(stamps).toHaveLength(count);
+ for (const stamp of stamps) {
+ expect(stamp.lookup(PDFName.of("F"), PDFNumber).asNumber()).toBe(196);
+ expect(stamp.get(PDFName.of("AP"))).toBeDefined();
+ }
+ return bytes;
+}
+
test.describe("Sign tool signature wallet", () => {
test("first run: type, save, place and apply a signature", async ({
page,
@@ -316,6 +345,154 @@ test.describe("Sign tool signature wallet", () => {
await expect(page.getByTestId("signature-wallet")).toBeHidden();
});
+ test("saving unapplied signatures keeps tool switching and browser history usable", async ({
+ page,
+ browserName,
+ }) => {
+ await page.setViewportSize({ width: 1135, height: 1134 });
+ await useBrowserStorage(page);
+ await openSign(page);
+
+ const errors: string[] = [];
+ page.on("pageerror", (error) => {
+ // WebKit reports deferred ResizeObserver notifications as a page error.
+ if (
+ browserName === "webkit" &&
+ error.message ===
+ "ResizeObserver loop completed with undelivered notifications."
+ ) {
+ return;
+ }
+ errors.push(error.stack || error.message);
+ });
+ await startFromIntro(page, "Draw");
+ const pad = page.getByTestId("signature-draw-pad");
+ await expect(pad).toBeVisible();
+ const box = await pad.boundingBox();
+ if (!box) throw new Error("Signature pad has no bounding box");
+ await page.mouse.move(box.x + 80, box.y + 80);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 200, box.y + 130, { steps: 10 });
+ await page.mouse.up();
+ await page.getByTestId("use-signature").click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+ const pdfPage = page.locator("[data-page-index]").first();
+ await expect(pdfPage).toBeVisible();
+ await pdfPage.click({ position: { x: 150, y: 180 } });
+ await pdfPage.click({ position: { x: 150, y: 300 } });
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (2)",
+ );
+ await expect(page.getByTestId("apply-signatures")).toBeEnabled();
+
+ await page.locator("#super-search-input").fill("Adjust page size");
+ await page.getByRole("option", { name: /Adjust page size/ }).click();
+ await expect(page.getByTestId("unsaved-save")).toBeVisible();
+ await page.getByTestId("unsaved-save").click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+ await expect(
+ page.getByLabel("Scale Factor", { exact: true }),
+ ).toBeVisible();
+ await expect(page).toHaveURL(/\/scale-pages$/);
+ await expect(pdfPage).toBeVisible();
+ await expectSavedSignatures(page, 2);
+ await pdfPage.click({ position: { x: 150, y: 420 } });
+ await page.locator("#super-search-input").fill("Sign");
+ await page.getByRole("option", { name: /^Sign Adds signature/ }).click();
+ await expect(page.getByTestId("signature-wallet")).toBeVisible();
+ await expect(page).toHaveURL(/\/sign$/);
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (0)",
+ );
+ await expect(page.getByTestId("apply-signatures")).toBeDisabled();
+ await expect(page.getByTestId("placement-status")).toContainText(
+ "Pick a signature",
+ );
+ await page.getByTestId("signature-tile").first().click();
+ await expect(page.getByTestId("placement-status")).toContainText(
+ "Click the page",
+ );
+ await pdfPage.click({ position: { x: 150, y: 420 } });
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (1)",
+ );
+ await page.goBack();
+ await expect(page.getByTestId("unsaved-save")).toBeVisible();
+ await page.getByTestId("unsaved-save").click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+ await expect(
+ page.getByLabel("Scale Factor", { exact: true }),
+ ).toBeVisible();
+ await page.goForward();
+ await expect(page.getByTestId("signature-wallet")).toBeVisible();
+ await expect(page).toHaveURL(/\/sign$/);
+ await expect(page.getByTestId("placed-signatures")).toContainText(
+ "On this document (0)",
+ );
+ await expect(page.getByTestId("apply-signatures")).toBeDisabled();
+ await expectSavedSignatures(page, 3);
+ expect(errors).toEqual([]);
+ });
+
+ test("Save & Leave applies pending text redactions before saving signatures", async ({
+ page,
+ }) => {
+ await useBrowserStorage(page);
+ await seedBrowserSignature(page, "My signature");
+ await openSign(page);
+ await page
+ .getByRole("button", { name: "My signature", exact: true })
+ .click();
+ await expect(page.getByTestId("placement-status")).toContainText(
+ "Click the page",
+ );
+ const pdfPage = page.locator("[data-page-index]").first();
+ await pdfPage.click({ position: { x: 150, y: 300 } });
+ await expect(page.getByTestId("apply-signatures")).toBeEnabled();
+ await page.keyboard.press("Escape");
+ await expect(page.getByTestId("placement-status")).toContainText(
+ "Pick a signature",
+ );
+ await expect(pdfPage.locator(".pdf-selection-layer")).toBeAttached();
+ const box = await pdfPage.boundingBox();
+ if (!box) throw new Error("PDF page has no bounding box");
+ const y = box.y + box.height * 0.092;
+ 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 redact = page
+ .locator('[data-text-selection-menu] button[aria-label="Redact"]')
+ .first();
+ await expect(redact).toBeVisible();
+ await redact.click();
+ await expect(page.getByText(/Apply Redactions/).first()).toBeVisible();
+ await page
+ .getByRole("button", { name: "Exit Redaction Mode", exact: true })
+ .click();
+ await page.locator("#super-search-input").fill("Sign");
+ await page.getByRole("option", { name: /^Sign Adds signature/ }).click();
+ await expect(page.getByTestId("signature-wallet")).toBeVisible();
+
+ await page.locator("#super-search-input").fill("Adjust page size");
+ await page.getByRole("option", { name: /Adjust page size/ }).click();
+ await page.getByTestId("unsaved-save").click();
+ await expect(page).toHaveURL(/\/scale-pages$/);
+ const bytes = await expectSavedSignatures(page, 1);
+ const { getDocument } = await import("pdfjs-dist/legacy/build/pdf.mjs");
+ const document = await getDocument({ data: bytes }).promise;
+ try {
+ const text = await (await document.getPage(1)).getTextContent();
+ const content = text.items
+ .map((item) => ("str" in item ? item.str : ""))
+ .join(" ");
+ expect(content).not.toContain("document for word");
+ expect(content).toContain("as");
+ } finally {
+ await document.destroy();
+ }
+ });
+
test("deleting the last saved signature preserves document controls", async ({
page,
}) => {
diff --git a/frontend/editor/src/core/tools/stamp/createStampTool.tsx b/frontend/editor/src/core/tools/stamp/createStampTool.tsx
index dd8fdd2842..9efcf62b1a 100644
--- a/frontend/editor/src/core/tools/stamp/createStampTool.tsx
+++ b/frontend/editor/src/core/tools/stamp/createStampTool.tsx
@@ -70,6 +70,7 @@ export const createStampTool = (config: StampToolConfig) => {
updateDrawSettings,
undo,
redo,
+ applySignaturesRef,
signatureApiRef,
getImageData,
setSignaturesApplied,
@@ -138,6 +139,8 @@ export const createStampTool = (config: StampToolConfig) => {
deactivateDrawMode();
}, [deactivateDrawMode]);
+ useEffect(() => handleDeactivateSignature, [handleDeactivateSignature]);
+
useEffect(() => {
if (base.selectedFiles.length > 0 && !hasOpenedViewer.current) {
setWorkbench("viewer");
@@ -154,7 +157,7 @@ export const createStampTool = (config: StampToolConfig) => {
}, [placedSignatures, setHasUnsavedChanges]);
const handleSaveToSystem = useCallback(async () => {
- if (applyInFlightRef.current) return;
+ if (applyInFlightRef.current) return false;
applyInFlightRef.current = true;
setIsApplying(true);
setApplyingSignatures(true);
@@ -191,6 +194,7 @@ export const createStampTool = (config: StampToolConfig) => {
setHasApplied(true);
handleDeactivateSignature();
setHasUnsavedChanges(false);
+ return true;
} else {
throw new Error("Signature flattening failed");
}
@@ -208,6 +212,7 @@ export const createStampTool = (config: StampToolConfig) => {
"Your signatures are still on the document. Try again.",
),
});
+ return false;
} finally {
applyInFlightRef.current = false;
setIsApplying(false);
@@ -233,6 +238,18 @@ export const createStampTool = (config: StampToolConfig) => {
setActiveFileIndex,
]);
+ useEffect(() => {
+ if (!enableApplyAction) return;
+ applySignaturesRef.current = async () => {
+ if (!(await handleSaveToSystem())) {
+ throw new Error("Signatures have not been applied");
+ }
+ };
+ return () => {
+ applySignaturesRef.current = null;
+ };
+ }, [applySignaturesRef, handleSaveToSystem]);
+
const renderSettings = () => {
const onSave = enableApplyAction ? handleSaveToSystem : undefined;
if (settingsPanel === "wallet") {