Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Save a field placed just before Back on Place fields

Claudea0113528acba
diff --git a/e2e/support/admin-session.ts b/e2e/support/admin-session.ts
new file mode 100644
index 0000000..91d743d
--- /dev/null
+++ b/e2e/support/admin-session.ts
@@ -0,0 +1,51 @@
+import { expect, type Page } from "@playwright/test";
+import pg from "pg";
+
+import { e2eDatabaseUrl } from "../../playwright.config";
+
+// The password every account in signing-flow.spec.ts is made with.
+export const E2E_PASSWORD = "correct horse battery staple 42";
+
+/**
+ * Signs in as the administrator that the first test in signing-flow.spec.ts
+ * sets up. The last test there turns on two-step sign-in for them, so it is
+ * turned off again first: these tests are about other things, and a
+ * password is enough for them.
+ */
+export async function signInAsAdministrator(page: Page): Promise<string> {
+ const database = new pg.Client({ connectionString: e2eDatabaseUrl });
+ let adminEmail = "";
+
+ await database.connect();
+
+ try {
+ const admin = await database.query<{ email: string; id: string }>(
+ `select id, email from public."user" where role = 'admin' order by "createdAt" limit 1`,
+ );
+
+ adminEmail = admin.rows[0]?.email ?? "";
+
+ await database.query(
+ `update public."user" set "twoFactorEnabled" = false where id = $1`,
+ [admin.rows[0]?.id],
+ );
+ await database.query(`delete from public."twoFactor" where "userId" = $1`, [
+ admin.rows[0]?.id,
+ ]);
+ await database.query(
+ `update public.app_settings set require_two_factor = false`,
+ );
+ } finally {
+ await database.end();
+ }
+
+ expect(adminEmail).not.toBe("");
+
+ await page.goto("/login");
+ await page.getByLabel("Email").fill(adminEmail);
+ await page.getByLabel("Password").fill(E2E_PASSWORD);
+ await page.getByRole("button", { name: "Log in" }).click();
+ await expect(page).toHaveURL(/\/dashboard$/);
+
+ return adminEmail;
+}
diff --git a/e2e/wizard-prepare-back.spec.ts b/e2e/wizard-prepare-back.spec.ts
new file mode 100644
index 0000000..53b9ce0
--- /dev/null
+++ b/e2e/wizard-prepare-back.spec.ts
@@ -0,0 +1,60 @@
+import { expect, test } from "@playwright/test";
+
+import { signInAsAdministrator } from "./support/admin-session";
+import { writeSamplePdf } from "./support/sample-pdf";
+
+// Runs after signing-flow.spec.ts, which sets up the install and its
+// administrator.
+
+test("Back from Place fields keeps a field placed just before it", async ({
+ page,
+}, testInfo) => {
+ await signInAsAdministrator(page);
+
+ const pdfPath = await writeSamplePdf(testInfo.outputPath("back.pdf"));
+
+ await page.goto("/envelopes/new");
+ await page.getByLabel("Envelope title").fill("Placed then back");
+ await page.getByLabel("Upload PDF").setInputFiles(pdfPath);
+ await page.getByRole("button", { name: "Next ->" }).click();
+ await expect(page).toHaveURL(/\/envelopes\/[^/]+\/signers$/);
+
+ const envelopeId =
+ /\/envelopes\/([^/]+)\/signers$/.exec(page.url())?.[1] ?? "";
+
+ await page.getByLabel("Signer 1 name").fill("Bailey Back");
+ await page.getByLabel("Signer 1 email").fill("[email protected]");
+ await page.getByRole("button", { name: "Next →" }).click();
+ await expect(page).toHaveURL(/\/prepare$/);
+ await expect(
+ page.getByRole("img", { name: "Rendered PDF page 1" }),
+ ).toBeVisible();
+
+ const back = page.getByRole("link", { exact: true, name: "Back" });
+ const backBox = await back.boundingBox();
+
+ await page.getByRole("button", { exact: true, name: "Signature" }).click();
+
+ const placementTarget = page.getByLabel("Place Signature on page 1");
+ const box = await placementTarget.boundingBox();
+
+ expect(box).not.toBeNull();
+ expect(backBox).not.toBeNull();
+ await placementTarget.click({
+ position: { x: box!.width * 0.3, y: box!.height * 0.6 },
+ });
+ await expect(
+ page.getByRole("button", { name: "Bailey Back · Sign" }),
+ ).toBeVisible();
+ // Straight away, before the autosave has had its moment.
+ await page.mouse.click(
+ backBox!.x + backBox!.width / 2,
+ backBox!.y + backBox!.height / 2,
+ );
+ await expect(page).toHaveURL(new RegExp(`/envelopes/${envelopeId}/signers$`));
+
+ await page.goto(`/envelopes/${envelopeId}/prepare`);
+ await expect(
+ page.getByRole("button", { name: "Bailey Back · Sign" }),
+ ).toBeVisible();
+});
diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsx
index bb06df4..084dadd 100644
--- a/src/components/envelopes/prepare-live-shell.tsx
+++ b/src/components/envelopes/prepare-live-shell.tsx
@@ -365,9 +365,7 @@ async function parseJsonResponse<T>(
response: Response,
): Promise<{ data: T | null; error: string | null }> {
const payload = (await response.json().catch(() => null)) as
- | { error?: string }
- | T
- | null;
+ { error?: string } | T | null;
if (!response.ok) {
return {
@@ -454,6 +452,7 @@ function PrepareLiveShellContent({
const [saveState, setSaveState] = useState<SaveState>("saved");
const [saveError, setSaveError] = useState<string | null>(null);
const [isContinuing, setIsContinuing] = useState(false);
+ const [isLeaving, setIsLeaving] = useState(false);
const [isFieldInteracting, setIsFieldInteracting] = useState(false);
const [isDocumentPanning, setIsDocumentPanning] = useState(false);
const [zoomLevel, setZoomLevel] = useState(DEFAULT_DOCUMENT_ZOOM_LEVEL);
@@ -475,6 +474,8 @@ function PrepareLiveShellContent({
currentFieldsRef.current = fields;
+ const backHref = `/envelopes/${envelopeId}/signers`;
+
const pageCount = record.pages.length;
const pageFields = fields.filter((field) => field.page === activePage);
const activePageRecord =
@@ -569,8 +570,22 @@ function PrepareLiveShellContent({
if (autosaveTimeoutRef.current) {
window.clearTimeout(autosaveTimeoutRef.current);
}
+
+ // Leaving the page (a link in the header, say) before the autosave
+ // ran would drop the last change. Send it on the way out; keepalive
+ // lets the request finish after the page has gone.
+ const unsaved = currentFieldsRef.current;
+
+ if (serializeFieldRequest(unsaved) !== lastSavedSignatureRef.current) {
+ void fetch(`/api/envelopes/${envelopeId}/fields`, {
+ body: JSON.stringify(buildFieldRequest(unsaved)),
+ headers: { "content-type": "application/json" },
+ keepalive: true,
+ method: "PUT",
+ }).catch(() => undefined);
+ }
};
- }, []);
+ }, [envelopeId]);
useEffect(() => {
if (!selectedFieldId) {
@@ -723,6 +738,44 @@ function PrepareLiveShellContent({
}
}
+ // Back saves a change the autosave has not sent yet, then goes. If the
+ // save fails, the sender stays here with the error, so nothing they can
+ // see on the page is lost.
+ async function handleBack(event: MouseEvent<HTMLAnchorElement>) {
+ if (
+ serializeFieldRequest(currentFieldsRef.current) ===
+ lastSavedSignatureRef.current
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+
+ if (isLeaving) {
+ return;
+ }
+
+ setIsLeaving(true);
+
+ if (autosaveTimeoutRef.current) {
+ window.clearTimeout(autosaveTimeoutRef.current);
+ autosaveTimeoutRef.current = null;
+ }
+
+ try {
+ const saveResult = await persistFields(currentFieldsRef.current);
+
+ if (saveResult.ok) {
+ window.location.assign(backHref);
+ }
+ } catch {
+ setSaveError("Your changes could not be saved. Try again.");
+ setSaveState("error");
+ } finally {
+ setIsLeaving(false);
+ }
+ }
+
function beginDocumentPan(event: ReactPointerEvent<HTMLDivElement>) {
documentPanGestureRef.current = beginDocumentPanGesture({
canStart: !armedTool,
@@ -758,11 +811,12 @@ function PrepareLiveShellContent({
return (
<CanvasShell
- backHref={`/envelopes/${envelopeId}/signers`}
+ backHref={backHref}
backLabel="Back"
nextDisabled={!canContinue}
nextLabel="Next →"
nextLoading={isContinuing}
+ onBack={(event) => void handleBack(event)}
onNext={handleContinue}
stepLabel="Step 3 of 4"
title={`"${record.title}"`}
@@ -831,16 +885,12 @@ function PrepareLiveShellContent({
<DocumentZoomControls
onDecrease={() =>
setZoomLevel((currentZoom) =>
- clampDocumentZoomLevel(
- currentZoom - DOCUMENT_ZOOM_STEP,
- ),
+ clampDocumentZoomLevel(currentZoom - DOCUMENT_ZOOM_STEP),
)
}
onIncrease={() =>
setZoomLevel((currentZoom) =>
- clampDocumentZoomLevel(
- currentZoom + DOCUMENT_ZOOM_STEP,
- ),
+ clampDocumentZoomLevel(currentZoom + DOCUMENT_ZOOM_STEP),
)
}
onReset={() => setZoomLevel(DEFAULT_DOCUMENT_ZOOM_LEVEL)}
@@ -893,7 +943,9 @@ function PrepareLiveShellContent({
<div className="flex justify-center lg:justify-end">
<SaveStatusIndicator
- onRetrySave={() => void persistFields(currentFieldsRef.current)}
+ onRetrySave={() =>
+ void persistFields(currentFieldsRef.current)
+ }
saveError={saveError}
saveState={saveState}
/>
@@ -1263,7 +1315,9 @@ function SignerCard({
.join("")}
</span>
<div className="min-w-0">
- <p className="truncate text-sm font-bold text-(--fg)">{signer.name}</p>
+ <p className="truncate text-sm font-bold text-(--fg)">
+ {signer.name}
+ </p>
<p className="mt-0.5 text-xs text-(--secondary)">
{fieldCount} field{fieldCount === 1 ? "" : "s"} placed
</p>
@@ -1292,7 +1346,9 @@ function EmptyFieldInspector({
return (
<div className="well px-4 py-4">
<p className="text-sm font-bold text-(--fg)">
- {activeTool ? `${activeTool.label} ready to place` : "No field selected"}
+ {activeTool
+ ? `${activeTool.label} ready to place`
+ : "No field selected"}
</p>
<p className="mt-1.5 text-sm leading-6 text-(--secondary)">
{activeTool
@@ -1808,20 +1864,18 @@ function setFieldRequired(
required: boolean,
setFields: Dispatch<SetStateAction<PrepareField[]>>,
) {
- setFields((currentFields) =>
- {
- const target = currentFields.find((field) => field.id === fieldId);
+ setFields((currentFields) => {
+ const target = currentFields.find((field) => field.id === fieldId);
- if (!target || !canBeOptional(target.type)) {
- return currentFields;
- }
+ if (!target || !canBeOptional(target.type)) {
+ return currentFields;
+ }
- // A radio group is required or optional as a whole.
- return currentFields.map((field) =>
- isSameChoice(target, field) ? { ...field, required } : field,
- );
- },
- );
+ // A radio group is required or optional as a whole.
+ return currentFields.map((field) =>
+ isSameChoice(target, field) ? { ...field, required } : field,
+ );
+ });
}
function deleteField(
diff --git a/src/components/layout/canvas-shell.tsx b/src/components/layout/canvas-shell.tsx
index bf4ff58..eec40bf 100644
--- a/src/components/layout/canvas-shell.tsx
+++ b/src/components/layout/canvas-shell.tsx
@@ -1,5 +1,5 @@
import Link from "next/link";
-import type { ReactNode } from "react";
+import type { MouseEvent, ReactNode } from "react";
import { ChevronLeftIcon } from "@/components/layout/nav-items";
import { Button } from "@/components/ui/button";
@@ -12,6 +12,8 @@ type CanvasShellProps = {
nextHref?: string;
nextLabel?: string;
nextLoading?: boolean;
+ /** Runs before the Back link navigates; it can prevent the navigation. */
+ onBack?: (event: MouseEvent<HTMLAnchorElement>) => void;
onNext?: () => void;
stepLabel: string;
title: string;
@@ -25,6 +27,7 @@ export function CanvasShell({
nextHref,
nextLabel,
nextLoading = false,
+ onBack,
onNext,
stepLabel,
title,
@@ -35,7 +38,11 @@ export function CanvasShell({
<div className="min-h-screen bg-(--page)">
<header className="sticky top-0 z-20 bg-[rgba(255,255,255,0.92)] shadow-[0_1px_0_rgba(28,29,43,0.06)] backdrop-blur-md">
<div className="flex min-h-[4.5rem] items-center justify-between gap-3 px-4 py-3 sm:px-6">
- <Link className="btn-quiet min-h-11 px-3.5" href={backHref}>
+ <Link
+ className="btn-quiet min-h-11 px-3.5"
+ href={backHref}
+ onClick={onBack}
+ >
<ChevronLeftIcon aria-hidden="true" className="-ml-1 size-4" />
{backLabel}
</Link>