Skip to content

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

fix(forms): preserve drafts and await completed saves (#8455)

ConnorYohf00130b0dc21
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index ea7e56621e..1b2b94c5cd 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -5245,6 +5245,7 @@ rescanFields = "Re-scan fields"
rescanFormFields = "Re-scan form fields"
save = "Save"
saveShortcut = "Ctrl+S to save"
+saving = "Saving..."
selectOptionPlaceholder = "— select —"
skippedEdits_one = "1 change could not be applied:"
skippedEdits_other = "{{count}} changes could not be applied:"
@@ -5252,9 +5253,7 @@ skippedEditsTruncated = "{{count}} more not listed."
unsavedChanges = "Unsaved changes"
[formFill.create]
-commit = "Add {{count}} field(s) to PDF"
empty = "No fields drawn yet."
-failed = "Failed to add fields"
goToField = "Go to this field"
hint = "Pick a field type, then draw it on the page."
placing = "Draw a {{type}} field on the page. Press Esc to stop."
@@ -5328,7 +5327,6 @@ modify = "Modify"
commit = "Save {{count}} change(s)"
delete = "Delete"
empty = "This PDF has no form fields yet."
-failed = "Failed to save changes"
groupSizeHint = "Use Option size"
hint = "Select a field to edit its properties, drag it on the page, or delete it."
restore = "Restore"
diff --git a/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx b/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx
index e3349664d1..e0d79cf6ab 100644
--- a/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx
+++ b/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx
@@ -1,4 +1,4 @@
-import { useRef, useEffect } from "react";
+import { useRef, useEffect, useState } from "react";
import { flushSync } from "react-dom";
import { useNavigationGuard } from "@app/contexts/NavigationContext";
import { UnsavedChangesDialog } from "@app/components/shared/UnsavedChangesDialog";
@@ -13,6 +13,9 @@ const NavigationWarningModal = () => {
navigationWarningHandlersRef,
} = useNavigationGuard();
+ const [saving, setSaving] = useState(false);
+ const savingRef = useRef(false);
+
// Store pendingNavigation in a ref so async handlers always have the latest,
// not a stale closure captured before an await.
const pendingNavigationRef = useRef(pendingNavigation);
@@ -21,6 +24,7 @@ const NavigationWarningModal = () => {
}, [pendingNavigation]);
const handleKeepWorking = () => {
+ if (savingRef.current) return;
cancelNavigation();
};
@@ -37,6 +41,7 @@ const NavigationWarningModal = () => {
};
const handleDiscardChanges = async () => {
+ if (savingRef.current) return;
const handlers = navigationWarningHandlersRef.current;
if (handlers?.onDiscardAndContinue) {
await handlers.onDiscardAndContinue();
@@ -45,6 +50,9 @@ const NavigationWarningModal = () => {
};
const handleApplyAndContinue = async () => {
+ if (savingRef.current) return;
+ savingRef.current = true;
+ setSaving(true);
const handlers = navigationWarningHandlersRef.current;
try {
if (handlers?.onApplyAndContinue) {
@@ -53,6 +61,9 @@ const NavigationWarningModal = () => {
finishAndNavigate();
} catch (error) {
console.error("Failed to apply changes before navigating:", error);
+ } finally {
+ savingRef.current = false;
+ setSaving(false);
}
};
@@ -77,6 +88,7 @@ const NavigationWarningModal = () => {
return (
<UnsavedChangesDialog
opened={showNavigationWarning}
+ saving={saving}
onKeepWorking={handleKeepWorking}
onDiscard={handleDiscardChanges}
onSave={hasApply ? handleApplyAndContinue : undefined}
diff --git a/frontend/editor/src/core/components/shared/UnsavedChangesDialog.tsx b/frontend/editor/src/core/components/shared/UnsavedChangesDialog.tsx
index dea864db69..75863d796c 100644
--- a/frontend/editor/src/core/components/shared/UnsavedChangesDialog.tsx
+++ b/frontend/editor/src/core/components/shared/UnsavedChangesDialog.tsx
@@ -33,7 +33,9 @@ export function UnsavedChangesDialog({
return (
<Modal
opened={opened}
- onClose={onKeepWorking}
+ onClose={() => {
+ if (!saving) onKeepWorking();
+ }}
centered
size={rem(400)}
radius="lg"
@@ -41,8 +43,8 @@ export function UnsavedChangesDialog({
withCloseButton={false}
overlayProps={{ blur: 4, opacity: 0.4 }}
transitionProps={{ transition: "pop", duration: 140 }}
- closeOnClickOutside={true}
- closeOnEscape={true}
+ closeOnClickOutside={!saving}
+ closeOnEscape={!saving}
zIndex={Z_INDEX_TOAST}
>
<Modal.Title className="sr-only">{heading}</Modal.Title>
@@ -76,7 +78,12 @@ export function UnsavedChangesDialog({
</Button>
)}
{onExport && (
- <Button fullWidth variant="primary" onClick={onExport}>
+ <Button
+ fullWidth
+ variant="primary"
+ disabled={saving}
+ onClick={onExport}
+ >
{t("exportAndContinue", "Export & Leave")}
</Button>
)}
@@ -84,6 +91,7 @@ export function UnsavedChangesDialog({
<Button
variant="secondary"
accent="neutral"
+ disabled={saving}
data-autofocus
onClick={onKeepWorking}
>
@@ -92,6 +100,7 @@ export function UnsavedChangesDialog({
<Button
variant="secondary"
accent="danger"
+ disabled={saving}
data-testid="unsaved-discard"
onClick={onDiscard}
>
diff --git a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
index 8685b01d4e..7344525ff3 100644
--- a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx
@@ -4,12 +4,13 @@ import { useDocumentManagerCapability } from "@embedpdf/plugin-document-manager/
interface PendingDocument {
buffer: ArrayBuffer;
name: string;
+ fileKey: string;
}
interface DocumentSwapBridgeProps {
pending: PendingDocument | null;
- onSwapped: (documentId: string) => void;
- onFailed: (error: unknown) => void;
+ onSwapped: (documentId: string, fileKey: string) => void;
+ onFailed: (fileKey: string, error: unknown) => void;
}
/** Activates replacement bytes once loaded, so the mounted document keeps
@@ -22,20 +23,30 @@ export function DocumentSwapBridge({
}: DocumentSwapBridgeProps) {
const { provides: documentManager } = useDocumentManagerCapability();
const generationRef = useRef(0);
+ const pendingRef = useRef(pending);
useEffect(() => {
- if (!documentManager || !pending) return;
const generation = ++generationRef.current;
+ pendingRef.current = documentManager ? pending : null;
+ if (!documentManager || !pending) return;
let cancelled = false;
+ let settled = false;
+ const fail = (error: unknown) => {
+ settled = true;
+ onFailed(pending.fileKey, error);
+ };
const previousId = documentManager.getActiveDocumentId();
- void documentManager
- .openDocumentBuffer({
- buffer: pending.buffer,
- name: pending.name,
- autoActivate: false,
- })
- .toPromise()
+ void Promise.resolve()
+ .then(() =>
+ 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.
@@ -46,7 +57,7 @@ export function DocumentSwapBridge({
.closeDocument(response.documentId)
.toPromise()
.catch(() => {});
- if (!cancelled) onFailed(error);
+ if (!cancelled) fail(error);
return;
}
if (cancelled || generation !== generationRef.current) {
@@ -60,7 +71,8 @@ export function DocumentSwapBridge({
try {
documentManager.setActiveDocument(response.documentId);
- onSwapped(response.documentId);
+ settled = true;
+ onSwapped(response.documentId, pending.fileKey);
if (previousId && previousId !== response.documentId) {
// A failed close only leaks a background document until unmount.
void documentManager
@@ -80,17 +92,28 @@ export function DocumentSwapBridge({
.closeDocument(response.documentId)
.toPromise()
.catch(() => {});
- if (!cancelled) onFailed(error);
+ if (!cancelled) fail(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);
+ if (!cancelled && generation === generationRef.current) fail(error);
});
return () => {
cancelled = true;
+ // A StrictMode replay or callback change restarts the same load. Only
+ // report cancellation when no replacement attempt owns that request.
+ queueMicrotask(() => {
+ if (
+ !settled &&
+ (generationRef.current === generation ||
+ pendingRef.current !== pending)
+ ) {
+ fail(new Error("The document load was cancelled."));
+ }
+ });
};
}, [documentManager, pending, onSwapped, onFailed]);
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index 9ef171cdf8..fcf93661b6 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -59,7 +59,11 @@ import {
import { useWheelZoom } from "@app/hooks/useWheelZoom";
import { useFormFill } from "@app/tools/formFill/FormFillContext";
import { FormSaveBar } from "@app/tools/formFill/FormSaveBar";
-import { FORM_APPLY_EVENT } from "@app/tools/formFill/formFillEvents";
+import { useDocumentLoadWaiter } from "@app/components/viewer/useDocumentLoadWaiter";
+import {
+ FORM_APPLY_EVENT,
+ type FormApplyDetail,
+} from "@app/tools/formFill/formFillEvents";
import { useViewerKeyCommand } from "@app/hooks/useViewerKeyCommand";
import { useMeasurementManager } from "@app/hooks/useMeasurementManager";
import { ScaleCalibrationDialog } from "@app/components/viewer/ScaleCalibrationDialog";
@@ -482,6 +486,8 @@ const EmbedPdfViewerContent = ({
]);
const formApplyInProgressRef = useRef(false);
+ const { waitForDocument, documentReady, documentFailed } =
+ useDocumentLoadWaiter();
const applyChangesInFlightRef = useRef<Promise<void> | null>(null);
// Get redaction context
@@ -983,7 +989,7 @@ const EmbedPdfViewerContent = ({
// Register checker for unsaved changes (annotations only for now)
useEffect(() => {
- if (previewFile) {
+ if (previewFile || isFormFillToolActive) {
return;
}
@@ -1011,6 +1017,7 @@ const EmbedPdfViewerContent = ({
}, [
historyApiRef,
previewFile,
+ isFormFillToolActive,
registerUnsavedChangesChecker,
unregisterUnsavedChangesChecker,
isManualRedactMode,
@@ -1146,10 +1153,13 @@ const EmbedPdfViewerContent = ({
// Apply form fill changes - reload the filled PDF into the viewer
const handleFormApply = useCallback(
async (filledBlob: Blob) => {
- if (formApplyInProgressRef.current) return;
- if (!currentFile || activeFileIds.length === 0) return;
+ if (formApplyInProgressRef.current)
+ throw new Error("A form save is already in progress.");
+ if (!currentFile || activeFileIds.length === 0)
+ throw new Error("No PDF is open.");
formApplyInProgressRef.current = true;
+ let savedFileKey: string | null = null;
try {
console.log(
"[Viewer] Applying form fill changes - reloading filled PDF",
@@ -1176,20 +1186,43 @@ const EmbedPdfViewerContent = ({
);
const newFileId = stubs[0]?.id;
- if (newFileId) setActiveFileId(newFileId);
+ savedFileKey = getFormFillFileId(stirlingFiles[0]);
+ if (!newFileId || !savedFileKey)
+ throw new Error("Saved file ID not found");
+ const loaded = waitForDocument(savedFileKey);
// Replace the current file in context
- await actions.consumeFiles([currentFileId], stirlingFiles, stubs);
+ await Promise.all([
+ actions
+ .consumeFiles([currentFileId], stirlingFiles, stubs)
+ .then(() => {
+ // Selecting an unpersisted ID falls back to another open PDF and remounts the viewer.
+ setActiveFileId(newFileId);
+ return fetchFormFields(
+ stirlingFiles[0],
+ getFormFillFileId(stirlingFiles[0]) ?? undefined,
+ );
+ }),
+ loaded,
+ ]);
console.log("[Viewer] Form fill changes applied successfully");
} catch (error) {
+ if (savedFileKey) documentFailed(savedFileKey, error);
console.error("[Viewer] Apply form changes failed:", error);
+ throw error;
} finally {
formApplyInProgressRef.current = false;
}
},
[
currentFile,
+ currentFileStableId,
+ selectedTool,
+ fetchFormFields,
+ waitForDocument,
+ documentFailed,
+ setActiveFileId,
activeFiles,
actions,
selectors,
@@ -1199,15 +1232,14 @@ const EmbedPdfViewerContent = ({
);
useEffect(() => {
+ if (previewFile) return;
const handler = (e: Event) => {
- const blob = (e as CustomEvent).detail?.blob;
- if (blob) {
- handleFormApply(blob);
- }
+ const detail = (e as CustomEvent<FormApplyDetail>).detail;
+ detail.complete(handleFormApply(detail.blob));
};
window.addEventListener(FORM_APPLY_EVENT, handler);
return () => window.removeEventListener(FORM_APPLY_EVENT, handler);
- }, [handleFormApply]);
+ }, [handleFormApply, previewFile]);
// Apply layer visibility changes - reload the modified PDF into the viewer
const layerApplyInProgressRef = useRef(false);
@@ -1320,7 +1352,7 @@ const EmbedPdfViewerContent = ({
// Register navigation warning handlers so the global modal can call our save/discard logic
useEffect(() => {
- if (previewFile) return;
+ if (previewFile || isFormFillToolActive) return;
registerNavigationWarningHandlers({
onApplyAndContinue: async () => {
@@ -1342,6 +1374,7 @@ const EmbedPdfViewerContent = ({
return () => unregisterNavigationWarningHandlers();
}, [
previewFile,
+ isFormFillToolActive,
applyChanges,
discardAndSaveApplied,
registerNavigationWarningHandlers,
@@ -1738,6 +1771,7 @@ const EmbedPdfViewerContent = ({
if (
currentFile &&
!isCurrentFileEncrypted &&
+ !formApplyInProgressRef.current &&
(fileChanged || providerChanged)
) {
console.log("[FormFill] Fetching form fields for:", currentFileId);
@@ -1844,6 +1878,8 @@ const EmbedPdfViewerContent = ({
onPageLayout={handleViewerPageLayout}
onDocumentSwapped={handleDocumentSwapped}
onDocumentSwapFailed={handleDocumentSwapFailed}
+ onDocumentReady={documentReady}
+ onDocumentLoadFailed={documentFailed}
restorePending={restorePending}
restoreRequest={restoreRequest}
onRestoreEvent={handleRestoreEvent}
diff --git a/frontend/editor/src/core/components/viewer/InitialDocumentLoadBridge.tsx b/frontend/editor/src/core/components/viewer/InitialDocumentLoadBridge.tsx
new file mode 100644
index 0000000000..3311d71293
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/InitialDocumentLoadBridge.tsx
@@ -0,0 +1,47 @@
+import { useEffect, useRef } from "react";
+import { useActiveDocument } from "@embedpdf/plugin-document-manager/react";
+
+interface InitialDocumentLoadBridgeProps {
+ fileKey: string | null;
+ onReady: (fileKey: string) => void;
+ onFailed: (fileKey: string, error: unknown) => void;
+}
+
+/** Reports the registry's initial load, which never passes through DocumentSwapBridge. */
+export function InitialDocumentLoadBridge({
+ fileKey,
+ onReady,
+ onFailed,
+}: InitialDocumentLoadBridgeProps) {
+ const { activeDocument } = useActiveDocument();
+ const completedRef = useRef(false);
+ const generationRef = useRef(0);
+ useEffect(() => {
+ const generation = ++generationRef.current;
+ return () => {
+ queueMicrotask(() => {
+ if (
+ fileKey &&
+ !completedRef.current &&
+ generationRef.current === generation
+ ) {
+ onFailed(fileKey, new Error("The document load was cancelled."));
+ }
+ });
+ };
+ }, [fileKey, onFailed]);
+ useEffect(() => {
+ if (!fileKey || completedRef.current) return;
+ if (activeDocument?.status === "loaded") {
+ completedRef.current = true;
+ onReady(fileKey);
+ } else if (activeDocument?.status === "error") {
+ completedRef.current = true;
+ onFailed(
+ fileKey,
+ new Error(activeDocument.error ?? "The saved PDF could not be opened."),
+ );
+ }
+ }, [fileKey, activeDocument, onReady, onFailed]);
+ return null;
+}
diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
index 784cee9f01..91ca801780 100644
--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx
@@ -115,6 +115,7 @@ import {
import { RedactionAPIBridge } from "@app/components/viewer/RedactionAPIBridge";
import { DocumentPermissionsAPIBridge } from "@app/components/viewer/DocumentPermissionsAPIBridge";
import { DocumentReadyWrapper } from "@app/components/viewer/DocumentReadyWrapper";
+import { InitialDocumentLoadBridge } from "@app/components/viewer/InitialDocumentLoadBridge";
import ToolLoadingFallback from "@app/components/tools/ToolLoadingFallback";
import { useFontFallbackConfig } from "@app/hooks/useFontFallbackConfig";
import { pdfiumWasmUrl } from "@app/services/wasmPrecompiler";
@@ -179,6 +180,10 @@ interface LocalEmbedPDFProps {
onDocumentSwapped?: (documentId: string) => void;
/** Fires when the swap bridge fails to open or activate a replacement document. */
onDocumentSwapFailed?: (error: unknown) => void;
+ /** Includes initial loads after a remount; keyed to the requested file's bytes. */
+ onDocumentReady?: (fileKey: string) => void;
+ /** Includes byte-read failures, engine errors and cancelled loads. */
+ onDocumentLoadFailed?: (fileKey: string, error: unknown) => void;
/** True while a view restore is in flight; gates the per-page layout hook. */
restorePending?: boolean;
restoreRequest?: DocumentRestoreRequest | null;
@@ -845,6 +850,8 @@ export function LocalEmbedPDF({
onPageLayout,
onDocumentSwapped,
onDocumentSwapFailed,
+ onDocumentReady,
+ onDocumentLoadFailed,
restorePending = false,
restoreRequest = null,
onRestoreEvent,
@@ -946,6 +953,30 @@ 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);
+ const loadOwnerRef = useRef<{ key: string | null; generation: number }>({
+ key: null,
+ generation: 0,
+ });
+ useEffect(() => {
+ const key = fileStableKey ?? url ?? null;
+ const generation = loadOwnerRef.current.generation + 1;
+ loadOwnerRef.current = { key, generation };
+ return () => {
+ // React may replay the effect for the same source. That is a retry, not a cancelled save.
+ queueMicrotask(() => {
+ if (
+ key &&
+ (loadOwnerRef.current.generation === generation ||
+ loadOwnerRef.current.key !== key)
+ ) {
+ onDocumentLoadFailed?.(
+ key,
+ new Error("The document load was cancelled."),
+ );
+ }
+ });
+ };
+ }, [fileStableKey, url, onDocumentLoadFailed]);
// Keyed by fileStableKey to avoid recomputing on every FileContext re-render.
const exportFileName = useMemo(() => {
@@ -960,10 +991,12 @@ export function LocalEmbedPDF({
const [initialDocument, setInitialDocument] = useState<{
buffer: ArrayBuffer;
name: string;
+ fileKey: string;
} | null>(null);
const [pendingDocument, setPendingDocument] = useState<{
buffer: ArrayBuffer;
name: string;
+ fileKey: string;
} | null>(null);
const initialDocumentOpenedRef = useRef(false);
const openedContentKeyRef = useRef<string | null>(null);
@@ -1023,12 +1056,15 @@ export function LocalEmbedPDF({
openedContentKeyRef.current = contentKey;
if (!initialDocumentOpenedRef.current) {
initialDocumentOpenedRef.current = true;
- setInitialDocument({ buffer, name });
+ setInitialDocument({ buffer, name, fileKey: contentKey });
return;
}
- setPendingDocument({ buffer, name });
+ setPendingDocument({ buffer, name, fileKey: contentKey });
};
const fail = (source: string) => (err: unknown) => {
+ if (cancelled) return;
+ const key = fileStableKey ?? url;
+ if (key) onDocumentLoadFailed?.(key, err);
console.error(
`[LocalEmbedPDF] Failed to read ${source} arrayBuffer:`,
err,
@@ -1072,7 +1108,13 @@ export function LocalEmbedPDF({
URL.revokeObjectURL(objectUrl);
}
};
- }, [file ? fileStableKey : null, url, shouldSkipBytes, exportFileName]);
+ }, [
+ file ? fileStableKey : null,
+ url,
+ shouldSkipBytes,
+ exportFileName,
+ onDocumentLoadFailed,
+ ]);
useEffect(() => {
// A pending revocation belongs to a previous mount of this effect; cancel
@@ -1092,27 +1134,45 @@ export function LocalEmbedPDF({
}, []);
const [swapAnnouncement, setSwapAnnouncement] = useState<string | null>(null);
+ const handleDocumentReady = useCallback(
+ (fileKey: string) => {
+ onDocumentReady?.(fileKey);
+ },
+ [onDocumentReady],
+ );
+ const handleDocumentLoadFailed = useCallback(
+ (fileKey: string, error: unknown) => {
+ onDocumentLoadFailed?.(fileKey, error);
+ },
+ [onDocumentLoadFailed],
+ );
const handleDocumentSwapped = useCallback(
- (documentId: string) => {
+ (documentId: string, fileKey: string) => {
+ onDocumentReady?.(fileKey);
onDocumentSwapped?.(documentId);
- setPendingDocument(null);
+ setPendingDocument((pending) =>
+ pending?.fileKey === fileKey ? null : pending,
+ );
setSwapAnnouncement(t("viewer.documentUpdated", "Document updated"));
setTimeout(() => setSwapAnnouncement(null), 3000);
},
- [onDocumentSwapped, t],
+ [onDocumentReady, onDocumentSwapped, t],
);
const handleDocumentSwapFailed = useCallback(
- (error: unknown) => {
+ (fileKey: string, error: unknown) => {
// The outgoing document stays active; the replacement never landed.
console.warn(
"[LocalEmbedPDF] Replacement document failed to open:",
error,
);
- onDocumentSwapFailed?.(error);
- setPendingDocument(null);
+ onDocumentLoadFailed?.(fileKey, error);
+ if (fileKey === fileStableKey) onDocumentSwapFailed?.(error);
+ setPendingDocument((pending) =>
+ pending?.fileKey === fileKey ? null : pending,
+ );
},
- [onDocumentSwapFailed],
+ [onDocumentLoadFailed, onDocumentSwapFailed, fileStableKey],
);
useEffect(() => {
@@ -1237,6 +1297,11 @@ export function LocalEmbedPDF({
fontFallback: fontFallbackConfig,
});
+ useEffect(() => {
+ const key = fileStableKey ?? url;
+ if (error && key) onDocumentLoadFailed?.(key, error);
+ }, [error, fileStableKey, url, onDocumentLoadFailed]);
+
const [engineTimeout, setEngineTimeout] = useState(false);
useEffect(() => {
if (!isLoading) {
@@ -1463,6 +1528,11 @@ export function LocalEmbedPDF({
plugins={plugins}
onInitialized={handleInitialized}
>
+ <InitialDocumentLoadBridge
+ fileKey={initialDocument?.fileKey ?? url ?? null}
+ onReady={handleDocumentReady}
+ onFailed={handleDocumentLoadFailed}
+ />
<DocumentSwapBridge
pending={pendingDocument}
onSwapped={handleDocumentSwapped}
diff --git a/frontend/editor/src/core/components/viewer/documentLoad.test.tsx b/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
new file mode 100644
index 0000000000..1bfd0d152d
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/documentLoad.test.tsx
@@ -0,0 +1,299 @@
+import React, { StrictMode } from "react";
+import { act, render, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { DocumentSwapBridge } from "@app/components/viewer/DocumentSwapBridge";
+import { InitialDocumentLoadBridge } from "@app/components/viewer/InitialDocumentLoadBridge";
+import { useDocumentLoadWaiter } from "@app/components/viewer/useDocumentLoadWaiter";
+
+const mocks = vi.hoisted(() => ({
+ open: vi.fn(),
+ close: vi.fn(),
+ activate: vi.fn(),
+ active: { status: "loading", error: null as string | null },
+}));
+vi.mock("@embedpdf/plugin-document-manager/react", () => {
+ const manager = {
+ getActiveDocumentId: () => "old",
+ openDocumentBuffer: mocks.open,
+ closeDocument: mocks.close,
+ setActiveDocument: mocks.activate,
+ };
+ return {
+ useDocumentManagerCapability: () => ({ provides: manager }),
+ useActiveDocument: () => ({ activeDocument: mocks.active }),
+ };
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+const pending = (fileKey: string) => ({
+ fileKey,
+ buffer: new ArrayBuffer(1),
+ name: "form.pdf",
+});
+
+describe("form save document completion", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.close.mockReturnValue({ toPromise: () => Promise.resolve() });
+ mocks.active = { status: "loading", error: null };
+ });
+
+ it("waits for the saved document's loaded task and ignores unrelated document events", async () => {
+ const load = deferred<void>();
+ mocks.open.mockReturnValue({
+ toPromise: async () => ({
+ documentId: "saved",
+ task: { toPromise: () => load.promise },
+ }),
+ });
+ const { result } = renderHook(useDocumentLoadWaiter);
+ const saved = result.current.waitForDocument("B-saved");
+ const completed = vi.fn();
+ void saved.then(completed);
+ result.current.documentReady("A");
+ result.current.documentFailed("A", new Error("unrelated"));
+ render(
+ <DocumentSwapBridge
+ pending={pending("B-saved")}
+ onSwapped={(_, key) => result.current.documentReady(key)}
+ onFailed={result.current.documentFailed}
+ />,
+ );
+ await act(async () => {});
+ expect(completed).not.toHaveBeenCalled();
+ await act(async () => load.resolve());
+ await saved;
+ expect(mocks.activate).toHaveBeenCalledWith("saved");
+ expect(completed).toHaveBeenCalledOnce();
+ });
+
+ it.each(["unmount", "clear"])(
+ "rejects a save when its swap is cancelled by %s",
+ async (action) => {
+ const load = deferred<void>();
+ mocks.open.mockReturnValue({
+ toPromise: async () => ({
+ documentId: "saved",
+ task: { toPromise: () => load.promise },
+ }),
+ });
+ const { result } = renderHook(useDocumentLoadWaiter);
+ const saved = result.current.waitForDocument("B");
+ const rejected = expect(saved).rejects.toThrow("cancelled");
+ const props = {
+ pending: pending("B"),
+ onSwapped: vi.fn(),
+ onFailed: result.current.documentFailed,
+ };
+ const view = render(<DocumentSwapBridge {...props} />);
+ await act(async () => {});
+ await act(async () => {
+ if (action === "unmount") view.unmount();
+ else view.rerender(<DocumentSwapBridge {...props} pending={null} />);
+ });
+ await rejected;
+ await act(async () => load.resolve());
+ expect(props.onSwapped).not.toHaveBeenCalled();
+ expect(mocks.close).toHaveBeenCalledWith("saved");
+ },
+ );
+
+ it("rejects the superseded request without failing its replacement", async () => {
+ const first = deferred<void>(),
+ second = deferred<void>();
+ mocks.open
+ .mockReturnValueOnce({
+ toPromise: async () => ({
+ documentId: "first",
+ task: { toPromise: () => first.promise },
+ }),
+ })
+ .mockReturnValueOnce({
+ toPromise: async () => ({
+ documentId: "second",
+ task: { toPromise: () => second.promise },
+ }),
+ });
+ const failed = vi.fn(),
+ swapped = vi.fn();
+ const view = render(
+ <DocumentSwapBridge
+ pending={pending("first")}
+ onSwapped={swapped}
+ onFailed={failed}
+ />,
+ );
+ await act(async () => {});
+ await act(async () =>
+ view.rerender(
+ <DocumentSwapBridge
+ pending={pending("second")}
+ onSwapped={swapped}
+ onFailed={failed}
+ />,
+ ),
+ );
+ expect(failed).toHaveBeenCalledWith("first", expect.any(Error));
+ await act(async () => {
+ first.resolve();
+ second.resolve();
+ });
+ expect(swapped).toHaveBeenCalledExactlyOnceWith("second", "second");
+ expect(failed).toHaveBeenCalledTimes(1);
+ });
+
+ it("survives StrictMode effect replay and callback identity changes", async () => {
+ const load = deferred<void>();
+ mocks.open.mockReturnValue({
+ toPromise: async () => ({
+ documentId: "saved",
+ task: { toPromise: () => load.promise },
+ }),
+ });
+ const failed = vi.fn(),
+ swapped = vi.fn(),
+ source = pending("B");
+ const view = render(
+ <StrictMode>
+ <DocumentSwapBridge
+ pending={source}
+ onSwapped={swapped}
+ onFailed={failed}
+ />
+ </StrictMode>,
+ );
+ await act(async () => {});
+ view.rerender(
+ <StrictMode>
+ <DocumentSwapBridge
+ pending={source}
+ onSwapped={(id, key) => swapped(id, key)}
+ onFailed={failed}
+ />
+ </StrictMode>,
+ );
+ await act(async () => load.resolve());
+ expect(failed).not.toHaveBeenCalled();
+ expect(swapped).toHaveBeenCalledExactlyOnceWith("saved", "B");
+ });
+
+ it("settles the save when a remounted viewer opens it as its initial document", async () => {
+ const { result } = renderHook(useDocumentLoadWaiter);
+ const saved = result.current.waitForDocument("B-saved");
+ const completed = vi.fn();
+ void saved.then(completed);
+ const view = render(
+ <InitialDocumentLoadBridge
+ fileKey="B-saved"
+ onReady={result.current.documentReady}
+ onFailed={result.current.documentFailed}
+ />,
+ );
+ expect(completed).not.toHaveBeenCalled();
+ mocks.active = { status: "loaded", error: null };
+ view.rerender(
+ <InitialDocumentLoadBridge
+ fileKey="B-saved"
+ onReady={result.current.documentReady}
+ onFailed={result.current.documentFailed}
+ />,
+ );
+ await saved;
+ expect(completed).toHaveBeenCalledOnce();
+ });
+
+ it("rejects a failed initial document load", async () => {
+ const { result } = renderHook(useDocumentLoadWaiter);
+ const saved = result.current.waitForDocument("B");
+ const rejected = expect(saved).rejects.toThrow("invalid PDF");
+ mocks.active = { status: "error", error: "invalid PDF" };
+ render(
+ <InitialDocumentLoadBridge
+ fileKey="B"
+ onReady={result.current.documentReady}
+ onFailed={result.current.documentFailed}
+ />,
+ );
+ await rejected;
+ });
+
+ it("rejects an initial load when only the inner viewer unmounts", async () => {
+ const { result } = renderHook(useDocumentLoadWaiter);
+ const saved = result.current.waitForDocument("B");
+ const rejected = expect(saved).rejects.toThrow("cancelled");
+ const view = render(
+ <StrictMode>
+ <InitialDocumentLoadBridge
+ fileKey="B"
+ onReady={result.current.documentReady}
+ onFailed={result.current.documentFailed}
+ />
+ </StrictMode>,
+ );
+ const failed = vi.fn();
+ void saved.catch(failed);
+ await act(async () => {});
+ expect(failed).not.toHaveBeenCalled();
+ await act(async () => view.unmount());
+ await rejected;
+ });
+
+ it("rejects a synchronous opening failure", async () => {
+ mocks.open.mockImplementation(() => {
+ throw new Error("open threw");
+ });
+ const failed = vi.fn();
+ render(
+ <DocumentSwapBridge
+ pending={pending("B")}
+ onSwapped={vi.fn()}
+ onFailed={failed}
+ />,
+ );
+ await waitFor(() =>
+ expect(failed).toHaveBeenCalledWith(
+ "B",
+ expect.objectContaining({ message: "open threw" }),
+ ),
+ );
+ });
+
+ it("rejects both an outstanding save and a late request after the viewer closes", async () => {
+ const { result, unmount } = renderHook(useDocumentLoadWaiter);
+ const saved = result.current.waitForDocument("B");
+ const rejected = expect(saved).rejects.toThrow("viewer closed");
+ unmount();
+ await rejected;
+ await expect(result.current.waitForDocument("late")).rejects.toThrow(
+ "viewer closed",
+ );
+ });
+
+ it("rejects an opening task failure without waiting for a load task", async () => {
+ mocks.open.mockReturnValue({
+ toPromise: () => Promise.reject(new Error("open failed")),
+ });
+ const failed = vi.fn();
+ render(
+ <DocumentSwapBridge
+ pending={pending("B")}
+ onSwapped={vi.fn()}
+ onFailed={failed}
+ />,
+ );
+ await waitFor(() =>
+ expect(failed).toHaveBeenCalledWith(
+ "B",
+ expect.objectContaining({ message: "open failed" }),
+ ),
+ );
+ });
+});
diff --git a/frontend/editor/src/core/components/viewer/useDocumentLoadWaiter.ts b/frontend/editor/src/core/components/viewer/useDocumentLoadWaiter.ts
new file mode 100644
index 0000000000..191d838d11
--- /dev/null
+++ b/frontend/editor/src/core/components/viewer/useDocumentLoadWaiter.ts
@@ -0,0 +1,53 @@
+import { useCallback, useEffect, useRef } from "react";
+
+/** Waits for a particular file's viewer load; unrelated document events cannot settle it. */
+export function useDocumentLoadWaiter() {
+ const mountedRef = useRef(true);
+ const pendingRef = useRef<{
+ fileKey: string;
+ resolve: () => void;
+ reject: (error: Error) => void;
+ } | null>(null);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ pendingRef.current?.reject(
+ new Error("The viewer closed before the form finished saving."),
+ );
+ pendingRef.current = null;
+ };
+ }, []);
+
+ const waitForDocument = useCallback((fileKey: string) => {
+ if (!mountedRef.current)
+ return Promise.reject(
+ new Error("The viewer closed before the form finished saving."),
+ );
+ pendingRef.current?.reject(
+ new Error("The pending document load was replaced."),
+ );
+ return new Promise<void>((resolve, reject) => {
+ pendingRef.current = { fileKey, resolve, reject };
+ });
+ }, []);
+
+ const documentReady = useCallback((fileKey: string) => {
+ if (pendingRef.current?.fileKey !== fileKey) return;
+ pendingRef.current.resolve();
+ pendingRef.current = null;
+ }, []);
+
+ const documentFailed = useCallback((fileKey: string, error: unknown) => {
+ if (pendingRef.current?.fileKey !== fileKey) return;
+ pendingRef.current.reject(
+ error instanceof Error
+ ? error
+ : new Error("The saved PDF could not be opened."),
+ );
+ pendingRef.current = null;
+ }, []);
+
+ return { waitForDocument, documentReady, documentFailed };
+}
diff --git a/frontend/editor/src/core/tests/stubbed/form-field-editing.spec.ts b/frontend/editor/src/core/tests/stubbed/form-field-editing.spec.ts
index 6300b4aa30..f0ac398e99 100644
--- a/frontend/editor/src/core/tests/stubbed/form-field-editing.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/form-field-editing.spec.ts
@@ -471,4 +471,187 @@ test.describe("Form field editor", () => {
await expect(commit).toBeDisabled();
});
+
+ test("Create and Modify share a draft and Ctrl+S saves both", async ({
+ page,
+ }) => {
+ await stubFormEndpoints(page, STUB_FIELDS);
+ await openFormTool(page);
+ await selectMode(page, "Modify");
+ await page.getByTestId("form-modify-row-firstName").click();
+ await page.getByLabel("Label", { exact: true }).fill("Given name");
+ await selectMode(page, "Create");
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(page.getByTestId("form-create-commit")).toContainText("1");
+ await page.getByTestId("form-create-type-text").click();
+ await drawField(page);
+ await selectMode(page, "Modify");
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(page.getByTestId("form-modify-commit")).toContainText("2");
+ await expect(
+ page.locator('[data-testid^="form-pending-row-"]'),
+ ).toHaveCount(1);
+ await page.keyboard.press("ControlOrMeta+s");
+ const batch = await readEditBatch(page);
+ expect(batch.add).toHaveLength(1);
+ expect(batch.modify).toEqual([
+ { targetName: "firstName", label: "Given name" },
+ ]);
+ await expect(
+ page.locator('[data-testid^="form-pending-row-"]'),
+ ).toHaveCount(0);
+ await expect(page.getByTestId("form-modify-commit")).toBeDisabled();
+ });
+
+ test("a failed save keeps the design draft and its active tab", async ({
+ page,
+ }) => {
+ await stubFormEndpoints(page, STUB_FIELDS);
+ await page.route("**/api/v1/form/edit-fields**", (route) =>
+ route.fulfill({
+ status: 400,
+ json: { detail: "Field could not be saved" },
+ }),
+ );
+ await openFormTool(page);
+ await selectMode(page, "Modify");
+ await page.getByTestId("form-modify-row-firstName").click();
+ await page.getByLabel("Label", { exact: true }).fill("Keep this draft");
+ await selectMode(page, "Fill");
+ await page.getByTestId("unsaved-save").click();
+ await expect(
+ page.getByText("Field could not be saved", { exact: true }),
+ ).toBeVisible();
+ await expect(page.getByLabel("Label", { exact: true })).toHaveValue(
+ "Keep this draft",
+ );
+ await expect(page.getByTestId("form-modify-commit")).toBeEnabled();
+ await selectMode(page, "Fill");
+ await page.getByTestId("unsaved-discard").click();
+ await selectMode(page, "Modify");
+ await expect(page.getByTestId("form-modify-commit")).toBeDisabled();
+ });
+
+ test("Fill edits require a decision before entering design and flatten alone enables Save", async ({
+ page,
+ }) => {
+ await stubFormEndpoints(page, STUB_FIELDS);
+ await openFormTool(page);
+ await page
+ .getByRole("textbox", { name: "First name", exact: true })
+ .fill("Unsaved answer");
+ await selectMode(page, "Create");
+ await expect(page.getByTestId("unsaved-save")).toBeVisible();
+ await page
+ .getByRole("button", { name: "Keep Working", exact: true })
+ .click();
+ await expect(
+ page.getByRole("textbox", { name: "First name", exact: true }),
+ ).toHaveValue("Unsaved answer");
+ await selectMode(page, "Modify");
+ await page.getByTestId("unsaved-discard").click();
+ await selectMode(page, "Fill");
+ await expect(
+ page.getByRole("textbox", { name: "First name", exact: true }),
+ ).toHaveValue("");
+ await expect(
+ page.getByRole("button", { name: "Save", exact: true }),
+ ).toBeDisabled();
+ await page.getByLabel("Flatten after filling", { exact: true }).check();
+ await expect(
+ page.getByRole("button", { name: "Save", exact: true }),
+ ).toBeEnabled();
+ });
+
+ test("saving remains busy until the replacement fields are loaded", async ({
+ page,
+ }) => {
+ await stubFormEndpoints(page, STUB_FIELDS);
+ await openFormTool(page);
+ await selectMode(page, "Modify");
+ await page.getByTestId("form-modify-row-firstName").click();
+ await page.getByLabel("Label", { exact: true }).fill("Fresh label");
+ let release!: () => void;
+ const ready = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let requested = false;
+ await page.route(
+ "**/api/v1/form/fields-with-coordinates",
+ async (route) => {
+ requested = true;
+ await ready;
+ await route.fulfill({
+ json: STUB_FIELDS.map((field) => ({
+ ...field,
+ label: "Fresh label",
+ })),
+ });
+ },
+ );
+ await page.getByTestId("form-modify-commit").click();
+ try {
+ await expect.poll(() => requested).toBe(true);
+ await expect(page.getByTestId("form-modify-commit")).toBeDisabled();
+ await expect(page.getByTestId("form-modify-commit")).toContainText("1");
+ } finally {
+ release();
+ }
+ await expect(page.getByTestId("form-modify-commit")).toContainText("0");
+ await expect(page.getByTestId("form-modify-row-firstName")).toContainText(
+ "Fresh label",
+ );
+ });
+ test("saving the second open PDF completes and keeps the form panel usable", async ({
+ page,
+ }) => {
+ const captured = await stubFormEndpoints(page, STUB_FIELDS);
+ await page.goto("/form-fill");
+ await uploadFiles(page, [
+ path.join(import.meta.dirname, "../test-fixtures/compare_sample_a.pdf"),
+ SAMPLE_PDF,
+ ]);
+ const row = page.getByRole("listitem").filter({ hasText: "sample.pdf" });
+ await row.hover();
+ await row
+ .getByRole("button", { name: "Open in Viewer", exact: true })
+ .click();
+ await selectMode(page, "Modify");
+ await page.getByTestId("form-modify-row-firstName").click();
+ await page.getByLabel("Label", { exact: true }).fill("Second document");
+ await page.getByTestId("form-modify-commit").click();
+ await expect.poll(() => captured["edit-fields"]).toBeTruthy();
+ expect((await readEditBatch(page)).modify).toEqual([
+ { targetName: "firstName", label: "Second document" },
+ ]);
+ await expect(page.getByTestId("form-modify-commit")).toContainText("0");
+ await selectMode(page, "Fill");
+ await page
+ .getByRole("textbox", { name: "First name", exact: true })
+ .fill("Still editable");
+ await expect(
+ page.getByRole("button", { name: "Save", exact: true }),
+ ).toBeEnabled();
+ });
+ test("leaving the form tool saves its design draft through the navigation dialog", async ({
+ page,
+ }) => {
+ await stubFormEndpoints(page, STUB_FIELDS);
+ await openFormTool(page);
+ await selectMode(page, "Modify");
+ await page.getByTestId("form-modify-row-firstName").click();
+ await page
+ .getByLabel("Label", { exact: true })
+ .fill("Saved before leaving");
+ await page
+ .getByRole("button", { name: "Back to all tools", exact: true })
+ .click();
+ await page.getByTestId("unsaved-save").click();
+ const batch = await readEditBatch(page);
+ expect(batch.modify).toEqual([
+ { targetName: "firstName", label: "Saved before leaving" },
+ ]);
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(modeTab(page, "Modify")).toHaveCount(0);
+ });
});
diff --git a/frontend/editor/src/core/tools/formFill/FormFieldCreatePanel.tsx b/frontend/editor/src/core/tools/formFill/FormFieldCreatePanel.tsx
index 8d6a319372..317d792355 100644
--- a/frontend/editor/src/core/tools/formFill/FormFieldCreatePanel.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFieldCreatePanel.tsx
@@ -1,41 +1,23 @@
/** Left panel for "create" mode; drawing happens in FormFieldCreationOverlay. */
-import React, { useCallback, useEffect, useRef, useState } from "react";
-import {
- Stack,
- Text,
- Group,
- Alert,
- Collapse,
- Paper,
- Tooltip,
-} from "@mantine/core";
+import { Text, Group, Alert, Tooltip } from "@mantine/core";
import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
import { useTranslation } from "react-i18next";
import { Icon } from "@app/ui/Icon";
-import { useViewer } from "@app/contexts/ViewerContext";
-import {
- pendingSelectionName,
- pendingIdFrom,
-} from "@app/tools/formFill/pendingSelection";
import { useFormFill } from "@app/tools/formFill/FormFillContext";
import {
CREATABLE_FIELD_TYPES,
type CreatableFieldType,
- type NewFieldDefinition,
} from "@app/tools/formFill/types";
-import {
- FIELD_TYPE_ICON,
- FIELD_TYPE_COLOR,
-} from "@app/tools/formFill/fieldMeta";
-import { FormFieldPropertyEditor } from "@app/tools/formFill/FormFieldPropertyEditor";
+import { FIELD_TYPE_ICON } from "@app/tools/formFill/fieldMeta";
+import { PendingFields } from "@app/tools/formFill/PendingFields";
import { SkippedEditsAlert } from "@app/tools/formFill/SkippedEditsAlert";
-import { useFormCommit } from "@app/tools/formFill/useFormCommit";
import styles from "@app/tools/formFill/FormFill.module.css";
interface FormFieldCreatePanelProps {
currentFile: File | Blob | null;
- onApplied?: (blob: Blob) => void;
+ onSave: () => Promise<boolean>;
+ saving: boolean;
+ changeCount: number;
}
const TYPE_LABEL: Record<
@@ -53,62 +35,15 @@ const TYPE_LABEL: Record<
export function FormFieldCreatePanel({
currentFile,
- onApplied,
+ onSave,
+ saving,
+ changeCount,
}: FormFieldCreatePanelProps) {
const { t } = useTranslation();
const typeLabel = (type: CreatableFieldType) =>
t(TYPE_LABEL[type].key, TYPE_LABEL[type].fallback);
- const {
- creationType,
- setCreationType,
- pendingFields,
- updatePendingField,
- removePendingField,
- commitNewFields,
- setPreviewing,
- selectedFieldName,
- setSelectedField,
- } = useFormFill();
-
- const [expandedId, setExpandedId] = useState<string | null>(null);
- const { scrollActions } = useViewer();
- const goToPage = (pageIndex: number) =>
- scrollActions.scrollToPage(pageIndex + 1);
- const { committing, error, commit } = useFormCommit(onApplied);
-
- // Auto-expand the property editor of a freshly-drawn field so its settings
- // (especially options for choice/radio) are visible immediately.
- const prevCountRef = useRef(0);
- const expandedRowRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- if (pendingFields.length > prevCountRef.current) {
- setExpandedId(pendingFields[pendingFields.length - 1].id);
- }
- prevCountRef.current = pendingFields.length;
- }, [pendingFields]);
-
- // Clicking a box on the page should land you on its settings, not leave you hunting the list.
- useEffect(() => {
- const id = selectedFieldName ? pendingIdFrom(selectedFieldName) : null;
- if (id) setExpandedId(id);
- }, [selectedFieldName]);
-
- // Newly drawn fields land at the bottom while the panel stays at the top, so their settings
- // open somewhere the user cannot see.
- useEffect(() => {
- if (!expandedId) return;
- expandedRowRef.current?.scrollIntoView({ block: "nearest" });
- }, [expandedId]);
-
- const handleCommit = useCallback(() => {
- if (!currentFile || pendingFields.length === 0) return;
- commit(
- () => commitNewFields(currentFile),
- "formFill.create.failed",
- "Failed to add fields",
- );
- }, [currentFile, pendingFields, commitNewFields, commit]);
+ const { creationType, setCreationType, pendingFields, setPreviewing } =
+ useFormFill();
return (
<div className={styles.root}>
@@ -151,135 +86,10 @@ export function FormFieldCreatePanel({
</Alert>
)}
- {error && (
- <Alert
- icon={<Icon name="triangle-alert" size={16} />}
- color="red"
- variant="light"
- p="xs"
- radius="sm"
- >
- <Text size="xs">{error}</Text>
- </Alert>
- )}
-
<SkippedEditsAlert />
</div>
- {/* Content stacks naturally; ToolPanel's own ScrollArea does the scrolling. */}
- <div className={styles.fieldListInner}>
- {pendingFields.length === 0 ? (
- <Text size="xs" c="dimmed" ta="center" py="md">
- {t("formFill.create.empty", "No fields drawn yet.")}
- </Text>
- ) : (
- <Stack gap={6}>
- {pendingFields.map((pf) => {
- const expanded = expandedId === pf.id;
- return (
- <Paper
- key={pf.id}
- withBorder
- p={6}
- radius="sm"
- ref={expanded ? expandedRowRef : undefined}
- data-testid={`form-pending-row-${pf.id}`}
- // The whole row opens its settings: hunting for the small pencil is a
- // needless step when the row is the thing you just clicked.
- onClick={() => setExpandedId(expanded ? null : pf.id)}
- style={{ cursor: "pointer" }}
- >
- <Group gap={6} wrap="nowrap" justify="space-between">
- <Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
- <span
- style={{
- color: `var(--mantine-color-${FIELD_TYPE_COLOR[pf.type]}-6)`,
- display: "flex",
- }}
- >
- <Icon name={FIELD_TYPE_ICON[pf.type]} size={16} />
- </span>
- <Text size="xs" truncate>
- {pf.name}
- </Text>
- <Text size="xs" c="dimmed">
- p{pf.pageIndex + 1}
- </Text>
- </Group>
- <Group gap={2} wrap="nowrap">
- <Tooltip
- label={t(
- "formFill.create.goToField",
- "Go to this field",
- )}
- withArrow
- >
- <ActionIcon
- size="sm"
- variant="tertiary"
- aria-label={t(
- "formFill.create.goToField",
- "Go to this field",
- )}
- onClick={(e) => {
- e.stopPropagation();
- setSelectedField(pendingSelectionName(pf.id));
- setExpandedId(pf.id);
- goToPage(pf.pageIndex);
- }}
- data-testid={`form-pending-goto-${pf.id}`}
- >
- <Icon name="locate-fixed" size={16} />
- </ActionIcon>
- </Tooltip>
- <Tooltip
- label={t("formFill.create.removeField", "Remove field")}
- withArrow
- >
- <ActionIcon
- size="sm"
- variant="tertiary"
- accent="danger"
- aria-label={t(
- "formFill.create.removeField",
- "Remove field",
- )}
- onClick={(e) => {
- e.stopPropagation();
- removePendingField(pf.id);
- }}
- data-testid={`form-pending-remove-${pf.id}`}
- >
- <Icon name="trash" size={16} />
- </ActionIcon>
- </Tooltip>
- </Group>
- </Group>
- <Collapse in={expanded}>
- {/* The row toggles on click, so the settings must not bubble into it or
- every field you touch closes the panel you are typing in. */}
- <div
- style={{ marginTop: 8 }}
- onClick={(e) => e.stopPropagation()}
- >
- <FormFieldPropertyEditor
- value={pf}
- onChange={(patch) =>
- updatePendingField(
- pf.id,
- patch as Partial<NewFieldDefinition>,
- )
- }
- showName
- />
- </div>
- </Collapse>
- </Paper>
- );
- })}
- </Stack>
- )}
- </div>
+ <PendingFields />
<div className={styles.footer}>
<Tooltip
@@ -311,13 +121,13 @@ export function FormFieldCreatePanel({
</Tooltip>
<Button
size="sm"
- onClick={handleCommit}
- loading={committing}
- disabled={!currentFile || pendingFields.length === 0}
+ onClick={onSave}
+ loading={saving}
+ disabled={!currentFile || changeCount === 0}
data-testid="form-create-commit"
>
- {t("formFill.create.commit", "Add {{count}} field(s) to PDF", {
- count: pendingFields.length,
+ {t("formFill.modify.commit", "Save {{count}} change(s)", {
+ count: changeCount,
})}
</Button>
</div>
diff --git a/frontend/editor/src/core/tools/formFill/FormFieldCreationOverlay.tsx b/frontend/editor/src/core/tools/formFill/FormFieldCreationOverlay.tsx
index beeb68928f..e8b2852afd 100644
--- a/frontend/editor/src/core/tools/formFill/FormFieldCreationOverlay.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFieldCreationOverlay.tsx
@@ -72,6 +72,7 @@ export function FormFieldCreationOverlay({
previewing,
state,
forFileId,
+ saving,
} = useFormFill();
const rootRef = useRef<HTMLDivElement>(null);
@@ -106,7 +107,8 @@ export function FormFieldCreationOverlay({
// Precompute snap edges once (not on every pointermove).
const snapTargets = useMemo(() => collectSnapTargets(snapRects), [snapRects]);
- const active = mode === "create" && creationType != null && !previewing;
+ const active =
+ mode === "create" && creationType != null && !previewing && !saving;
// Stale-file guard: don't draw on a page whose fields belong to another file.
const fileMismatch =
diff --git a/frontend/editor/src/core/tools/formFill/FormFieldEditOverlay.tsx b/frontend/editor/src/core/tools/formFill/FormFieldEditOverlay.tsx
index 687ace7798..18f9da3e0e 100644
--- a/frontend/editor/src/core/tools/formFill/FormFieldEditOverlay.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFieldEditOverlay.tsx
@@ -211,6 +211,7 @@ export function FormFieldEditOverlay({
pendingFields,
updatePendingField,
previewing,
+ saving,
} = useFormFill();
const rootRef = useRef<HTMLDivElement>(null);
@@ -508,6 +509,7 @@ export function FormFieldEditOverlay({
useEffect(() => {
if (mode !== "modify" || !selectedField) return;
const onKey = (e: KeyboardEvent) => {
+ if (saving) return;
// Read only: every page's overlay runs this, so writing the shared flag here
// would let an idle page clear the flag of the page actually being dragged.
const dragging = interactionRef.current != null;
@@ -571,6 +573,7 @@ export function FormFieldEditOverlay({
return () => window.removeEventListener("keydown", onKey);
}, [
mode,
+ saving,
setSelectedField,
selectedField,
selectedSingleWidget,
@@ -643,6 +646,7 @@ export function FormFieldEditOverlay({
return (
<div
+ inert={saving}
ref={rootRef}
data-testid={`form-edit-overlay-${pageIndex}`}
onPointerDown={(e) => {
diff --git a/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx b/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx
index 384eaa949a..051045cae4 100644
--- a/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFieldModifyPanel.tsx
@@ -1,16 +1,8 @@
/** Left panel for "modify" mode; page highlighting lives in FormFieldEditOverlay. */
-import {
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
- type RefObject,
-} from "react";
+import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
Text,
Group,
- Alert,
Collapse,
Paper,
NumberInput,
@@ -36,13 +28,15 @@ import {
type EditableFieldProps,
} from "@app/tools/formFill/FormFieldPropertyEditor";
import { isTextEntryTarget } from "@app/tools/formFill/usePageScale";
+import { PendingFields } from "@app/tools/formFill/PendingFields";
import { SkippedEditsAlert } from "@app/tools/formFill/SkippedEditsAlert";
-import { useFormCommit } from "@app/tools/formFill/useFormCommit";
import styles from "@app/tools/formFill/FormFill.module.css";
interface FormFieldModifyPanelProps {
currentFile: File | Blob | null;
- onApplied?: (blob: Blob) => void;
+ onSave: () => Promise<boolean>;
+ saving: boolean;
+ changeCount: number;
}
interface FieldGeometry {
@@ -111,25 +105,11 @@ function editorValue(
};
}
-function CommitErrorAlert({ error }: { error: string | null }) {
- if (!error) return null;
- return (
- <Alert
- icon={<Icon name="triangle-alert" size={16} />}
- color="red"
- variant="light"
- p="xs"
- radius="sm"
- >
- <Text size="xs">{error}</Text>
- </Alert>
- );
-}
-
function NoFieldsMessage() {
const { t } = useTranslation();
- const { state } = useFormFill();
- if (state.fields.length > 0 || state.loading) return null;
+ const { state, pendingFields } = useFormFill();
+ if (state.fields.length > 0 || pendingFields.length > 0 || state.loading)
+ return null;
return (
<Text size="xs" c="dimmed" ta="center" py="md">
{t("formFill.modify.empty", "This PDF has no form fields yet.")}
@@ -414,21 +394,20 @@ function PageSection({
export function FormFieldModifyPanel({
currentFile,
- onApplied,
+ onSave,
+ saving,
+ changeCount,
}: FormFieldModifyPanelProps) {
const { t } = useTranslation();
const {
state,
selectedFieldName,
setSelectedField,
- modifiedFields,
- deletedFieldNames,
- commitModifications,
hasUncommittedChanges,
+ pendingFields,
dragActiveRef,
} = useFormFill();
- const { committing, error, commit } = useFormCommit(onApplied);
const selectedRowRef = useRef<HTMLDivElement>(null);
// A long form is easier to scan a page at a time; pages start open so nothing hides itself.
@@ -477,18 +456,6 @@ export function FormFieldModifyPanel({
return () => window.removeEventListener("keydown", onKey);
}, [selectedFieldName, setSelectedField, dragActiveRef]);
- const changeCount =
- Object.keys(modifiedFields).length + deletedFieldNames.length;
-
- const handleCommit = useCallback(() => {
- if (!currentFile || !hasUncommittedChanges) return;
- commit(
- () => commitModifications(currentFile),
- "formFill.modify.failed",
- "Failed to save changes",
- );
- }, [currentFile, hasUncommittedChanges, commitModifications, commit]);
-
return (
<div className={styles.root}>
<div className={styles.header}>
@@ -499,13 +466,12 @@ export function FormFieldModifyPanel({
)}
</Text>
- <CommitErrorAlert error={error} />
-
<SkippedEditsAlert />
<NoFieldsMessage />
</div>
+ {pendingFields.length > 0 && <PendingFields />}
<ScrollArea className={styles.fieldList}>
<div className={styles.fieldListInner}>
{sortedPages.map((pageIdx, i) => (
@@ -525,8 +491,8 @@ export function FormFieldModifyPanel({
<div className={styles.footer}>
<Button
size="sm"
- onClick={handleCommit}
- loading={committing}
+ onClick={onSave}
+ loading={saving}
disabled={!currentFile || !hasUncommittedChanges}
data-testid="form-modify-commit"
>
diff --git a/frontend/editor/src/core/tools/formFill/FormFieldOverlay.tsx b/frontend/editor/src/core/tools/formFill/FormFieldOverlay.tsx
index e15948c228..4eb244a43b 100644
--- a/frontend/editor/src/core/tools/formFill/FormFieldOverlay.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFieldOverlay.tsx
@@ -649,6 +649,7 @@ export function FormFieldOverlay({
state,
forFileId,
mode,
+ saving,
} = useFormFill();
// While the editor owns the page the outlines and handles do the interacting; these widgets
// are here to show what the field looks like, not to be typed into.
@@ -804,6 +805,7 @@ export function FormFieldOverlay({
pointerEvents: "none", // allow click-through except on widgets
zIndex: 5, // above TilingLayer, below LinkLayer
}}
+ inert={saving}
data-form-overlay-page={pageIndex}
>
{pageFields.map((field: FormField) =>
diff --git a/frontend/editor/src/core/tools/formFill/FormFill.tsx b/frontend/editor/src/core/tools/formFill/FormFill.tsx
index 69be33bc8a..62bb42889b 100644
--- a/frontend/editor/src/core/tools/formFill/FormFill.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFill.tsx
@@ -49,7 +49,9 @@ import {
import type { FormMode } from "@app/tools/formFill/types";
import { FormFieldCreatePanel } from "@app/tools/formFill/FormFieldCreatePanel";
import { FormFieldModifyPanel } from "@app/tools/formFill/FormFieldModifyPanel";
+import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
import { dispatchFormApply } from "@app/tools/formFill/formFillEvents";
+import { useFormAutoMode } from "@app/tools/formFill/useFormAutoMode";
import styles from "@app/tools/formFill/FormFill.module.css";
// ---------------------------------------------------------------------------
@@ -66,6 +68,11 @@ interface ModeTabDef {
// Main FormFill component
// ---------------------------------------------------------------------------
+async function applyFormChanges(blob: Blob): Promise<void> {
+ assertFilesNotBlocked();
+ await dispatchFormApply(blob);
+}
+
const FormFill = (_props: BaseToolProps) => {
const { t } = useTranslation();
const {
@@ -73,6 +80,8 @@ const FormFill = (_props: BaseToolProps) => {
registerUnsavedChangesChecker,
unregisterUnsavedChangesChecker,
setHasUnsavedChanges,
+ registerNavigationWarningHandlers,
+ unregisterNavigationWarningHandlers,
} = useNavigation();
const { state: fileState } = useFileState();
@@ -86,9 +95,14 @@ const FormFill = (_props: BaseToolProps) => {
mode,
setMode,
hasUncommittedChanges,
- forFileId,
- commitNewFields,
- commitModifications,
+ commitDesign,
+ discardDesign,
+ discardValues,
+ pendingFields,
+ modifiedFields,
+ deletedFieldNames,
+ saving,
+ setSaving,
setCreationType,
setSelectedField,
setPreviewing,
@@ -125,15 +139,10 @@ const FormFill = (_props: BaseToolProps) => {
const { scrollActions } = useViewer();
const [flatten, setFlatten] = useState(false);
- const [saving, setSaving] = useState(false);
const [extracting, setExtracting] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
- const [lastSavedFlatten, setLastSavedFlatten] = useState<boolean | null>(
- null,
- );
- const flattenChanged =
- lastSavedFlatten !== null && flatten !== lastSavedFlatten;
+ const flattenChanged = flatten;
const savingRef = useRef(false);
@@ -156,29 +165,8 @@ const FormFill = (_props: BaseToolProps) => {
const activeFieldRef = useRef<HTMLDivElement>(null);
useFieldShortcuts();
- // A document with nothing to fill lands on Create: Fill would show an empty panel and leave
- // the user hunting for the tab that does what they came for. Decided once per document, and
- // only after the field list has settled - fields arrive a beat after the fetch reports done,
- // so deciding immediately sends a form that does have fields to the wrong tab.
- const autoModeFileRef = useRef<string | null>(null);
- const fieldCountRef = useRef(0);
- fieldCountRef.current = formState.fields.length;
- const modeRef = useRef(mode);
- modeRef.current = mode;
- useEffect(() => {
- if (formState.loading || !forFileId) return undefined;
- if (autoModeFileRef.current === forFileId) return undefined;
- const settle = window.setTimeout(() => {
- autoModeFileRef.current = forFileId;
- if (fieldCountRef.current === 0 && modeRef.current === "fill") {
- setMode("create");
- }
- }, 300);
- return () => window.clearTimeout(settle);
- }, [formState.loading, formState.fields.length, forFileId, setMode]);
-
const isDirtyRef = useRef(formState.isDirty);
- isDirtyRef.current = formState.isDirty;
+ isDirtyRef.current = formState.isDirty || flatten;
// Fields drawn or edited but never applied are lost on navigation, so the app's existing
// leave-warning needs to hear about them the way other tools report theirs.
@@ -186,15 +174,24 @@ const FormFill = (_props: BaseToolProps) => {
hasUncommittedRef.current = hasUncommittedChanges;
useEffect(() => {
registerUnsavedChangesChecker(
- () => hasUncommittedRef.current || isDirtyRef.current,
+ () =>
+ hasUncommittedRef.current || isDirtyRef.current || savingRef.current,
);
return () => unregisterUnsavedChangesChecker();
}, [registerUnsavedChangesChecker, unregisterUnsavedChangesChecker]);
// requestNavigation gates on this flag rather than on the checker above.
useEffect(() => {
- setHasUnsavedChanges(hasUncommittedChanges || formState.isDirty);
- }, [hasUncommittedChanges, formState.isDirty, setHasUnsavedChanges]);
+ setHasUnsavedChanges(
+ hasUncommittedChanges || formState.isDirty || flatten || saving,
+ );
+ }, [
+ hasUncommittedChanges,
+ formState.isDirty,
+ flatten,
+ saving,
+ setHasUnsavedChanges,
+ ]);
// Subscribing read: getFiles() during render doesn't re-run when the workbench
// changes, so the panel kept showing the pre-hydration (or pre-version) file.
@@ -250,6 +247,7 @@ const FormFill = (_props: BaseToolProps) => {
}, [currentFile, allValues]);
const isActive = selectedTool === "formFill";
+ useFormAutoMode(getFormFillFileId(currentFile), isActive);
// Arming lives in an app-level provider, so leaving the tool would otherwise keep the page
// in crosshair mode and stage fields for whatever the user opened next.
@@ -269,107 +267,127 @@ const FormFill = (_props: BaseToolProps) => {
}
}, [formState.activeFieldName]);
- const handleSave = useCallback(async () => {
- // Ref-based guard prevents concurrent saves that cause file duplication
- if (savingRef.current) return;
- if (!currentFile || !isStirlingFile(currentFile)) return;
-
- if (!validateForm()) {
+ const handleSave = useCallback(async (): Promise<boolean> => {
+ if (
+ savingRef.current ||
+ formState.loading ||
+ !currentFile ||
+ !isStirlingFile(currentFile)
+ )
+ return false;
+ if (mode === "fill" && !validateForm()) {
setSaveError(
t("formFill.requiredFieldsError", "Please fill in all required fields"),
);
- return;
+ return false;
}
-
savingRef.current = true;
setSaving(true);
setSaveError(null);
-
try {
- const filledBlob = await submitForm(currentFile, flatten);
-
- // Track the flatten value at save so toggling it later re-enables Save
- setLastSavedFlatten(flatten);
-
- // Route through the viewer's handleFormApply: a direct consumeFiles call
- // loses the viewer's file tracking, and with it scroll position and rotation.
- dispatchFormApply(filledBlob);
+ assertFilesNotBlocked();
+ if (mode === "fill") {
+ await applyFormChanges(await submitForm(currentFile, flatten));
+ setFlatten(false);
+ } else {
+ await commitDesign(currentFile, applyFormChanges);
+ }
+ return true;
} catch (err) {
const status = isAxiosError(err) ? err.response?.status : undefined;
- const message =
- status === 413
- ? "File too large. Try reducing the PDF size first."
- : (await serverMessage(err)) ||
- (status === 400
- ? "Invalid form data. Please check all fields."
- : undefined) ||
- (err instanceof Error ? err.message : undefined) ||
- "Failed to save filled form";
- setSaveError(message);
- console.error("[FormFill] Save failed:", err);
+ setSaveError(
+ (await serverMessage(err)) ||
+ (status === 413
+ ? "File too large. Try reducing the PDF size first."
+ : undefined) ||
+ (err instanceof Error ? err.message : undefined) ||
+ t("formFill.applyFailed", "Could not apply the changes"),
+ );
+ return false;
} finally {
savingRef.current = false;
setSaving(false);
}
- }, [currentFile, submitForm, flatten, validateForm]);
-
- const applyCurrentMode = useCallback(async () => {
- if (!currentFile) return;
- if (mode === "create") {
- dispatchFormApply(await commitNewFields(currentFile));
- return;
- }
- if (mode === "modify") {
- dispatchFormApply(await commitModifications(currentFile));
- return;
+ }, [
+ formState.loading,
+ currentFile,
+ mode,
+ validateForm,
+ t,
+ setSaving,
+ submitForm,
+ flatten,
+ commitDesign,
+ ]);
+
+ const discardCurrentDraft = useCallback(() => {
+ if (mode === "fill") {
+ discardValues();
+ setFlatten(false);
+ } else {
+ discardDesign();
}
- await handleSave();
- }, [mode, currentFile, commitNewFields, commitModifications, handleSave]);
+ setSaveError(null);
+ }, [mode, discardValues, discardDesign]);
- // Switching tabs throws away that tab's working state, so it asks first. Owned here rather
- // than through the app-wide warning handlers, which hold a single registration app-wide.
- const [pendingMode, setPendingMode] = useState<FormMode | null>(null);
- const [switching, setSwitching] = useState(false);
+ useEffect(() => {
+ if (!isActive) return;
+ registerNavigationWarningHandlers({
+ onApplyAndContinue: async () => {
+ if (!(await handleSave()))
+ throw new Error("Form changes could not be saved.");
+ },
+ onDiscardAndContinue: async () => {
+ discardCurrentDraft();
+ },
+ });
+ return () => unregisterNavigationWarningHandlers();
+ }, [
+ isActive,
+ handleSave,
+ discardCurrentDraft,
+ registerNavigationWarningHandlers,
+ unregisterNavigationWarningHandlers,
+ ]);
+ const [pendingMode, setPendingMode] = useState<FormMode | null>(null);
const requestMode = useCallback(
(next: FormMode) => {
- if (next === mode) return;
- if (hasUncommittedChanges) {
+ if (next === mode || saving || formState.loading) return;
+ const crossesSurface = (mode === "fill") !== (next === "fill");
+ if (
+ crossesSurface &&
+ (formState.isDirty || flatten || hasUncommittedChanges)
+ ) {
setPendingMode(next);
return;
}
+ setSaveError(null);
setMode(next);
},
- [mode, hasUncommittedChanges, setMode],
+ [
+ mode,
+ saving,
+ formState.loading,
+ formState.isDirty,
+ flatten,
+ hasUncommittedChanges,
+ setMode,
+ ],
);
const discardAndSwitch = useCallback(() => {
- const next = pendingMode;
+ if (savingRef.current) return;
+ discardCurrentDraft();
+ if (pendingMode) setMode(pendingMode);
setPendingMode(null);
- if (next) setMode(next);
- }, [pendingMode, setMode]);
+ }, [discardCurrentDraft, pendingMode, setMode]);
const applyAndSwitch = useCallback(async () => {
- const next = pendingMode;
- setSwitching(true);
- try {
- await applyCurrentMode();
- setPendingMode(null);
- if (next) setMode(next);
- } catch (err) {
- // Swallowing this left the dialog open with no explanation when the backend refused a
- // name, so the reason it gives has to reach the user.
- setSaveError(
- (await serverMessage(err)) ||
- (err instanceof Error ? err.message : null) ||
- t("formFill.applyFailed", "Could not apply the changes"),
- );
- setPendingMode(null);
- console.error("[FormFill] Could not apply before switching tabs:", err);
- } finally {
- setSwitching(false);
- }
- }, [pendingMode, applyCurrentMode, setMode, t]);
+ const saved = await handleSave();
+ if (saved && pendingMode) setMode(pendingMode);
+ setPendingMode(null);
+ }, [handleSave, pendingMode, setMode]);
// Keyboard shortcut: Ctrl+S to save
const flattenChangedRef = useRef(flattenChanged);
@@ -379,7 +397,12 @@ const FormFill = (_props: BaseToolProps) => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === "s") {
e.preventDefault();
- if (isDirtyRef.current || flattenChangedRef.current) handleSave();
+ if (
+ isDirtyRef.current ||
+ flattenChangedRef.current ||
+ hasUncommittedRef.current
+ )
+ void handleSave();
}
};
window.addEventListener("keydown", handleKeyDown);
@@ -389,14 +412,14 @@ const FormFill = (_props: BaseToolProps) => {
// Data loss prevention: warn on beforeunload if dirty
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
- if (formState.isDirty) {
+ if (formState.isDirty || flatten || hasUncommittedChanges || saving) {
e.preventDefault();
e.returnValue = "";
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
- }, [formState.isDirty]);
+ }, [formState.isDirty, flatten, hasUncommittedChanges, saving]);
const handleRefresh = useCallback(() => {
if (currentFile) {
@@ -469,14 +492,22 @@ const FormFill = (_props: BaseToolProps) => {
if (!isActive) return null;
- // const currentModeDef = MODE_TABS.find((t) => t.id === mode)!;
+ const changeCount =
+ pendingFields.length +
+ deletedFieldNames.length +
+ Object.keys(modifiedFields).filter(
+ (name) => !deletedFieldNames.includes(name),
+ ).length;
+ const designProps = { currentFile, onSave: handleSave, saving, changeCount };
return (
- <div className={styles.root}>
+ <div className={styles.root} inert={saving}>
<UnsavedChangesDialog
opened={pendingMode !== null}
- saving={switching}
- onKeepWorking={() => setPendingMode(null)}
+ saving={saving}
+ onKeepWorking={() => {
+ if (!savingRef.current) setPendingMode(null);
+ }}
onDiscard={discardAndSwitch}
onSave={applyAndSwitch}
/>
@@ -502,11 +533,25 @@ const FormFill = (_props: BaseToolProps) => {
/>
</div>
+ {saveError && (
+ <Alert color="red" variant="light" p="xs" radius="sm">
+ <Text size="xs">{saveError}</Text>
+ </Alert>
+ )}
+ {mode !== "fill" && formState.loading && (
+ <Text size="xs">
+ {t("formFill.analyzingFields", "Analysing form fields...")}
+ </Text>
+ )}
+ {mode !== "fill" && formState.error && (
+ <Alert color="red">{formState.error}</Alert>
+ )}
+
{/* ---- Create mode ---- */}
- {mode === "create" && <FormFieldCreatePanel currentFile={currentFile} />}
+ {mode === "create" && <FormFieldCreatePanel {...designProps} />}
{/* ---- Modify mode ---- */}
- {mode === "modify" && <FormFieldModifyPanel currentFile={currentFile} />}
+ {mode === "modify" && <FormFieldModifyPanel {...designProps} />}
{/* ---- Fill Form content ---- */}
{mode === "fill" && (
@@ -606,7 +651,10 @@ const FormFill = (_props: BaseToolProps) => {
size="sm"
onClick={handleSave}
loading={saving}
- disabled={!formState.isDirty && !flattenChanged}
+ disabled={
+ formState.loading ||
+ (!formState.isDirty && !flattenChanged)
+ }
>
{t("formFill.save", "Save")}
</Button>
@@ -664,11 +712,6 @@ const FormFill = (_props: BaseToolProps) => {
</div>
{/* Error message */}
- {saveError && (
- <Alert color="red" variant="light" p="xs" radius="sm">
- <Text size="xs">{saveError}</Text>
- </Alert>
- )}
</>
)}
@@ -786,9 +829,11 @@ const FormFill = (_props: BaseToolProps) => {
{(formState.isDirty || flattenChanged) && (
<span className={styles.unsavedDot} />
)}
- {formState.isDirty || flattenChanged
- ? t("formFill.unsavedChanges", "Unsaved changes")
- : t("formFill.allSaved", "All saved")}
+ {saving
+ ? t("formFill.saving", "Saving...")
+ : formState.isDirty || flattenChanged
+ ? t("formFill.unsavedChanges", "Unsaved changes")
+ : t("formFill.allSaved", "All saved")}
</span>
<span>{t("formFill.saveShortcut", "Ctrl+S to save")}</span>
</div>
diff --git a/frontend/editor/src/core/tools/formFill/FormFillContext.test.tsx b/frontend/editor/src/core/tools/formFill/FormFillContext.test.tsx
index 8e523a939e..de62fd48b6 100644
--- a/frontend/editor/src/core/tools/formFill/FormFillContext.test.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFillContext.test.tsx
@@ -8,6 +8,7 @@ import React from "react";
import {
FormFillProvider,
useFormFill,
+ useAllFormValues,
} from "@app/tools/formFill/FormFillContext";
import type { FieldEditResult } from "@app/tools/formFill/types";
@@ -77,7 +78,9 @@ describe("FormFillContext staged-edit ownership", () => {
]),
);
await act(async () => {
- await hook.current.commitModifications(blob());
+ await hook.current.commitDesign(blob(), (updated) =>
+ hook.current.fetchFields(updated, "file-A-edited"),
+ );
});
expect(hook.current.skippedEdits).toHaveLength(1);
@@ -154,7 +157,9 @@ describe("FormFillContext staged-edit ownership", () => {
]),
);
await act(async () => {
- await hook.current.commitModifications(blob());
+ await hook.current.commitDesign(blob(), (updated) =>
+ hook.current.fetchFields(updated, "file-A-edited"),
+ );
});
// The commit's own re-fetch keeps the report...
@@ -172,103 +177,154 @@ describe("FormFillContext staged-edit ownership", () => {
});
});
-describe("FormFillContext bundled field list", () => {
+describe("FormFillContext shared design draft", () => {
beforeEach(() => {
applyFieldEdits.mockReset();
fetchFields.mockReset();
fetchFields.mockResolvedValue([]);
});
- const bundled = [
- { name: "bundled", type: "text", widgets: [{ pageIndex: 0, x: 1, y: 2 }] },
- ] as unknown as FieldEditResult["fields"];
-
- async function commitWith(
- hook: { current: ReturnType<typeof useFormFill> },
- edited: Blob,
- fields: FieldEditResult["fields"],
- ) {
- // The viewer switches to pdfbox whenever the form tool is open, which is when commits happen.
- act(() => hook.current.setProviderMode("pdfbox"));
+ it("retains both design tabs and saves adds, modifications and deletions together", async () => {
+ const { result: hook } = renderHook(() => useFormFill(), { wrapper });
await act(async () => {
await hook.current.fetchFields(blob(), "file-A");
});
- act(() => hook.current.stageModification("f", { x: 1 }));
- applyFieldEdits.mockResolvedValue({
- blob: edited,
- skipped: [],
- skippedTotal: 0,
- fields,
+ act(() => hook.current.setMode("create"));
+ act(() =>
+ hook.current.addPendingField({
+ type: "text",
+ name: "new",
+ pageIndex: 0,
+ x: 1,
+ y: 2,
+ width: 100,
+ height: 20,
+ }),
+ );
+ act(() => hook.current.setMode("modify"));
+ act(() => hook.current.stageModification("existing", { label: "Renamed" }));
+ act(() => hook.current.stageModification("deleted", { label: "Ignored" }));
+ act(() => hook.current.toggleFieldDeleted("deleted"));
+ act(() => hook.current.setMode("create"));
+ expect(hook.current.pendingFields).toHaveLength(1);
+ expect(hook.current.modifiedFields.existing.label).toBe("Renamed");
+ applyFieldEdits.mockResolvedValue(result([]));
+ let finish!: () => void;
+ const persisted = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const apply = vi.fn(() => persisted);
+ let saving!: Promise<void>;
+ act(() => {
+ saving = hook.current.commitDesign(blob(), apply);
+ });
+ await waitFor(() => expect(apply).toHaveBeenCalled());
+ expect(hook.current.hasUncommittedChanges).toBe(true);
+ expect(applyFieldEdits.mock.calls[0][1]).toEqual({
+ add: [expect.objectContaining({ name: "new" })],
+ modify: [{ targetName: "existing", label: "Renamed" }],
+ delete: ["deleted"],
});
await act(async () => {
- await hook.current.commitModifications(blob());
+ finish();
+ await saving;
});
- }
+ expect(hook.current.hasUncommittedChanges).toBe(false);
+ expect(hook.current.canUndo).toBe(false);
+ });
- it("skips the follow-up request when the commit already returned the fields", async () => {
+ it("keeps the draft and undo history when persistence fails", async () => {
const { result: hook } = renderHook(() => useFormFill(), { wrapper });
- const edited = blob();
- await commitWith(hook, edited, bundled);
- const callsBefore = fetchFields.mock.calls.length;
-
await act(async () => {
- await hook.current.fetchFields(edited, "file-A-edited");
+ await hook.current.fetchFields(blob(), "file-A");
});
-
- // The whole point: no second upload for the post-commit fetch.
- expect(fetchFields.mock.calls).toHaveLength(callsBefore);
- await waitFor(() =>
- expect(hook.current.state.fields.map((f) => f.name)).toEqual(["bundled"]),
+ act(() =>
+ hook.current.stageModification("existing", { label: "Retry me" }),
);
+ applyFieldEdits.mockResolvedValue(result([]));
+ await act(async () => {
+ await expect(
+ hook.current.commitDesign(blob(), async () => {
+ throw new Error("Storage failed");
+ }),
+ ).rejects.toThrow("Storage failed");
+ });
+ expect(hook.current.modifiedFields.existing.label).toBe("Retry me");
+ expect(hook.current.canUndo).toBe(true);
+ act(() => hook.current.discardDesign());
+ expect(hook.current.hasUncommittedChanges).toBe(false);
+ expect(hook.current.canUndo).toBe(false);
});
- it("still asks the backend when the commit returned no fields", async () => {
+ it("does not reapply edits already persisted when the preview fails to reopen", async () => {
const { result: hook } = renderHook(() => useFormFill(), { wrapper });
- const edited = blob();
- await commitWith(hook, edited, undefined);
- const callsBefore = fetchFields.mock.calls.length;
-
await act(async () => {
- await hook.current.fetchFields(edited, "file-A-edited");
+ await hook.current.fetchFields(blob(), "file-A");
});
-
- expect(fetchFields.mock.calls.length).toBe(callsBefore + 1);
+ act(() => hook.current.stageModification("existing", { label: "Saved" }));
+ applyFieldEdits.mockResolvedValue(result([]));
+ await act(async () => {
+ await expect(
+ hook.current.commitDesign(blob(), async (updated) => {
+ await hook.current.fetchFields(updated, "file-A-edited");
+ throw new Error("Preview failed");
+ }),
+ ).rejects.toThrow("Preview failed");
+ });
+ expect(hook.current.hasUncommittedChanges).toBe(false);
+ expect(hook.current.canUndo).toBe(false);
});
- it("ignores a bundle whose size does not match the file being fetched", async () => {
+ it("uses a bundled field list during persistence and never reuses it afterwards", async () => {
const { result: hook } = renderHook(() => useFormFill(), { wrapper });
- await commitWith(hook, blob(), bundled);
- const callsBefore = fetchFields.mock.calls.length;
-
- // A different document must never adopt the previous commit's field list.
+ act(() => hook.current.setProviderMode("pdfbox"));
+ await act(async () => {
+ await hook.current.fetchFields(blob(), "file-A");
+ });
+ act(() => hook.current.stageModification("existing", { label: "Renamed" }));
+ const fields = [{ name: "bundled", type: "text", value: "", widgets: [] }];
+ applyFieldEdits.mockResolvedValue({ ...result([]), fields });
+ const before = fetchFields.mock.calls.length;
await act(async () => {
- await hook.current.fetchFields(
- new Blob(["%PDF-1.4 a longer unrelated document"]),
- "file-B",
+ await hook.current.commitDesign(blob(), (updated) =>
+ hook.current.fetchFields(updated, "file-A-edited"),
);
});
-
- expect(fetchFields.mock.calls.length).toBe(callsBefore + 1);
+ expect(fetchFields).toHaveBeenCalledTimes(before);
+ expect(hook.current.state.fields).toEqual(fields);
+ await act(async () => {
+ await hook.current.fetchFields(blob(), "file-A-edited");
+ });
+ expect(fetchFields).toHaveBeenCalledTimes(before + 1);
});
+});
- it("does not reuse the bundle for a second fetch", async () => {
+describe("FormFillContext value retention", () => {
+ it("does not mark filled values clean before the PDF is persisted", async () => {
const { result: hook } = renderHook(() => useFormFill(), { wrapper });
- const edited = blob();
- await commitWith(hook, edited, bundled);
-
await act(async () => {
- await hook.current.fetchFields(edited, "file-A-edited");
+ await hook.current.fetchFields(blob(), "file-A");
});
- const afterFirst = fetchFields.mock.calls.length;
+ act(() => hook.current.setValue("who", "Ada"));
await act(async () => {
- await hook.current.fetchFields(edited, "file-A-edited");
+ await hook.current.submitForm(blob());
});
+ expect(hook.current.state.isDirty).toBe(true);
+ act(() => hook.current.discardValues());
+ expect(hook.current.getValue("who")).toBe("");
+ expect(hook.current.state.isDirty).toBe(false);
+ });
- expect(fetchFields.mock.calls.length).toBe(afterFirst + 1);
+ it("updates value subscribers on every edit", () => {
+ const { result: hook } = renderHook(
+ () => ({ form: useFormFill(), values: useAllFormValues() }),
+ { wrapper },
+ );
+ act(() => hook.current.form.setValue("who", "Ada"));
+ act(() => hook.current.form.setValue("who", "Grace"));
+ expect(hook.current.values.who).toBe("Grace");
});
-});
-describe("FormFillContext value retention", () => {
beforeEach(() => {
applyFieldEdits.mockReset();
fetchFields.mockReset();
diff --git a/frontend/editor/src/core/tools/formFill/FormFillContext.tsx b/frontend/editor/src/core/tools/formFill/FormFillContext.tsx
index 0df56c4bb5..cca1592d88 100644
--- a/frontend/editor/src/core/tools/formFill/FormFillContext.tsx
+++ b/frontend/editor/src/core/tools/formFill/FormFillContext.tsx
@@ -99,7 +99,7 @@ class FormValuesStore {
setValue(fieldName: string, value: string): void {
if (this._values[fieldName] === value) return;
- this._values[fieldName] = value;
+ this._values = { ...this._values, [fieldName]: value };
this._version++;
this._fieldListeners.get(fieldName)?.forEach((l) => l());
this._globalListeners.forEach((l) => l());
@@ -248,7 +248,7 @@ export interface FormFillContextValue {
/** Current tool mode. */
mode: FormMode;
- /** Switch mode. Switching clears the other mode's uncommitted working state. */
+ /** Switching Create/Modify keeps their shared design draft. */
setMode: (mode: FormMode) => void;
// --- Create mode ---
@@ -270,8 +270,15 @@ export interface FormFillContextValue {
updatePendingField: (id: string, patch: Partial<NewFieldDefinition>) => void;
removePendingField: (id: string) => void;
clearPendingFields: () => void;
- /** POST queued fields to the backend; resolves to the updated PDF blob. */
- commitNewFields: (file: File | Blob) => Promise<Blob>;
+ /** Applies the shared design draft and clears it only after persistence succeeds. */
+ commitDesign: (
+ file: File | Blob,
+ apply: (blob: Blob) => Promise<void>,
+ ) => Promise<void>;
+ discardDesign: () => void;
+ discardValues: () => void;
+ saving: boolean;
+ setSaving: (saving: boolean) => void;
// --- Modify mode ---
/** Field currently selected for editing in modify mode. */
@@ -292,8 +299,6 @@ export interface FormFillContextValue {
toggleFieldDeleted: (name: string) => void;
/** Discard all staged modifications and deletions. */
clearModifications: () => void;
- /** POST staged modifications + deletions; resolves to the updated PDF blob. */
- commitModifications: (file: File | Blob) => Promise<Blob>;
/** True when create or modify mode has uncommitted work. */
hasUncommittedChanges: boolean;
@@ -414,6 +419,8 @@ export function FormFillProvider({
);
const [pendingFields, setPendingFields] = useState<PendingField[]>([]);
const [previewing, setPreviewing] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const committingDesignRef = useRef(false);
// Undo covers the staged edits, which is what the user has been doing here; the applied
// document keeps its own version history elsewhere.
@@ -495,6 +502,8 @@ export function FormFillProvider({
} | null>(null);
const clearEditingState = useCallback(() => {
+ undoStackRef.current = [];
+ setCanUndo(false);
setCreationType(null);
setPendingFields([]);
setSelectedField(null);
@@ -520,6 +529,7 @@ export function FormFillProvider({
// different file would edit the wrong PDF. Checked here, before any await, because
// forFileIdRef is null for the whole fetch and the success path may never run.
if (
+ !committingDesignRef.current &&
editedFileIdRef.current != null &&
(fileId ?? null) !== editedFileIdRef.current
) {
@@ -580,7 +590,10 @@ export function FormFillProvider({
// pdfbox returns signature fields without a rendered appearance; merge the
// pdfium ones by name, since appending would list a signature twice.
- if (providerModeRef.current === "pdfbox") {
+ if (
+ providerModeRef.current === "pdfbox" &&
+ fields.some((field) => field.type === "signature")
+ ) {
try {
// Convert File/Blob to ArrayBuffer for pdfiumService
const arrayBuffer = await file.arrayBuffer();
@@ -679,7 +692,6 @@ export function FormFillProvider({
valuesStore.values,
flatten,
);
- dispatch({ type: "MARK_CLEAN" });
return blob;
},
[valuesStore],
@@ -740,19 +752,22 @@ export function FormFillProvider({
clearEditingState();
}, [valuesStore, clearEditingState]);
- // --- Mode switching ---
- const setMode = useCallback(
- (next: FormMode) => {
- setModeState((prev) => {
- if (prev === next) return prev;
- // Leaving a mode discards its uncommitted working state so the user
- // doesn't carry half-drawn fields or staged edits between modes.
- clearEditingState();
- return next;
- });
- },
- [clearEditingState],
- );
+ const discardValues = useCallback(() => {
+ valuesStore.reset(
+ Object.fromEntries(
+ fieldsRef.current.map((field) => [field.name, field.value ?? ""]),
+ ),
+ );
+ dispatch({ type: "MARK_CLEAN" });
+ dispatch({ type: "SET_VALIDATION_ERRORS", errors: {} });
+ }, [valuesStore]);
+
+ const setMode = useCallback((next: FormMode) => {
+ setCreationType(null);
+ setPreviewing(false);
+ setSelectedField(null);
+ setModeState(next);
+ }, []);
// --- Create mode ---
const addPendingField = useCallback(
@@ -814,29 +829,6 @@ export function FormFillProvider({
setCreationType(null);
}, []);
- const commitNewFields = useCallback(
- async (file: File | Blob): Promise<Blob> => {
- // Strip the client-side id before sending to the backend.
- const definitions: NewFieldDefinition[] = pendingFields.map(
- ({ id: _id, ...rest }) => rest,
- );
- const result = await applyFieldEdits(file, { add: definitions });
- bundledFieldsRef.current = result.fields
- ? { fields: result.fields, size: result.blob.size }
- : null;
- setSkippedEdits(result.skipped);
- setSkippedTotal(result.skippedTotal);
- skipReportFileIdRef.current = PENDING_SKIP_REPORT;
- setPendingFields([]);
- setCreationType(null);
- // The batch is gone, so the stamp must not survive to trigger a clear on the
- // post-commit re-fetch; that would wipe the skip report we just set.
- editedFileIdRef.current = null;
- return result.blob;
- },
- [pendingFields],
- );
-
// --- Modify mode ---
const stageModification = useCallback(
(targetName: string, patch: Partial<ModifyFieldDefinition>) => {
@@ -872,30 +864,41 @@ export function FormFillProvider({
setSelectedField(null);
}, []);
- const commitModifications = useCallback(
- async (file: File | Blob): Promise<Blob> => {
- // Apply property/geometry changes (for fields not being deleted) and the
- // deletions in a single backend round-trip.
- const updates = Object.values(modifiedFields).filter(
- (m) => !deletedFieldNames.includes(m.targetName),
- );
- const result = await applyFieldEdits(file, {
- modify: updates,
- delete: deletedFieldNames,
- });
- bundledFieldsRef.current = result.fields
- ? { fields: result.fields, size: result.blob.size }
- : null;
- setSkippedEdits(result.skipped);
- setSkippedTotal(result.skippedTotal);
- skipReportFileIdRef.current = PENDING_SKIP_REPORT;
- setModifiedFields({});
- setDeletedFieldNames([]);
- setSelectedField(null);
- editedFileIdRef.current = null;
- return result.blob;
+ const commitDesign = useCallback(
+ async (
+ file: File | Blob,
+ apply: (blob: Blob) => Promise<void>,
+ ): Promise<void> => {
+ const sourceFileId = lastKnownFileIdRef.current;
+ committingDesignRef.current = true;
+ try {
+ const result = await applyFieldEdits(file, {
+ add: pendingFields.map(({ id: _id, ...definition }) => definition),
+ modify: Object.values(modifiedFields).filter(
+ (edit) => !deletedFieldNames.includes(edit.targetName),
+ ),
+ delete: deletedFieldNames,
+ });
+ bundledFieldsRef.current = result.fields
+ ? { fields: result.fields, size: result.blob.size }
+ : null;
+ await apply(result.blob);
+ clearEditingState();
+ setSkippedEdits(result.skipped);
+ setSkippedTotal(result.skippedTotal);
+ skipReportFileIdRef.current =
+ forFileIdRef.current ?? PENDING_SKIP_REPORT;
+ } catch (error) {
+ // A replacement fetch starts only after persistence. Reapplying its draft would
+ // duplicate fields if storage succeeded but the viewer could not open the PDF.
+ if (lastKnownFileIdRef.current !== sourceFileId) clearEditingState();
+ throw error;
+ } finally {
+ bundledFieldsRef.current = null;
+ committingDesignRef.current = false;
+ }
},
- [modifiedFields, deletedFieldNames],
+ [pendingFields, modifiedFields, deletedFieldNames, clearEditingState],
);
const hasUncommittedChanges =
@@ -964,7 +967,11 @@ export function FormFillProvider({
updatePendingField,
removePendingField,
clearPendingFields,
- commitNewFields,
+ commitDesign,
+ discardDesign: clearEditingState,
+ discardValues,
+ saving,
+ setSaving,
selectedFieldName,
setSelectedField,
modifiedFields,
@@ -973,7 +980,6 @@ export function FormFillProvider({
deletedFieldNames,
toggleFieldDeleted,
clearModifications,
- commitModifications,
hasUncommittedChanges,
skippedEdits,
skippedTotal,
@@ -1008,7 +1014,10 @@ export function FormFillProvider({
updatePendingField,
removePendingField,
clearPendingFields,
- commitNewFields,
+ commitDesign,
+ clearEditingState,
+ discardValues,
+ saving,
selectedFieldName,
modifiedFields,
stageModification,
@@ -1016,7 +1025,6 @@ export function FormFillProvider({
deletedFieldNames,
toggleFieldDeleted,
clearModifications,
- commitModifications,
hasUncommittedChanges,
skippedEdits,
skippedTotal,
diff --git a/frontend/editor/src/core/tools/formFill/PendingFields.tsx b/frontend/editor/src/core/tools/formFill/PendingFields.tsx
new file mode 100644
index 0000000000..d6f88b3b6d
--- /dev/null
+++ b/frontend/editor/src/core/tools/formFill/PendingFields.tsx
@@ -0,0 +1,172 @@
+/** Shared pending-field editor so newly drawn fields remain editable in either design tab. */
+import { useEffect, useRef, useState } from "react";
+import { Stack, Text, Group, Collapse, Paper, Tooltip } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Icon } from "@app/ui/Icon";
+import { useViewer } from "@app/contexts/ViewerContext";
+import {
+ pendingSelectionName,
+ pendingIdFrom,
+} from "@app/tools/formFill/pendingSelection";
+import { useFormFill } from "@app/tools/formFill/FormFillContext";
+import {
+ FIELD_TYPE_ICON,
+ FIELD_TYPE_COLOR,
+} from "@app/tools/formFill/fieldMeta";
+import { FormFieldPropertyEditor } from "@app/tools/formFill/FormFieldPropertyEditor";
+import type { NewFieldDefinition } from "@app/tools/formFill/types";
+import styles from "@app/tools/formFill/FormFill.module.css";
+
+export function PendingFields() {
+ const { t } = useTranslation();
+ const {
+ pendingFields,
+ updatePendingField,
+ removePendingField,
+ selectedFieldName,
+ setSelectedField,
+ } = useFormFill();
+ const [expandedId, setExpandedId] = useState<string | null>(null);
+ const { scrollActions } = useViewer();
+ const goToPage = (pageIndex: number) =>
+ scrollActions.scrollToPage(pageIndex + 1);
+
+ // Auto-expand the property editor of a freshly-drawn field so its settings
+ // (especially options for choice/radio) are visible immediately.
+ const prevCountRef = useRef(0);
+ const expandedRowRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (pendingFields.length > prevCountRef.current) {
+ setExpandedId(pendingFields[pendingFields.length - 1].id);
+ }
+ prevCountRef.current = pendingFields.length;
+ }, [pendingFields]);
+
+ // Clicking a box on the page should land you on its settings, not leave you hunting the list.
+ useEffect(() => {
+ const id = selectedFieldName ? pendingIdFrom(selectedFieldName) : null;
+ if (id) setExpandedId(id);
+ }, [selectedFieldName]);
+
+ // Newly drawn fields land at the bottom while the panel stays at the top, so their settings
+ // open somewhere the user cannot see.
+ useEffect(() => {
+ if (!expandedId) return;
+ expandedRowRef.current?.scrollIntoView({ block: "nearest" });
+ }, [expandedId]);
+
+ return (
+ <div className={styles.fieldListInner}>
+ {pendingFields.length === 0 ? (
+ <Text size="xs" c="dimmed" ta="center" py="md">
+ {t("formFill.create.empty", "No fields drawn yet.")}
+ </Text>
+ ) : (
+ <Stack gap={6}>
+ {pendingFields.map((pf) => {
+ const expanded = expandedId === pf.id;
+ return (
+ <Paper
+ key={pf.id}
+ withBorder
+ p={6}
+ radius="sm"
+ ref={expanded ? expandedRowRef : undefined}
+ data-testid={`form-pending-row-${pf.id}`}
+ // The whole row opens its settings: hunting for the small pencil is a
+ // needless step when the row is the thing you just clicked.
+ onClick={() => setExpandedId(expanded ? null : pf.id)}
+ style={{ cursor: "pointer" }}
+ >
+ <Group gap={6} wrap="nowrap" justify="space-between">
+ <Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
+ <span
+ style={{
+ color: `var(--mantine-color-${FIELD_TYPE_COLOR[pf.type]}-6)`,
+ display: "flex",
+ }}
+ >
+ <Icon name={FIELD_TYPE_ICON[pf.type]} size={16} />
+ </span>
+ <Text size="xs" truncate>
+ {pf.name}
+ </Text>
+ <Text size="xs" c="dimmed">
+ p{pf.pageIndex + 1}
+ </Text>
+ </Group>
+ <Group gap={2} wrap="nowrap">
+ <Tooltip
+ label={t("formFill.create.goToField", "Go to this field")}
+ withArrow
+ >
+ <ActionIcon
+ size="sm"
+ variant="tertiary"
+ aria-label={t(
+ "formFill.create.goToField",
+ "Go to this field",
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ setSelectedField(pendingSelectionName(pf.id));
+ setExpandedId(pf.id);
+ goToPage(pf.pageIndex);
+ }}
+ data-testid={`form-pending-goto-${pf.id}`}
+ >
+ <Icon name="locate-fixed" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ <Tooltip
+ label={t("formFill.create.removeField", "Remove field")}
+ withArrow
+ >
+ <ActionIcon
+ size="sm"
+ variant="tertiary"
+ accent="danger"
+ aria-label={t(
+ "formFill.create.removeField",
+ "Remove field",
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ removePendingField(pf.id);
+ }}
+ data-testid={`form-pending-remove-${pf.id}`}
+ >
+ <Icon name="trash" size={16} />
+ </ActionIcon>
+ </Tooltip>
+ </Group>
+ </Group>
+ <Collapse in={expanded}>
+ {/* The row toggles on click, so the settings must not bubble into it or
+ every field you touch closes the panel you are typing in. */}
+ <div
+ style={{ marginTop: 8 }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <FormFieldPropertyEditor
+ value={pf}
+ onChange={(patch) =>
+ updatePendingField(
+ pf.id,
+ patch as Partial<NewFieldDefinition>,
+ )
+ }
+ showName
+ />
+ </div>
+ </Collapse>
+ </Paper>
+ );
+ })}
+ </Stack>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/core/tools/formFill/formFillEvents.test.ts b/frontend/editor/src/core/tools/formFill/formFillEvents.test.ts
new file mode 100644
index 0000000000..e32bbe6878
--- /dev/null
+++ b/frontend/editor/src/core/tools/formFill/formFillEvents.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+import {
+ dispatchFormApply,
+ FORM_APPLY_EVENT,
+ type FormApplyDetail,
+} from "@app/tools/formFill/formFillEvents";
+
+describe("form save handoff", () => {
+ it("rejects when no viewer can accept the save", async () => {
+ await expect(dispatchFormApply(new Blob())).rejects.toThrow("not ready");
+ });
+
+ it("waits for replacement and field refresh", async () => {
+ let finish!: () => void;
+ const applied = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ window.addEventListener(
+ FORM_APPLY_EVENT,
+ (event) => {
+ (event as CustomEvent<FormApplyDetail>).detail.complete(applied);
+ },
+ { once: true },
+ );
+ let completed = false;
+ const saved = dispatchFormApply(new Blob()).then(() => {
+ completed = true;
+ });
+ await Promise.resolve();
+ expect(completed).toBe(false);
+ finish();
+ await saved;
+ expect(completed).toBe(true);
+ });
+
+ it("propagates persistence failures to the save surface", async () => {
+ window.addEventListener(
+ FORM_APPLY_EVENT,
+ (event) => {
+ (event as CustomEvent<FormApplyDetail>).detail.complete(
+ Promise.reject(new Error("Storage failed")),
+ );
+ },
+ { once: true },
+ );
+ await expect(dispatchFormApply(new Blob())).rejects.toThrow(
+ "Storage failed",
+ );
+ });
+});
diff --git a/frontend/editor/src/core/tools/formFill/formFillEvents.ts b/frontend/editor/src/core/tools/formFill/formFillEvents.ts
index b1decb9b61..24a5b38c33 100644
--- a/frontend/editor/src/core/tools/formFill/formFillEvents.ts
+++ b/frontend/editor/src/core/tools/formFill/formFillEvents.ts
@@ -3,11 +3,24 @@ export const FORM_APPLY_EVENT = "formfill:apply";
export interface FormApplyDetail {
blob: Blob;
+ complete: (application: Promise<void>) => void;
}
-/** Dispatch a produced PDF blob to the viewer for reload + refresh. */
-export function dispatchFormApply(blob: Blob): void {
- window.dispatchEvent(
- new CustomEvent<FormApplyDetail>(FORM_APPLY_EVENT, { detail: { blob } }),
- );
+/** Resolves after the viewer has stored the PDF, replaced it and refreshed its fields. */
+export function dispatchFormApply(blob: Blob): Promise<void> {
+ return new Promise((resolve, reject) => {
+ let handled = false;
+ window.dispatchEvent(
+ new CustomEvent<FormApplyDetail>(FORM_APPLY_EVENT, {
+ detail: {
+ blob,
+ complete: (application) => {
+ handled = true;
+ application.then(resolve, reject);
+ },
+ },
+ }),
+ );
+ if (!handled) reject(new Error("The PDF viewer is not ready to save."));
+ });
}
diff --git a/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts b/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts
index 7c78444152..5753af1e32 100644
--- a/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts
+++ b/frontend/editor/src/core/tools/formFill/useFieldShortcuts.ts
@@ -19,6 +19,7 @@ type Copied = Omit<NewFieldDefinition, "name"> & { name?: string };
export function useFieldShortcuts() {
const {
mode,
+ saving,
state,
selectedFieldName,
setSelectedField,
@@ -34,6 +35,7 @@ export function useFieldShortcuts() {
// Refs, so the listener is installed once instead of on every selection change.
const latest = useRef({
mode,
+ saving,
state,
selectedFieldName,
setSelectedField,
@@ -45,6 +47,7 @@ export function useFieldShortcuts() {
});
latest.current = {
mode,
+ saving,
state,
selectedFieldName,
setSelectedField,
@@ -58,7 +61,7 @@ export function useFieldShortcuts() {
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const ctx = latest.current;
- if (ctx.mode === "fill") return;
+ if (ctx.mode === "fill" || ctx.saving) return;
// Never steal a shortcut from a field the user is typing in.
if (isTextEntryTarget(event.target)) return;
diff --git a/frontend/editor/src/core/tools/formFill/useFormAutoMode.test.tsx b/frontend/editor/src/core/tools/formFill/useFormAutoMode.test.tsx
new file mode 100644
index 0000000000..425420b340
--- /dev/null
+++ b/frontend/editor/src/core/tools/formFill/useFormAutoMode.test.tsx
@@ -0,0 +1,151 @@
+import React, { useEffect } from "react";
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ FormFillProvider,
+ useFormFill,
+} from "@app/tools/formFill/FormFillContext";
+import { useFormAutoMode } from "@app/tools/formFill/useFormAutoMode";
+import type { FormField } from "@app/tools/formFill/types";
+
+const { fetchBackend } = vi.hoisted(() => ({ fetchBackend: vi.fn() }));
+vi.mock("@app/tools/formFill/providers/PdfBoxFormProvider", () => ({
+ PdfBoxFormProvider: class {
+ name = "pdfbox";
+ fetchFields = fetchBackend;
+ },
+}));
+vi.mock("@app/tools/formFill/providers/PdfiumFormProvider", () => ({
+ PdfiumFormProvider: class {
+ name = "pdfium";
+ async fetchFields() {
+ return [];
+ }
+ },
+}));
+vi.mock("@app/tools/formFill/formApi", () => ({ applyFieldEdits: vi.fn() }));
+vi.mock("@app/services/pdfiumService", () => ({
+ fetchSignatureFieldsWithAppearances: vi.fn(),
+}));
+
+const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <FormFillProvider>{children}</FormFillProvider>
+);
+const file = new Blob(["pdf"]);
+const field: FormField = {
+ name: "name",
+ label: "Name",
+ type: "text",
+ value: "",
+ options: null,
+ displayOptions: null,
+ required: false,
+ readOnly: false,
+ multiSelect: false,
+ multiline: false,
+ tooltip: null,
+ widgets: [],
+};
+
+describe("automatic form tab selection", () => {
+ beforeEach(() => {
+ fetchBackend.mockReset();
+ });
+
+ it.each([true, false])(
+ "waits for PDFBox on entry even when viewer effect runs first: %s",
+ async (viewerFirst) => {
+ let finish!: (fields: FormField[]) => void;
+ fetchBackend.mockImplementation(
+ () =>
+ new Promise<FormField[]>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const { result, rerender } = renderHook(
+ ({ active }) => {
+ const form = useFormFill();
+ const switchProvider = () => {
+ if (active) {
+ form.setProviderMode("pdfbox");
+ void form.fetchFields(file, "A");
+ }
+ };
+ useEffect(() => {
+ if (viewerFirst) switchProvider();
+ }, [active]);
+ useFormAutoMode("A", active);
+ useEffect(() => {
+ if (!viewerFirst) switchProvider();
+ }, [active]);
+ return form;
+ },
+ { wrapper, initialProps: { active: false } },
+ );
+ await act(async () => {
+ await result.current.fetchFields(file, "A");
+ });
+ rerender({ active: true });
+ expect(result.current.state.loading).toBe(true);
+ expect(result.current.mode).toBe("fill");
+ await act(async () => finish([field]));
+ expect(result.current.state.fields).toEqual([field]);
+ expect(result.current.mode).toBe("fill");
+ },
+ );
+
+ it("selects Create immediately after a successful empty PDFBox result", async () => {
+ fetchBackend.mockResolvedValue([]);
+ const { result } = renderHook(
+ () => {
+ useFormAutoMode("A", true);
+ return useFormFill();
+ },
+ { wrapper },
+ );
+ act(() => result.current.setProviderMode("pdfbox"));
+ await act(async () => {
+ await result.current.fetchFields(file, "A");
+ });
+ expect(result.current.mode).toBe("create");
+ act(() => result.current.setMode("fill"));
+ expect(result.current.mode).toBe("fill");
+ });
+
+ it("ignores a completed result for a different file", async () => {
+ fetchBackend.mockResolvedValue([]);
+ const { result } = renderHook(
+ () => {
+ useFormAutoMode("B", true);
+ return useFormFill();
+ },
+ { wrapper },
+ );
+ act(() => result.current.setProviderMode("pdfbox"));
+ await act(async () => {
+ await result.current.fetchFields(file, "A");
+ });
+ expect(result.current.mode).toBe("fill");
+ await act(async () => {
+ await result.current.fetchFields(file, "B");
+ });
+ expect(result.current.mode).toBe("create");
+ });
+
+ it("does not treat a failed fetch as an empty form", async () => {
+ fetchBackend.mockRejectedValue(new Error("offline"));
+ const { result } = renderHook(
+ () => {
+ useFormAutoMode("A", true);
+ return useFormFill();
+ },
+ { wrapper },
+ );
+ act(() => result.current.setProviderMode("pdfbox"));
+ await act(async () => {
+ await result.current.fetchFields(file, "A");
+ });
+ expect(result.current.state.error).toBe("offline");
+ expect(result.current.mode).toBe("fill");
+ });
+});
diff --git a/frontend/editor/src/core/tools/formFill/useFormAutoMode.ts b/frontend/editor/src/core/tools/formFill/useFormAutoMode.ts
new file mode 100644
index 0000000000..78d9427334
--- /dev/null
+++ b/frontend/editor/src/core/tools/formFill/useFormAutoMode.ts
@@ -0,0 +1,35 @@
+import { useEffect, useRef } from "react";
+import { useFormFill } from "@app/tools/formFill/FormFillContext";
+
+/** Chooses Create only after PDFBox has confirmed the current file has no fields. */
+export function useFormAutoMode(fileKey: string | null, active: boolean) {
+ const { state, mode, setMode, forFileId, activeProviderName, saving } =
+ useFormFill();
+ const decidedFileRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (
+ !active ||
+ saving ||
+ state.loading ||
+ state.error ||
+ activeProviderName !== "pdfbox" ||
+ !fileKey ||
+ forFileId !== fileKey ||
+ decidedFileRef.current === fileKey
+ )
+ return;
+ decidedFileRef.current = fileKey;
+ if (state.fields.length === 0 && mode === "fill") setMode("create");
+ }, [
+ active,
+ saving,
+ state.loading,
+ state.error,
+ state.fields.length,
+ activeProviderName,
+ fileKey,
+ forFileId,
+ mode,
+ setMode,
+ ]);
+}
diff --git a/frontend/editor/src/core/tools/formFill/useFormCommit.ts b/frontend/editor/src/core/tools/formFill/useFormCommit.ts
index 89c361dae6..0219ead06b 100644
--- a/frontend/editor/src/core/tools/formFill/useFormCommit.ts
+++ b/frontend/editor/src/core/tools/formFill/useFormCommit.ts
@@ -1,12 +1,4 @@
-/**
- * Shared commit flow for the create and modify panels: run an action producing
- * the edited PDF blob, hand it to the viewer, track committing/error state.
- */
-import { useState, useCallback } from "react";
-import { useTranslation } from "react-i18next";
import { isAxiosError } from "axios";
-import { dispatchFormApply } from "@app/tools/formFill/formFillEvents";
-import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
/**
* responseType "blob" means an error's ProblemDetail arrives as a Blob, so read
@@ -29,39 +21,3 @@ export async function serverMessage(err: unknown): Promise<string | null> {
return null;
}
}
-
-export function useFormCommit(onApplied?: (blob: Blob) => void) {
- const { t } = useTranslation();
- const [committing, setCommitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- const commit = useCallback(
- async (
- run: () => Promise<Blob>,
- errorKey: string,
- errorFallback: string,
- ) => {
- setCommitting(true);
- setError(null);
- try {
- assertFilesNotBlocked();
- const blob = await run();
- assertFilesNotBlocked();
- dispatchFormApply(blob);
- onApplied?.(blob);
- } catch (err) {
- setError(
- (await serverMessage(err)) ||
- (err instanceof Error ? err.message : undefined) ||
- t(errorKey, errorFallback),
- );
- console.error("[FormFill] commit failed:", err);
- } finally {
- setCommitting(false);
- }
- },
- [onApplied, t],
- );
-
- return { committing, error, setError, commit };
-}