Skip to content

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

feat(files): add a Clear recents button to the sidebar (#8625)

Reece Browneaf692181faf3
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 865d7dddc3..d492bb98a3 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -5085,6 +5085,17 @@ uploadFailedBody = "Could not add the selected files."
uploadFailedTitle = "Upload failed"
viewAll = "View all {{count}} files"
+[fileSidebar.clearRecents]
+body_one = "Clear 1 file from recents? This can't be undone."
+body_other = "Clear {{count}} files from recents? This can't be undone."
+button = "Clear recents"
+confirm = "Clear recents"
+error = "Could not clear. Try again."
+openNote_one = "1 of them is open in the workbench."
+openNote_other = "{{count}} of them are open in the workbench."
+skipOpen = "Skip open files"
+title = "Clear recents?"
+
[fileSidebar.fileItem]
closeViewer = "Close viewer"
dataLost = "Data lost"
diff --git a/frontend/src/editor/core/components/shared/ClearRecentsDialog.tsx b/frontend/src/editor/core/components/shared/ClearRecentsDialog.tsx
new file mode 100644
index 0000000000..b9882ede67
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/ClearRecentsDialog.tsx
@@ -0,0 +1,125 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Alert, Group, Modal, Stack, Text } from "@mantine/core";
+import { Icon } from "@editor/ui/Icon";
+import { Button } from "@editor/ui/Button";
+
+interface ClearRecentsDialogProps {
+ opened: boolean;
+ /** Files the clear will remove. */
+ clearCount: number;
+ /** How many of those are open in the workbench. */
+ openCount: number;
+ onClose: () => void;
+ /** Perform the clear, leaving open files alone if asked; may throw to surface an error. */
+ onConfirm: (skipOpen: boolean) => Promise<void>;
+}
+
+export function ClearRecentsDialog({
+ opened,
+ clearCount,
+ openCount,
+ onClose,
+ onConfirm,
+}: ClearRecentsDialogProps) {
+ const { t } = useTranslation();
+ // Which choice is running, so only that button spins.
+ const [submitting, setSubmitting] = useState<"all" | "skipOpen" | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (opened) {
+ setSubmitting(null);
+ setError(null);
+ }
+ }, [opened]);
+
+ const runClear = async (skipOpen: boolean) => {
+ setSubmitting(skipOpen ? "skipOpen" : "all");
+ setError(null);
+ try {
+ await onConfirm(skipOpen);
+ onClose();
+ } catch (err) {
+ console.error("Failed to clear recents:", err);
+ setError(
+ t("fileSidebar.clearRecents.error", "Could not clear. Try again."),
+ );
+ } finally {
+ setSubmitting(null);
+ }
+ };
+
+ return (
+ <Modal
+ opened={opened}
+ // Closing mid-clear would let a reopen start a second run over the first.
+ onClose={submitting ? () => {} : onClose}
+ title={t("fileSidebar.clearRecents.title", "Clear recents?")}
+ centered
+ size="md"
+ >
+ <Stack gap="md">
+ <Text size="sm">
+ {t(
+ "fileSidebar.clearRecents.body",
+ "Clear {{count}} file(s) from recents? This can't be undone.",
+ { count: clearCount },
+ )}
+ </Text>
+ {openCount > 0 && (
+ <Text size="sm">
+ {t(
+ "fileSidebar.clearRecents.openNote",
+ "{{count}} of them are open in the workbench.",
+ { count: openCount },
+ )}
+ </Text>
+ )}
+
+ {error && (
+ <Alert
+ color="red"
+ icon={<Icon name="circle-alert" size={20} />}
+ variant="light"
+ role="alert"
+ >
+ {error}
+ </Alert>
+ )}
+
+ <Group justify="flex-end">
+ <Button
+ variant="secondary"
+ onClick={onClose}
+ disabled={submitting !== null}
+ >
+ {t("filesPage.cancel", "Cancel")}
+ </Button>
+ {/* Skipping every file would clear nothing, so the choice is only
+ offered when some files aren't open. */}
+ {openCount > 0 && openCount < clearCount && (
+ <Button
+ variant="secondary"
+ loading={submitting === "skipOpen"}
+ disabled={submitting === "all"}
+ onClick={() => void runClear(true)}
+ data-testid="file-sidebar-clear-recents-skip-open"
+ >
+ {t("fileSidebar.clearRecents.skipOpen", "Skip open files")}
+ </Button>
+ )}
+ <Button
+ accent="danger"
+ loading={submitting === "all"}
+ disabled={submitting === "skipOpen"}
+ onClick={() => void runClear(false)}
+ data-testid="file-sidebar-clear-recents-confirm"
+ >
+ {t("fileSidebar.clearRecents.confirm", "Clear recents")}
+ </Button>
+ </Group>
+ </Stack>
+ </Modal>
+ );
+}
diff --git a/frontend/src/editor/core/components/shared/FileSidebar.css b/frontend/src/editor/core/components/shared/FileSidebar.css
index 74c3bcb322..26770d3c8d 100644
--- a/frontend/src/editor/core/components/shared/FileSidebar.css
+++ b/frontend/src/editor/core/components/shared/FileSidebar.css
@@ -294,6 +294,57 @@
margin-top: 2px;
}
+.file-sidebar-group-header-row {
+ position: relative;
+ display: flex;
+ align-items: center;
+}
+
+.file-sidebar-group-header-row:hover {
+ background: var(--c-hover);
+}
+
+/* The row carries the hover tint, so the header and its action read as one. */
+.file-sidebar-group-header-row .file-sidebar-group-header:hover {
+ background: transparent;
+}
+
+/* Sits over the count and swaps with it on hover or focus, so counts stay aligned
+ across groups whether or not a group has an action. */
+.file-sidebar-group-action {
+ position: absolute;
+ right: 2px;
+ opacity: 0;
+ pointer-events: none;
+}
+
+.file-sidebar-group-header-row:is(:hover, :has(:focus-visible))
+ .file-sidebar-group-action {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+.file-sidebar-group-header-row:has(.file-sidebar-group-action):is(
+ :hover,
+ :has(:focus-visible)
+ )
+ .file-sidebar-group-count {
+ visibility: hidden;
+}
+
+/* Touch screens have no hover to reveal it, so it stays in place of the count. */
+@media (hover: none) {
+ .file-sidebar-group-action {
+ opacity: 1;
+ pointer-events: auto;
+ }
+
+ .file-sidebar-group-header-row:has(.file-sidebar-group-action)
+ .file-sidebar-group-count {
+ visibility: hidden;
+ }
+}
+
.file-sidebar-group-header {
display: flex;
align-items: center;
diff --git a/frontend/src/editor/core/components/shared/FileSidebar.tsx b/frontend/src/editor/core/components/shared/FileSidebar.tsx
index 205ece747d..b0c88b22ec 100644
--- a/frontend/src/editor/core/components/shared/FileSidebar.tsx
+++ b/frontend/src/editor/core/components/shared/FileSidebar.tsx
@@ -47,6 +47,7 @@ import BulkUploadToServerModal from "@editor/components/shared/BulkUploadToServe
import { getFileOrigin } from "@editor/components/filesPage/fileOrigin";
import { VersionHistoryModal } from "@editor/components/filesPage/VersionHistoryModal";
import { DeleteFilesDialog } from "@editor/components/filesPage/DeleteFilesDialog";
+import { ClearRecentsDialog } from "@editor/components/shared/ClearRecentsDialog";
import { RenameFileDialog } from "@editor/components/shared/RenameFileDialog";
import { duplicateStoredFile } from "@editor/utils/duplicateFile";
import { SidebarChecklistSlot } from "@editor/components/shared/SidebarChecklistSlot";
@@ -200,6 +201,28 @@ function SidebarActionRow({ action }: { action: SidebarAction }) {
);
}
+function ClearRecentsButton({
+ onClick,
+ className,
+}: {
+ onClick: () => void;
+ className?: string;
+}) {
+ const { t } = useTranslation();
+ return (
+ <ActionIcon
+ variant="quiet"
+ className={`file-sidebar-section-btn${className ? ` ${className}` : ""}`}
+ onClick={onClick}
+ title={t("fileSidebar.clearRecents.button", "Clear recents")}
+ aria-label={t("fileSidebar.clearRecents.button", "Clear recents")}
+ data-testid="file-sidebar-clear-recents"
+ >
+ <Icon name="trash" size={"1rem"} />
+ </ActionIcon>
+ );
+}
+
interface LibraryHeaderProps {
stubs: StirlingFileStub[];
scrolled: boolean;
@@ -207,6 +230,8 @@ interface LibraryHeaderProps {
onGoogleDrive: () => void;
onAddFiles: () => void;
onOpenFilesPage: () => void;
+ /** Set only for a flat list; a grouped list carries it on its Recent group. */
+ onClearRecents?: () => void;
}
function LibraryHeader({
@@ -216,6 +241,7 @@ function LibraryHeader({
onGoogleDrive,
onAddFiles,
onOpenFilesPage,
+ onClearRecents,
}: LibraryHeaderProps) {
const { t } = useTranslation();
return (
@@ -250,6 +276,7 @@ function LibraryHeader({
>
<Icon name="search" size={"1rem"} />
</ActionIcon>
+ {onClearRecents && <ClearRecentsButton onClick={onClearRecents} />}
{isGoogleDriveEnabled && (
<ActionIcon
variant="quiet"
@@ -313,31 +340,44 @@ interface FileGroupProps {
isOpen: boolean;
onToggle: () => void;
renderFileRow: RenderFileRow;
+ /** A control beside the header; the header is itself a button, so it can't nest. */
+ action?: React.ReactNode;
}
-function FileGroup({ group, isOpen, onToggle, renderFileRow }: FileGroupProps) {
+function FileGroup({
+ group,
+ isOpen,
+ onToggle,
+ renderFileRow,
+ action,
+}: FileGroupProps) {
return (
<div className="file-sidebar-group">
- <Button
- variant="quiet"
- fullWidth
- justify="between"
- className="file-sidebar-group-header"
- onClick={onToggle}
- aria-expanded={isOpen}
- leftSection={
- <FileGroupSymbol
- icon={group.icon}
- color={group.color}
- isOpen={isOpen}
- />
- }
- rightSection={
- <span className="file-sidebar-group-count">{group.stubs.length}</span>
- }
- >
- <span className="file-sidebar-group-label">{group.label}</span>
- </Button>
+ <div className="file-sidebar-group-header-row">
+ <Button
+ variant="quiet"
+ fullWidth
+ justify="between"
+ className="file-sidebar-group-header"
+ onClick={onToggle}
+ aria-expanded={isOpen}
+ leftSection={
+ <FileGroupSymbol
+ icon={group.icon}
+ color={group.color}
+ isOpen={isOpen}
+ />
+ }
+ rightSection={
+ <span className="file-sidebar-group-count">
+ {group.stubs.length}
+ </span>
+ }
+ >
+ <span className="file-sidebar-group-label">{group.label}</span>
+ </Button>
+ {action}
+ </div>
<div className="file-sidebar-group-items">
{isOpen && group.stubs.map(renderFileRow)}
</div>
@@ -353,6 +393,8 @@ interface GroupedFileListProps {
renderFileRow: RenderFileRow;
total: number;
onViewAll: () => void;
+ /** Absent when nothing is clearable, which hides the button. */
+ onClearRecents?: () => void;
}
function GroupedFileList({
@@ -362,6 +404,7 @@ function GroupedFileList({
renderFileRow,
total,
onViewAll,
+ onClearRecents,
}: GroupedFileListProps) {
const { t } = useTranslation();
return (
@@ -375,6 +418,14 @@ function GroupedFileList({
isOpen={isOpen}
onToggle={() => onGroupOpenChange(group.id, !isOpen)}
renderFileRow={renderFileRow}
+ action={
+ group.id === "recent" && onClearRecents ? (
+ <ClearRecentsButton
+ onClick={onClearRecents}
+ className="file-sidebar-group-action"
+ />
+ ) : undefined
+ }
/>
);
})}
@@ -474,6 +525,7 @@ function FileLibrarySection({
onGoogleDrive={onGoogleDrive}
onAddFiles={onAddFiles}
onOpenFilesPage={list.onOpenFilesPage}
+ onClearRecents={list.groups ? undefined : list.onClearRecents}
/>
<BulkAddProgressRow />
<LibraryFileList scrollRef={scrollRef} {...list} />
@@ -559,6 +611,10 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
const [deleteTarget, setDeleteTarget] = useState<StirlingFileStub | null>(
null,
);
+ // Fixed when the dialog opens, so files added while it is up aren't cleared.
+ const [clearTargets, setClearTargets] = useState<StirlingFileStub[] | null>(
+ null,
+ );
const [renameTarget, setRenameTarget] = useState<StirlingFileStub | null>(
null,
);
@@ -828,6 +884,40 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
}
return counts;
}, [allFileStubs]);
+ // Foldered files are kept: the user filed them deliberately.
+ const clearableStubs = useMemo(
+ () => allFileStubs.filter((s) => s.folderId == null),
+ [allFileStubs],
+ );
+ const openClearTargetIds = useMemo(() => {
+ const open = new Set(state.files.ids.map(String));
+ return new Set(
+ (clearTargets ?? []).filter((s) => open.has(s.id)).map((s) => s.id),
+ );
+ }, [clearTargets, state.files.ids]);
+ const handleConfirmClearRecents = useCallback(
+ async (skipOpen: boolean) => {
+ const removed = await fileActions.clearRecentFiles(
+ (clearTargets ?? []).map((s) => s.id),
+ skipOpen ? new Set(state.files.ids.map(String)) : undefined,
+ );
+ // A cleared file's unsaved changes went with it; left set, the flag would
+ // prompt about them on the next navigation.
+ if (activeFileId && removed.includes(activeFileId as FileId)) {
+ navActions.setHasUnsavedChanges(false);
+ }
+ await refreshStubs();
+ },
+ [
+ clearTargets,
+ state.files.ids,
+ fileActions,
+ refreshStubs,
+ activeFileId,
+ navActions,
+ ],
+ );
+
const [groupOpen, setGroupOpen] = useState<Record<string, boolean>>({});
const setGroupOpenState = useCallback(
(id: string, open: boolean) =>
@@ -1209,6 +1299,11 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
onGoogleDrive={handleGoogleDriveClick}
onAddFiles={openNativeFilePicker}
onOpenFilesPage={() => navActions.setWorkbench("myFiles")}
+ onClearRecents={
+ clearableStubs.length > 0
+ ? () => setClearTargets(clearableStubs)
+ : undefined
+ }
/>
)}
</div>
@@ -1243,6 +1338,14 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
onConfirm={handleConfirmSidebarDelete}
/>
+ <ClearRecentsDialog
+ opened={clearTargets !== null}
+ clearCount={clearTargets?.length ?? 0}
+ openCount={openClearTargetIds.size}
+ onClose={() => setClearTargets(null)}
+ onConfirm={handleConfirmClearRecents}
+ />
+
{/* Getting-started checklist, floating above the footer (SaaS only). */}
<SidebarChecklistSlot />
diff --git a/frontend/src/editor/core/contexts/FileContext.tsx b/frontend/src/editor/core/contexts/FileContext.tsx
index 6fd60d333c..72e5067d2b 100644
--- a/frontend/src/editor/core/contexts/FileContext.tsx
+++ b/frontend/src/editor/core/contexts/FileContext.tsx
@@ -1178,6 +1178,35 @@ function FileContextInner({
// Don't clear IndexedDB automatically - only clear in-memory state
// IndexedDB should only be cleared when explicitly requested by user
},
+ clearRecentFiles: async (
+ fileIds: FileId[],
+ spare: ReadonlySet<string> = new Set(),
+ ) => {
+ // Re-read, since another tab may have filed a target into a folder or
+ // built a newer version on it. A file not stored yet stays a target.
+ const stored = new Map(
+ (await fileStorage.getAllStirlingFileStubs()).map((s) => [s.id, s]),
+ );
+ const targets = fileIds.filter((id) => {
+ const stub = stored.get(id);
+ return (
+ !spare.has(id) && stub?.folderId == null && stub?.isLeaf !== false
+ );
+ });
+ // A spared open file can be an older version no kept file needs.
+ const orphans = (await fileStorage.orphanedAncestorIds(targets)).filter(
+ (id) => !spare.has(id),
+ );
+ const doomed = [...targets, ...orphans];
+ if (indexedDB && enablePersistence) {
+ await indexedDB.deleteMultiple(doomed);
+ }
+ cancelPendingAdmissions(doomed);
+ forgetPdfAccess(doomed);
+ lifecycleManager.removeFiles(doomed, stateRef);
+ void reportFilesRemoved(doomed);
+ return doomed;
+ },
clearAllData: async () => {
for (const request of ownerRequests.current.values())
request.resolve(false);
diff --git a/frontend/src/editor/core/tests/stubbed/clear-recents.spec.ts b/frontend/src/editor/core/tests/stubbed/clear-recents.spec.ts
new file mode 100644
index 0000000000..8cea97280a
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/clear-recents.spec.ts
@@ -0,0 +1,101 @@
+import path from "path";
+import type { Page } from "@playwright/test";
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { uploadFiles } from "@editor/tests/helpers/ui-helpers";
+
+/** Stubbed coverage for the sidebar's Clear recents confirm flow. */
+
+const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
+const SAMPLE = path.join(FIXTURES, "sample.pdf");
+const OTHER = path.join(FIXTURES, "compare_sample_a.pdf");
+
+const rows = (page: Page) => page.locator(".file-sidebar-file-item");
+const dialog = (page: Page) => page.getByRole("dialog");
+
+async function openClearDialog(page: Page): Promise<void> {
+ await page
+ .locator(".file-sidebar-group-header-row", { hasText: "Recent" })
+ .hover();
+ await page.getByTestId("file-sidebar-clear-recents").click();
+ await expect(dialog(page)).toBeVisible();
+}
+
+async function openInViewer(page: Page): Promise<void> {
+ await page.locator('input[type="file"]').first().setInputFiles(SAMPLE);
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ await expect(firstPage).toBeVisible({ timeout: 30_000 });
+ await expect(firstPage.locator(".pdf-selection-layer")).toBeAttached({
+ timeout: 15_000,
+ });
+}
+
+async function confirmClear(page: Page): Promise<void> {
+ await page.getByTestId("file-sidebar-clear-recents-confirm").click();
+}
+
+test("a failed storage delete shows the error and clears nothing", async ({
+ page,
+}) => {
+ await uploadFiles(page, SAMPLE);
+ await openClearDialog(page);
+ await page.evaluate(() => {
+ IDBObjectStore.prototype.delete = function (this: IDBObjectStore) {
+ this.transaction.abort();
+ return {} as IDBRequest;
+ };
+ });
+ await confirmClear(page);
+
+ await expect(dialog(page)).toContainText("Could not clear. Try again.");
+ await page.keyboard.press("Escape");
+ await expect(rows(page)).toHaveCount(1);
+ await page.reload();
+ await expect(rows(page)).toHaveCount(1, { timeout: 10_000 });
+});
+
+test("files added while the dialog is open are not cleared", async ({
+ page,
+}) => {
+ await uploadFiles(page, SAMPLE);
+ await openClearDialog(page);
+ await expect(dialog(page)).toContainText("Clear 1 file from recents?");
+
+ await page.locator('[data-testid="file-input"]').setInputFiles(OTHER);
+ await expect(rows(page)).toHaveCount(2);
+ await confirmClear(page);
+
+ await expect(dialog(page)).toHaveCount(0);
+ await expect(rows(page)).toHaveCount(1);
+ await expect(rows(page).first()).toContainText("compare_sample_a.pdf");
+});
+
+test("clearing the open file with unsaved changes asks nothing and leaves no prompt behind", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await openInViewer(page);
+ // A highlight is the cheapest way to leave the viewer with unsaved changes.
+ const firstPage = page.locator('[data-page-index="0"]').first();
+ const box = await firstPage.boundingBox();
+ if (!box) throw new Error("Page wrapper has no bounding box");
+ const y = box.y + box.height * 0.105;
+ await page.mouse.move(box.x + box.width * 0.15, y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * 0.6, y, { steps: 15 });
+ await page.mouse.up();
+ await page.getByRole("button", { name: "Highlight" }).first().click();
+
+ await openClearDialog(page);
+ await confirmClear(page);
+ await expect(rows(page)).toHaveCount(0);
+ await expect(page.getByRole("button", { name: "Keep Working" })).toHaveCount(
+ 0,
+ );
+
+ // Leaving the viewer prompts if unsaved changes were left behind.
+ await page.getByTestId("my-files-button").click();
+ await expect(page).toHaveURL(/\/files/);
+ await expect(
+ page.getByRole("dialog", { name: "Unsaved Changes" }),
+ ).toHaveCount(0);
+});
diff --git a/frontend/src/editor/core/tests/stubbed/files-page.spec.ts b/frontend/src/editor/core/tests/stubbed/files-page.spec.ts
index d72baf17f9..64e2f0b3a9 100644
--- a/frontend/src/editor/core/tests/stubbed/files-page.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/files-page.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";
import { readFileSync } from "node:fs";
import type { Locator, Page, Route } from "@playwright/test";
import { DATABASE_CONFIGS } from "@editor/services/indexedDBManager";
+import { uploadFiles } from "@editor/tests/helpers/ui-helpers";
/** Stubbed coverage for the /files page UI invariants. */
@@ -12,6 +13,11 @@ interface SeedFile {
folderId?: string;
versionNumber?: number;
toolHistory?: Array<{ toolId: string; timestamp: number }>;
+ /** Desktop disk link; with isDirty, edits not yet saved back to disk. */
+ localFilePath?: string;
+ isDirty?: boolean;
+ /** Defaults to the seed time; earlier means local edits newer than the cloud copy. */
+ remoteStorageUpdatedAt?: number;
}
/** Seed IDB + register the cloud entries with the server stub. */
@@ -120,13 +126,17 @@ async function seedFiles(
toolHistory: f.toolHistory ?? [],
folderId: f.folderId ?? null,
remoteStorageId: f.remoteStorageId,
- remoteStorageUpdatedAt: f.remoteStorageId ? now : null,
+ remoteStorageUpdatedAt: f.remoteStorageId
+ ? (f.remoteStorageUpdatedAt ?? now)
+ : null,
remoteOwnerUsername: f.remoteStorageId ? "testuser" : null,
remoteOwnedByCurrentUser: f.remoteStorageId ? true : null,
remoteAccessRole: f.remoteStorageId ? "owner" : null,
remoteSharedViaLink: false,
remoteHasShareLinks: false,
remoteShareToken: null,
+ localFilePath: f.localFilePath,
+ isDirty: f.isDirty,
});
}
tx.oncomplete = () => db.close();
@@ -1501,4 +1511,191 @@ test.describe("Files page", () => {
expect(await cards.count()).toBeLessThan(COUNT / 2);
});
});
+
+ test.describe("Clear recents", () => {
+ test.use({ autoGoto: false });
+
+ test("clears everything outside folders, including open and unsaved files, and never touches the cloud", async ({
+ page,
+ }) => {
+ await stubStorageApis(page);
+ await seedFiles(
+ page,
+ [
+ { id: "loose", name: "loose.pdf", remoteStorageId: null },
+ { id: "cloudy", name: "cloudy.pdf", remoteStorageId: 7 },
+ {
+ id: "filed",
+ name: "filed.pdf",
+ remoteStorageId: null,
+ folderId: "vf-1",
+ },
+ {
+ id: "dirty",
+ name: "dirty.pdf",
+ remoteStorageId: null,
+ localFilePath: "C:/docs/dirty.pdf",
+ isDirty: true,
+ },
+ {
+ id: "edited",
+ name: "edited.pdf",
+ remoteStorageId: 8,
+ remoteStorageUpdatedAt: 1,
+ },
+ ],
+ [{ id: "vf-1", name: "Kept" }],
+ );
+ const serverDeletes: string[] = [];
+ page.on("request", (req) => {
+ if (req.method() === "DELETE" && req.url().includes("/api/v1/storage"))
+ serverDeletes.push(req.url());
+ });
+
+ await page.goto("/editor", { waitUntil: "domcontentloaded" });
+ const rows = page.locator(".file-sidebar-file-item");
+ await expect(rows).toHaveCount(5, { timeout: 10_000 });
+ // An upload lands open in the workbench; the clear closes it too.
+ await uploadFiles(
+ page,
+ `${import.meta.dirname}/../test-fixtures/sample.pdf`,
+ );
+ await expect(rows).toHaveCount(6);
+
+ // The grouped sidebar shows it on the Recent header, revealed on hover.
+ await page
+ .locator(".file-sidebar-group-header-row", { hasText: "Recent" })
+ .hover();
+ await page.getByTestId("file-sidebar-clear-recents").click();
+ const dialog = page.getByRole("dialog");
+ await expect(dialog).toContainText("Clear 5 files from recents?");
+ await expect(dialog).toContainText("This can't be undone.");
+ await expect(dialog).toContainText("1 of them is open in the workbench.");
+ await page.getByTestId("file-sidebar-clear-recents-confirm").click();
+
+ await expect(rows).toHaveCount(1);
+ await expect(rows.filter({ hasText: "filed.pdf" })).toHaveCount(1);
+ // Only kept files are left, so there is nothing more to clear.
+ await expect(page.getByTestId("file-sidebar-clear-recents")).toHaveCount(
+ 0,
+ );
+ expect(serverDeletes).toEqual([]);
+ });
+
+ test("files another tab filed or built on while the dialog is open are kept", async ({
+ page,
+ }) => {
+ await stubStorageApis(page);
+ await seedFiles(
+ page,
+ [
+ { id: "loose", name: "loose.pdf", remoteStorageId: null },
+ { id: "moved", name: "moved.pdf", remoteStorageId: null },
+ { id: "base", name: "base.pdf", remoteStorageId: null },
+ ],
+ [{ id: "vf-1", name: "Kept" }],
+ );
+ await page.goto("/editor", { waitUntil: "domcontentloaded" });
+ const rows = page.locator(".file-sidebar-file-item");
+ await expect(rows).toHaveCount(3, { timeout: 10_000 });
+
+ await page
+ .locator(".file-sidebar-group-header-row", { hasText: "Recent" })
+ .hover();
+ await page.getByTestId("file-sidebar-clear-recents").click();
+ await expect(page.getByRole("dialog")).toContainText(
+ "Clear 3 files from recents?",
+ );
+ // Written straight to storage, as another tab would: "moved" goes into a
+ // folder, and "base" gets a newer version on top of it.
+ await page.evaluate(
+ () =>
+ new Promise<void>((resolve, reject) => {
+ const open = indexedDB.open("stirling-pdf-files");
+ open.onerror = () => reject(open.error);
+ open.onsuccess = () => {
+ const db = open.result;
+ const tx = db.transaction("files", "readwrite");
+ const store = tx.objectStore("files");
+ const moved = store.get("moved");
+ moved.onsuccess = () =>
+ store.put({ ...moved.result, folderId: "vf-1" });
+ const base = store.get("base");
+ base.onsuccess = () => {
+ store.put({ ...base.result, isLeaf: false });
+ store.put({
+ ...base.result,
+ id: "base-v2",
+ fileId: "base-v2",
+ quickKey: "base-v2",
+ parentFileId: "base",
+ versionNumber: 2,
+ });
+ };
+ tx.oncomplete = () => {
+ db.close();
+ resolve();
+ };
+ tx.onerror = () => reject(tx.error);
+ };
+ }),
+ );
+ await page.getByTestId("file-sidebar-clear-recents-confirm").click();
+
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(rows.filter({ hasText: "loose.pdf" })).toHaveCount(0);
+ await expect(rows.filter({ hasText: "moved.pdf" })).toHaveCount(1);
+ // The new version still has the old one under it as history.
+ const history = await page.evaluate(
+ () =>
+ new Promise<boolean>((resolve, reject) => {
+ const open = indexedDB.open("stirling-pdf-files");
+ open.onerror = () => reject(open.error);
+ open.onsuccess = () => {
+ const db = open.result;
+ const get = db
+ .transaction("files")
+ .objectStore("files")
+ .get("base");
+ get.onsuccess = () => {
+ db.close();
+ resolve(get.result != null);
+ };
+ get.onerror = () => reject(get.error);
+ };
+ }),
+ );
+ expect(history).toBe(true);
+ });
+
+ test("Skip open files clears the rest and leaves open files alone", async ({
+ page,
+ }) => {
+ await stubStorageApis(page);
+ await seedFiles(page, [
+ { id: "loose", name: "loose.pdf", remoteStorageId: null },
+ ]);
+ await page.goto("/editor", { waitUntil: "domcontentloaded" });
+ const rows = page.locator(".file-sidebar-file-item");
+ await expect(rows).toHaveCount(1, { timeout: 10_000 });
+ await uploadFiles(
+ page,
+ `${import.meta.dirname}/../test-fixtures/sample.pdf`,
+ );
+ await expect(rows).toHaveCount(2);
+
+ await page
+ .locator(".file-sidebar-group-header-row", { hasText: "Recent" })
+ .hover();
+ await page.getByTestId("file-sidebar-clear-recents").click();
+ await expect(page.getByRole("dialog")).toContainText(
+ "1 of them is open in the workbench.",
+ );
+ await page.getByTestId("file-sidebar-clear-recents-skip-open").click();
+
+ await expect(page.getByRole("dialog")).toHaveCount(0);
+ await expect(rows).toHaveCount(1);
+ await expect(rows.first()).toContainText("sample.pdf");
+ });
+ });
});
diff --git a/frontend/src/editor/core/types/fileContext.ts b/frontend/src/editor/core/types/fileContext.ts
index 6286f0a964..99796581aa 100644
--- a/frontend/src/editor/core/types/fileContext.ts
+++ b/frontend/src/editor/core/types/fileContext.ts
@@ -450,6 +450,13 @@ export interface FileContextActions {
reorderFiles: (orderedFileIds: FileId[]) => void;
clearAllFiles: () => Promise<void>;
clearAllData: () => Promise<void>;
+ /** Delete unfiled files from storage and the workbench, with any ancestors no
+ * kept file needs. Rejects before closing anything if storage fails.
+ * Resolves to the ids removed. */
+ clearRecentFiles: (
+ fileIds: FileId[],
+ spare?: ReadonlySet<string>,
+ ) => Promise<FileId[]>;
// File pinning - accepts StirlingFile for safer type checking
pinFile: (file: StirlingFile) => void;