Skip to content

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

fix(files): lock processing-folder files until completion (#8120)

Reece Brownee5e7154bab24
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index b7f57b6aaf..a7e6dd57b5 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -4682,10 +4682,11 @@ done = "Ready"
doneHint = "Processed - opens the result"
failed = "Failed"
processing = "Processing"
-processingHint = "Processing - available when it finishes"
+processingHint = "This file will be available when processing is complete"
retry = "Retry"
retryHint = "Run this file again"
waiting = "Queued"
+waitingHint = "This file is queued and will be available when processing is complete"
[filesPage.empty]
hint = "Drop PDFs anywhere on this page to upload, or use the New folder button to organize your files."
@@ -4733,6 +4734,7 @@ moveFolderFailed = "Could not move folder."
moveFolderFailedDetail = "Could not move folder: {{message}}"
openDiskFileFailed = "Could not open {{name}}."
openDiskFileFailedDetail = "Could not open {{name}}: {{message}}"
+processingStatusUnavailable = "Could not refresh processing status. File locks have been released until the connection recovers."
readFolderFailed = "Could not read the folder."
readFolderFailedDetail = "Could not read the folder: {{message}}"
removeFilesFailed = "Could not remove files."
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx
index 4856b8aba1..5e143cead3 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx
@@ -1,6 +1,13 @@
import { describe, it, expect, vi } from "vitest";
-import { render as baseRender } from "@testing-library/react";
+import {
+ fireEvent,
+ render as baseRender,
+ screen,
+ within,
+} from "@testing-library/react";
import { MantineProvider } from "@mantine/core";
+import { FileGrid } from "@app/components/filesPage/FileGrid";
+import { FileContextProvider } from "@app/contexts/FileContext";
import type { FileId } from "@app/types/file";
import type { StirlingFileStub } from "@app/types/fileContext";
@@ -38,9 +45,8 @@ const buildStub = (id: string, name: string): StirlingFileStub =>
}) as StirlingFileStub;
describe("FileGrid item memoization", () => {
- it("re-renders only the cards whose selection changed", async () => {
- const { FileGrid } = await import("@app/components/filesPage/FileGrid");
- const { FileContextProvider } = await import("@app/contexts/FileContext");
+ it("re-renders only the cards whose selection changed", () => {
+ badgeRenders.n = 0;
const files = ["a", "b", "c", "d"].map((id) => buildStub(id, `${id}.pdf`));
const entries = files.map((file) => ({ kind: "file" as const, file }));
@@ -95,3 +101,65 @@ describe("FileGrid item memoization", () => {
// which the default budget cannot absorb alongside the rest of the suite.
}, 20_000);
});
+
+describe("FileGrid processing locks", () => {
+ it.each(["grid", "list"] as const)(
+ "disables opening a locked disk file in %s view",
+ async (viewMode) => {
+ const onOpenDiskFile = vi.fn();
+ const entry = {
+ kind: "diskFile" as const,
+ disk: {
+ path: "/processing/report.pdf",
+ name: "report.pdf",
+ sizeBytes: 1_000,
+ lastModified: 0,
+ },
+ diskState: "waiting" as const,
+ processingLocked: true,
+ };
+
+ const view = render(
+ <FileContextProvider>
+ <FileGrid
+ entries={[entry]}
+ selectedFileIds={new Set<FileId>()}
+ viewMode={viewMode}
+ onSelectFile={() => {}}
+ onOpenFolder={() => {}}
+ onOpenFile={() => {}}
+ onOpenDiskFile={onOpenDiskFile}
+ onMoveFiles={() => {}}
+ onMoveFolder={() => {}}
+ onRenameFolder={() => {}}
+ onDeleteFolder={() => {}}
+ onChangeFolderAppearance={() => {}}
+ onRemoveFiles={() => {}}
+ onPromptMoveFiles={() => {}}
+ />
+ </FileContextProvider>,
+ );
+
+ const fileItem = view.container.querySelector(
+ viewMode === "grid"
+ ? ".files-page-card"
+ : ".files-page-list-row:not(.is-header)",
+ );
+ expect(fileItem).not.toBeNull();
+ fireEvent.doubleClick(fileItem!);
+
+ fireEvent.click(
+ within(fileItem as HTMLElement).getByRole("button", {
+ name: /fileMenu|File actions/,
+ }),
+ );
+ const addToWorkspace = await screen.findByRole("menuitem", {
+ name: /addToWorkspace|Add to workspace/,
+ });
+ expect(addToWorkspace).toBeDisabled();
+ fireEvent.click(addToWorkspace);
+
+ expect(onOpenDiskFile).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
index d7de52671d..b26f22d7a2 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
@@ -60,8 +60,10 @@ export interface FilesPageEntry {
file?: StirlingFileStub;
/** A file read straight off a mounted directory (kind "diskFile"). */
disk?: DiskFileEntry;
- /** The disk file's processing state; absent on a folder with no pipeline. */
+ /** The file's processing state; absent on a folder with no pipeline. */
diskState?: DiskFileState;
+ /** Whether opening this file must wait for its processing-folder run. */
+ processingLocked?: boolean;
hasOriginal?: boolean;
/** Parent breadcrumb path for search results outside the current folder. */
parentPath?: string;
@@ -540,6 +542,7 @@ function GridView({
key={`disk-${entry.disk.path}`}
entry={entry.disk}
state={entry.diskState}
+ locked={entry.processingLocked ?? false}
hasOriginal={entry.hasOriginal}
actions={actions}
/>
@@ -552,6 +555,7 @@ function GridView({
file={entry.file}
parentPath={entry.parentPath}
processingState={entry.diskState}
+ locked={entry.processingLocked ?? false}
isSelected={selectedFileIds.has(entry.file.id)}
isInWorkspace={
activeWorkspaceFileIds?.has(entry.file.id) ?? false
@@ -811,6 +815,20 @@ function ProcessingFolderStats({
);
}
+/** Why the file cannot be opened: being replaced now, or waiting its turn to be. */
+function useLockedHint(state?: DiskFileState): string {
+ const { t } = useTranslation();
+ return state === "processing"
+ ? t(
+ "filesPage.diskState.processingHint",
+ "Processing - available when it finishes",
+ )
+ : t(
+ "filesPage.diskState.waitingHint",
+ "Queued for processing - available when its folder has run it",
+ );
+}
+
/** A file's pipeline state chip; a failed state adds an inline retry. */
function FileStateBadge({
state,
@@ -881,6 +899,7 @@ const NO_BADGES: FileItemPolicyRef[] = [];
interface FileActionsMenuProps {
file: StirlingFileStub;
triggerRef: React.RefObject<HTMLButtonElement | null>;
+ locked?: boolean;
/** Download / rename / duplicate menu items offered. */
downloadAvailable: boolean;
renameAvailable: boolean;
@@ -897,6 +916,7 @@ interface FileActionsMenuProps {
function FileActionsMenu({
file,
triggerRef,
+ locked = false,
downloadAvailable,
renameAvailable,
duplicateAvailable,
@@ -928,15 +948,16 @@ function FileActionsMenu({
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
+ disabled={locked}
leftSection={<Icon name="external-link" size={20} />}
onClick={(e) => {
e.stopPropagation();
- actions.openFile(file);
+ if (!locked) actions.openFile(file);
}}
>
{t("filesPage.addToWorkspace", "Add to workspace")}
</Menu.Item>
- <OpenInNewWindowMenuItem file={file} />
+ <OpenInNewWindowMenuItem file={file} disabled={locked} />
<Menu.Item
leftSection={<Icon name="folder-input" size={20} />}
onClick={(e) => {
@@ -1065,6 +1086,8 @@ interface FileCardProps {
saveToServerDisabledReason?: string | null;
badges: FileItemPolicyRef[];
processingState?: DiskFileState;
+ /** The folder still owes this file a run; see FilesPageEntry.processingLocked. */
+ locked?: boolean;
actions: FileGridActions;
}
@@ -1082,9 +1105,11 @@ const FileCard = React.memo(function FileCard({
saveToServerDisabledReason,
badges,
processingState,
+ locked = false,
actions,
}: FileCardProps) {
const { t } = useTranslation();
+ const lockedHint = useLockedHint(processingState);
const cardRef = useRef<HTMLDivElement>(null);
const fileSize = useMemo(() => formatFileSize(file.size), [file.size]);
const fileDate = useMemo(
@@ -1097,10 +1122,9 @@ const FileCard = React.memo(function FileCard({
actions.selectFile(file.id, e.shiftKey, e.metaKey || e.ctrlKey),
[actions, file.id],
);
- const onDoubleClick = useCallback(
- () => actions.openFile(file),
- [actions, file],
- );
+ const onDoubleClick = useCallback(() => {
+ if (!locked) actions.openFile(file);
+ }, [locked, actions, file]);
const handleDragStart = useCallback(
(e: React.DragEvent<HTMLDivElement>) => {
@@ -1145,7 +1169,8 @@ const FileCard = React.memo(function FileCard({
onKeyDown={(e) => {
if (e.key === "Enter") onDoubleClick();
}}
- className={`files-page-card${isSelected ? " is-selected" : ""}${isInWorkspace ? " is-in-workspace" : ""}`}
+ className={`files-page-card${isSelected ? " is-selected" : ""}${isInWorkspace ? " is-in-workspace" : ""}${locked ? " is-locked" : ""}`}
+ title={locked ? lockedHint : undefined}
>
{isInWorkspace && (
<span
@@ -1224,6 +1249,7 @@ const FileCard = React.memo(function FileCard({
<FileActionsMenu
file={file}
triggerRef={kebabRef}
+ locked={locked}
downloadAvailable={downloadAvailable}
renameAvailable={renameAvailable}
duplicateAvailable={duplicateAvailable}
@@ -1401,6 +1427,7 @@ function ListView({
key={`disk-${entry.disk.path}`}
entry={entry.disk}
state={entry.diskState}
+ locked={entry.processingLocked ?? false}
hasOriginal={entry.hasOriginal}
actions={actions}
/>
@@ -1413,6 +1440,7 @@ function ListView({
file={entry.file}
parentPath={entry.parentPath}
processingState={entry.diskState}
+ locked={entry.processingLocked ?? false}
isSelected={selectedFileIds.has(entry.file.id)}
isInWorkspace={
activeWorkspaceFileIds?.has(entry.file.id) ?? false
@@ -1660,6 +1688,8 @@ interface FileRowProps {
saveToServerDisabledReason?: string | null;
badges: FileItemPolicyRef[];
processingState?: DiskFileState;
+ /** The folder still owes this file a run; see FilesPageEntry.processingLocked. */
+ locked?: boolean;
actions: FileGridActions;
}
@@ -1677,9 +1707,11 @@ const FileRow = React.memo(function FileRow({
saveToServerDisabledReason,
badges,
processingState,
+ locked = false,
actions,
}: FileRowProps) {
const { t } = useTranslation();
+ const lockedHint = useLockedHint(processingState);
const kebabRef = useRef<HTMLButtonElement>(null);
const fileSize = useMemo(() => formatFileSize(file.size), [file.size]);
const fileDate = useMemo(
@@ -1694,7 +1726,9 @@ const FileRow = React.memo(function FileRow({
);
const onClick = (e: React.MouseEvent) =>
actions.selectFile(file.id, e.shiftKey, e.metaKey || e.ctrlKey);
- const onOpen = () => actions.openFile(file);
+ const onOpen = () => {
+ if (!locked) actions.openFile(file);
+ };
return (
<div
role="row"
@@ -1718,7 +1752,8 @@ const FileRow = React.memo(function FileRow({
onKeyDown={(e) => {
if (e.key === "Enter") onOpen();
}}
- className={`files-page-list-row${isSelected ? " is-selected" : ""}${isInWorkspace ? " is-in-workspace" : ""}`}
+ className={`files-page-list-row${isSelected ? " is-selected" : ""}${isInWorkspace ? " is-in-workspace" : ""}${locked ? " is-locked" : ""}`}
+ title={locked ? lockedHint : undefined}
>
{/* Each direct child is a gridcell: a role="row" may only own cells, so the
checkbox and the actions menu have to sit inside one.
@@ -1821,6 +1856,7 @@ const FileRow = React.memo(function FileRow({
<FileActionsMenu
file={file}
triggerRef={kebabRef}
+ locked={locked}
downloadAvailable={downloadAvailable}
renameAvailable={renameAvailable}
duplicateAvailable={duplicateAvailable}
@@ -1844,21 +1880,22 @@ export { ROOT_FOLDER_ID };
const DiskFileCard = React.memo(function DiskFileCard({
entry,
state,
+ locked = false,
hasOriginal,
actions,
}: {
entry: DiskFileEntry;
state?: DiskFileState;
+ /** The folder still owes this file a run; see FilesPageEntry.processingLocked. */
+ locked?: boolean;
hasOriginal?: boolean;
actions: FileGridActions;
}) {
- // A file mid-processing is locked: its bytes are about to be replaced, so opening
- // it would show a result that is not there yet.
- const locked = state === "processing";
const onOpen = () => {
if (!locked) actions.openDiskFile(entry);
};
const { t } = useTranslation();
+ const lockedHint = useLockedHint(state);
const thumbnail = useDiskThumbnail(entry);
const extension = entry.name.includes(".")
? entry.name.split(".").pop()!.toUpperCase()
@@ -1873,14 +1910,7 @@ const DiskFileCard = React.memo(function DiskFileCard({
onKeyDown={(e) => {
if (e.key === "Enter") onOpen();
}}
- title={
- locked
- ? t(
- "filesPage.diskState.processingHint",
- "Processing - available when it finishes",
- )
- : entry.path
- }
+ title={locked ? lockedHint : entry.path}
>
<div className="files-page-card-thumb">
{thumbnail ? (
@@ -1933,6 +1963,7 @@ const DiskFileCard = React.memo(function DiskFileCard({
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
+ disabled={locked}
leftSection={<Icon name="external-link" size={20} />}
onClick={(e) => {
e.stopPropagation();
@@ -1963,21 +1994,22 @@ const DiskFileCard = React.memo(function DiskFileCard({
const DiskFileRow = React.memo(function DiskFileRow({
entry,
state,
+ locked = false,
hasOriginal,
actions,
}: {
entry: DiskFileEntry;
state?: DiskFileState;
+ /** The folder still owes this file a run; see FilesPageEntry.processingLocked. */
+ locked?: boolean;
hasOriginal?: boolean;
actions: FileGridActions;
}) {
- // A file mid-processing is locked: its bytes are about to be replaced, so opening
- // it would show a result that is not there yet.
- const locked = state === "processing";
const onOpen = () => {
if (!locked) actions.openDiskFile(entry);
};
const { t } = useTranslation();
+ const lockedHint = useLockedHint(state);
const thumbnail = useDiskThumbnail(entry);
const ext = entry.name.includes(".")
? entry.name.split(".").pop()!.toUpperCase()
@@ -1991,7 +2023,7 @@ const DiskFileRow = React.memo(function DiskFileRow({
onKeyDown={(e) => {
if (e.key === "Enter") onOpen();
}}
- title={entry.path}
+ title={locked ? lockedHint : entry.path}
>
<span aria-hidden="true" />
<span
@@ -2056,6 +2088,7 @@ const DiskFileRow = React.memo(function DiskFileRow({
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
+ disabled={locked}
leftSection={<Icon name="external-link" size={20} />}
onClick={onOpen}
>
diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
index 163de3a6d6..d304a3d383 100644
--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
@@ -138,7 +138,8 @@ export default function FileManagerView() {
useState<StirlingFileStub | null>(null);
const folders = useFolders();
const { actions: fileActions } = useFileActions();
- const { fileIds: activeWorkspaceFileIds } = useAllFiles();
+ const { fileIds: activeWorkspaceFileIds, fileStubs: activeWorkspaceFiles } =
+ useAllFiles();
const activeWorkspaceFileIdSet = useMemo(
() => new Set(activeWorkspaceFileIds.map((id) => id as string)),
[activeWorkspaceFileIds],
@@ -602,14 +603,66 @@ export default function FileManagerView() {
// Per-file state from the backend's ledger: processing in place leaves no output folder to
// infer it from. Polled while the folder is open so badges follow the sweep live, and the
// poll stands down with the tab rather than asking every 3s into a background window.
- const { data: processingFiles } = useQuery({
+ const {
+ data: processingFiles,
+ dataUpdatedAt: processingFilesUpdatedAt,
+ errorUpdatedAt: processingFilesErrorAt,
+ status: processingFilesStatus,
+ } = useQuery({
queryKey: processingFilesKey,
- // A failed read reports no states rather than an error: the badges are ambient
- // and the next tick retries.
- queryFn: () => listFiles(processingRecordId!).catch(() => []),
+ queryFn: () => listFiles(processingRecordId!),
enabled: processingView && Boolean(processingRecordId),
refetchInterval: PROCESSING_FILES_POLL_MS,
+ retry: false,
+ });
+
+ const activeProcessingKey = processingView ? (processingRecordId ?? "") : "";
+ const [processingPollFailures, setProcessingPollFailures] = useState({
+ key: "",
+ count: 0,
});
+ const processingPollEvent = useRef({ key: "", updatedAt: 0 });
+ useEffect(() => {
+ const key = activeProcessingKey;
+ if (processingPollEvent.current.key !== key) {
+ processingPollEvent.current = { key, updatedAt: 0 };
+ setProcessingPollFailures({ key, count: 0 });
+ }
+ if (!key) return;
+
+ const updatedAt =
+ processingFilesStatus === "error"
+ ? processingFilesErrorAt
+ : processingFilesUpdatedAt;
+ if (!updatedAt || updatedAt <= processingPollEvent.current.updatedAt)
+ return;
+
+ processingPollEvent.current.updatedAt = updatedAt;
+ setProcessingPollFailures((failures) => ({
+ key,
+ count:
+ processingFilesStatus === "error"
+ ? (failures.key === key ? failures.count : 0) + 1
+ : 0,
+ }));
+ }, [
+ activeProcessingKey,
+ processingFilesErrorAt,
+ processingFilesStatus,
+ processingFilesUpdatedAt,
+ ]);
+ const processingStatesUnavailable =
+ processingPollFailures.key === activeProcessingKey &&
+ processingPollFailures.count >= PROCESSING_FILES_FAILURE_LIMIT;
+ useEffect(() => {
+ if (!processingStatesUnavailable) return;
+ setFolderError(
+ t(
+ "filesPage.error.processingStatusUnavailable",
+ "Could not refresh processing status. File locks have been released until the connection recovers.",
+ ),
+ );
+ }, [processingStatesUnavailable, setFolderError, t]);
// Stable empties for a folder with no processing: a fresh Map/Set is never
// Object.is equal, so returning one would re-render every reader for nothing.
@@ -654,6 +707,61 @@ export default function FileManagerView() {
const [diskStateFilter, setDiskStateFilter] = useState<DiskFileState | "all">(
"all",
);
+ const processingLockedFor = useCallback(
+ (key: string): boolean => {
+ if (!processingView || processingStatesUnavailable) return false;
+ const state = fileStates.get(key);
+ return state !== "done" && state !== "failed";
+ },
+ [processingView, processingStatesUnavailable, fileStates],
+ );
+
+ const processingLockedFileIds = useMemo(
+ () =>
+ new Set(
+ allFiles
+ .filter(
+ (file) =>
+ (file.folderId ?? null) === (currentFolderId ?? null) &&
+ processingLockedFor(file.name),
+ )
+ .map((file) => file.id),
+ ),
+ [allFiles, currentFolderId, processingLockedFor],
+ );
+
+ const processingLockedDiskQuickKeys = useMemo(
+ () =>
+ new Set(
+ diskEntries
+ .filter((file) => processingLockedFor(file.name))
+ .map((file) => `${file.name}|${file.sizeBytes}|${file.lastModified}`),
+ ),
+ [diskEntries, processingLockedFor],
+ );
+
+ useEffect(() => {
+ const openLockedFileIds = activeWorkspaceFiles
+ .filter(
+ (file) =>
+ !file.isDirty &&
+ (processingLockedFileIds.has(file.id) ||
+ processingLockedDiskQuickKeys.has(
+ file.quickKey ??
+ `${file.name}|${file.size}|${file.lastModified ?? 0}`,
+ )),
+ )
+ .map((file) => file.id);
+ if (openLockedFileIds.length > 0) {
+ void fileActions.removeFiles(openLockedFileIds, false);
+ }
+ }, [
+ activeWorkspaceFiles,
+ fileActions,
+ processingLockedDiskQuickKeys,
+ processingLockedFileIds,
+ ]);
+
const diskStateFor = useCallback(
(name: string): DiskFileState | undefined => fileStates.get(name),
[fileStates],
@@ -798,6 +906,8 @@ export default function FileManagerView() {
kind: "diskFile",
disk,
diskState: outputDirectory ? diskStateFor(disk.name) : undefined,
+ processingLocked:
+ Boolean(outputDirectory) && processingLockedFor(disk.name),
hasOriginal: outputDirectory
? revertables.has(disk.name)
: undefined,
@@ -831,7 +941,12 @@ export default function FileManagerView() {
.map<FilesPageEntry>((file) => ({
kind: "file",
file,
- diskState: processingView ? diskStateFor(file.name) : undefined,
+ diskState:
+ processingView &&
+ (file.folderId ?? null) === (currentFolderId ?? null)
+ ? diskStateFor(file.name)
+ : undefined,
+ processingLocked: processingLockedFileIds.has(file.id),
parentPath:
inSearch && (file.folderId ?? null) !== (currentFolderId ?? null)
? pathForFolderId(file.folderId ?? null) || undefined
@@ -854,6 +969,7 @@ export default function FileManagerView() {
diskEntries,
outputDirectory,
processingView,
+ processingLockedFileIds,
diskStateFor,
revertables,
diskStateFilter,
@@ -1064,8 +1180,11 @@ export default function FileManagerView() {
);
const handleAddToWorkspace = useCallback(
- (fileIds: FileId[]) => openFilesInWorkbench(fileIds),
- [openFilesInWorkbench],
+ (fileIds: FileId[]) => {
+ const openable = fileIds.filter((id) => !processingLockedFileIds.has(id));
+ return openable.length > 0 ? openFilesInWorkbench(openable) : undefined;
+ },
+ [openFilesInWorkbench, processingLockedFileIds],
);
const handleOpenFile = useCallback(
@@ -2183,6 +2302,7 @@ export default function FileManagerView() {
*/
/** How often a working folder's per-file states re-read while it is open. */
const PROCESSING_FILES_POLL_MS = 3000;
+const PROCESSING_FILES_FAILURE_LIMIT = 3;
const EMPTY_FILE_STATES: ReadonlyMap<string, DiskFileState> = new Map();
const EMPTY_REVERTABLES: ReadonlySet<string> = new Set();
diff --git a/frontend/editor/src/core/components/filesPage/OpenInNewWindowMenuItem.test.tsx b/frontend/editor/src/core/components/filesPage/OpenInNewWindowMenuItem.test.tsx
new file mode 100644
index 0000000000..c59a41d125
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/OpenInNewWindowMenuItem.test.tsx
@@ -0,0 +1,64 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { MantineProvider, Menu } from "@mantine/core";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { OpenInNewWindowMenuItem } from "@app/components/filesPage/OpenInNewWindowMenuItem";
+import type { FileId } from "@app/types/file";
+import type { StirlingFileStub } from "@app/types/fileContext";
+
+const openInNewWindow = vi.fn();
+
+vi.mock("@app/extensions/openInNewWindow", () => ({
+ useOpenInNewWindow: () => ({
+ canOpenInNewWindow: () => true,
+ openInNewWindow,
+ }),
+}));
+
+const file = {
+ id: "file-1" as FileId,
+ name: "document.pdf",
+ type: "application/pdf",
+ size: 1,
+ lastModified: 0,
+ isLeaf: true,
+ originalFileId: "file-1",
+ versionNumber: 1,
+} as StirlingFileStub;
+
+function renderItem(disabled: boolean) {
+ render(
+ <MantineProvider>
+ <Menu opened>
+ <Menu.Target>
+ <button type="button">Actions</button>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <OpenInNewWindowMenuItem file={file} disabled={disabled} />
+ </Menu.Dropdown>
+ </Menu>
+ </MantineProvider>,
+ );
+}
+
+describe("OpenInNewWindowMenuItem", () => {
+ beforeEach(() => openInNewWindow.mockClear());
+ afterEach(cleanup);
+
+ it("opens an available file", () => {
+ renderItem(false);
+
+ fireEvent.click(screen.getByRole("menuitem", { name: "openInNewWindow" }));
+
+ expect(openInNewWindow).toHaveBeenCalledWith(file);
+ });
+
+ it("does not open a processing-locked file", () => {
+ renderItem(true);
+
+ const item = screen.getByRole("menuitem", { name: "openInNewWindow" });
+ expect(item).toBeDisabled();
+ fireEvent.click(item);
+
+ expect(openInNewWindow).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/core/components/filesPage/OpenInNewWindowMenuItem.tsx b/frontend/editor/src/core/components/filesPage/OpenInNewWindowMenuItem.tsx
index 051d3ad73b..534fd56b58 100644
--- a/frontend/editor/src/core/components/filesPage/OpenInNewWindowMenuItem.tsx
+++ b/frontend/editor/src/core/components/filesPage/OpenInNewWindowMenuItem.tsx
@@ -6,6 +6,7 @@ import { useOpenInNewWindow } from "@app/extensions/openInNewWindow";
interface OpenInNewWindowMenuItemProps {
file: StirlingFileStub;
+ disabled?: boolean;
}
/**
@@ -15,6 +16,7 @@ interface OpenInNewWindowMenuItemProps {
*/
export function OpenInNewWindowMenuItem({
file,
+ disabled = false,
}: OpenInNewWindowMenuItemProps) {
const { t } = useTranslation();
const { canOpenInNewWindow, openInNewWindow } = useOpenInNewWindow();
@@ -23,10 +25,11 @@ export function OpenInNewWindowMenuItem({
return (
<Menu.Item
+ disabled={disabled}
leftSection={<Icon name="external-link" size={20} />}
onClick={(e) => {
e.stopPropagation();
- openInNewWindow(file);
+ if (!disabled) openInNewWindow(file);
}}
>
{t("openInNewWindow", "Open in new window")}