Skip to content

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

Send every Save back to where the file came from (#8794)

Anthony Stirling6f89d1c64377
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index a8a07c8bc8..843d700e39 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -4673,7 +4673,6 @@ closeFile = "Close file"
[fileEditor]
closedFile = "Closed {{name}}"
-couldNotSave = "Could not save {{name}}"
filesReordered_one = "File reordered"
filesReordered_other = "{{count}} files reordered"
loadedFromStorage_one = "Loaded {{count}} file from storage"
@@ -4801,7 +4800,7 @@ addFiles = "Add files"
addingFiles = "Adding files…"
collapse = "Collapse sidebar"
customizeGroups = "Customize groups"
-dataLostBody = "This browser lost this file's contents. Upload it again to keep working with it."
+dataLostBody = "Couldn't find this file's contents. Add it again to keep working with it."
dataLostTitle = "File data is unavailable"
downloadFailed = "Download failed"
dropHint = "Open files to get started"
@@ -4824,7 +4823,7 @@ viewAll = "View all {{count}} files"
[fileSidebar.fileItem]
closeViewer = "Close viewer"
dataLost = "Data lost"
-dataLostTooltip = "This browser lost this file's contents. Upload it again to keep working with it."
+dataLostTooltip = "Couldn't find this file's contents. Add it again to keep working with it."
delete = "Delete"
duplicate = "Duplicate"
moreActions = "More actions"
@@ -7991,8 +7990,6 @@ triggerImport = "Runs on import"
[policies.enforcement]
applying = "Applying {{names}}"
applyingProgress = "Applying {{names}} ({{done}} of {{total}})"
-exportFailureBody = "Security policies couldn't be applied. Files were exported as-is."
-exportFailureTitle = "Exported without enforcement"
failureBody = "Some policies couldn't be applied to {{failures}} of {{total}} file(s)."
failureTitle = "Exported without full enforcement"
printPolicyAppliedBody = "This PDF was updated to meet a policy. Review the changes, then print again."
@@ -12027,6 +12024,13 @@ title = "Sanitize PDF"
[sanitizePdf]
tags = "clean,secure,safe,remove-threats"
+[saveFile.menu]
+more = "More save options"
+saveCopy = "Save a copy..."
+
+[saveFile.toolbar]
+mixed = "Save all"
+
[scalePages]
tags = "resize,adjust,scale,page size,resize page,scale page,change size,adjust size,enlarge,shrink page,fit to page,A4,letter size"
title = "Adjust page-scale"
diff --git a/frontend/src/editor/core/components/fileEditor/FileEditor.tsx b/frontend/src/editor/core/components/fileEditor/FileEditor.tsx
index 0d35523a9d..3e7cb27502 100644
--- a/frontend/src/editor/core/components/fileEditor/FileEditor.tsx
+++ b/frontend/src/editor/core/components/fileEditor/FileEditor.tsx
@@ -19,6 +19,7 @@ import { alert } from "@editor/components/toast";
import { downloadFileWithPolicy as downloadFile } from "@editor/services/exportWithPolicy";
import { useToolWorkflow } from "@editor/contexts/ToolWorkflowContext";
import { usePolicyFileBadges } from "@editor/hooks/usePolicyFileBadges";
+import { useSaveStoredFile } from "@editor/hooks/useSaveStoredFile";
import type { FileItemPolicyRef } from "@editor/components/shared/PolicyBadges";
const EMPTY_POLICIES: FileItemPolicyRef[] = [];
@@ -48,6 +49,7 @@ const FileEditor = ({
const { state, selectors } = useFileState();
const { addFiles, removeFiles, reorderFiles } = useFileManagement();
const { actions: fileActions } = useFileActions();
+ const saver = useSaveStoredFile();
const { selectedFileIds, setSelectedFiles } = useFileSelection();
const activeStirlingFileStubs = useMemo(
@@ -221,40 +223,33 @@ const FileEditor = ({
async (fileId: FileId) => {
const record = stubsRef.current.find((r) => r.id === fileId);
const file = record ? selectors.getFile(record.id) : null;
- console.log("[FileEditor] handleDownloadFile called:", {
+ if (!record || !file) return;
+ // Beside a save to another home this is a one-off copy, not a new disk link.
+ const linksToDisk = !saver.targetFor(record);
+ const result = await downloadFile({
+ data: file,
+ filename: record.name,
+ localPath: linksToDisk ? record.localFilePath : undefined,
fileId,
- hasRecord: !!record,
- hasFile: !!file,
- localFilePath: record?.localFilePath,
- isDirty: record?.isDirty,
});
- if (record && file) {
- const result = await downloadFile({
- data: file,
- filename: file.name,
- localPath: record.localFilePath,
- fileId,
- });
- console.log("[FileEditor] Download complete, checking dirty state:", {
- localFilePath: record.localFilePath,
- isDirty: record.isDirty,
- savedPath: result.savedPath,
+ if (linksToDisk && result.savedPath) {
+ fileActions.updateStirlingFileStub(fileId, {
+ localFilePath: record.localFilePath ?? result.savedPath,
+ isDirty: false,
});
- if (result.savedPath) {
- console.log("[FileEditor] Marking file as clean:", fileId);
- fileActions.updateStirlingFileStub(fileId, {
- localFilePath: record.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- } else {
- console.log("[FileEditor] Skipping clean mark:", {
- savedPath: result.savedPath,
- isDirty: record.isDirty,
- });
- }
}
},
- [selectors, fileActions],
+ [selectors, fileActions, saver],
+ );
+
+ const handleSaveFile = useCallback(
+ async (fileId: FileId) => {
+ const record = stubsRef.current.find((r) => r.id === fileId);
+ if (!record) return false;
+ const file = selectors.getFile(fileId) ?? undefined;
+ return (await saver.saveStoredFile(record, file)) === "saved";
+ },
+ [saver, selectors],
);
const handleUnzipFile = useCallback(
@@ -393,6 +388,9 @@ const FileEditor = ({
onViewFile={handleViewFile}
onReorderFiles={handleReorderFiles}
onDownloadFile={handleDownloadFile}
+ onSaveFile={handleSaveFile}
+ unsaved={saver.isUnsaved(record)}
+ saveTarget={saver.targetFor(record)}
onUnzipFile={handleUnzipFile}
toolMode={toolMode}
isSupported={isFileSupported(record.name)}
diff --git a/frontend/src/editor/core/components/fileEditor/FileEditorStatusDot.tsx b/frontend/src/editor/core/components/fileEditor/FileEditorStatusDot.tsx
index 1074c204ed..5eb6b03cbd 100644
--- a/frontend/src/editor/core/components/fileEditor/FileEditorStatusDot.tsx
+++ b/frontend/src/editor/core/components/fileEditor/FileEditorStatusDot.tsx
@@ -1,9 +1,16 @@
import { StirlingFileStub } from "@editor/types/fileContext";
+import {
+ TargetStatusDot,
+ type TargetStatus,
+} from "@editor/components/fileEditor/TargetStatusDot";
interface FileEditorStatusDotProps {
file: StirlingFileStub;
+ /** Set when Save sends this file to a save target. */
+ target?: TargetStatus;
}
-export function FileEditorStatusDot(_props: FileEditorStatusDotProps) {
- return null;
+export function FileEditorStatusDot({ target }: FileEditorStatusDotProps) {
+ // With no disk copy to fall behind, only a save target's state shows.
+ return target?.unsaved ? <TargetStatusDot {...target} /> : null;
}
diff --git a/frontend/src/editor/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/src/editor/core/components/fileEditor/FileEditorThumbnail.tsx
index 59fda2b940..02acf151f8 100644
--- a/frontend/src/editor/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/src/editor/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -23,16 +23,12 @@ import { zipFileService } from "@editor/services/zipFileService";
import styles from "@editor/components/fileEditor/FileEditorThumbnail.module.css";
import { useFileContext } from "@editor/contexts/FileContext";
-import {
- useFileSelector,
- useFileSelectors,
-} from "@editor/contexts/file/fileHooks";
+import { useFileSelector } from "@editor/contexts/file/fileHooks";
import { FileId } from "@editor/types/file";
import ToolChain from "@editor/components/shared/ToolChain";
import HoverActionMenu, {
HoverAction,
} from "@editor/components/shared/HoverActionMenu";
-import { downloadFileWithPolicy as downloadFile } from "@editor/services/exportWithPolicy";
import { PrivateContent } from "@editor/components/shared/PrivateContent";
import { CloseFilesConfirmModal } from "@editor/components/shared/CloseFilesConfirmModal";
import UploadToServerModal from "@editor/components/shared/UploadToServerModal";
@@ -47,6 +43,8 @@ import DocumentThumbnail from "@editor/components/shared/filePreview/DocumentThu
import { LARGE_PDF_PARSE_LIMIT } from "@editor/utils/thumbnailUtils";
import { truncateCenter } from "@editor/utils/textUtils";
import { FileEditorStatusDot } from "@editor/components/fileEditor/FileEditorStatusDot";
+import type { SaveTarget } from "@editor/services/saveTargets";
+import { SAVES_TO_DISK } from "@editor/services/downloadService";
import { useToolEligibleFileIds } from "@editor/contexts/ToolFileEligibilityContext";
import { useDamagedFileRepair } from "@editor/contexts/DamagedFileRepairContext";
@@ -62,6 +60,12 @@ interface FileEditorThumbnailProps {
selectedFileIds: FileId[],
) => void;
onDownloadFile: (fileId: FileId) => void;
+ /** Saves where the toolbar's Save would; false when nothing was saved. */
+ onSaveFile: (fileId: FileId) => Promise<boolean>;
+ /** Unsaved against where Save sends the file. */
+ unsaved?: boolean;
+ /** Set when Save sends this file somewhere other than disk or a download. */
+ saveTarget?: SaveTarget;
onUnzipFile?: (fileId: FileId) => void;
toolMode?: boolean;
isSupported?: boolean;
@@ -74,6 +78,9 @@ const FileEditorThumbnail = ({
onViewFile,
onReorderFiles,
onDownloadFile,
+ onSaveFile,
+ unsaved = false,
+ saveTarget,
onUnzipFile,
isSupported = true,
policies = [],
@@ -98,7 +105,6 @@ const FileEditorThumbnail = ({
actions: fileActions,
openEncryptedUnlockPrompt,
} = useFileContext();
- const selectors = useFileSelectors();
const isMobile = useIsMobile();
const actualFile = useMemo(
@@ -252,38 +258,9 @@ const FileEditorThumbnail = ({
}, [file.id, file.name, onCloseFile, t]);
const handleSaveAndClose = useCallback(async () => {
- const fileToSave = selectors.getFile(file.id);
- if (fileToSave) {
- try {
- const result = await downloadFile({
- data: fileToSave,
- filename: file.name,
- localPath: file.localFilePath,
- fileId: file.id,
- });
- if (!result.cancelled && result.savedPath) {
- fileActions.updateStirlingFileStub(file.id, {
- localFilePath: file.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- } else if (result.cancelled) {
- setShowCloseModal(false);
- return;
- }
- } catch (error) {
- console.error(`Failed to save ${file.name}:`, error);
- alert({
- alertType: "error",
- title: t("fileEditor.saveFailed", "Save failed"),
- body: t("fileEditor.couldNotSave", "Could not save {{name}}", {
- name: file.name,
- }),
- privateBody: true,
- expandable: true,
- });
- setShowCloseModal(false);
- return;
- }
+ if (!(await onSaveFile(file.id))) {
+ setShowCloseModal(false);
+ return;
}
onCloseFile(file.id);
alert({
@@ -296,15 +273,7 @@ const FileEditorThumbnail = ({
durationMs: 3500,
});
setShowCloseModal(false);
- }, [
- file.id,
- file.name,
- file.localFilePath,
- onCloseFile,
- selectors,
- fileActions,
- t,
- ]);
+ }, [file.id, file.name, onCloseFile, onSaveFile, t]);
const [showVersionHistory, setShowVersionHistory] = useState(false);
@@ -321,6 +290,12 @@ const FileEditorThumbnail = ({
const backgroundPolicy = policies.find((p) => p.background && !p.enforcing);
const hoverActions = useMemo<HoverAction[]>(() => {
+ const targetLabel = saveTarget?.saveLabel(file);
+ // A plain "Save" beside the save to another home would read as that save.
+ const downloadLabel =
+ saveTarget && SAVES_TO_DISK
+ ? t("saveFile.menu.saveCopy", "Save a copy...")
+ : terminology.download;
const uploadLabel = isUploaded
? t("fileManager.updateOnServer", "Update on Server")
: t("fileManager.uploadToServer", "Upload to Server");
@@ -399,14 +374,29 @@ const FileEditorThumbnail = ({
}
},
},
+ ...(saveTarget && targetLabel
+ ? [
+ {
+ id: "saveToTarget",
+ icon: <Icon name={saveTarget.icon} size={20} />,
+ label: targetLabel,
+ disabled: policyEnforcing || saveTarget.saving === file.id,
+ tooltip: policyEnforcing
+ ? enforcingTooltip(targetLabel)
+ : undefined,
+ onClick: (e: React.MouseEvent) => {
+ e.stopPropagation();
+ void onSaveFile(file.id);
+ },
+ },
+ ]
+ : []),
{
id: "download",
icon: <Icon name={icons.download} size={20} />,
- label: terminology.download,
+ label: downloadLabel,
disabled: policyEnforcing,
- tooltip: policyEnforcing
- ? enforcingTooltip(terminology.download)
- : undefined,
+ tooltip: policyEnforcing ? enforcingTooltip(downloadLabel) : undefined,
onClick: (e) => {
e.stopPropagation();
onDownloadFile(file.id);
@@ -502,6 +492,9 @@ const FileEditorThumbnail = ({
terminology,
onViewFile,
onDownloadFile,
+ onSaveFile,
+ saveTarget,
+ file,
onUnzipFile,
handleCloseWithConfirmation,
policyEnforcing,
@@ -714,7 +707,14 @@ const FileEditorThumbnail = ({
)}
</div>
- <FileEditorStatusDot file={file} />
+ <FileEditorStatusDot
+ file={file}
+ target={
+ saveTarget
+ ? { unsaved, label: saveTarget.statusLabel(unsaved) }
+ : undefined
+ }
+ />
</div>
</div>
{/* end thumbUnit */}
@@ -772,7 +772,7 @@ const FileEditorThumbnail = ({
<CloseFilesConfirmModal
opened={showCloseModal}
message={
- file.isDirty && file.localFilePath
+ unsaved
? t("confirmCloseUnsaved", "This file has unsaved changes.")
: t(
"confirmCloseMessage",
@@ -781,15 +781,13 @@ const FileEditorThumbnail = ({
}
files={[{ id: file.id, name: file.name }]}
closeLabel={
- file.isDirty && file.localFilePath
+ unsaved
? t("confirmCloseDiscard", "Discard changes and close")
: t("confirmCloseConfirm", "Close File")
}
onClose={handleConfirmClose}
onCancel={handleCancelClose}
- onSave={
- file.isDirty && file.localFilePath ? handleSaveAndClose : undefined
- }
+ onSave={unsaved ? handleSaveAndClose : undefined}
/>
{/* Shared edit notice modal */}
diff --git a/frontend/src/editor/core/components/fileEditor/TargetStatusDot.tsx b/frontend/src/editor/core/components/fileEditor/TargetStatusDot.tsx
new file mode 100644
index 0000000000..049e5732b7
--- /dev/null
+++ b/frontend/src/editor/core/components/fileEditor/TargetStatusDot.tsx
@@ -0,0 +1,28 @@
+import { Tooltip } from "@mantine/core";
+import styles from "@editor/components/fileEditor/FileEditorThumbnail.module.css";
+
+export interface TargetStatus {
+ unsaved: boolean;
+ /** e.g. "Changes not saved to OneDrive yet". */
+ label: string;
+}
+
+/** A card's save state when Save sends the file to a save target. */
+export function TargetStatusDot({ unsaved, label }: TargetStatus) {
+ return (
+ <div className={styles.thumbBadgesRight}>
+ <Tooltip label={label}>
+ <span
+ className={styles.statusDot}
+ style={{
+ backgroundColor: unsaved
+ ? "var(--mantine-color-yellow-6)"
+ : "var(--mantine-color-green-6)",
+ }}
+ aria-label={label}
+ data-testid="file-card-save-status"
+ />
+ </Tooltip>
+ </div>
+ );
+}
diff --git a/frontend/src/editor/core/components/pageTracks/PageTracks.tsx b/frontend/src/editor/core/components/pageTracks/PageTracks.tsx
index e1daf81edd..d235dd1be8 100644
--- a/frontend/src/editor/core/components/pageTracks/PageTracks.tsx
+++ b/frontend/src/editor/core/components/pageTracks/PageTracks.tsx
@@ -33,7 +33,10 @@ import { useWheelZoom } from "@editor/hooks/useWheelZoom";
import { PrivateContent } from "@editor/components/shared/PrivateContent";
import { truncateCenter } from "@editor/utils/textUtils";
import { FileId } from "@editor/types/file";
-import { WorkbenchExportFile } from "@editor/types/workbenchBar";
+import {
+ WorkbenchExportFile,
+ WorkbenchExportOptions,
+} from "@editor/types/workbenchBar";
import { useWorkbenchViewFileActions } from "@editor/hooks/useWorkbenchViewFileActions";
import { CloseFilesConfirmModal } from "@editor/components/shared/CloseFilesConfirmModal";
import { alert } from "@editor/components/toast";
@@ -802,46 +805,62 @@ export default function PageTracks() {
void save();
}, [save]);
- // Downloads what the editor shows: an unchanged track is its stored file, an
- // edited one or a split is rendered from its pages without being saved.
- const getExportFiles = useCallback(async (): Promise<
- WorkbenchExportFile[] | null
- > => {
- const lookup = {
- getStub: fileSelectors.getStirlingFileStub,
- getFile: fileSelectors.getFile,
- signal: inspectionLifetime.current.signal,
- };
- const trackIds = workspace.order.filter(
- (id) => (workspace.tracks[id]?.pages.length ?? 0) > 0,
- );
- try {
- assertFilesNotBlocked(
- policyIdsForTracks(
- workspace,
- trackIds.filter((id) => changedSet.has(id)),
- lookup.getStub,
- ),
+ // Exports what the editor shows: an unchanged track is its stored file, an
+ // edited one or a split is rendered from its pages without being saved. A save
+ // home versions the edits first, so the home and the workbench hold the same file.
+ const getExportFiles = useCallback(
+ async ({ commitEdits = false }: WorkbenchExportOptions = {}): Promise<
+ WorkbenchExportFile[] | null
+ > => {
+ const committed =
+ commitEdits && changedSet.size > 0 ? await save() : undefined;
+ if (committed === null) return null;
+ const lookup = {
+ getStub: fileSelectors.getStirlingFileStub,
+ getFile: fileSelectors.getFile,
+ signal: inspectionLifetime.current.signal,
+ };
+ const trackIds = workspace.order.filter(
+ (id) => (workspace.tracks[id]?.pages.length ?? 0) > 0,
);
- const files: WorkbenchExportFile[] = [];
- for (const id of trackIds) {
- const track = workspace.tracks[id];
- if (!track) continue;
- if (!changedSet.has(id)) {
- const file = lookup.getFile(id);
- if (file) files.push({ file, fileId: id });
- continue;
+ try {
+ assertFilesNotBlocked(
+ policyIdsForTracks(
+ workspace,
+ trackIds.filter((id) => changedSet.has(id)),
+ lookup.getStub,
+ ),
+ );
+ const files: WorkbenchExportFile[] = [];
+ for (const id of trackIds) {
+ const track = workspace.tracks[id];
+ if (!track) continue;
+ const version = committed?.get(id);
+ if (version) {
+ files.push({
+ file: version.file,
+ fileId: version.file.fileId,
+ stub: version.stub,
+ });
+ continue;
+ }
+ if (!changedSet.has(id)) {
+ const file = lookup.getFile(id);
+ if (file) files.push({ file, fileId: id });
+ continue;
+ }
+ const built = await buildTrackFile(track, lookup);
+ if (built) files.push({ file: built.file });
}
- const built = await buildTrackFile(track, lookup);
- if (built) files.push({ file: built.file });
+ return files;
+ } catch (error) {
+ if (lookup.signal.aborted) return null;
+ alertExportFailure(error, t);
+ return null;
}
- return files;
- } catch (error) {
- if (lookup.signal.aborted) return null;
- alertExportFailure(error, t);
- return null;
- }
- }, [changedSet, fileSelectors, t, workspace]);
+ },
+ [changedSet, fileSelectors, save, t, workspace],
+ );
const [downloadingSelection, setDownloadingSelection] = useState(false);
const downloadSelection = useCallback(
@@ -922,7 +941,7 @@ export default function PageTracks() {
return;
}
// Saving versions the file under a new id; one that emptied is already closed.
- const savedId = versioned.get(request);
+ const savedId = versioned.get(request)?.file.fileId;
if (savedId) setCloseOnceSaved(savedId);
}, [closeRequest, closeRequestEdits, fileActions, save]);
diff --git a/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.ts b/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.ts
index 1282d3ac8b..acfaf4885d 100644
--- a/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.ts
+++ b/frontend/src/editor/core/components/pageTracks/hooks/useTrackSave.ts
@@ -8,6 +8,7 @@ import {
} from "@editor/contexts/file/fileActions";
import {
createStirlingFile,
+ StirlingFile,
StirlingFileStub,
} from "@editor/types/fileContext";
import { FileId } from "@editor/types/file";
@@ -59,10 +60,16 @@ export interface TrackSaveHook {
progress: TrackSaveProgress | null;
/**
* Writes changed tracks back as a new version of their own file: all of them,
- * or only those in `trackIds`. Resolves to each versioned file's old id mapped
- * to its new one, or null if nothing was saved.
+ * or only those in `trackIds`. Resolves to each versioned file's old id, and
+ * each materialised split's track id, mapped to the saved file, or null if
+ * nothing was saved.
*/
- save: (trackIds?: FileId[]) => Promise<Map<FileId, FileId> | null>;
+ save: (trackIds?: FileId[]) => Promise<Map<FileId, SavedVersion> | null>;
+}
+
+export interface SavedVersion {
+ file: StirlingFile;
+ stub?: StirlingFileStub;
}
interface BuiltTrack {
@@ -146,7 +153,7 @@ export function useTrackSave(
// Version each file-backed track in place (a new version of its own
// file). One at a time so each lands in its own slot rather than clumping
// at the top of the file list.
- const versioned = new Map<FileId, FileId>();
+ const versioned = new Map<FileId, SavedVersion>();
for (const entry of built) {
if (entry.inputFileId == null) continue;
const processedFile = await generateProcessedFileMetadata(entry.file);
@@ -157,13 +164,14 @@ export function useTrackSave(
processedFile?.thumbnailUrl,
processedFile,
);
+ const file = createStirlingFile(entry.file, outputStub.id);
await actions.consumeFiles(
[entry.inputFileId],
- [createStirlingFile(entry.file, outputStub.id)],
+ [file],
[outputStub],
{ silent: true },
);
- versioned.set(entry.inputFileId, outputStub.id);
+ versioned.set(entry.inputFileId, { stub: outputStub, file });
onVersionedRef.current?.(entry.inputFileId, outputStub.id);
}
@@ -172,6 +180,7 @@ export function useTrackSave(
// workspace, via sync) as their own tracks.
const splitEntries = built.filter((entry) => entry.inputFileId == null);
const materializedIds = new Map<FileId, FileId>();
+ const saved = new Map<FileId, SavedVersion>(versioned);
if (splitEntries.length > 0) {
const added = await actions.addFiles(
splitEntries.map((entry) => entry.file),
@@ -181,7 +190,9 @@ export function useTrackSave(
// new file lines up with the split track it was built from.
splitEntries.forEach((entry, index) => {
const file = added[index];
- if (file) materializedIds.set(entry.trackId, file.fileId);
+ if (!file) return;
+ materializedIds.set(entry.trackId, file.fileId);
+ saved.set(entry.trackId, { file });
});
}
@@ -199,7 +210,9 @@ export function useTrackSave(
const emptiedSet = new Set(emptied);
const order = workspace.order.flatMap((id) => {
if (emptiedSet.has(id)) return [];
- return [versioned.get(id) ?? materializedIds.get(id) ?? id];
+ return [
+ versioned.get(id)?.file.fileId ?? materializedIds.get(id) ?? id,
+ ];
});
// Each new split file should sit right after its source in the open-
// file list (the source may itself have been versioned to a new id).
@@ -208,7 +221,9 @@ export function useTrackSave(
const source = workspace.tracks[trackId]?.splitFromFileId;
return {
fileId,
- afterFileId: source ? (versioned.get(source) ?? source) : null,
+ afterFileId: source
+ ? (versioned.get(source)?.file.fileId ?? source)
+ : null,
};
},
);
@@ -219,7 +234,7 @@ export function useTrackSave(
});
}
- return versioned;
+ return saved;
} catch (error) {
if (cancellation.signal.aborted) return null;
if (error instanceof PolicyBlockedError) {
diff --git a/frontend/src/editor/core/components/shared/FileSidebar.tsx b/frontend/src/editor/core/components/shared/FileSidebar.tsx
index 87a9f61d8d..578f251b69 100644
--- a/frontend/src/editor/core/components/shared/FileSidebar.tsx
+++ b/frontend/src/editor/core/components/shared/FileSidebar.tsx
@@ -689,7 +689,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
title: t("fileSidebar.dataLostTitle", "File data is unavailable"),
body: t(
"fileSidebar.dataLostBody",
- "This browser lost this file's contents. Upload it again to keep working with it.",
+ "Couldn't find this file's contents. Add it again to keep working with it.",
),
expandable: false,
durationMs: 6000,
@@ -860,7 +860,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
title: t("fileSidebar.dataLostTitle", "File data is unavailable"),
body: t(
"fileSidebar.dataLostBody",
- "This browser lost this file's contents. Upload it again to keep working with it.",
+ "Couldn't find this file's contents. Add it again to keep working with it.",
),
expandable: false,
durationMs: 6000,
diff --git a/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx b/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx
index 3c45613bf7..e4b8366786 100644
--- a/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx
+++ b/frontend/src/editor/core/components/shared/FileSidebarFileItem.tsx
@@ -268,7 +268,7 @@ export const FileItem = React.memo(function FileItem({
if (needsBytes && dataUnavailable)
return t(
"fileSidebar.fileItem.dataLostTooltip",
- "This browser lost this file's contents. Upload it again to keep working with it.",
+ "Couldn't find this file's contents. Add it again to keep working with it.",
);
return null;
};
@@ -361,7 +361,7 @@ export const FileItem = React.memo(function FileItem({
<Tooltip
label={t(
"fileSidebar.fileItem.dataLostTooltip",
- "This browser lost this file's contents. Upload it again to keep working with it.",
+ "Couldn't find this file's contents. Add it again to keep working with it.",
)}
withArrow
position="top"
diff --git a/frontend/src/editor/core/components/shared/WorkbenchBar.css b/frontend/src/editor/core/components/shared/WorkbenchBar.css
index ebd1c26aeb..d70737b490 100644
--- a/frontend/src/editor/core/components/shared/WorkbenchBar.css
+++ b/frontend/src/editor/core/components/shared/WorkbenchBar.css
@@ -474,3 +474,59 @@
align-self: flex-start;
}
}
+
+/* Changes not yet saved to where Save goes. */
+.workbench-bar-unsaved-anchor {
+ position: relative;
+ display: inline-flex;
+}
+
+.workbench-bar-unsaved-dot {
+ position: absolute;
+ top: -4px;
+ right: -4px;
+ width: 0.4375rem;
+ height: 0.4375rem;
+ border-radius: 999px;
+ background: var(--mantine-color-yellow-6);
+ box-shadow: 0 0 0 1.5px var(--c-bg-raised);
+ pointer-events: none;
+}
+
+.workbench-bar-menu-unsaved-dot {
+ width: 0.4375rem;
+ height: 0.4375rem;
+ border-radius: 999px;
+ background: var(--mantine-color-yellow-6);
+}
+
+.workbench-bar-menu-hint {
+ font-size: 0.75rem;
+ color: var(--c-text-muted);
+}
+
+/* Without a menu the wrapper must not change the bar's layout. */
+.workbench-bar-save-plain {
+ display: contents;
+}
+
+/* Save and "More save options" joined, so they read as one control. */
+.workbench-bar-save-group {
+ --save-group-line: color-mix(
+ in srgb,
+ var(--c-border-strong) 55%,
+ transparent
+ );
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ padding: 2px 3px;
+ border: 1px solid var(--save-group-line);
+ border-radius: 8px;
+}
+
+.workbench-bar-save-group-caret {
+ display: inline-flex;
+ padding-left: 3px;
+ border-left: 1px solid var(--save-group-line);
+}
diff --git a/frontend/src/editor/core/components/shared/WorkbenchBar.tsx b/frontend/src/editor/core/components/shared/WorkbenchBar.tsx
index 793e7f8f0a..7adbd59c5f 100644
--- a/frontend/src/editor/core/components/shared/WorkbenchBar.tsx
+++ b/frontend/src/editor/core/components/shared/WorkbenchBar.tsx
@@ -26,7 +26,6 @@ import {
import { useWorkbenchBar } from "@editor/contexts/WorkbenchBarContext";
import {
useAllFiles,
- useFileSelectors,
useFileSelection,
useFileActions,
} from "@editor/contexts/FileContext";
@@ -47,10 +46,6 @@ import {
POLICY_IN_FLIGHT_STATUSES,
usePolicyRuns,
} from "@editor/components/policies/policyRunStore";
-import { downloadFileWithPolicy as downloadFile } from "@editor/services/exportWithPolicy";
-import { enforceExportPolicies } from "@editor/services/policyExport";
-import { downloadFile as downloadRaw } from "@editor/services/downloadService";
-import { alert as showAlert } from "@editor/components/toast";
import {
WorkbenchBarButtonConfig,
WorkbenchBarRenderContext,
@@ -64,6 +59,8 @@ import { WorkbenchBarActionsProps } from "@editor/components/shared/workbenchBar
import { useIsMobile, useIsPhone } from "@editor/hooks/useIsMobile";
import "@editor/components/shared/WorkbenchBar.css";
import { NotificationBell } from "@editor/components/notifications/NotificationBell";
+import { useWorkbenchSave } from "@editor/hooks/useWorkbenchSave";
+import { useSaveButton } from "@editor/components/shared/workbenchBar/useSaveButton";
const SECTION_ORDER: WorkbenchBarSection[] = ["top", "middle", "bottom"];
@@ -169,24 +166,15 @@ export default function WorkbenchBar({
const isPhone = useIsPhone();
const [mobileToolsExpanded, setMobileToolsExpanded] = useState(false);
- const selectors = useFileSelectors();
- const { selectedFiles, selectedFileIds } = useFileSelection();
+ const { selectedFileIds } = useFileSelection();
const { actions: fileActions } = useFileActions();
const { files: activeFiles } = useAllFiles();
const { activeFileId, setActiveFileId } = useViewer();
const policyFileBadges = usePolicyFileBadges();
+ const workbenchSave = useWorkbenchSave();
// Block print/export while any file the export would touch is under active
- // policy enforcement: the viewer exports its active file, every other view
- // exports the selection (or all files when nothing is selected).
- const exportTargetIds: string[] =
- currentView === "viewer"
- ? activeFileId
- ? [activeFileId]
- : []
- : selectedFileIds.length > 0
- ? selectedFileIds
- : activeFiles.filter(isStirlingFile).map((f) => f.fileId);
- const enforcingFileId = exportTargetIds.find((id) =>
+ // policy enforcement.
+ const enforcingFileId = workbenchSave.targetIds.find((id) =>
(policyFileBadges.get(id) ?? []).some((p) => p.enforcing),
);
const policyEnforcing = enforcingFileId != null;
@@ -232,113 +220,13 @@ export default function WorkbenchBar({
}).filter((entry) => entry.buttons.length > 0);
}, [buttons]);
- const handleExportAll = useCallback(
- async (forceNewFile = false) => {
- if (currentView === "viewer") {
- const buffer = await viewerContext?.exportActions?.saveAsCopy?.();
- if (!buffer) return;
- const fileToExport =
- activeFiles.find(
- (file) => isStirlingFile(file) && file.fileId === activeFileId,
- ) ?? activeFiles[0];
- if (!fileToExport) return;
- const stub = isStirlingFile(fileToExport)
- ? selectors.getStirlingFileStub(fileToExport.fileId)
- : undefined;
- try {
- const result = await downloadFile({
- data: new Blob([buffer], { type: "application/pdf" }),
- // Stub name, not File.name: a rename only writes the stub.
- filename: stub?.name ?? fileToExport.name,
- localPath: forceNewFile ? undefined : stub?.localFilePath,
- fileId: stub?.id,
- });
- if (!forceNewFile && !result.cancelled && stub && result.savedPath) {
- fileActions.updateStirlingFileStub(stub.id, {
- localFilePath: stub.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- }
- } catch (error) {
- console.error("[WorkbenchBar] Failed to export viewer file:", error);
- }
- return;
- }
-
- const viewExport = await viewFileActions?.getExportFiles?.();
- if (viewExport === null) return;
- const filesToExport = viewExport
- ? viewExport.map((entry) => entry.file)
- : selectedFiles.length > 0
- ? selectedFiles
- : activeFiles;
- const stubs = viewExport
- ? viewExport.map((entry) =>
- entry.fileId
- ? selectors.getStirlingFileStub(entry.fileId)
- : undefined,
- )
- : filesToExport.map((file) =>
- isStirlingFile(file)
- ? selectors.getStirlingFileStub(file.fileId)
- : undefined,
- );
-
- // Enforce all files in one batch so the toast shows progress across the
- // whole set (e.g. "report.pdf (2 of 5)") rather than N invisible solo runs.
- let enforced: File[];
- try {
- enforced = await enforceExportPolicies(
- filesToExport,
- stubs.map((s) => s?.id),
- );
- } catch {
- enforced = filesToExport;
- showAlert({
- alertType: "warning",
- title: t("policies.enforcement.exportFailureTitle"),
- body: t("policies.enforcement.exportFailureBody"),
- });
- }
-
- for (let idx = 0; idx < filesToExport.length; idx++) {
- const file = filesToExport[idx];
- const stub = stubs[idx];
- try {
- const result = await downloadRaw({
- data: enforced[idx],
- // Stub name, not File.name: a rename only writes the stub.
- filename: stub?.name ?? file.name,
- localPath: forceNewFile ? undefined : stub?.localFilePath,
- fileId: stub?.id,
- });
- if (result.cancelled) continue;
- if (!forceNewFile && stub && result.savedPath) {
- fileActions.updateStirlingFileStub(stub.id, {
- localFilePath: stub.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- }
- } catch (error) {
- console.error(
- "[WorkbenchBar] Failed to export file:",
- file.name,
- error,
- );
- }
- }
- },
- [
- currentView,
- selectedFiles,
- activeFiles,
- activeFileId,
- viewerContext,
- viewFileActions,
- selectors,
- fileActions,
- ],
- );
+ const saveButton = useSaveButton({
+ saver: workbenchSave.saver,
+ targets: workbenchSave.targetStubs,
+ singleFile: currentView === "viewer",
+ onSaveLocalCopy: () => void workbenchSave.saveCopy(),
+ fileFor: workbenchSave.viewerFileFor,
+ });
const printAccess = usePdfAccess(activeFileId);
const canPrint =
@@ -417,12 +305,13 @@ export default function WorkbenchBar({
showsFileActions: !isCustomView && currentView !== "myFiles",
actionsDisabled,
policyEnforcing,
- downloadLabel: downloadTooltip,
- downloadIconName: icons.download,
- saveAsIconName: icons.saveAs,
+ downloadLabel: saveButton.label ?? downloadTooltip,
+ downloadIconName: saveButton.icon ?? icons.download,
+ downloadUnsaved: saveButton.unsaved,
+ saveMenu: saveButton.menu,
onPrint: canPrint ? handlePrint : undefined,
printDisabledReason,
- onExport: handleExportAll,
+ onExport: () => void workbenchSave.save(),
onClose: handleClose,
};
diff --git a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
index 7b35d7857d..91ad9c0151 100644
--- a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
+++ b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarDesktopActions.tsx
@@ -1,4 +1,6 @@
-import React from "react";
+import React, { useState } from "react";
+import { Menu } from "@mantine/core";
+import { Tooltip } from "@editor/components/shared/Tooltip";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
import { ActionIcon } from "@editor/ui/ActionIcon";
@@ -14,8 +16,8 @@ interface WorkbenchBarDesktopActionsProps extends WorkbenchBarActionsProps {
}
/**
- * Desktop version of the workbench bar's global actions: print / export /
- * save-as sit as icons, with close split off behind a separator.
+ * Desktop version of the workbench bar's global actions: print and save sit
+ * as icons, with close split off behind a separator.
*/
export default function WorkbenchBarDesktopActions({
currentView,
@@ -24,7 +26,8 @@ export default function WorkbenchBarDesktopActions({
policyEnforcing,
downloadLabel,
downloadIconName,
- saveAsIconName,
+ downloadUnsaved,
+ saveMenu,
onPrint,
printDisabledReason,
onExport,
@@ -32,6 +35,7 @@ export default function WorkbenchBarDesktopActions({
enforcingProgress,
}: WorkbenchBarDesktopActionsProps) {
const { t } = useTranslation();
+ const [saveMenuOpen, setSaveMenuOpen] = useState(false);
const exportDisabled = actionsDisabled || policyEnforcing;
const closeLabel =
currentView === "fileEditor" || currentView === "pageEditor"
@@ -66,36 +70,84 @@ export default function WorkbenchBarDesktopActions({
)}
{/* Saving, and closing what was saved: only where a document is open. */}
- {showsFileActions &&
- renderWithTooltip(
- <ActionIcon
- variant="tertiary"
- hover={false}
- className="workbench-bar-action-icon"
- onClick={() => onExport()}
- disabled={exportDisabled}
- aria-label={downloadLabel}
- >
- <Icon name={downloadIconName} size="1rem" />
- </ActionIcon>,
- tooltipFor(downloadLabel),
- )}
-
- {showsFileActions &&
- saveAsIconName &&
- renderWithTooltip(
- <ActionIcon
- variant="tertiary"
- hover={false}
- className="workbench-bar-action-icon"
- onClick={() => onExport(true)}
- disabled={exportDisabled}
- aria-label={t("workbenchBar.saveAs", "Save As")}
- >
- <Icon name={saveAsIconName} size="1rem" />
- </ActionIcon>,
- tooltipFor(t("workbenchBar.saveAs", "Save As")),
- )}
+ {showsFileActions && (
+ // With a menu, Save and its arrow read as one control.
+ <div
+ className={
+ saveMenu ? "workbench-bar-save-group" : "workbench-bar-save-plain"
+ }
+ role={saveMenu ? "group" : undefined}
+ aria-label={saveMenu ? downloadLabel : undefined}
+ >
+ {renderWithTooltip(
+ <ActionIcon
+ variant="tertiary"
+ hover={false}
+ className="workbench-bar-action-icon"
+ onClick={() => onExport()}
+ disabled={exportDisabled}
+ aria-label={downloadLabel}
+ >
+ <span className="workbench-bar-unsaved-anchor">
+ <Icon name={downloadIconName} size="1rem" />
+ {downloadUnsaved && (
+ <span className="workbench-bar-unsaved-dot" />
+ )}
+ </span>
+ </ActionIcon>,
+ tooltipFor(downloadLabel),
+ )}
+ {saveMenu && (
+ <Tooltip
+ content={tooltipFor(t("saveFile.menu.more", "More save options"))}
+ position="bottom"
+ offset={6}
+ arrow
+ // Over the open menu it would cover the first items.
+ disabled={saveMenuOpen}
+ portalTarget={document.body}
+ >
+ <div className="workbench-bar-tooltip-wrapper workbench-bar-save-group-caret">
+ <Menu
+ shadow="md"
+ width={270}
+ position="bottom-end"
+ opened={saveMenuOpen}
+ onChange={setSaveMenuOpen}
+ >
+ <Menu.Target>
+ <ActionIcon
+ variant="tertiary"
+ hover={false}
+ className="workbench-bar-action-icon"
+ disabled={exportDisabled}
+ aria-label={t("saveFile.menu.more", "More save options")}
+ >
+ <Icon name="chevron-down" size="1rem" />
+ </ActionIcon>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {saveMenu.map((item) => (
+ <Menu.Item
+ key={item.key}
+ leftSection={<Icon name={item.icon} size="1rem" />}
+ onClick={item.onClick}
+ >
+ {item.label}
+ {item.description && (
+ <div className="workbench-bar-menu-hint">
+ {item.description}
+ </div>
+ )}
+ </Menu.Item>
+ ))}
+ </Menu.Dropdown>
+ </Menu>
+ </div>
+ </Tooltip>
+ )}
+ </div>
+ )}
{/* Separator: export group | close */}
{showsFileActions && (
diff --git a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
index 053157fb3f..c743e3db49 100644
--- a/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
+++ b/frontend/src/editor/core/components/shared/workbenchBar/WorkbenchBarMobileActions.tsx
@@ -6,7 +6,7 @@ import { WorkbenchBarActionsProps } from "@editor/components/shared/workbenchBar
/**
* Mobile version of the workbench bar's global actions: the icon row won't fit
- * on a phone, so print / export / save-as / close collapse into one overflow menu.
+ * on a phone, so print / save / close collapse into one overflow menu.
*/
export default function WorkbenchBarMobileActions({
currentView,
@@ -15,7 +15,8 @@ export default function WorkbenchBarMobileActions({
policyEnforcing,
downloadLabel,
downloadIconName,
- saveAsIconName,
+ downloadUnsaved,
+ saveMenu,
onPrint,
printDisabledReason,
onExport,
@@ -32,7 +33,7 @@ export default function WorkbenchBarMobileActions({
if (!showPrint && !showFileActions) return null;
return (
- <Menu shadow="md" width={230} position="bottom-end">
+ <Menu shadow="md" width={270} position="bottom-end">
<Menu.Target>
<ActionIcon
variant="tertiary"
@@ -40,7 +41,12 @@ export default function WorkbenchBarMobileActions({
className="workbench-bar-action-icon"
aria-label={t("workbenchBar.moreActions", "More actions")}
>
- <Icon name="ellipsis-vertical" size={"1.25rem"} />
+ <span className="workbench-bar-unsaved-anchor">
+ <Icon name="ellipsis-vertical" size={"1.25rem"} />
+ {showFileActions && downloadUnsaved && (
+ <span className="workbench-bar-unsaved-dot" />
+ )}
+ </span>
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
@@ -57,21 +63,28 @@ export default function WorkbenchBarMobileActions({
{showFileActions && (
<Menu.Item
leftSection={<Icon name={downloadIconName} size="1.1rem" />}
+ rightSection={
+ downloadUnsaved && (
+ <span className="workbench-bar-menu-unsaved-dot" />
+ )
+ }
disabled={exportDisabled}
onClick={() => void onExport()}
>
{downloadLabel}
</Menu.Item>
)}
- {showFileActions && saveAsIconName && (
- <Menu.Item
- leftSection={<Icon name={saveAsIconName} size="1.1rem" />}
- disabled={exportDisabled}
- onClick={() => void onExport(true)}
- >
- {t("workbenchBar.saveAs", "Save As")}
- </Menu.Item>
- )}
+ {showFileActions &&
+ saveMenu?.map((item) => (
+ <Menu.Item
+ key={item.key}
+ leftSection={<Icon name={item.icon} size="1.1rem" />}
+ disabled={exportDisabled}
+ onClick={item.onClick}
+ >
+ {item.label}
+ </Menu.Item>
+ ))}
{showFileActions && (
<>
<Menu.Divider />
diff --git a/frontend/src/editor/core/components/shared/workbenchBar/types.ts b/frontend/src/editor/core/components/shared/workbenchBar/types.ts
index 5dbc20b4d9..b49866101a 100644
--- a/frontend/src/editor/core/components/shared/workbenchBar/types.ts
+++ b/frontend/src/editor/core/components/shared/workbenchBar/types.ts
@@ -1,8 +1,9 @@
import type { IconName } from "@editor/ui/Icon";
import { WorkbenchType } from "@editor/types/workbench";
+import type { SaveMenuItem } from "@editor/services/saveTargets";
/** Shared shape for the workbench bar's file-level global actions (print,
- * export, save-as, close) so the mobile and desktop clusters stay in step. */
+ * save, close) so the mobile and desktop clusters stay in step. */
export interface WorkbenchBarActionsProps {
currentView: WorkbenchType;
/** Custom workbench views own their content, so file actions don't apply. */
@@ -16,9 +17,12 @@ export interface WorkbenchBarActionsProps {
/** Context-aware label for the download/export action. */
downloadLabel: string;
downloadIconName: IconName;
- saveAsIconName?: IconName;
+ /** Changes not yet saved to where Save goes. */
+ downloadUnsaved?: boolean;
+ /** The other destinations, for the "More save options" menu. */
+ saveMenu?: SaveMenuItem[];
onPrint?: () => void;
printDisabledReason?: string;
- onExport: (forceNewFile?: boolean) => void;
+ onExport: () => void;
onClose: () => void;
}
diff --git a/frontend/src/editor/core/components/shared/workbenchBar/useSaveButton.test.ts b/frontend/src/editor/core/components/shared/workbenchBar/useSaveButton.test.ts
new file mode 100644
index 0000000000..5afbe7a06f
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/workbenchBar/useSaveButton.test.ts
@@ -0,0 +1,123 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import { useSaveButton } from "@editor/components/shared/workbenchBar/useSaveButton";
+import type { SaveStoredFile } from "@editor/hooks/useSaveStoredFile";
+import type { SaveTarget } from "@editor/services/saveTargets";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+import type { FileId } from "@editor/types/file";
+
+const disk = vi.hoisted(() => ({ saves: false }));
+
+vi.mock("@editor/services/downloadService", () => ({
+ get SAVES_TO_DISK() {
+ return disk.saves;
+ },
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback: string) => fallback,
+ }),
+}));
+
+const stub = (id: string, extra: Partial<StirlingFileStub> = {}) =>
+ ({ id: id as FileId, name: `${id}.pdf`, ...extra }) as StirlingFileStub;
+
+const cloud: SaveTarget = {
+ id: "cloud",
+ handles: (s) => s.id.startsWith("c"),
+ isUnsaved: () => true,
+ saveLabel: (s) => `Update ${s.name} in cloud`,
+ saveAllLabel: () => "Save all to cloud",
+ statusLabel: () => "Not in cloud",
+ icon: "cloud-upload",
+ save: async () => "saved",
+ menuItems: () => [
+ {
+ key: "copy",
+ label: "Save a copy to cloud",
+ icon: "copy",
+ onClick: vi.fn(),
+ },
+ ],
+};
+
+function saver(targets: SaveTarget[]): SaveStoredFile {
+ const targetFor = (s: StirlingFileStub) => targets.find((t) => t.handles(s));
+ return {
+ targetFor,
+ isUnsaved: (s) =>
+ targetFor(s)?.isUnsaved(s) ?? Boolean(s.isDirty && s.localFilePath),
+ saveStoredFile: async () => "saved",
+ saveLocalCopy: async () => "saved",
+ };
+}
+
+beforeEach(() => {
+ disk.saves = false;
+});
+
+const base = {
+ singleFile: true,
+ onSaveLocalCopy: vi.fn(),
+ fileFor: async () => undefined,
+};
+
+it("leaves the browser toolbar alone when nothing has a save target", () => {
+ const { result } = renderHook(() =>
+ useSaveButton({
+ ...base,
+ saver: saver([]),
+ targets: [stub("a")],
+ }),
+ );
+ expect(result.current).toEqual({
+ label: undefined,
+ icon: undefined,
+ unsaved: false,
+ });
+});
+
+it("moves desktop Save As into the menu and dots unsaved disk edits", () => {
+ disk.saves = true;
+ const { result } = renderHook(() =>
+ useSaveButton({
+ ...base,
+ saver: saver([]),
+ targets: [stub("a", { isDirty: true, localFilePath: "C:/a.pdf" })],
+ }),
+ );
+ expect(result.current.unsaved).toBe(true);
+ expect(result.current.menu?.map((item) => item.label)).toEqual([
+ "Save a copy...",
+ ]);
+});
+
+it("names the target and lists its destinations for one file", () => {
+ const { result } = renderHook(() =>
+ useSaveButton({
+ ...base,
+ saver: saver([cloud]),
+ targets: [stub("c1")],
+ }),
+ );
+ expect(result.current.label).toBe("Update c1.pdf in cloud");
+ expect(result.current.icon).toBe("cloud-upload");
+ expect(result.current.menu?.map((item) => item.label)).toEqual([
+ "Download",
+ "Save a copy to cloud",
+ ]);
+});
+
+it("says each file goes home when targets are mixed", () => {
+ const { result } = renderHook(() =>
+ useSaveButton({
+ ...base,
+ singleFile: false,
+ saver: saver([cloud]),
+ targets: [stub("c1"), stub("a")],
+ }),
+ );
+ expect(result.current.label).toBe("Save all");
+ expect(result.current.icon).toBeUndefined();
+ expect(result.current.menu).toBeUndefined();
+});
diff --git a/frontend/src/editor/core/components/shared/workbenchBar/useSaveButton.ts b/frontend/src/editor/core/components/shared/workbenchBar/useSaveButton.ts
new file mode 100644
index 0000000000..5a848f357c
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/workbenchBar/useSaveButton.ts
@@ -0,0 +1,71 @@
+import { useTranslation } from "react-i18next";
+import type { IconName } from "@editor/ui/Icon";
+import type { SaveStoredFile } from "@editor/hooks/useSaveStoredFile";
+import {
+ saveTargetLabel,
+ sharedSaveTarget,
+ type SaveMenuItem,
+} from "@editor/services/saveTargets";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+import { SAVES_TO_DISK } from "@editor/services/downloadService";
+
+export interface SaveButton {
+ /** Replaces the plain Download/Save label when a target handles the files. */
+ label?: string;
+ icon?: IconName;
+ unsaved: boolean;
+ /** The other destinations, for the "More save options" menu. */
+ menu?: SaveMenuItem[];
+}
+
+interface Options {
+ saver: SaveStoredFile;
+ targets: StirlingFileStub[];
+ /** The viewer acts on one file, so it also offers that file's destinations. */
+ singleFile: boolean;
+ onSaveLocalCopy: () => void;
+ /** The file as the viewer shows it, annotations included. */
+ fileFor: (stub: StirlingFileStub) => Promise<File | undefined>;
+}
+
+/** What the toolbar's Save does for these files, and the other destinations. */
+export function useSaveButton({
+ saver,
+ targets,
+ singleFile,
+ onSaveLocalCopy,
+ fileFor,
+}: Options): SaveButton {
+ const { t } = useTranslation();
+ const unsaved = targets.some(saver.isUnsaved);
+ const shared = sharedSaveTarget(targets, saver.targetFor);
+ const label = shared
+ ? saveTargetLabel(shared, targets)
+ : targets.some((stub) => saver.targetFor(stub))
+ ? t("saveFile.toolbar.mixed", "Save all")
+ : undefined;
+ const icon = shared?.icon;
+
+ const stub = singleFile ? targets[0] : undefined;
+ const target = stub ? saver.targetFor(stub) : undefined;
+ if (!SAVES_TO_DISK && !target) return { label, icon, unsaved };
+
+ const menu: SaveMenuItem[] = [
+ SAVES_TO_DISK
+ ? {
+ key: "local",
+ label: t("saveFile.menu.saveCopy", "Save a copy..."),
+ icon: "laptop",
+ onClick: onSaveLocalCopy,
+ }
+ : {
+ key: "local",
+ label: t("download", "Download"),
+ icon: "download",
+ onClick: onSaveLocalCopy,
+ },
+ ];
+ if (stub && target?.menuItems)
+ menu.push(...target.menuItems(stub, () => fileFor(stub)));
+ return { label, icon, unsaved, menu };
+}
diff --git a/frontend/src/editor/core/components/tools/shared/ReviewToolStep.tsx b/frontend/src/editor/core/components/tools/shared/ReviewToolStep.tsx
index f4f80dd174..0f454aa69b 100644
--- a/frontend/src/editor/core/components/tools/shared/ReviewToolStep.tsx
+++ b/frontend/src/editor/core/components/tools/shared/ReviewToolStep.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from "react";
-import { Stack } from "@mantine/core";
+import { Menu, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
import { Icon } from "@editor/ui/Icon";
@@ -13,6 +13,11 @@ import { useFileActionIcons } from "@editor/hooks/useFileActionIcons";
import { saveOperationResults } from "@editor/services/operationResultsSaveService";
import { useFileActions, useFileSelectors } from "@editor/contexts/FileContext";
import i18n from "@editor/i18n";
+import { useSaveStoredFile } from "@editor/hooks/useSaveStoredFile";
+import { useSaveButton } from "@editor/components/shared/workbenchBar/useSaveButton";
+import type { FileId } from "@editor/types/file";
+
+const SAVE_MENU_BUTTON_WIDTH = "3rem";
/**
* Nearest scrolling ancestor - in the right rail that is the tool panel's
@@ -61,6 +66,29 @@ function ReviewStepContent<TParams = unknown>({
const stepRef = useRef<HTMLDivElement>(null);
const { actions: fileActions } = useFileActions();
const selectors = useFileSelectors();
+ const saver = useSaveStoredFile();
+ const outputStubs = selectors.getStirlingFileStubs(
+ (operation.outputFileIds ?? []) as FileId[],
+ );
+ // Results inherit their source's home, so Save sends them back there too.
+ const savesToTarget = outputStubs.some((stub) => saver.targetFor(stub));
+ const saveButton = useSaveButton({
+ saver,
+ targets: outputStubs,
+ singleFile: outputStubs.length === 1,
+ onSaveLocalCopy: () =>
+ void (async () => {
+ for (const stub of outputStubs) {
+ const outcome = await saver.saveLocalCopy(
+ stub,
+ selectors.getFile(stub.id),
+ );
+ if (outcome === "cancelled") break;
+ }
+ })(),
+ fileFor: async (stub) => selectors.getFile(stub.id),
+ });
+ const saveLabel = saveButton.label ?? terminology.download;
const handleUndo = async () => {
try {
@@ -79,6 +107,16 @@ function ReviewStepContent<TParams = unknown>({
const handleDownload = async () => {
if (!operation.downloadUrl) return;
+ if (savesToTarget) {
+ for (const stub of outputStubs) {
+ const outcome = await saver.saveStoredFile(
+ stub,
+ selectors.getFile(stub.id),
+ );
+ if (outcome === "cancelled") break;
+ }
+ return;
+ }
try {
await saveOperationResults({
downloadUrl: operation.downloadUrl,
@@ -171,17 +209,67 @@ function ReviewStepContent<TParams = unknown>({
</Button>
</Tooltip>
)}
- {operation.downloadUrl && (
+ {operation.downloadUrl && !saveButton.menu && (
<Button
data-testid="download-result-button"
- leftSection={<Icon name={icons.download} />}
+ leftSection={<Icon name={saveButton.icon ?? icons.download} />}
fullWidth
style={{ marginBottom: "1rem" }}
onClick={handleDownload}
>
- {terminology.download}
+ {saveLabel}
</Button>
)}
+ {operation.downloadUrl && saveButton.menu && (
+ <Button.Group style={{ marginBottom: "1rem", width: "100%" }}>
+ <Button
+ data-testid="download-result-button"
+ leftSection={<Icon name={saveButton.icon ?? icons.download} />}
+ style={{
+ flex: 1,
+ minWidth: 0,
+ // Mantine's left-section padding plus the menu button's width, so the
+ // label centres on the whole group rather than this half.
+ paddingInlineStart: `calc(var(--button-padding-x) / 1.5 + ${SAVE_MENU_BUTTON_WIDTH})`,
+ }}
+ onClick={handleDownload}
+ >
+ {saveLabel}
+ </Button>
+ <Menu shadow="md" width={270} position="bottom-end">
+ <Menu.Target>
+ <Button
+ data-testid="download-result-menu"
+ px="none"
+ style={{
+ width: SAVE_MENU_BUTTON_WIDTH,
+ borderInlineStart:
+ "1px solid color-mix(in srgb, currentColor 35%, transparent)",
+ }}
+ aria-label={t("saveFile.menu.more", "More save options")}
+ >
+ <Icon name="chevron-down" />
+ </Button>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {saveButton.menu.map((item) => (
+ <Menu.Item
+ key={item.key}
+ leftSection={<Icon name={item.icon} size="1rem" />}
+ onClick={item.onClick}
+ >
+ {item.label}
+ {item.description && (
+ <Text size="xs" c="dimmed">
+ {item.description}
+ </Text>
+ )}
+ </Menu.Item>
+ ))}
+ </Menu.Dropdown>
+ </Menu>
+ </Button.Group>
+ )}
<SuggestedToolsSection />
</Stack>
diff --git a/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx b/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx
index 4857af0e6e..7a3cbb4d52 100644
--- a/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/src/editor/core/components/viewer/EmbedPdfViewer.tsx
@@ -48,6 +48,7 @@ import type {
} from "@editor/components/viewer/viewerTypes";
import { createStirlingFilesAndStubs } from "@editor/services/fileStubHelpers";
import { rememberPlainPdfExport } from "@editor/services/pdfAccessService";
+import { hasUnsavedWork } from "@editor/services/unsavedWork";
import {
isStirlingFile,
getFormFillFileId,
@@ -862,10 +863,11 @@ const EmbedPdfViewerContent = ({
return;
case "s":
case "S":
- // Ctrl+S: Save/apply changes
+ // Ctrl+S: Save/apply changes. Every apply adds a version, so only
+ // when there is something to apply.
if (!event.shiftKey) {
event.preventDefault();
- if (viewerApplyChanges) {
+ if (viewerApplyChanges && hasUnsavedWork()) {
viewerApplyChanges();
}
}
diff --git a/frontend/src/editor/core/hooks/useCommitEditsBeforeSave.test.ts b/frontend/src/editor/core/hooks/useCommitEditsBeforeSave.test.ts
new file mode 100644
index 0000000000..cf45f9058e
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useCommitEditsBeforeSave.test.ts
@@ -0,0 +1,94 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useCommitEditsBeforeSave } from "@editor/hooks/useCommitEditsBeforeSave";
+import type { NavigationWarningHandlers } from "@editor/contexts/NavigationContext";
+import {
+ __resetUnsavedWork,
+ registerUnsavedWorkChecker,
+} from "@editor/services/unsavedWork";
+
+const handlersRef = vi.hoisted(() => ({
+ current: null as NavigationWarningHandlers | null,
+}));
+
+vi.mock("@editor/contexts/NavigationContext", () => ({
+ useNavigationActions: () => ({
+ actions: { navigationWarningHandlersRef: handlersRef },
+ }),
+}));
+
+let commit: ReturnType<typeof vi.fn<() => Promise<void>>>;
+
+beforeEach(() => {
+ commit = vi.fn(async () => {});
+ handlersRef.current = { onApplyAndContinue: commit };
+});
+
+afterEach(() => __resetUnsavedWork());
+
+describe("useCommitEditsBeforeSave", () => {
+ it("saves without committing when the editor has no edits", async () => {
+ registerUnsavedWorkChecker(() => false);
+ const save = vi.fn();
+ const { result } = renderHook(() => useCommitEditsBeforeSave(save));
+
+ await act(() => result.current());
+
+ expect(commit).not.toHaveBeenCalled();
+ expect(save).toHaveBeenCalledTimes(1);
+ });
+
+ it("saves without committing when no editor can commit", async () => {
+ registerUnsavedWorkChecker(() => true);
+ handlersRef.current = null;
+ const save = vi.fn();
+ const { result } = renderHook(() => useCommitEditsBeforeSave(save));
+
+ await act(() => result.current());
+
+ expect(save).toHaveBeenCalledTimes(1);
+ });
+
+ it("saves without committing when told not to", async () => {
+ registerUnsavedWorkChecker(() => true);
+ const save = vi.fn();
+ const { result } = renderHook(() =>
+ useCommitEditsBeforeSave(save, { commitEdits: false }),
+ );
+
+ await act(() => result.current());
+
+ expect(commit).not.toHaveBeenCalled();
+ expect(save).toHaveBeenCalledTimes(1);
+ });
+
+ it("commits the edits, then runs the latest save once", async () => {
+ registerUnsavedWorkChecker(() => true);
+ const first = vi.fn();
+ const latest = vi.fn();
+ let renderLatest = () => {};
+ commit.mockImplementation(async () => renderLatest());
+ const { result, rerender } = renderHook(
+ ({ save }) => useCommitEditsBeforeSave(save),
+ { initialProps: { save: first } },
+ );
+ renderLatest = () => rerender({ save: latest });
+
+ await act(() => result.current());
+
+ expect(commit).toHaveBeenCalledTimes(1);
+ expect(first).not.toHaveBeenCalled();
+ expect(latest).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not save when the commit fails", async () => {
+ registerUnsavedWorkChecker(() => true);
+ commit.mockRejectedValue(new Error("export failed"));
+ const save = vi.fn();
+ const { result } = renderHook(() => useCommitEditsBeforeSave(save));
+
+ await act(() => result.current());
+
+ expect(save).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/editor/core/hooks/useCommitEditsBeforeSave.ts b/frontend/src/editor/core/hooks/useCommitEditsBeforeSave.ts
new file mode 100644
index 0000000000..e228e43dd9
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useCommitEditsBeforeSave.ts
@@ -0,0 +1,46 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useNavigationActions } from "@editor/contexts/NavigationContext";
+import { hasUnsavedWork } from "@editor/services/unsavedWork";
+
+/**
+ * Wraps a save so the open editor's uncommitted edits (viewer annotations, page
+ * edits, form values) first become a version, and the saved file is the one the
+ * app holds. Commits through the navigation prompt's apply handler, and only when
+ * there are edits, because every commit adds a version. With `commitEdits` false
+ * it saves straight away. Runs the latest `save`, not the one from the render
+ * that started it.
+ */
+export function useCommitEditsBeforeSave(
+ save: () => Promise<void> | void,
+ { commitEdits = true }: { commitEdits?: boolean } = {},
+): () => Promise<void> {
+ const {
+ actions: { navigationWarningHandlersRef },
+ } = useNavigationActions();
+ const saveRef = useRef(save);
+ saveRef.current = save;
+ const [savesQueued, setSavesQueued] = useState(0);
+ const savesRun = useRef(0);
+
+ // The committed version reaches the file selectors on the next render, so the
+ // save runs from an effect rather than straight after the commit.
+ useEffect(() => {
+ if (savesQueued === savesRun.current) return;
+ savesRun.current = savesQueued;
+ void saveRef.current();
+ }, [savesQueued]);
+
+ return useCallback(async () => {
+ const commit = navigationWarningHandlersRef.current?.onApplyAndContinue;
+ if (!commitEdits || !commit || !hasUnsavedWork()) {
+ await saveRef.current();
+ return;
+ }
+ try {
+ await commit();
+ } catch {
+ return; // the editor has already told the user
+ }
+ setSavesQueued((count) => count + 1);
+ }, [commitEdits, navigationWarningHandlersRef]);
+}
diff --git a/frontend/src/editor/core/hooks/useFileActionIcons.ts b/frontend/src/editor/core/hooks/useFileActionIcons.ts
index ec00a91ed9..45e79989ee 100644
--- a/frontend/src/editor/core/hooks/useFileActionIcons.ts
+++ b/frontend/src/editor/core/hooks/useFileActionIcons.ts
@@ -1,17 +1,13 @@
import type { IconName } from "@editor/ui/Icon";
/** File action icons for web builds. Desktop overrides this file to swap in
- * Save/Save As instead of Download. */
+ * Save instead of Download. */
export function useFileActionIcons(): {
upload: IconName;
download: IconName;
- saveAs: IconName | undefined;
} {
return {
upload: "upload",
download: "download",
- // Web builds do not expose a Save As action - the button is hidden when
- // this is undefined. Desktop builds override this file.
- saveAs: undefined,
};
}
diff --git a/frontend/src/editor/core/hooks/useSaveStoredFile.test.ts b/frontend/src/editor/core/hooks/useSaveStoredFile.test.ts
new file mode 100644
index 0000000000..2dbd63ac86
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useSaveStoredFile.test.ts
@@ -0,0 +1,191 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import { useSaveStoredFile } from "@editor/hooks/useSaveStoredFile";
+import type { SaveTarget } from "@editor/services/saveTargets";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+import type { FileId } from "@editor/types/file";
+
+const mocks = vi.hoisted(() => ({
+ alert: vi.fn(),
+ download: vi.fn(),
+ updateStub: vi.fn(),
+ enforce: vi.fn(async (files: File[]) => files),
+ targets: [] as SaveTarget[],
+ getStirlingFile: vi.fn(async (): Promise<File | null> => null),
+}));
+
+vi.mock("@editor/components/toast", () => ({ alert: mocks.alert }));
+vi.mock("@editor/contexts/FileContext", () => ({
+ useFileActions: () => ({
+ actions: { updateStirlingFileStub: mocks.updateStub },
+ }),
+}));
+vi.mock("@editor/hooks/useSaveTargets", () => ({
+ useSaveTargets: () => mocks.targets,
+}));
+vi.mock("@editor/services/downloadService", () => ({
+ downloadFile: mocks.download,
+}));
+vi.mock("@editor/services/fileStorage", () => ({
+ fileStorage: { getStirlingFile: mocks.getStirlingFile },
+}));
+vi.mock("@editor/services/policyExport", () => ({
+ enforceExportPolicies: mocks.enforce,
+}));
+
+const pdf = () => new File(["%PDF"], "old-name.pdf");
+const stub = (extra: Partial<StirlingFileStub> = {}): StirlingFileStub =>
+ ({ id: "f1" as FileId, name: "Report.pdf", ...extra }) as StirlingFileStub;
+
+function target(save: SaveTarget["save"]): SaveTarget {
+ return {
+ id: "cloud",
+ handles: (s) => s.id === ("f1" as FileId),
+ isUnsaved: () => true,
+ saveLabel: () => "Update in cloud",
+ saveAllLabel: () => "Save all to cloud",
+ statusLabel: () => "Not in cloud",
+ icon: "cloud-upload",
+ save,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.targets = [];
+ mocks.download.mockResolvedValue({ savedPath: "C:/docs/Report.pdf" });
+});
+
+it("saves a disk file in place and marks it clean", async () => {
+ const { result } = renderHook(() => useSaveStoredFile());
+ const file = pdf();
+ const outcome = await result.current.saveStoredFile(
+ stub({ localFilePath: "C:/docs/Report.pdf", isDirty: true }),
+ file,
+ );
+ expect(outcome).toBe("saved");
+ expect(mocks.enforce).toHaveBeenCalledWith([file], ["f1"]);
+ expect(mocks.download).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filename: "Report.pdf",
+ localPath: "C:/docs/Report.pdf",
+ }),
+ );
+ expect(mocks.updateStub).toHaveBeenCalledWith("f1", {
+ localFilePath: "C:/docs/Report.pdf",
+ isDirty: false,
+ });
+});
+
+it("a local copy never changes the file's disk link", async () => {
+ const { result } = renderHook(() => useSaveStoredFile());
+ await result.current.saveLocalCopy(
+ stub({ localFilePath: "C:/docs/Report.pdf" }),
+ pdf(),
+ );
+ expect(mocks.download).toHaveBeenCalledWith(
+ expect.objectContaining({ localPath: undefined }),
+ );
+ expect(mocks.updateStub).not.toHaveBeenCalled();
+});
+
+it("sends a handled file to its target instead of downloading", async () => {
+ const save = vi.fn(async () => "saved" as const);
+ mocks.targets = [target(save)];
+ const { result } = renderHook(() => useSaveStoredFile());
+ expect(await result.current.saveStoredFile(stub(), pdf())).toBe("saved");
+ expect(save).toHaveBeenCalled();
+ expect(mocks.download).not.toHaveBeenCalled();
+});
+
+it("falls back to the built-in save when the target hands it back", async () => {
+ mocks.targets = [target(async () => "fallback")];
+ const { result } = renderHook(() => useSaveStoredFile());
+ expect(await result.current.saveStoredFile(stub(), pdf())).toBe("saved");
+ expect(mocks.download).toHaveBeenCalledWith(
+ expect.objectContaining({ localPath: undefined }),
+ );
+});
+
+it("reports a cancelled Save As", async () => {
+ mocks.download.mockResolvedValue({ cancelled: true });
+ const { result } = renderHook(() => useSaveStoredFile());
+ expect(await result.current.saveStoredFile(stub(), pdf())).toBe("cancelled");
+});
+
+it("reports a missing file instead of saving nothing", async () => {
+ const { result } = renderHook(() => useSaveStoredFile());
+ expect(await result.current.saveStoredFile(stub())).toBe("failed");
+ expect(mocks.alert).toHaveBeenCalledWith(
+ expect.objectContaining({ alertType: "error" }),
+ );
+});
+
+it("reports a storage error as a failed save", async () => {
+ mocks.getStirlingFile.mockRejectedValueOnce(new Error("IndexedDB closed"));
+ const { result } = renderHook(() => useSaveStoredFile());
+ expect(await result.current.saveStoredFile(stub())).toBe("failed");
+ expect(mocks.alert).toHaveBeenCalled();
+});
+
+it("counts unsaved disk edits and asks the target for its own files", () => {
+ const { result, rerender } = renderHook(() => useSaveStoredFile());
+ expect(
+ result.current.isUnsaved(stub({ isDirty: true, localFilePath: "C:/a" })),
+ ).toBe(true);
+ expect(result.current.isUnsaved(stub({ isDirty: true }))).toBe(false);
+ mocks.targets = [target(async () => "saved")];
+ rerender();
+ expect(result.current.isUnsaved(stub())).toBe(true);
+});
+
+it("does not run export policies again on a file that already had them", async () => {
+ const { result } = renderHook(() => useSaveStoredFile());
+ const file = pdf();
+ const outcome = await result.current.saveStoredFile(
+ stub({ localFilePath: "C:/docs/Report.pdf", isDirty: true }),
+ file,
+ { policiesEnforced: true },
+ );
+ expect(outcome).toBe("saved");
+ expect(mocks.enforce).not.toHaveBeenCalled();
+ expect(mocks.download).toHaveBeenCalledWith(
+ expect.objectContaining({ data: file }),
+ );
+});
+
+it("does nothing when the file's disk copy already holds this version", async () => {
+ const { result } = renderHook(() => useSaveStoredFile());
+ const outcome = await result.current.saveStoredFile(
+ stub({ localFilePath: "C:/docs/Report.pdf", isDirty: false }),
+ pdf(),
+ );
+ expect(outcome).toBe("saved");
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(mocks.updateStub).not.toHaveBeenCalled();
+});
+
+it("does nothing when the save target already holds this version", async () => {
+ const save = vi.fn(async () => "saved" as const);
+ mocks.targets = [{ ...target(save), isUnsaved: () => false }];
+ const { result } = renderHook(() => useSaveStoredFile());
+ expect(await result.current.saveStoredFile(stub(), pdf())).toBe("saved");
+ expect(save).not.toHaveBeenCalled();
+ expect(mocks.download).not.toHaveBeenCalled();
+});
+
+it("writes over a disk copy that changed under the file, even with nothing unsaved", async () => {
+ const { result } = renderHook(() => useSaveStoredFile());
+ const outcome = await result.current.saveStoredFile(
+ stub({
+ localFilePath: "C:/docs/Report.pdf",
+ isDirty: false,
+ diskConflictAt: 1_700_000_000_000,
+ }),
+ pdf(),
+ );
+ expect(outcome).toBe("saved");
+ expect(mocks.download).toHaveBeenCalledWith(
+ expect.objectContaining({ localPath: "C:/docs/Report.pdf" }),
+ );
+});
diff --git a/frontend/src/editor/core/hooks/useSaveStoredFile.ts b/frontend/src/editor/core/hooks/useSaveStoredFile.ts
new file mode 100644
index 0000000000..ec21938877
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useSaveStoredFile.ts
@@ -0,0 +1,139 @@
+import { useCallback, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { alert } from "@editor/components/toast";
+import { useFileActions } from "@editor/contexts/FileContext";
+import { useSaveTargets } from "@editor/hooks/useSaveTargets";
+import { downloadFile } from "@editor/services/downloadService";
+import { fileStorage } from "@editor/services/fileStorage";
+import { enforceExportPolicies } from "@editor/services/policyExport";
+import type { SaveOutcome, SaveTarget } from "@editor/services/saveTargets";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+
+export interface SaveOptions {
+ /** Export policies already ran on the file passed in, so they do not run again. */
+ policiesEnforced?: boolean;
+}
+
+export interface SaveStoredFile {
+ /** The target Save sends this file to, or undefined for disk and downloads. */
+ targetFor: (stub: StirlingFileStub) => SaveTarget | undefined;
+ /** Unsaved against where Save sends this file. */
+ isUnsaved: (stub: StirlingFileStub) => boolean;
+ /** Save where the toolbar's Save would; nothing to do when that home already
+ * holds this version. */
+ saveStoredFile: (
+ stub: StirlingFileStub,
+ file?: File,
+ options?: SaveOptions,
+ ) => Promise<SaveOutcome>;
+ /** A one-off copy (a download or a Save As) that keeps the file's home. */
+ saveLocalCopy: (
+ stub: StirlingFileStub,
+ file?: File,
+ options?: SaveOptions,
+ ) => Promise<SaveOutcome>;
+}
+
+/** The toolbar's Save for one stored file, for every place that saves. */
+export function useSaveStoredFile(): SaveStoredFile {
+ const { t } = useTranslation();
+ const { actions } = useFileActions();
+ const targets = useSaveTargets();
+
+ const targetFor = useCallback(
+ (stub: StirlingFileStub) => targets.find((target) => target.handles(stub)),
+ [targets],
+ );
+
+ const isUnsaved = useCallback(
+ (stub: StirlingFileStub) => {
+ const target = targetFor(stub);
+ return target
+ ? target.isUnsaved(stub)
+ : Boolean(stub.isDirty && stub.localFilePath);
+ },
+ [targetFor],
+ );
+
+ const write = useCallback(
+ async (
+ stub: StirlingFileStub,
+ file: File | undefined,
+ local: "save" | "copy",
+ { policiesEnforced = false }: SaveOptions = {},
+ ): Promise<SaveOutcome> => {
+ const fail = (body: string): SaveOutcome => {
+ alert({
+ alertType: "error",
+ title: t("fileEditor.saveFailed", "Save failed"),
+ body,
+ privateBody: true,
+ expandable: false,
+ });
+ return "failed";
+ };
+ // Its home already holds this version, and a rewrite would only wake the
+ // disk watcher. A file flagged as changed on disk is not current: saving
+ // is how the user keeps their version over the disk one.
+ const homeCurrent =
+ local === "save" &&
+ Boolean(targetFor(stub) || stub.localFilePath) &&
+ !isUnsaved(stub) &&
+ !stub.diskConflictAt;
+ if (homeCurrent) return "saved";
+ try {
+ const source = file ?? (await fileStorage.getStirlingFile(stub.id));
+ if (!source)
+ return fail(
+ t(
+ "fileSidebar.dataLostBody",
+ "Couldn't find this file's contents. Add it again to keep working with it.",
+ ),
+ );
+ const [enforced] = policiesEnforced
+ ? [source]
+ : await enforceExportPolicies([source], [stub.id]);
+ const data = enforced ?? source;
+ const target = local === "save" ? targetFor(stub) : undefined;
+ if (target) {
+ const outcome = await target.save(stub, data);
+ if (outcome !== "fallback") return outcome;
+ }
+ const linksToDisk = local === "save" && !target;
+ const result = await downloadFile({
+ data,
+ // Stub name, not File.name: a rename only writes the stub.
+ filename: stub.name,
+ localPath: linksToDisk ? stub.localFilePath : undefined,
+ fileId: stub.id,
+ });
+ if (result.cancelled) return "cancelled";
+ if (linksToDisk && result.savedPath)
+ actions.updateStirlingFileStub(stub.id, {
+ localFilePath: stub.localFilePath ?? result.savedPath,
+ isDirty: false,
+ });
+ return "saved";
+ } catch (error) {
+ return fail(error instanceof Error ? error.message : String(error));
+ }
+ },
+ [actions, targetFor, isUnsaved, t],
+ );
+
+ const saveStoredFile = useCallback(
+ (stub: StirlingFileStub, file?: File, options?: SaveOptions) =>
+ write(stub, file, "save", options),
+ [write],
+ );
+ const saveLocalCopy = useCallback(
+ (stub: StirlingFileStub, file?: File, options?: SaveOptions) =>
+ write(stub, file, "copy", options),
+ [write],
+ );
+
+ return useMemo(
+ () => ({ targetFor, isUnsaved, saveStoredFile, saveLocalCopy }),
+ [targetFor, isUnsaved, saveStoredFile, saveLocalCopy],
+ );
+}
diff --git a/frontend/src/editor/core/hooks/useSaveTargets.ts b/frontend/src/editor/core/hooks/useSaveTargets.ts
new file mode 100644
index 0000000000..5e7ee1b86a
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useSaveTargets.ts
@@ -0,0 +1,8 @@
+import type { SaveTarget } from "@editor/services/saveTargets";
+
+const NONE: SaveTarget[] = [];
+
+/** Places Save can write back to besides disk and downloads. */
+export function useSaveTargets(): SaveTarget[] {
+ return NONE;
+}
diff --git a/frontend/src/editor/core/hooks/useWorkbenchSave.ts b/frontend/src/editor/core/hooks/useWorkbenchSave.ts
new file mode 100644
index 0000000000..8368d449a8
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useWorkbenchSave.ts
@@ -0,0 +1,221 @@
+import { useCallback, useContext } from "react";
+import { useTranslation } from "react-i18next";
+import { alert as showAlert } from "@editor/components/toast";
+import {
+ useAllFiles,
+ useFileSelection,
+ useFileSelectors,
+} from "@editor/contexts/FileContext";
+import { useNavigationState } from "@editor/contexts/NavigationContext";
+import { ViewerContext, useViewer } from "@editor/contexts/ViewerContext";
+import { useWorkbenchBar } from "@editor/contexts/WorkbenchBarContext";
+import { useCommitEditsBeforeSave } from "@editor/hooks/useCommitEditsBeforeSave";
+import {
+ useSaveStoredFile,
+ type SaveStoredFile,
+} from "@editor/hooks/useSaveStoredFile";
+import {
+ downloadFile as downloadRaw,
+ SAVES_TO_DISK,
+} from "@editor/services/downloadService";
+import { downloadFileWithPolicy } from "@editor/services/exportWithPolicy";
+import { enforceExportPolicies } from "@editor/services/policyExport";
+import {
+ isStirlingFile,
+ type StirlingFileStub,
+} from "@editor/types/fileContext";
+import type { FileId } from "@editor/types/file";
+
+async function enforcedViewerFile(
+ buffer: ArrayBuffer,
+ stub: StirlingFileStub,
+): Promise<File> {
+ const file = new File([buffer], stub.name, { type: "application/pdf" });
+ const [enforced] = await enforceExportPolicies([file], [stub.id]);
+ return enforced ?? file;
+}
+
+export interface WorkbenchSave {
+ /** What Save acts on: the viewer's open file, every page editor track, else
+ * the selection, or every file when nothing is selected. */
+ targetIds: string[];
+ targetStubs: StirlingFileStub[];
+ saver: SaveStoredFile;
+ /** Commits the open editor's edits when the save goes home, then saves each
+ * target there. */
+ save: () => Promise<void>;
+ /** A copy of each target that leaves its home alone. */
+ saveCopy: () => Promise<void>;
+ /** The file as the viewer shows it, unapplied annotations included, with
+ * export policies run on it. Undefined outside the viewer. */
+ viewerFileFor: (stub: StirlingFileStub) => Promise<File | undefined>;
+}
+
+/** The workbench's Save, shared by the toolbar and the keyboard shortcut so
+ * both act on the same files the same way. */
+export function useWorkbenchSave(): WorkbenchSave {
+ const { t } = useTranslation();
+ const { workbench: currentView } = useNavigationState();
+ const viewerContext = useContext(ViewerContext);
+ const { activeFileId } = useViewer();
+ const { viewFileActions } = useWorkbenchBar();
+ const selectors = useFileSelectors();
+ const { selectedFiles, selectedFileIds } = useFileSelection();
+ const { files: activeFiles } = useAllFiles();
+ const saver = useSaveStoredFile();
+
+ const allFileIds = activeFiles.filter(isStirlingFile).map((f) => f.fileId);
+ let targetIds: string[];
+ if (currentView === "viewer") targetIds = activeFileId ? [activeFileId] : [];
+ else if (currentView === "pageEditor" || selectedFileIds.length === 0)
+ targetIds = allFileIds;
+ else targetIds = selectedFileIds;
+ const targetStubs = selectors.getStirlingFileStubs(targetIds as FileId[]);
+ // A save to disk links the file to wherever it lands, so every one goes home.
+ const savesHome =
+ SAVES_TO_DISK ||
+ targetStubs.some((stub) => saver.targetFor(stub) || stub.localFilePath);
+
+ const handleExportAll = useCallback(
+ async (forceNewFile = false) => {
+ if (currentView === "viewer") {
+ const fileToExport =
+ activeFiles.find(
+ (file) => isStirlingFile(file) && file.fileId === activeFileId,
+ ) ?? activeFiles[0];
+ if (!fileToExport) return;
+ const stub = isStirlingFile(fileToExport)
+ ? selectors.getStirlingFileStub(fileToExport.fileId)
+ : undefined;
+ // A save home has already committed the viewer's edits as a version, so
+ // the stored file is what the viewer shows and needs no second export.
+ if (stub && savesHome && !forceNewFile) {
+ await saver.saveStoredFile(stub, selectors.getFile(stub.id));
+ return;
+ }
+ const buffer = await viewerContext?.exportActions?.saveAsCopy?.();
+ if (!buffer) return;
+ if (stub) {
+ const file = new File([buffer], stub.name, {
+ type: "application/pdf",
+ });
+ const save = forceNewFile
+ ? saver.saveLocalCopy
+ : saver.saveStoredFile;
+ await save(stub, file);
+ return;
+ }
+ try {
+ await downloadFileWithPolicy({
+ data: new Blob([buffer], { type: "application/pdf" }),
+ filename: fileToExport.name,
+ });
+ } catch (error) {
+ console.error("[WorkbenchSave] Failed to export viewer file:", error);
+ }
+ return;
+ }
+
+ const viewExport = await viewFileActions?.getExportFiles?.({
+ commitEdits: !forceNewFile && savesHome,
+ });
+ if (viewExport === null) return;
+ let filesToExport: File[];
+ let stubs: (StirlingFileStub | undefined)[];
+ if (viewExport) {
+ filesToExport = viewExport.map((entry) => entry.file);
+ stubs = viewExport.map((entry) => {
+ if (entry.stub) return entry.stub;
+ return entry.fileId
+ ? selectors.getStirlingFileStub(entry.fileId)
+ : undefined;
+ });
+ } else {
+ filesToExport = selectedFiles.length > 0 ? selectedFiles : activeFiles;
+ stubs = filesToExport.map((file) =>
+ isStirlingFile(file)
+ ? selectors.getStirlingFileStub(file.fileId)
+ : undefined,
+ );
+ }
+
+ // Enforce all files in one batch so the toast shows progress across the
+ // whole set (e.g. "report.pdf (2 of 5)") rather than N invisible solo runs.
+ let enforced: File[];
+ try {
+ enforced = await enforceExportPolicies(
+ filesToExport,
+ stubs.map((s) => s?.id),
+ );
+ } catch (error) {
+ // A required policy failed. Saving without it would skip what it exists
+ // to enforce, so the save stops, as a single-file save does.
+ showAlert({
+ alertType: "error",
+ title: t("fileEditor.saveFailed", "Save failed"),
+ body: error instanceof Error ? error.message : String(error),
+ privateBody: true,
+ expandable: false,
+ });
+ return;
+ }
+
+ for (let idx = 0; idx < filesToExport.length; idx++) {
+ const file = filesToExport[idx];
+ const stub = stubs[idx];
+ if (stub) {
+ const save = forceNewFile
+ ? saver.saveLocalCopy
+ : saver.saveStoredFile;
+ const outcome = await save(stub, enforced[idx], {
+ policiesEnforced: true,
+ });
+ if (outcome === "cancelled") break;
+ continue;
+ }
+ try {
+ const result = await downloadRaw({
+ data: enforced[idx],
+ filename: file.name,
+ });
+ if (result.cancelled) break;
+ } catch (error) {
+ console.error(
+ "[WorkbenchSave] Failed to export file:",
+ file.name,
+ error,
+ );
+ }
+ }
+ },
+ [
+ currentView,
+ selectedFiles,
+ activeFiles,
+ activeFileId,
+ viewerContext,
+ viewFileActions,
+ selectors,
+ saver,
+ savesHome,
+ t,
+ ],
+ );
+
+ const viewerFileFor = useCallback(
+ async (stub: StirlingFileStub): Promise<File | undefined> => {
+ if (currentView !== "viewer") return undefined;
+ const buffer = await viewerContext?.exportActions?.saveAsCopy?.();
+ return buffer ? enforcedViewerFile(buffer, stub) : undefined;
+ },
+ [currentView, viewerContext],
+ );
+
+ // A view with its own export commits its edits inside it.
+ const save = useCommitEditsBeforeSave(() => handleExportAll(), {
+ commitEdits: savesHome && !viewFileActions?.getExportFiles,
+ });
+ const saveCopy = useCallback(() => handleExportAll(true), [handleExportAll]);
+
+ return { targetIds, targetStubs, saver, save, saveCopy, viewerFileFor };
+}
diff --git a/frontend/src/editor/core/services/downloadService.ts b/frontend/src/editor/core/services/downloadService.ts
index 40d6345e80..9fe36523d6 100644
--- a/frontend/src/editor/core/services/downloadService.ts
+++ b/frontend/src/editor/core/services/downloadService.ts
@@ -8,6 +8,10 @@ export interface DownloadRequest {
fileId?: string;
}
+/** Whether {@link downloadFile} writes to a path the app learns (`savedPath`), so
+ * a saved file can stay linked to it. False where a download leaves the app. */
+export const SAVES_TO_DISK = false;
+
export interface DownloadResult {
savedPath?: string;
cancelled?: boolean;
diff --git a/frontend/src/editor/core/services/saveTargets.ts b/frontend/src/editor/core/services/saveTargets.ts
new file mode 100644
index 0000000000..420b740c2b
--- /dev/null
+++ b/frontend/src/editor/core/services/saveTargets.ts
@@ -0,0 +1,60 @@
+import type { IconName } from "@editor/ui/Icon";
+import type { FileId } from "@editor/types/file";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+
+export type SaveOutcome = "saved" | "cancelled" | "failed";
+
+export interface SaveMenuItem {
+ key: string;
+ label: string;
+ description?: string;
+ icon: IconName;
+ onClick: () => void;
+}
+
+/**
+ * A place Save can write a file back to, such as a cloud drive. Files no target
+ * handles save the built-in way: to their disk path if they have one, else a
+ * download.
+ */
+export interface SaveTarget {
+ id: string;
+ handles: (stub: StirlingFileStub) => boolean;
+ /** True when this version is not saved to the target yet. */
+ isUnsaved: (stub: StirlingFileStub) => boolean;
+ /** What Save does for this file, e.g. "Update Report.pdf in OneDrive". */
+ saveLabel: (stub: StirlingFileStub) => string;
+ /** Label for several files, e.g. "Save all to OneDrive". */
+ saveAllLabel: () => string;
+ statusLabel: (unsaved: boolean) => string;
+ icon: IconName;
+ /** "fallback" hands the file back to the built-in save, e.g. a download. */
+ save: (
+ stub: StirlingFileStub,
+ file: File,
+ ) => Promise<SaveOutcome | "fallback">;
+ /** Other destinations this target offers for one file. */
+ menuItems?: (
+ stub: StirlingFileStub,
+ file: () => Promise<File | undefined>,
+ ) => SaveMenuItem[];
+ /** The file being saved right now, if any. */
+ saving?: FileId | null;
+}
+
+export function sharedSaveTarget(
+ stubs: StirlingFileStub[],
+ targetFor: (stub: StirlingFileStub) => SaveTarget | undefined,
+): SaveTarget | undefined {
+ const first = stubs.length > 0 ? targetFor(stubs[0]) : undefined;
+ return first && stubs.every((stub) => targetFor(stub) === first)
+ ? first
+ : undefined;
+}
+
+export function saveTargetLabel(
+ target: SaveTarget,
+ stubs: StirlingFileStub[],
+): string {
+ return stubs.length > 1 ? target.saveAllLabel() : target.saveLabel(stubs[0]);
+}
diff --git a/frontend/src/editor/core/tests/stubbed/disk-link-imports.spec.ts b/frontend/src/editor/core/tests/stubbed/disk-link-imports.spec.ts
index 71ca7f8db0..5adb29b100 100644
--- a/frontend/src/editor/core/tests/stubbed/disk-link-imports.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/disk-link-imports.spec.ts
@@ -61,6 +61,37 @@ async function expectLinked(page: Page) {
]);
}
+// Save leaves a file alone when its disk copy is already current, so a save
+// in place needs an unsaved change to write.
+async function markStoredFileUnsaved(page: Page) {
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve, reject) => {
+ const request = indexedDB.open("stirling-pdf-files");
+ request.onsuccess = () => {
+ const db = request.result;
+ const store = db
+ .transaction("files", "readwrite")
+ .objectStore("files");
+ const read = store.getAll();
+ read.onsuccess = () => {
+ for (const record of read.result)
+ store.put({ ...record, isDirty: true });
+ store.transaction.oncomplete = () => {
+ db.close();
+ resolve();
+ };
+ };
+ read.onerror = () => {
+ db.close();
+ reject(read.error);
+ };
+ };
+ request.onerror = () => reject(request.error);
+ }),
+ );
+}
+
test.beforeEach(async ({ page }) => {
await installTauri(page);
await page.goto("/editor");
@@ -77,6 +108,7 @@ test("the sidebar native picker keeps its path after reload and saves in place",
await page.getByTestId("files-button").click();
await expectLinked(page);
await expect(page.locator(".file-sidebar-file-item")).toHaveCount(1);
+ await markStoredFileUnsaved(page);
await page.reload();
await dismissModals(page);
await expectLinked(page);
diff --git a/frontend/src/editor/core/tests/stubbed/disk-link-save.spec.ts b/frontend/src/editor/core/tests/stubbed/disk-link-save.spec.ts
new file mode 100644
index 0000000000..653a797cad
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/disk-link-save.spec.ts
@@ -0,0 +1,182 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import {
+ installTauri,
+ gotoFiles,
+ openCard,
+ stage,
+ dismissModals,
+} from "@editor/tests/helpers/tauriDiskStub";
+import fs from "node:fs";
+import path from "node:path";
+
+// Save in the desktop build: the toolbar marks unsaved disk edits, Save As lives
+// in "More save options", and Ctrl+S writes the file back in place.
+test.use({ filesViewMode: "grid" });
+
+const FIXTURES = path.resolve("src/editor/core/tests/test-fixtures");
+const PDF = Array.from(
+ fs.readFileSync(path.join(FIXTURES, "annotation-text-sample.pdf")),
+);
+const REPORT = "C:/Docs/quarterly-report.pdf";
+const MTIME = 1_700_000_000_000;
+
+async function requireDiskLinking(page: Page) {
+ const invoked = await page.evaluate(
+ () => (window as unknown as { __invoked?: string[] }).__invoked ?? [],
+ );
+ test.skip(
+ !invoked.includes("file_disk_state"),
+ "needs the desktop build (vite --mode desktop)",
+ );
+}
+
+const written = (page: Page) =>
+ page.evaluate(
+ () =>
+ (window as unknown as { __writtenPaths?: string[] }).__writtenPaths ?? [],
+ );
+
+const savedLeaves = (page: Page) =>
+ page.evaluate(async (reportPath) => {
+ const db = await new Promise<IDBDatabase>((resolve, reject) => {
+ const req = indexedDB.open("stirling-pdf-files");
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ });
+ const records = await new Promise<
+ { isLeaf?: boolean; isDirty?: boolean; size: number }[]
+ >((resolve, reject) => {
+ const req = db.transaction(["files"]).objectStore("files").getAll();
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ });
+ db.close();
+ const onDisk = (
+ window as unknown as {
+ __disk: Record<string, { bytes: number[] } | undefined>;
+ }
+ ).__disk[reportPath]?.bytes.length;
+ return records
+ .filter((record) => record.isLeaf !== false)
+ .map((record) => ({
+ dirty: Boolean(record.isDirty),
+ matchesDisk: record.size === onDisk,
+ }));
+ }, REPORT);
+
+async function openReport(page: Page, { isDirty }: { isDirty: boolean }) {
+ await installTauri(page);
+ await gotoFiles(page);
+ await stage(page, { [REPORT]: { bytes: PDF, modifiedMs: MTIME } }, [
+ {
+ id: "f-report",
+ name: "quarterly-report.pdf",
+ path: REPORT,
+ bytes: PDF,
+ isDirty,
+ },
+ ]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await openCard(page, "quarterly-report.pdf");
+}
+
+test.describe("Saving files that live on disk", () => {
+ test("the toolbar marks unsaved disk edits and Ctrl+S saves in place", async ({
+ page,
+ }) => {
+ await openReport(page, { isDirty: true });
+
+ const save = page.getByRole("button", { name: "Save", exact: true });
+ await expect(save).toBeVisible({ timeout: 20_000 });
+ await expect(save.locator(".workbench-bar-unsaved-dot")).toBeVisible();
+
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ await firstPage.hover();
+ await page.keyboard.press("Control+s");
+ await expect.poll(() => written(page)).toContain(REPORT);
+ await expect
+ .poll(() => savedLeaves(page))
+ .toEqual([{ dirty: false, matchesDisk: true }]);
+ await expect(save.locator(".workbench-bar-unsaved-dot")).toHaveCount(0);
+ });
+
+ test("the viewer's Save writes the stored version in place", async ({
+ page,
+ }) => {
+ await openReport(page, { isDirty: true });
+
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ const save = page.getByRole("button", { name: "Save", exact: true });
+ await save.click();
+ await expect.poll(() => written(page)).toContain(REPORT);
+ await expect
+ .poll(() => savedLeaves(page))
+ .toEqual([{ dirty: false, matchesDisk: true }]);
+ });
+
+ test("Ctrl+S with nothing unsaved leaves the file alone", async ({
+ page,
+ }) => {
+ const applies: string[] = [];
+ page.on("console", (message) => {
+ if (message.text().includes("[Viewer] Applying changes"))
+ applies.push(message.text());
+ });
+ await openReport(page, { isDirty: false });
+
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ await firstPage.hover();
+ await page.keyboard.press("Control+s");
+ await page.evaluate(
+ () =>
+ new Promise((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve)),
+ ),
+ );
+
+ expect(applies).toEqual([]);
+ expect(await written(page)).toEqual([]);
+ expect(await savedLeaves(page)).toEqual([
+ { dirty: false, matchesDisk: true },
+ ]);
+ });
+
+ test("Save As moves into More save options", async ({ page }) => {
+ await openReport(page, { isDirty: true });
+
+ await expect(page.getByRole("button", { name: "Save As" })).toHaveCount(0);
+ await page.getByRole("button", { name: "More save options" }).click();
+ await expect(
+ page.getByRole("menuitem", { name: "Save a copy...", exact: true }),
+ ).toBeVisible();
+ });
+
+ test("a narrow window marks unsaved disk edits in More actions", async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 740, height: 900 });
+ await openReport(page, { isDirty: true });
+
+ const more = page.getByRole("button", { name: "More actions" });
+ await expect(more.locator(".workbench-bar-unsaved-dot")).toBeVisible({
+ timeout: 20_000,
+ });
+ const dot = (await more
+ .locator(".workbench-bar-unsaved-dot")
+ .boundingBox())!;
+ const glyph = (await more.locator("svg").boundingBox())!;
+ expect(dot.x).toBeLessThan(glyph.x + glyph.width);
+ expect(dot.y + dot.height).toBeGreaterThan(glyph.y);
+ await more.click();
+ await expect(
+ page
+ .getByRole("menuitem", { name: "Save", exact: true })
+ .locator(".workbench-bar-menu-unsaved-dot"),
+ ).toBeVisible();
+ });
+});
diff --git a/frontend/src/editor/core/types/workbenchBar.ts b/frontend/src/editor/core/types/workbenchBar.ts
index 179d558f47..337200ab79 100644
--- a/frontend/src/editor/core/types/workbenchBar.ts
+++ b/frontend/src/editor/core/types/workbenchBar.ts
@@ -1,5 +1,6 @@
import React from "react";
import type { FileId } from "@editor/types/file";
+import type { StirlingFileStub } from "@editor/types/fileContext";
/** "bar-lead" follows the view switcher, for content naming what the view is showing;
* "bar" renders among the bar's own actions on the right; top/middle/bottom are lanes
@@ -57,6 +58,15 @@ export interface WorkbenchExportFile {
* to its disk location and lets export policies version it. Omit for bytes
* the workbench does not hold, such as unsaved edits. */
fileId?: FileId;
+ /** Set for a version the export just committed: it is not in the file
+ * selectors until the next render. */
+ stub?: StirlingFileStub;
+}
+
+export interface WorkbenchExportOptions {
+ /** Commit unsaved edits as new versions first, so the exported files are ones
+ * the workbench holds. Cancelling or failing that commit cancels the export. */
+ commitEdits?: boolean;
}
/**
@@ -68,6 +78,8 @@ export interface WorkbenchViewFileActions {
* The files to download in place of the open ones, or null to cancel. The bar
* cancels silently, so a view returning null has already told the user why.
*/
- getExportFiles?: () => Promise<WorkbenchExportFile[] | null>;
+ getExportFiles?: (
+ options?: WorkbenchExportOptions,
+ ) => Promise<WorkbenchExportFile[] | null>;
onClose?: () => void;
}
diff --git a/frontend/src/editor/desktop/components/SaveShortcutListener.tsx b/frontend/src/editor/desktop/components/SaveShortcutListener.tsx
index fbf6ad48e5..d3e44db41f 100644
--- a/frontend/src/editor/desktop/components/SaveShortcutListener.tsx
+++ b/frontend/src/editor/desktop/components/SaveShortcutListener.tsx
@@ -6,7 +6,7 @@ import { useDiskWatcher } from "@editor/hooks/useDiskWatcher";
/**
* Desktop-only component that sets up keyboard shortcuts and exit warnings
- * - Ctrl/Cmd+S to save selected files
+ * - Ctrl/Cmd+S to run the toolbar's Save
* - Ctrl/Cmd+N to open an empty new window
* - Loads files queued for this window ("Open in new window" from My Files)
* - Warning on app exit if unsaved files
diff --git a/frontend/src/editor/desktop/components/fileEditor/FileEditorStatusDot.tsx b/frontend/src/editor/desktop/components/fileEditor/FileEditorStatusDot.tsx
index 69b097bebf..5e4b4abc95 100644
--- a/frontend/src/editor/desktop/components/fileEditor/FileEditorStatusDot.tsx
+++ b/frontend/src/editor/desktop/components/fileEditor/FileEditorStatusDot.tsx
@@ -3,13 +3,23 @@ import { useTranslation } from "react-i18next";
import { StirlingFileStub } from "@editor/types/fileContext";
import { diskLinkState } from "@editor/services/diskLinkState";
import styles from "@editor/components/fileEditor/FileEditorThumbnail.module.css";
+import {
+ TargetStatusDot,
+ type TargetStatus,
+} from "@editor/components/fileEditor/TargetStatusDot";
interface FileEditorStatusDotProps {
file: StirlingFileStub;
+ /** Set when Save sends this file to a save target. */
+ target?: TargetStatus;
}
-export function FileEditorStatusDot({ file }: FileEditorStatusDotProps) {
+export function FileEditorStatusDot({
+ file,
+ target,
+}: FileEditorStatusDotProps) {
const { t } = useTranslation();
+ if (target) return <TargetStatusDot {...target} />;
// Orphaned needs its own case: sharing "not saved to disk" would make a
// deleted original indistinguishable from a file never saved.
diff --git a/frontend/src/editor/desktop/hooks/useExitWarning.test.ts b/frontend/src/editor/desktop/hooks/useExitWarning.test.ts
new file mode 100644
index 0000000000..df5f2225e2
--- /dev/null
+++ b/frontend/src/editor/desktop/hooks/useExitWarning.test.ts
@@ -0,0 +1,27 @@
+import { expect, it } from "vitest";
+import { filesToSaveOnQuit } from "@editor/hooks/useExitWarning";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+import type { FileId } from "@editor/types/file";
+
+const stub = (id: string, extra: Partial<StirlingFileStub> = {}) =>
+ ({ id: id as FileId, name: `${id}.pdf`, ...extra }) as StirlingFileStub;
+const diskUnsaved = (s: StirlingFileStub) =>
+ Boolean(s.isDirty && s.localFilePath);
+
+it("offers edits whose disk original was deleted", () => {
+ const orphan = stub("orphan", {
+ isDirty: true,
+ orphanedFilePath: "C:/docs/gone.pdf",
+ });
+ expect(filesToSaveOnQuit([orphan], diskUnsaved)).toEqual([orphan]);
+});
+
+it("offers files a save target has not received yet", () => {
+ const cloud = stub("cloud");
+ expect(filesToSaveOnQuit([cloud], (s) => s.id === cloud.id)).toEqual([cloud]);
+});
+
+it("skips files with nothing unsaved", () => {
+ const clean = stub("clean", { localFilePath: "C:/docs/clean.pdf" });
+ expect(filesToSaveOnQuit([clean], diskUnsaved)).toEqual([]);
+});
diff --git a/frontend/src/editor/desktop/hooks/useExitWarning.ts b/frontend/src/editor/desktop/hooks/useExitWarning.ts
index 5a25036798..474b1d9c47 100644
--- a/frontend/src/editor/desktop/hooks/useExitWarning.ts
+++ b/frontend/src/editor/desktop/hooks/useExitWarning.ts
@@ -1,19 +1,33 @@
import { useEffect, useRef } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { message } from "@tauri-apps/plugin-dialog";
-import { useFileSelectors, useFileActions } from "@editor/contexts/FileContext";
-import { downloadFile } from "@editor/services/downloadService";
+import { useFileSelectors } from "@editor/contexts/FileContext";
+import { useSaveStoredFile } from "@editor/hooks/useSaveStoredFile";
import type { StirlingFileStub } from "@editor/types/fileContext";
import { useTranslation } from "react-i18next";
+/**
+ * Files to offer saving before the window closes. A file whose disk original
+ * was deleted has lost its link, so it no longer counts as unsaved against a
+ * home, but its edits exist nowhere else.
+ */
+export function filesToSaveOnQuit(
+ stubs: StirlingFileStub[],
+ isUnsaved: (stub: StirlingFileStub) => boolean,
+): StirlingFileStub[] {
+ return stubs.filter((stub) => stub.isDirty || isUnsaved(stub));
+}
+
export function useExitWarning() {
const { t } = useTranslation();
const selectors = useFileSelectors();
- const { actions: fileActions } = useFileActions();
+ const saver = useSaveStoredFile();
const selectorsRef = useRef(selectors);
+ const saverRef = useRef(saver);
const isClosingRef = useRef(false);
selectorsRef.current = selectors;
+ saverRef.current = saver;
useEffect(() => {
const appWindow = getCurrentWindow();
@@ -25,8 +39,10 @@ export function useExitWarning() {
return;
}
- const allStubs = selectorsRef.current.getStirlingFileStubs();
- const dirtyStubs = allStubs.filter((stub) => stub.isDirty);
+ const dirtyStubs = filesToSaveOnQuit(
+ selectorsRef.current.getStirlingFileStubs(),
+ saverRef.current.isUnsaved,
+ );
// Nothing unsaved: don't preventDefault, so the window closes natively
// without depending on the JS dialog/destroy round-trip below.
@@ -111,47 +127,20 @@ export function useExitWarning() {
fn();
});
};
- }, [fileActions, t]);
+ }, [t]);
const saveDirtyFiles = async (dirtyStubs: StirlingFileStub[]) => {
- const filesById = new Map(
- selectorsRef.current.getFiles().map((file) => [file.fileId, file]),
- );
let failedCount = 0;
let cancelled = false;
-
for (const stub of dirtyStubs) {
- const file = filesById.get(stub.id);
- if (!file || !stub.localFilePath) {
- if (!file) {
- failedCount += 1;
- continue;
- }
- }
-
- try {
- const result = await downloadFile({
- data: file,
- filename: file.name,
- localPath: stub.localFilePath,
- });
-
- if (result.cancelled) {
- cancelled = true;
- break;
- }
-
- if (result.savedPath) {
- fileActions.updateStirlingFileStub(stub.id, {
- localFilePath: stub.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- }
- } catch {
- failedCount += 1;
+ const file = selectorsRef.current.getFile(stub.id);
+ const outcome = await saverRef.current.saveStoredFile(stub, file);
+ if (outcome === "cancelled") {
+ cancelled = true;
+ break;
}
+ if (outcome === "failed") failedCount += 1;
}
-
return { failedCount, cancelled };
};
}
diff --git a/frontend/src/editor/desktop/hooks/useFileActionIcons.ts b/frontend/src/editor/desktop/hooks/useFileActionIcons.ts
index 81771dacc5..07af1ce9b8 100644
--- a/frontend/src/editor/desktop/hooks/useFileActionIcons.ts
+++ b/frontend/src/editor/desktop/hooks/useFileActionIcons.ts
@@ -3,18 +3,14 @@ import type { IconName } from "@editor/ui/Icon";
/**
* File action icons for desktop builds.
* Opens a local folder rather than uploading, and saves rather than
- * downloading. A defined \`saveAs\` makes WorkbenchBar show the Save As button.
+ * downloading.
*/
export function useFileActionIcons(): {
upload: IconName;
download: IconName;
- saveAs: IconName | undefined;
} {
return {
upload: "folder-open",
download: "save",
- // Returning this causes WorkbenchBar to render the Save As button. On
- // desktop, downloadFile() without a localPath shows a native save dialog.
- saveAs: "save-all",
};
}
diff --git a/frontend/src/editor/desktop/hooks/useSaveShortcut.ts b/frontend/src/editor/desktop/hooks/useSaveShortcut.ts
index b8fb0b7885..6c4ea7eb21 100644
--- a/frontend/src/editor/desktop/hooks/useSaveShortcut.ts
+++ b/frontend/src/editor/desktop/hooks/useSaveShortcut.ts
@@ -1,72 +1,18 @@
import { useEffect } from "react";
-import {
- useFileSelector,
- useFileSelectors,
- useFileActions,
-} from "@editor/contexts/FileContext";
-// Save through the export gateway so a "run on export" policy enforces before
-// the file is written out (no-op when no such policy is active).
-import { downloadFileWithPolicy as downloadFile } from "@editor/services/exportWithPolicy";
+import { useWorkbenchSave } from "@editor/hooks/useWorkbenchSave";
-/**
- * Desktop-only keyboard shortcut: Ctrl/Cmd+S to save selected files
- * Only saves files that have a localFilePath (came from disk)
- * Matches WorkbenchBar button behavior: saves selected files if any, otherwise all files
- */
+/** Desktop-only keyboard shortcut: Ctrl/Cmd+S runs the toolbar's Save. */
export function useSaveShortcut() {
- const selectors = useFileSelectors();
- const currentSelectedFileIds = useFileSelector((s) => s.ui.selectedFileIds);
- const { actions: fileActions } = useFileActions();
+ const { save } = useWorkbenchSave();
useEffect(() => {
- const handleKeyDown = async (event: KeyboardEvent) => {
- // Check for Ctrl+S (Windows/Linux) or Cmd+S (Mac)
- if ((event.ctrlKey || event.metaKey) && event.key === "s") {
- event.preventDefault();
-
- // Get selected files or all files if nothing selected
- const selectedFileIds = currentSelectedFileIds;
- const filesToSave =
- selectedFileIds.length > 0
- ? selectors.getFiles(selectedFileIds)
- : selectors.getFiles();
- const stubsToSave =
- selectedFileIds.length > 0
- ? selectors.getStirlingFileStubs(selectedFileIds)
- : selectors.getStirlingFileStubs();
-
- if (filesToSave.length === 0) {
- return;
- }
-
- // Save files (Save As for files without localFilePath)
- for (let i = 0; i < filesToSave.length; i++) {
- const file = filesToSave[i];
- const stub = stubsToSave[i];
- if (!stub) continue;
-
- try {
- const result = await downloadFile({
- data: file,
- filename: file.name,
- localPath: stub.localFilePath,
- });
-
- // Mark file as clean after successful save
- if (result.savedPath) {
- fileActions.updateStirlingFileStub(stub.id, {
- localFilePath: stub.localFilePath ?? result.savedPath,
- isDirty: false,
- });
- }
- } catch (error) {
- console.error(`Failed to save ${file.name}:`, error);
- }
- }
- }
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (!(event.ctrlKey || event.metaKey) || event.key !== "s") return;
+ event.preventDefault();
+ void save();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
- }, [selectors, currentSelectedFileIds, fileActions]);
+ }, [save]);
}
diff --git a/frontend/src/editor/desktop/services/downloadService.ts b/frontend/src/editor/desktop/services/downloadService.ts
index 58db68ea40..af5c66cb0b 100644
--- a/frontend/src/editor/desktop/services/downloadService.ts
+++ b/frontend/src/editor/desktop/services/downloadService.ts
@@ -10,6 +10,8 @@ import {
export type { DownloadRequest, DownloadResult };
+export const SAVES_TO_DISK = true;
+
export async function downloadFile(
request: DownloadRequest,
): Promise<DownloadResult> {