Skip to content

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

Support renaming files in Page Editor (#8415)

James Bruntonf550fbf95db4
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 1714c28661..f6ce57f5c9 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6810,6 +6810,7 @@ title = "Couldn't save changes"
close = "Close file"
collapse = "Collapse"
expand = "Expand"
+rename = "Rename file"
[pageTracks.wrap]
label = "Wrap pages"
diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
index ae34e5ad6b..5ac4b86c9d 100644
--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
@@ -83,7 +83,7 @@ import { VersionHistoryModal } from "@app/components/filesPage/VersionHistoryMod
import { RenameFileDialog } from "@app/components/shared/RenameFileDialog";
import { duplicateStoredFile } from "@app/utils/duplicateFile";
import { downloadFileFromStorage } from "@app/utils/downloadUtils";
-import { fileStorage } from "@app/services/fileStorage";
+import { renameStoredFile } from "@app/services/renameStoredFile";
import { materializeServerStubs } from "@app/services/fileSyncService";
import {
FILES_PAGE_DRAG_TYPE,
@@ -953,19 +953,16 @@ export default function FileManagerView() {
if (!file) return;
const local = await localCopyOf(file);
if (!local) return;
- // quickKey is name|size|lastModified; a stale one would make a re-upload
- // of the original look like a duplicate of the renamed file.
- const quickKey = `${name}|${local.size}|${local.lastModified}`;
- const saved = await fileStorage.updateFileMetadata(local.id, {
+ const saved = await renameStoredFile(
+ local,
name,
- quickKey,
- });
+ fileActions.updateStirlingFileStub,
+ );
if (!saved) {
throw new Error(
t("fileSidebar.rename.error", "Could not rename the file."),
);
}
- fileActions.updateStirlingFileStub(local.id, { name, quickKey });
setRenameTarget(null);
await refresh();
},
diff --git a/frontend/editor/src/core/components/pageTracks/PageTracks.module.css b/frontend/editor/src/core/components/pageTracks/PageTracks.module.css
index 103f5c68ee..923a8da56b 100644
--- a/frontend/editor/src/core/components/pageTracks/PageTracks.module.css
+++ b/frontend/editor/src/core/components/pageTracks/PageTracks.module.css
@@ -85,6 +85,15 @@
min-width: 0;
}
+.trackNameInput {
+ flex: 0 1 18rem;
+ min-width: 6rem;
+}
+
+.trackNameInput input {
+ font-weight: 600;
+}
+
.trackMeta {
font-size: 0.75rem;
color: var(--c-text-muted);
diff --git a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
index 5cfe773ae6..610e328ee3 100644
--- a/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
+++ b/frontend/editor/src/core/components/pageTracks/PageTracks.tsx
@@ -56,10 +56,11 @@ import { useTrackThumbnails } from "@app/components/pageTracks/hooks/useTrackThu
import { useTrackSave } from "@app/components/pageTracks/hooks/useTrackSave";
import { usePageTracksShortcuts } from "@app/components/pageTracks/hooks/usePageTracksShortcuts";
import { usePageTracksWorkbenchBarButtons } from "@app/components/pageTracks/hooks/usePageTracksWorkbenchBarButtons";
-import { totalPageCount } from "@app/components/pageTracks/types";
+import { Track, totalPageCount } from "@app/components/pageTracks/types";
import { opensAsTrack } from "@app/components/pageTracks/trackFileKind";
import TrackRow, { DropHint } from "@app/components/pageTracks/TrackRow";
import { DisabledFileTrack } from "@app/components/pageTracks/DisabledFileTrack";
+import { renameStoredFile } from "@app/services/renameStoredFile";
import styles from "@app/components/pageTracks/PageTracks.module.css";
const PAGE_PREFIX = "page:";
@@ -923,6 +924,31 @@ export default function PageTracks() {
void fileActions.removeFiles([closeOnceSaved], false);
}, [closeOnceSaved, fileActions, fileState.files.byId]);
+ // An open file's name lives in storage, so renaming it is immediate, like
+ // the file sidebar; a split has no file until saved, so only its track holds
+ // the name it will be saved under.
+ const renameTrack = useCallback(
+ async (track: Track, name: string) => {
+ if (!track.isNew) {
+ const stub = fileSelectors.getStirlingFileStub(track.fileId);
+ const saved = stub
+ ? await renameStoredFile(
+ stub,
+ name,
+ fileActions.updateStirlingFileStub,
+ )
+ : false;
+ if (!saved) {
+ throw new Error(
+ t("fileSidebar.rename.error", "Could not rename the file."),
+ );
+ }
+ }
+ dispatch({ type: "renameTrack", fileId: track.fileId, name });
+ },
+ [fileSelectors, fileActions, dispatch, t],
+ );
+
useWorkbenchViewFileActions(
useMemo(
() => ({ getExportFiles, onClose: () => setCloseRequest("all") }),
@@ -1032,6 +1058,7 @@ export default function PageTracks() {
onSelectTrack={selection.selectTrack}
onSelectNumbers={selectNumbersInTrack}
onOpenInViewer={openInViewer}
+ onRename={renameTrack}
onClearSelection={clearSelection}
onSplit={splitTrack}
onInsertBlank={insertBlank}
diff --git a/frontend/editor/src/core/components/pageTracks/TrackNameField.test.tsx b/frontend/editor/src/core/components/pageTracks/TrackNameField.test.tsx
new file mode 100644
index 0000000000..fe1c053f94
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/TrackNameField.test.tsx
@@ -0,0 +1,70 @@
+import { describe, expect, it, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { MantineProvider } from "@mantine/core";
+import { TrackNameField } from "@app/components/pageTracks/TrackNameField";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),
+}));
+
+function show(onRename = vi.fn().mockResolvedValue(undefined)) {
+ render(
+ <MantineProvider env="test">
+ <TrackNameField name="report.pdf" onRename={onRename} />
+ </MantineProvider>,
+ );
+ return { onRename };
+}
+
+async function startEditing() {
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("button", { name: "Rename file" }));
+ const input = screen.getByRole("textbox", { name: "File name" });
+ await user.clear(input);
+ return { user, input };
+}
+
+describe("TrackNameField", () => {
+ it("submits the new name, keeping the extension, on Enter", async () => {
+ const { onRename } = show();
+ const { user } = await startEditing();
+
+ await user.keyboard("summary{Enter}");
+
+ expect(onRename).toHaveBeenCalledExactlyOnceWith("summary.pdf");
+ await waitFor(() =>
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument(),
+ );
+ });
+
+ it("cancels on Escape without renaming", async () => {
+ const { onRename } = show();
+ const { user } = await startEditing();
+
+ await user.keyboard("summary{Escape}");
+
+ expect(onRename).not.toHaveBeenCalled();
+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
+ });
+
+ it("stays open when the name has an illegal character", async () => {
+ const { onRename } = show();
+ const { user, input } = await startEditing();
+
+ await user.keyboard("a/b{Enter}");
+
+ expect(onRename).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ });
+
+ it("stays open with the message when the rename fails", async () => {
+ show(vi.fn().mockRejectedValue(new Error("Disk full")));
+ const { user, input } = await startEditing();
+
+ await user.keyboard("summary{Enter}");
+
+ await waitFor(() => expect(input).toHaveAttribute("aria-invalid", "true"));
+ expect(screen.getByText("Disk full")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/core/components/pageTracks/TrackNameField.tsx b/frontend/editor/src/core/components/pageTracks/TrackNameField.tsx
new file mode 100644
index 0000000000..b55fc06380
--- /dev/null
+++ b/frontend/editor/src/core/components/pageTracks/TrackNameField.tsx
@@ -0,0 +1,125 @@
+import { useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@app/ui/Icon";
+import { ActionIcon } from "@app/ui/ActionIcon";
+import { Input } from "@app/ui/Input";
+import { Tooltip } from "@app/components/shared/Tooltip";
+import { PrivateContent } from "@app/components/shared/PrivateContent";
+import { truncateCenter } from "@app/utils/textUtils";
+import { ILLEGAL_FILE_NAME_CHARS, splitFileName } from "@app/utils/fileUtils";
+import styles from "@app/components/pageTracks/PageTracks.module.css";
+
+interface TrackNameFieldProps {
+ name: string;
+ /** Gets the new full name. Rejecting keeps the field open with the message. */
+ onRename: (name: string) => Promise<void>;
+}
+
+/**
+ * A track's name, renamed in place. Only the base name is editable: the
+ * extension stays fixed so a rename can't leave the file claiming the wrong
+ * type. Enter or blur commits, Escape cancels.
+ */
+export function TrackNameField({ name, onRename }: TrackNameFieldProps) {
+ const { t } = useTranslation();
+ const [base, extension] = splitFileName(name);
+ // null while not editing.
+ const [draft, setDraft] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ // A ref, not state: Enter commits and the blur that follows must see it set
+ // within the same tick.
+ const committing = useRef(false);
+
+ const stopEditing = () => {
+ setDraft(null);
+ setError(null);
+ };
+
+ const commit = async () => {
+ if (draft === null || committing.current) return;
+ const nextBase = draft.trim();
+ const nextName = `${nextBase}${extension}`;
+ if (!nextBase || nextName === name) {
+ stopEditing();
+ return;
+ }
+ if (ILLEGAL_FILE_NAME_CHARS.test(nextBase)) {
+ setError(
+ t(
+ "fileSidebar.rename.illegalCharacters",
+ "A file name can't contain \\ / : * ? \" < > |",
+ ),
+ );
+ return;
+ }
+ committing.current = true;
+ try {
+ await onRename(nextName);
+ stopEditing();
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : t("fileSidebar.rename.error", "Could not rename the file."),
+ );
+ } finally {
+ committing.current = false;
+ }
+ };
+
+ const renameLabel = t("pageTracks.track.rename", "Rename file");
+
+ if (draft === null) {
+ return (
+ <>
+ <span className={styles.trackName}>
+ <PrivateContent>{truncateCenter(name, 40)}</PrivateContent>
+ </span>
+ <Tooltip position="bottom" content={renameLabel}>
+ <ActionIcon
+ className={styles.trackLeadAction}
+ variant="quiet"
+ size="sm"
+ aria-label={renameLabel}
+ onClick={() => setDraft(base)}
+ >
+ <Icon name="pencil" size="1rem" />
+ </ActionIcon>
+ </Tooltip>
+ </>
+ );
+ }
+
+ return (
+ <Tooltip position="bottom" content={error} open={error != null}>
+ <Input
+ className={styles.trackNameInput}
+ inputSize="sm"
+ autoFocus
+ value={draft}
+ invalid={error != null}
+ maxLength={200}
+ aria-label={t("fileSidebar.rename.label", "File name")}
+ aria-invalid={error != null}
+ trailingIcon={extension || undefined}
+ onChange={(event) => {
+ setDraft(event.currentTarget.value);
+ setError(null);
+ }}
+ onFocus={(event) => event.currentTarget.select()}
+ onBlur={() => void commit()}
+ // The header is the track's drag handle; selecting text must not drag it.
+ onPointerDown={(event) => event.stopPropagation()}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void commit();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ stopEditing();
+ }
+ }}
+ />
+ </Tooltip>
+ );
+}
diff --git a/frontend/editor/src/core/components/pageTracks/TrackRow.tsx b/frontend/editor/src/core/components/pageTracks/TrackRow.tsx
index 311b99712e..12c42f1dab 100644
--- a/frontend/editor/src/core/components/pageTracks/TrackRow.tsx
+++ b/frontend/editor/src/core/components/pageTracks/TrackRow.tsx
@@ -13,8 +13,7 @@ import { Icon } from "@app/ui/Icon";
import { ActionIcon } from "@app/ui/ActionIcon";
import { Tooltip } from "@app/components/shared/Tooltip";
import { SelectByNumberPopover } from "@app/components/pageTracks/SelectByNumberPopover";
-import { PrivateContent } from "@app/components/shared/PrivateContent";
-import { truncateCenter } from "@app/utils/textUtils";
+import { TrackNameField } from "@app/components/pageTracks/TrackNameField";
import { FileId } from "@app/types/file";
import { Track } from "@app/components/pageTracks/types";
import { TrackThumbnailStore } from "@app/components/pageTracks/hooks/useTrackThumbnails";
@@ -129,6 +128,8 @@ export interface TrackRowProps {
/** Selects these 1-based pages of the track, replacing its selection. */
onSelectNumbers: (fileId: FileId, pageNumbers: number[]) => void;
onOpenInViewer: (fileId: FileId) => void;
+ /** Rejects with a user-facing message when the rename fails. */
+ onRename: (track: Track, name: string) => Promise<void>;
/** Called when the click landed on empty lane surface, not on a page. */
onClearSelection: () => void;
/** Split this track so `startPageId` begins a new track. */
@@ -161,6 +162,7 @@ function TrackRowImpl({
onSelectTrack,
onSelectNumbers,
onOpenInViewer,
+ onRename,
onClearSelection,
onSplit,
onInsertBlank,
@@ -423,9 +425,10 @@ function TrackRowImpl({
)}
</ActionIcon>
</Tooltip>
- <span className={styles.trackName}>
- <PrivateContent>{truncateCenter(name, 40)}</PrivateContent>
- </span>
+ <TrackNameField
+ name={name}
+ onRename={(nextName) => onRename(track, nextName)}
+ />
<span className={styles.trackMeta}>
{[
versionNumber != null && versionNumber > 1
diff --git a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
index f4eeff45c0..094e7d3f37 100644
--- a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
+++ b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.test.ts
@@ -675,3 +675,41 @@ describe("trackEditorReducer history", () => {
expect(trackSignature(pagesOf(state, A))).toEqual(original);
});
});
+
+describe("trackEditorReducer renameTrack", () => {
+ it("renames without dirtying the track or leaving the old name in history", () => {
+ const rotated = trackEditorReducer(twoTracks(), {
+ type: "rotate",
+ pageIds: [pagesOf(twoTracks(), A)[0].id],
+ delta: 90,
+ });
+ const renamed = trackEditorReducer(rotated, {
+ type: "renameTrack",
+ fileId: A,
+ name: "renamed.pdf",
+ });
+ expect(renamed.present.tracks[A].name).toBe("renamed.pdf");
+ expect(changedTrackIds(renamed)).toEqual(changedTrackIds(rotated));
+
+ const undone = trackEditorReducer(renamed, { type: "undo" });
+ expect(undone.present.tracks[A].name).toBe("renamed.pdf");
+ });
+
+ it("is a no-op for an unknown track or an unchanged name", () => {
+ const state = twoTracks();
+ expect(
+ trackEditorReducer(state, {
+ type: "renameTrack",
+ fileId: "missing" as FileId,
+ name: "x.pdf",
+ }),
+ ).toBe(state);
+ expect(
+ trackEditorReducer(state, {
+ type: "renameTrack",
+ fileId: A,
+ name: `${A}.pdf`,
+ }),
+ ).toBe(state);
+ });
+});
diff --git a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
index 1c21ad52c4..17eef0118a 100644
--- a/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
+++ b/frontend/editor/src/core/components/pageTracks/trackWorkspaceReducer.ts
@@ -76,6 +76,9 @@ export type TrackEditorAction =
/** Swaps a page with its neighbour in the same track. */
| { type: "shiftPage"; pageId: string; by: -1 | 1 }
| { type: "dropTracks"; fileIds: FileId[] }
+ /** Renames a track everywhere it appears, history included: a name is not a
+ * page edit, so undo must not bring the old one back. */
+ | { type: "renameTrack"; fileId: FileId; name: string }
/** Drops the just-saved split tracks and records the order their new files
* should take, so sync slots each one back where its track sat. */
| {
@@ -576,6 +579,27 @@ export function trackEditorReducer(
};
}
+ case "renameTrack": {
+ const { fileId, name } = action;
+ const track = state.present.tracks[fileId];
+ if (!track || track.name === name) return state;
+ const rename = (workspace: TrackWorkspace): TrackWorkspace => {
+ const target = workspace.tracks[fileId];
+ if (!target || target.name === name) return workspace;
+ return {
+ ...workspace,
+ tracks: { ...workspace.tracks, [fileId]: { ...target, name } },
+ };
+ };
+ return {
+ ...state,
+ present: rename(state.present),
+ baseline: rename(state.baseline),
+ past: state.past.map(rename),
+ future: state.future.map(rename),
+ };
+ }
+
case "dropTracks": {
const drop = new Set(action.fileIds);
if (!state.present.order.some((id) => drop.has(id))) return state;
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index 2874cbcfa4..41f6b996e2 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -55,6 +55,7 @@ import {
type DeleteScope,
} from "@app/services/serverStorageDelete";
import { fileStorage, onRecordUnreadable } from "@app/services/fileStorage";
+import { renameStoredFile } from "@app/services/renameStoredFile";
import { downloadFileWithPolicy } from "@app/services/exportWithPolicy";
import { useOpenInNewWindow } from "@app/extensions/openInNewWindow";
import { openSuperSearch } from "@app/components/shared/superSearch/openSuperSearch";
@@ -757,24 +758,20 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
[allFileStubs],
);
- // Persist the rename before updating the open workspace copy.
const handleConfirmRename = useCallback(
async (name: string) => {
const stub = renameTarget;
if (!stub) return;
- // quickKey is name|size|lastModified; a stale one would make a re-upload
- // of the original look like a duplicate of the renamed file.
- const quickKey = `${name}|${stub.size}|${stub.lastModified}`;
- const saved = await fileStorage.updateFileMetadata(stub.id, {
+ const saved = await renameStoredFile(
+ stub,
name,
- quickKey,
- });
+ fileActions.updateStirlingFileStub,
+ );
if (!saved) {
throw new Error(
t("fileSidebar.rename.error", "Could not rename the file."),
);
}
- fileActions.updateStirlingFileStub(stub.id, { name, quickKey });
setRenameTarget(null);
await refreshStubs();
},
diff --git a/frontend/editor/src/core/components/shared/RenameFileDialog.tsx b/frontend/editor/src/core/components/shared/RenameFileDialog.tsx
index cb364bc4af..539c3af32f 100644
--- a/frontend/editor/src/core/components/shared/RenameFileDialog.tsx
+++ b/frontend/editor/src/core/components/shared/RenameFileDialog.tsx
@@ -3,10 +3,7 @@ import { useTranslation } from "react-i18next";
import { Alert, Group, Modal, Stack, TextInput } from "@mantine/core";
import { Icon } from "@app/ui/Icon";
import { Button } from "@app/ui/Button";
-import { splitFileName } from "@app/utils/fileUtils";
-
-/** Characters Windows/macOS reject in a filename, which is also what a download saves as. */
-const ILLEGAL_NAME_CHARS = /[\\/:*?"<>|]/;
+import { ILLEGAL_FILE_NAME_CHARS, splitFileName } from "@app/utils/fileUtils";
interface RenameFileDialogProps {
opened: boolean;
@@ -44,7 +41,7 @@ export function RenameFileDialog({
const submit = async () => {
const nextBase = value.trim();
if (!nextBase) return;
- if (ILLEGAL_NAME_CHARS.test(nextBase)) {
+ if (ILLEGAL_FILE_NAME_CHARS.test(nextBase)) {
setError(
t(
"fileSidebar.rename.illegalCharacters",
diff --git a/frontend/editor/src/core/components/shared/Tooltip.tsx b/frontend/editor/src/core/components/shared/Tooltip.tsx
index 17e43b7534..ef2d887966 100644
--- a/frontend/editor/src/core/components/shared/Tooltip.tsx
+++ b/frontend/editor/src/core/components/shared/Tooltip.tsx
@@ -28,6 +28,7 @@ interface ForwardedHandlers {
onClick?: React.MouseEventHandler;
onFocus?: React.FocusEventHandler;
onBlur?: React.FocusEventHandler;
+ onKeyDown?: React.KeyboardEventHandler;
}
export interface TooltipProps {
@@ -347,10 +348,10 @@ export const Tooltip: React.FC<TooltipProps> = ({
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
- if (manualCloseOnly) return;
- if (e.key === "Escape") setOpen(false);
+ if (!manualCloseOnly && e.key === "Escape") setOpen(false);
+ (children.props as ForwardedHandlers).onKeyDown?.(e);
},
- [setOpen, manualCloseOnly],
+ [setOpen, manualCloseOnly, children.props],
);
// Keep open while pointer is over the tooltip; close when leaving it (if not pinned)
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.test.ts b/frontend/editor/src/core/contexts/file/lifecycle.test.ts
index 8bb6dcd46c..eee69c0875 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.test.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.test.ts
@@ -22,4 +22,33 @@ describe("FileLifecycleManager", () => {
expect(URL.revokeObjectURL).toHaveBeenCalledWith(blobUrl);
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1);
});
+
+ it("renames the held File so tools name their output after the new name", () => {
+ const fileId = "file-1" as FileId;
+ const original = new File(["pdf"], "old.pdf", {
+ type: "application/pdf",
+ lastModified: 42,
+ });
+ const filesRef = { current: new Map<FileId, File>([[fileId, original]]) };
+ const manager = new FileLifecycleManager(filesRef, vi.fn());
+
+ manager.updateStirlingFileStub(fileId, { name: "new.pdf" });
+
+ const held = filesRef.current.get(fileId);
+ expect(held?.name).toBe("new.pdf");
+ expect(held?.type).toBe("application/pdf");
+ expect(held?.lastModified).toBe(42);
+ expect(held).toMatchObject({ fileId, quickKey: "new.pdf|3|42" });
+ });
+
+ it("keeps the held File when the update does not rename", () => {
+ const fileId = "file-1" as FileId;
+ const original = new File(["pdf"], "file.pdf");
+ const filesRef = { current: new Map<FileId, File>([[fileId, original]]) };
+ const manager = new FileLifecycleManager(filesRef, vi.fn());
+
+ manager.updateStirlingFileStub(fileId, { isDirty: true });
+
+ expect(filesRef.current.get(fileId)).toBe(original);
+ });
});
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.ts b/frontend/editor/src/core/contexts/file/lifecycle.ts
index 6c0eecb0d2..96b892b865 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.ts
@@ -10,6 +10,7 @@ import {
FileContextState,
StirlingFileStub,
ProcessedFilePage,
+ createStirlingFile,
} from "@app/types/fileContext";
import {
forgetFile,
@@ -217,6 +218,17 @@ export class FileLifecycleManager {
return;
}
+ // Tools name their output after the held File, not the stub, so a rename
+ // must replace it or the next tool run brings the old name back.
+ const held = this.filesRef.current.get(fileId);
+ if (held && updates.name !== undefined && updates.name !== held.name) {
+ const renamed = new File([held], updates.name, {
+ type: held.type,
+ lastModified: held.lastModified,
+ });
+ this.filesRef.current.set(fileId, createStirlingFile(renamed, fileId));
+ }
+
this.dispatch({
type: "UPDATE_FILE_RECORD",
payload: { id: fileId, updates },
diff --git a/frontend/editor/src/core/services/renameStoredFile.ts b/frontend/editor/src/core/services/renameStoredFile.ts
new file mode 100644
index 0000000000..6c961480a3
--- /dev/null
+++ b/frontend/editor/src/core/services/renameStoredFile.ts
@@ -0,0 +1,24 @@
+import { fileStorage } from "@app/services/fileStorage";
+import type { FileId } from "@app/types/file";
+import type { StirlingFileStub } from "@app/types/fileContext";
+
+/**
+ * Renames a stored file, then its open workspace copy. Storage is written
+ * first so a failed write leaves the open copy as it was. Resolves false when
+ * storage has no record of the file.
+ */
+export async function renameStoredFile(
+ stub: Pick<StirlingFileStub, "id" | "size" | "lastModified">,
+ name: string,
+ updateStub: (id: FileId, updates: Partial<StirlingFileStub>) => void,
+): Promise<boolean> {
+ // quickKey is name|size|lastModified; a stale one would make a re-upload of
+ // the original look like a duplicate of the renamed file.
+ const quickKey = `${name}|${stub.size}|${stub.lastModified}`;
+ const saved = await fileStorage.updateFileMetadata(stub.id, {
+ name,
+ quickKey,
+ });
+ if (saved) updateStub(stub.id, { name, quickKey });
+ return saved;
+}
diff --git a/frontend/editor/src/core/utils/fileUtils.ts b/frontend/editor/src/core/utils/fileUtils.ts
index 8e6150ccc8..b4148942f5 100644
--- a/frontend/editor/src/core/utils/fileUtils.ts
+++ b/frontend/editor/src/core/utils/fileUtils.ts
@@ -101,6 +101,9 @@ export function splitFileName(name: string): [string, string] {
return dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];
}
+/** Characters Windows/macOS reject in a filename, which is also what a download saves as. */
+export const ILLEGAL_FILE_NAME_CHARS = /[\\/:*?"<>|]/;
+
/**
* Checks if a file is a PDF based on extension and MIME type
* @param file - File or file-like object with name and type properties