Skip to content

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

Faster folders, working breadcrumbs and bug fixes (#7675)

Reece Browne153da239c375
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 4c1084f028..0225fbb3a6 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -4289,6 +4289,7 @@ back = "Back"
backToFolder = "Back to {{folder}}"
backToMyFiles = "Back to File library"
breadcrumbs = "Folder path"
+breadcrumbsOverflow = "Show parent folders"
bulkActions = "Actions"
cancel = "Cancel"
classification = "Classification"
@@ -4410,7 +4411,6 @@ everywhereHint = "Deletes the file from this device and the cloud."
[filesPage.empty]
hint = "Drop PDFs anywhere on this page to upload, or use the New folder button to organize your files."
-newFolderCta = "Create folder"
title = "This folder is empty"
uploadCta = "Upload files"
@@ -4420,10 +4420,6 @@ offlineHint = "Reconnect to load your cloud library."
offlineTitle = "No cached cloud files"
title = "No cloud files yet"
-[filesPage.empty.local]
-hint = "Files saved without uploading stay here. Drop a file to add one."
-title = "No local-only files"
-
[filesPage.empty.noResults]
hint = "No files in this folder match your filter. Try a different term or clear the filter."
title = "No matching 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
new file mode 100644
index 0000000000..4856b8aba1
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.render.test.tsx
@@ -0,0 +1,97 @@
+import { describe, it, expect, vi } from "vitest";
+import { render as baseRender } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import type { FileId } from "@app/types/file";
+import type { StirlingFileStub } from "@app/types/fileContext";
+
+/**
+ * The grid's items are memoized so a selection click re-renders the cards whose
+ * selection changed rather than the whole folder. That only holds while every prop
+ * they take stays stable - one inline object or closure at a call site silently
+ * undoes it, with no visible symptom until a folder is large. These count renders
+ * so that regression fails here instead of in someone's 500-file folder.
+ */
+
+// @app/ui wraps Mantine, so the provider has to be in the tree.
+const render = (ui: Parameters<typeof baseRender>[0]) =>
+ baseRender(ui, { wrapper: MantineProvider });
+// Every card renders this exactly once, so its calls are a per-card render count.
+const badgeRenders: { n: number } = { n: 0 };
+vi.mock("@app/components/shared/PolicyBadges", () => ({
+ PolicyBadges: () => {
+ badgeRenders.n += 1;
+ return null;
+ },
+}));
+const buildStub = (id: string, name: string): StirlingFileStub =>
+ ({
+ id: id as FileId,
+ name,
+ type: "application/pdf",
+ size: 1_000,
+ lastModified: 0,
+ isLeaf: true,
+ originalFileId: id,
+ versionNumber: 1,
+ // Set so useLazyThumbnail short-circuits instead of reading IndexedDB.
+ thumbnailUrl: "data:image/svg+xml,%3Csvg/%3E",
+ }) 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");
+
+ const files = ["a", "b", "c", "d"].map((id) => buildStub(id, `${id}.pdf`));
+ const entries = files.map((file) => ({ kind: "file" as const, file }));
+
+ const props = {
+ entries,
+ viewMode: "grid" as const,
+ onSelectFile: () => {},
+ onOpenFolder: () => {},
+ onOpenFile: () => {},
+ onMoveFiles: () => {},
+ onMoveFolder: () => {},
+ onRenameFolder: () => {},
+ onDeleteFolder: () => {},
+ onChangeFolderAppearance: () => {},
+ onRemoveFiles: () => {},
+ onPromptMoveFiles: () => {},
+ };
+
+ const view = render(
+ <FileContextProvider>
+ <FileGrid {...props} selectedFileIds={new Set<FileId>()} />
+ </FileContextProvider>,
+ );
+ const cards = () =>
+ view.container.querySelectorAll(".files-page-card:not(.is-folder)");
+ expect(cards()).toHaveLength(4);
+ const initialRenders = badgeRenders.n;
+ expect(initialRenders).toBeGreaterThanOrEqual(4);
+
+ // Selecting one file changes isSelected for exactly one card. The rest take
+ // identical props, so memo should skip them.
+ view.rerender(
+ <FileContextProvider>
+ <FileGrid
+ {...props}
+ selectedFileIds={new Set<FileId>(["a" as FileId])}
+ />
+ </FileContextProvider>,
+ );
+ expect(cards()).toHaveLength(4);
+ expect(
+ view.container.querySelectorAll(".files-page-card.is-selected"),
+ ).toHaveLength(1);
+
+ // The point of the exercise: one card changed, so the re-render count moves by
+ // one card's worth and not four. Unmemoized items redraw the whole folder here.
+ const rerendered = badgeRenders.n - initialRenders;
+ const perCard = initialRenders / 4;
+ expect(rerendered).toBe(perCard);
+ // The real provider tree and four thumbnail-bearing cards cost seconds to mount,
+ // which the default budget cannot absorb alongside the rest of the suite.
+ }, 20_000);
+});
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsx
index d1cb9f32b6..2822b6b31d 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsx
@@ -5,6 +5,7 @@ import {
type FilesPageEntry,
} from "@app/components/filesPage/FileGrid";
import { FileContextProvider } from "@app/contexts/FileContext";
+import { NewFolderButton } from "@app/components/filesPage/NewFolderButton";
import type { StirlingFileStub } from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
@@ -109,6 +110,17 @@ export const Empty: Story = {
loading: false,
currentTab: "all",
onEmptyUpload: () => {},
- onEmptyCreateFolder: () => {},
+ // The page owns this control, so the story stands one up to keep both CTAs on
+ // screen here.
+ emptyNewFolderControl: (
+ <NewFolderButton
+ label="New folder"
+ size="md"
+ currentFolderId={null}
+ canAddLocalFolder={false}
+ onAddLocalFolder={() => {}}
+ onOpenDialog={() => {}}
+ />
+ ),
},
};
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
index 8ab5bdbca9..7fc393edb5 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
@@ -5,6 +5,7 @@ import { Button } from "@app/ui/Button";
import { ActionIcon } from "@app/ui/ActionIcon";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import { PolicyBadges as PolicyBadgeRow } from "@app/components/shared/PolicyBadges";
+import type { FileItemPolicyRef } from "@app/components/shared/PolicyBadges";
import FolderIcon from "@mui/icons-material/Folder";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
@@ -16,7 +17,6 @@ import DriveFileRenameOutlineIcon from "@mui/icons-material/DriveFileRenameOutli
import ContentCopyOutlinedIcon from "@mui/icons-material/ContentCopyOutlined";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import UploadFileIcon from "@mui/icons-material/UploadFile";
-import CreateNewFolderIcon from "@mui/icons-material/CreateNewFolder";
import SearchIcon from "@mui/icons-material/Search";
import { FileId } from "@app/types/file";
@@ -27,8 +27,11 @@ import {
folderKind,
} from "@app/types/folder";
import type { DiskFileEntry } from "@app/services/localFolderContents";
-import { useFolders } from "@app/contexts/FolderContext";
import { usePolicyFileBadges } from "@app/hooks/usePolicyFileBadges";
+import {
+ useVirtualFileRows,
+ rowHeightPx,
+} from "@app/components/filesPage/useVirtualFileRows";
import { StirlingFileStub } from "@app/types/fileContext";
import { formatFileSize, getFileDate } from "@app/utils/fileUtils";
import {
@@ -149,16 +152,65 @@ interface FileGridProps {
sortMode?: FilesPageSortMode;
onChangeSortMode?: (mode: FilesPageSortMode) => void;
/** Drives the empty-state copy. */
- currentTab?: "all" | "local" | "cloud" | "recent" | "shared" | "sharedByMe";
+ currentTab?: "all" | "cloud" | "recent" | "shared" | "sharedByMe";
/** A filter is applied; an empty result then means "no matches", not "no files". */
searchActive?: boolean;
/** Cloud reachability; switches the cloud empty-state copy. */
serverReachable?: boolean;
/** Empty-state CTA handlers; if absent the matching button hides. */
onEmptyUpload?: () => void;
- onEmptyCreateFolder?: () => void;
+ /** The New-folder control for the empty state, built by the page that owns the
+ * destinations. Passed in rather than rebuilt here so the empty state and the
+ * header cannot offer different things. */
+ emptyNewFolderControl?: React.ReactNode;
/** Non-null disables the New folder CTA with this reason as tooltip. */
newFolderDisabledReason?: string | null;
+ /**
+ * Where a failed drop reports its message. A prop rather than the folder
+ * context so the grid renders without a FolderProvider (its tests do), and
+ * so no item needs a context subscription that memoization would then fight.
+ */
+ onActionError?: (message: string) => void;
+}
+
+/**
+ * One stable dispatch object shared by every card and row. The grid's
+ * callback props change identity on every parent render, and per-item
+ * closures would too — either defeats React.memo and turns each selection
+ * click or landed thumbnail into a full-list re-render. Items call these
+ * with their own id/record instead; the ref always sees the current props,
+ * so behavior stays live while identity stays fixed. Selection-aware
+ * behavior (drag payloads, multi-move) lives here too, so items never hold
+ * the selection Set — whose identity changes on every click — as a prop.
+ */
+interface FileGridActions {
+ selectFile: (id: FileId, shiftKey: boolean, ctrlKey: boolean) => void;
+ openFolder: (id: FolderId) => void;
+ openFile: (file: StirlingFileStub) => void;
+ openDiskFile: (entry: DiskFileEntry) => void;
+ renameFolder: (folder: FolderRecord) => void;
+ deleteFolder: (folder: FolderRecord) => void;
+ changeFolderAppearance: (
+ folderId: FolderId,
+ appearance: { color?: string; icon?: string | null },
+ ) => void;
+ /**
+ * Failures surface here, not in the item: the memoized folder items would
+ * otherwise each need the folder context for its error banner, and one
+ * context subscription inside an item undoes what the memo buys.
+ */
+ dropFilesOnFolder: (fileIds: FileId[], target: FolderId) => void;
+ dropFolderOnFolder: (folderId: FolderId, target: FolderId) => void;
+ removeFile: (id: FileId) => void;
+ /** Move this file — or the whole selection when it is part of one. */
+ requestMoveFile: (id: FileId) => void;
+ /** Drag payload for this file — or the whole selection when selected. */
+ fileDragPayload: (id: FileId) => string;
+ saveToServer: (file: StirlingFileStub) => void;
+ versionHistory: (file: StirlingFileStub) => void;
+ downloadFile: (file: StirlingFileStub) => void;
+ renameFile: (file: StirlingFileStub) => void;
+ duplicateFile: (file: StirlingFileStub) => void;
}
export function FileGrid(props: FileGridProps & { loading?: boolean }) {
@@ -170,10 +222,78 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {
searchActive,
serverReachable,
onEmptyUpload,
- onEmptyCreateFolder,
- newFolderDisabledReason,
+ emptyNewFolderControl,
} = props;
+ const latest = useRef(props);
+ latest.current = props;
+ const { t } = useTranslation();
+ const translateRef = useRef(t);
+ translateRef.current = t;
+ // One subscription for the whole grid: every row calling the badge hook
+ // would rebuild the full badge map per row on any file or run change. The
+ // hook keeps per-file array identity stable across rebuilds, so memoized
+ // items re-render only when their own badges change.
+ const policyBadges = usePolicyFileBadges();
+ const actions = useMemo<FileGridActions>(() => {
+ const reportDrop = (err: unknown, label: string) => {
+ console.error(`[FileGrid] ${label}`, err);
+ const translate = translateRef.current;
+ latest.current.onActionError?.(
+ err instanceof Error
+ ? translate("filesPage.error.actionFailedDetail", {
+ action: label,
+ message: err.message,
+ defaultValue: `Could not ${label}: ${err.message}`,
+ })
+ : translate("filesPage.error.actionFailed", {
+ action: label,
+ defaultValue: `Could not ${label}.`,
+ }),
+ );
+ };
+ return {
+ selectFile: (id, shiftKey, ctrlKey) =>
+ latest.current.onSelectFile(id, shiftKey, ctrlKey),
+ openFolder: (id) => latest.current.onOpenFolder(id),
+ openFile: (file) => latest.current.onOpenFile(file),
+ openDiskFile: (entry) => latest.current.onOpenDiskFile?.(entry),
+ renameFolder: (folder) => latest.current.onRenameFolder(folder),
+ deleteFolder: (folder) => latest.current.onDeleteFolder(folder),
+ changeFolderAppearance: (folderId, appearance) =>
+ latest.current.onChangeFolderAppearance(folderId, appearance),
+ dropFilesOnFolder: (fileIds, target) => {
+ Promise.resolve(latest.current.onMoveFiles(fileIds, target)).catch(
+ (err) => reportDrop(err, "move files into folder"),
+ );
+ },
+ dropFolderOnFolder: (folderId, target) => {
+ Promise.resolve(latest.current.onMoveFolder(folderId, target)).catch(
+ (err) => reportDrop(err, "move folder"),
+ );
+ },
+ removeFile: (id) => latest.current.onRemoveFiles([id]),
+ requestMoveFile: (id) => {
+ const selected = latest.current.selectedFileIds;
+ latest.current.onPromptMoveFiles(
+ selected.has(id) ? Array.from(selected) : [id],
+ );
+ },
+ fileDragPayload: (id) => {
+ const selected = latest.current.selectedFileIds;
+ return serialiseFilesPageDragPayload({
+ kind: "files",
+ fileIds: selected.has(id) ? Array.from(selected) : [id],
+ });
+ },
+ saveToServer: (file) => latest.current.onSaveToServer?.(file),
+ versionHistory: (file) => latest.current.onVersionHistory?.(file),
+ downloadFile: (file) => latest.current.onDownloadFile?.(file),
+ renameFile: (file) => latest.current.onRenameFile?.(file),
+ duplicateFile: (file) => latest.current.onDuplicateFile?.(file),
+ };
+ }, []);
+
if (loading && entries.length === 0) {
return <SkeletonGrid viewMode={viewMode} />;
}
@@ -185,8 +305,7 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {
searchActive={searchActive}
serverReachable={serverReachable}
onUpload={onEmptyUpload}
- onCreateFolder={onEmptyCreateFolder}
- newFolderDisabledReason={newFolderDisabledReason}
+ newFolderControl={emptyNewFolderControl}
/>
);
// When a filter empties the list view, keep the column headers in place and
@@ -195,7 +314,7 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {
if (viewMode === "list" && searchActive) {
return (
<>
- <ListView {...props} />
+ <ListView {...props} actions={actions} policyBadges={policyBadges} />
{emptyState}
</>
);
@@ -204,9 +323,11 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {
}
if (viewMode === "list") {
- return <ListView {...props} />;
+ return (
+ <ListView {...props} actions={actions} policyBadges={policyBadges} />
+ );
}
- return <GridView {...props} />;
+ return <GridView {...props} actions={actions} policyBadges={policyBadges} />;
}
function SkeletonGrid({ viewMode }: { viewMode: FilesPageViewMode }) {
@@ -263,16 +384,15 @@ function SkeletonGrid({ viewMode }: { viewMode: FilesPageViewMode }) {
interface EmptyStateProps {
/** Drives copy + iconography. */
- tab?: "all" | "local" | "cloud" | "recent" | "shared" | "sharedByMe";
+ tab?: "all" | "cloud" | "recent" | "shared" | "sharedByMe";
/** When true the empty list is the result of a filter, not a bare folder. */
searchActive?: boolean;
/** Switches the cloud empty-state copy. */
serverReachable?: boolean;
/** CTA handlers; absent => button hidden. */
onUpload?: () => void;
- onCreateFolder?: () => void;
- /** Non-null disables New folder CTA with this reason. */
- newFolderDisabledReason?: string | null;
+ /** Absent => no New folder CTA. */
+ newFolderControl?: React.ReactNode;
}
function EmptyState({
@@ -280,8 +400,7 @@ function EmptyState({
searchActive = false,
serverReachable = true,
onUpload,
- onCreateFolder,
- newFolderDisabledReason,
+ newFolderControl,
}: EmptyStateProps) {
const { t } = useTranslation();
@@ -308,14 +427,6 @@ function EmptyState({
const { titleKey, titleFallback, hintKey, hintFallback } = (() => {
switch (tab) {
- case "local":
- return {
- titleKey: "filesPage.empty.local.title",
- titleFallback: "No local-only files",
- hintKey: "filesPage.empty.local.hint",
- hintFallback:
- "Files saved without uploading stay here. Drop a file to add one.",
- };
case "cloud":
return serverReachable
? {
@@ -368,8 +479,7 @@ function EmptyState({
const readOnlyTab =
tab === "recent" || tab === "shared" || tab === "sharedByMe";
const showUpload = Boolean(onUpload) && !readOnlyTab;
- const showCreateFolder =
- Boolean(onCreateFolder) && !readOnlyTab && tab !== "local";
+ const showCreateFolder = Boolean(newFolderControl) && !readOnlyTab;
const showCtas = showUpload || showCreateFolder;
return (
<div className="files-page-empty">
@@ -389,62 +499,45 @@ function EmptyState({
{t("filesPage.empty.uploadCta", "Upload files")}
</Button>
)}
- {showCreateFolder &&
- (newFolderDisabledReason ? (
- <Tooltip
- label={newFolderDisabledReason}
- withinPortal
- multiline
- w={260}
- >
- {/* Wrap so tooltip hovers while button is disabled. */}
- <span style={{ display: "inline-flex" }}>
- <Button
- size="md"
- variant="secondary"
- leftSection={<CreateNewFolderIcon fontSize="small" />}
- disabled
- style={{ pointerEvents: "auto" }}
- >
- {t("filesPage.empty.newFolderCta", "Create folder")}
- </Button>
- </span>
- </Tooltip>
- ) : (
- <Button
- size="md"
- variant="secondary"
- leftSection={<CreateNewFolderIcon fontSize="small" />}
- onClick={onCreateFolder}
- >
- {t("filesPage.empty.newFolderCta", "Create folder")}
- </Button>
- ))}
+ {showCreateFolder && newFolderControl}
</div>
)}
</div>
);
}
-function GridView(props: FileGridProps) {
- const {
- entries,
- selectedFileIds,
- activeWorkspaceFileIds,
- onSelectFile,
- onOpenFolder,
- onOpenFile,
- onOpenDiskFile,
- onMoveFiles,
- onMoveFolder,
- onRenameFolder,
- onDeleteFolder,
- onChangeFolderAppearance,
- } = props;
- const menuHandlersFor = useFileMenuHandlers(props);
+function GridView({
+ entries,
+ selectedFileIds,
+ activeWorkspaceFileIds,
+ onSaveToServer,
+ onVersionHistory,
+ onDownloadFile,
+ onRenameFile,
+ onDuplicateFile,
+ saveToServerDisabledReason,
+ serverReachable,
+ actions,
+ policyBadges,
+}: FileGridProps & {
+ actions: FileGridActions;
+ policyBadges: Map<string, FileItemPolicyRef[]>;
+}) {
+ const { range, padTop, padBottom, setContainer } = useVirtualFileRows(
+ entries.length,
+ rowHeightPx(true),
+ true,
+ );
return (
- <div className="files-page-grid" role="list">
- {entries.map((entry) => {
+ <div className="files-page-grid" role="list" ref={setContainer}>
+ {padTop > 0 && (
+ <div
+ aria-hidden="true"
+ className="files-page-virtual-pad"
+ style={{ height: padTop }}
+ />
+ )}
+ {entries.slice(range.start, range.end).map((entry) => {
if (entry.kind === "folder" && entry.folder) {
return (
<FolderCard
@@ -452,17 +545,8 @@ function GridView(props: FileGridProps) {
folder={entry.folder}
fileCount={entry.folderFileCount ?? 0}
parentPath={entry.parentPath}
- selectedFileIds={selectedFileIds}
- onOpen={() => onOpenFolder(entry.folder!.id)}
- onRename={() => onRenameFolder(entry.folder!)}
- onDelete={() => onDeleteFolder(entry.folder!)}
- onChangeAppearance={(appearance) =>
- onChangeFolderAppearance(entry.folder!.id, appearance)
- }
- onMoveFiles={(fileIds) => onMoveFiles(fileIds, entry.folder!.id)}
- onMoveFolder={(folderId) =>
- onMoveFolder(folderId, entry.folder!.id)
- }
+ serverReachable={serverReachable ?? false}
+ actions={actions}
/>
);
}
@@ -471,7 +555,7 @@ function GridView(props: FileGridProps) {
<DiskFileCard
key={`disk-${entry.disk.path}`}
entry={entry.disk}
- onOpen={() => onOpenDiskFile?.(entry.disk!)}
+ actions={actions}
/>
);
}
@@ -485,18 +569,27 @@ function GridView(props: FileGridProps) {
isInWorkspace={
activeWorkspaceFileIds?.has(entry.file.id) ?? false
}
- selectedFileIds={selectedFileIds}
multiSelectActive={selectedFileIds.size >= 2}
- onClick={(e) =>
- onSelectFile(entry.file!.id, e.shiftKey, e.metaKey || e.ctrlKey)
- }
- onDoubleClick={() => onOpenFile(entry.file!)}
- {...menuHandlersFor(entry.file)}
+ downloadAvailable={Boolean(onDownloadFile)}
+ renameAvailable={Boolean(onRenameFile)}
+ duplicateAvailable={Boolean(onDuplicateFile)}
+ saveToServerAvailable={Boolean(onSaveToServer)}
+ versionHistoryAvailable={Boolean(onVersionHistory)}
+ saveToServerDisabledReason={saveToServerDisabledReason}
+ badges={policyBadges.get(entry.file.id) ?? NO_BADGES}
+ actions={actions}
/>
);
}
return null;
})}
+ {padBottom > 0 && (
+ <div
+ aria-hidden="true"
+ className="files-page-virtual-pad"
+ style={{ height: padBottom }}
+ />
+ )}
</div>
);
}
@@ -506,31 +599,19 @@ interface FolderCardProps {
fileCount: number;
/** Subtitle for search results outside current folder. */
parentPath?: string;
- selectedFileIds: Set<FileId>;
- onOpen: () => void;
- onRename: () => void;
- onDelete: () => void;
- onChangeAppearance: (appearance: {
- color?: string;
- icon?: string | null;
- }) => void;
- onMoveFiles: (fileIds: FileId[]) => void | Promise<void>;
- onMoveFolder: (folderId: FolderId) => void | Promise<void>;
+ serverReachable: boolean;
+ actions: FileGridActions;
}
-function FolderCard({
+const FolderCard = React.memo(function FolderCard({
folder,
fileCount,
parentPath,
- onOpen,
- onRename,
- onDelete,
- onChangeAppearance,
- onMoveFiles,
- onMoveFolder,
+ serverReachable,
+ actions,
}: FolderCardProps) {
const { t } = useTranslation();
- const { serverReachable, setError } = useFolders();
+ const onOpen = () => actions.openFolder(folder.id);
// Only a server folder can go offline: the other kinds take their name, look and
// lifetime from elsewhere, so their edit items are hidden rather than disabled.
const kind = folderKind(folder);
@@ -541,29 +622,16 @@ function FolderCard({
"filesPage.offlineNoFolderEdits",
"Offline - folder changes are disabled.",
);
- const surfaceDrop = (err: unknown, label: string) => {
- console.error(`[FolderCard] ${label}`, err);
- setError(
- err instanceof Error
- ? `Could not ${label}: ${err.message}`
- : `Could not ${label}.`,
- );
- };
const kebabRef = useRef<HTMLButtonElement>(null);
const { handlers: dropHandlers, isOver: isDropTarget } = useDropTarget({
dragType: FILES_PAGE_DRAG_TYPE,
onDrop: (e) => {
const payload = parseFilesPageDragPayload(e.dataTransfer);
if (!payload) return;
- // Surface rejections instead of silent no-op on IDB failures.
if (payload.kind === "files") {
- Promise.resolve(onMoveFiles(payload.fileIds)).catch((err) =>
- surfaceDrop(err, "move files into folder"),
- );
+ actions.dropFilesOnFolder(payload.fileIds, folder.id);
} else if (payload.kind === "folder") {
- Promise.resolve(onMoveFolder(payload.folderId)).catch((err) =>
- surfaceDrop(err, "move folder"),
- );
+ actions.dropFolderOnFolder(payload.folderId, folder.id);
}
},
});
@@ -655,7 +723,7 @@ function FolderCard({
<Menu.Item
color="red"
leftSection={<DeleteIcon fontSize="small" />}
- onClick={onDelete}
+ onClick={() => actions.deleteFolder(folder)}
>
{t(
"filesPage.removeLocalFolder",
@@ -667,7 +735,7 @@ function FolderCard({
<>
<Menu.Item
leftSection={<DriveFileRenameOutlineIcon fontSize="small" />}
- onClick={onRename}
+ onClick={() => actions.renameFolder(folder)}
disabled={editsDisabled}
title={editsDisabled ? offlineHint : undefined}
>
@@ -679,14 +747,16 @@ function FolderCard({
</Menu.Label>
<FolderAppearancePicker
folder={folder}
- onChange={onChangeAppearance}
+ onChange={(appearance) =>
+ actions.changeFolderAppearance(folder.id, appearance)
+ }
disabled={editsDisabled}
/>
<Menu.Divider />
<Menu.Item
color="red"
leftSection={<DeleteIcon fontSize="small" />}
- onClick={onDelete}
+ onClick={() => actions.deleteFolder(folder)}
disabled={editsDisabled}
title={editsDisabled ? offlineHint : undefined}
>
@@ -699,50 +769,47 @@ function FolderCard({
</div>
</div>
);
-}
+});
-/** Shield badges for the policies that have run on a file. */
-function PolicyBadges({ fileId }: { fileId: string }) {
- const badges = usePolicyFileBadges().get(fileId) ?? [];
- return <PolicyBadgeRow policies={badges} />;
-}
+/** Stable empty value so badge-less rows keep identical props across renders. */
+const NO_BADGES: FileItemPolicyRef[] = [];
/** Per-file actions. Shared verbatim by the grid card and the list row, and
* kept in step with the file sidebar's kebab so both surfaces offer the same. */
interface FileActionsMenuProps {
file: StirlingFileStub;
triggerRef: React.RefObject<HTMLButtonElement | null>;
- onOpen: () => void;
- onMove: () => void;
- onRemove: () => void;
- onDownload?: () => void;
- onRename?: () => void;
- onDuplicate?: () => void;
- onSaveToServer?: () => void;
- onVersionHistory?: () => void;
+ /** Download / rename / duplicate menu items offered. */
+ downloadAvailable: boolean;
+ renameAvailable: boolean;
+ duplicateAvailable: boolean;
+ /** Kebab Save to server offered; only fires when file is local-only. */
+ saveToServerAvailable: boolean;
+ /** Version-history menu item offered; shown only when file has >1 version. */
+ versionHistoryAvailable: boolean;
+ /** When set, the kebab Save to server is disabled with this tooltip. */
saveToServerDisabledReason?: string | null;
+ actions: FileGridActions;
}
function FileActionsMenu({
file,
triggerRef,
- onOpen,
- onMove,
- onRemove,
- onDownload,
- onRename,
- onDuplicate,
- onSaveToServer,
- onVersionHistory,
+ downloadAvailable,
+ renameAvailable,
+ duplicateAvailable,
+ saveToServerAvailable,
+ versionHistoryAvailable,
saveToServerDisabledReason,
+ actions,
}: FileActionsMenuProps) {
const { t } = useTranslation();
const terminology = useFileActionTerminology();
const DownloadIcon = useFileActionIcons().download;
const showSaveToServer =
- Boolean(onSaveToServer) && file.remoteStorageId == null;
+ saveToServerAvailable && file.remoteStorageId == null;
const showVersionHistory =
- Boolean(onVersionHistory) && (file.versionNumber ?? 1) > 1;
+ versionHistoryAvailable && (file.versionNumber ?? 1) > 1;
return (
<Menu shadow="md" position="bottom-end" withinPortal width={220}>
<Menu.Target>
@@ -762,7 +829,7 @@ function FileActionsMenu({
leftSection={<OpenInNewIcon fontSize="small" />}
onClick={(e) => {
e.stopPropagation();
- onOpen();
+ actions.openFile(file);
}}
>
{t("filesPage.addToWorkspace", "Add to workspace")}
@@ -772,44 +839,46 @@ function FileActionsMenu({
leftSection={<DriveFileMoveIcon fontSize="small" />}
onClick={(e) => {
e.stopPropagation();
- onMove();
+ actions.requestMoveFile(file.id);
}}
data-testid="file-menu-move-to"
>
{t("filesPage.moveTo", "Move to…")}
</Menu.Item>
- {(onDownload || onRename || onDuplicate) && <Menu.Divider />}
- {onDownload && (
+ {(downloadAvailable || renameAvailable || duplicateAvailable) && (
+ <Menu.Divider />
+ )}
+ {downloadAvailable && (
<Menu.Item
leftSection={<DownloadIcon fontSize="small" />}
onClick={(e) => {
e.stopPropagation();
- onDownload();
+ actions.downloadFile(file);
}}
data-testid="file-menu-download"
>
{terminology.download}
</Menu.Item>
)}
- {onRename && (
+ {renameAvailable && (
<Menu.Item
leftSection={<DriveFileRenameOutlineIcon fontSize="small" />}
onClick={(e) => {
e.stopPropagation();
- onRename();
+ actions.renameFile(file);
}}
data-testid="file-menu-rename"
>
{t("filesPage.rename", "Rename")}
</Menu.Item>
)}
- {onDuplicate && (
+ {duplicateAvailable && (
<Menu.Item
leftSection={<ContentCopyOutlinedIcon fontSize="small" />}
onClick={(e) => {
e.stopPropagation();
- onDuplicate();
+ actions.duplicateFile(file);
}}
data-testid="file-menu-duplicate"
>
@@ -820,7 +889,7 @@ function FileActionsMenu({
{(showSaveToServer || showVersionHistory) && <Menu.Divider />}
{/* Per-file Save to server; shown for local-only files. When
storage is off it stays visible but disabled with a tooltip. */}
- {showSaveToServer && onSaveToServer && (
+ {showSaveToServer && (
<Tooltip
label={saveToServerDisabledReason}
disabled={!saveToServerDisabledReason}
@@ -834,7 +903,7 @@ function FileActionsMenu({
disabled={Boolean(saveToServerDisabledReason)}
onClick={(e) => {
e.stopPropagation();
- onSaveToServer();
+ actions.saveToServer(file);
}}
style={
saveToServerDisabledReason
@@ -846,12 +915,12 @@ function FileActionsMenu({
</Menu.Item>
</Tooltip>
)}
- {showVersionHistory && onVersionHistory && (
+ {showVersionHistory && (
<Menu.Item
leftSection={<HistoryIcon fontSize="small" />}
onClick={(e) => {
e.stopPropagation();
- onVersionHistory();
+ actions.versionHistory(file);
}}
>
{t("filesPage.versionHistory", "Version history")}
@@ -864,7 +933,7 @@ function FileActionsMenu({
leftSection={<DeleteIcon fontSize="small" />}
onClick={(e) => {
e.stopPropagation();
- onRemove();
+ actions.removeFile(file.id);
}}
>
{t("filesPage.remove", "Delete")}
@@ -874,77 +943,42 @@ function FileActionsMenu({
);
}
-/** Binds one file's kebab handlers, so grid and list wire them identically. */
-function useFileMenuHandlers(
- props: FileGridProps,
-): (file: StirlingFileStub) => FileMenuHandlers {
- const {
- selectedFileIds,
- onRemoveFiles,
- onPromptMoveFiles,
- onSaveToServer,
- onVersionHistory,
- onDownloadFile,
- onRenameFile,
- onDuplicateFile,
- saveToServerDisabledReason,
- } = props;
- return (file: StirlingFileStub) => ({
- onRemove: () => onRemoveFiles([file.id]),
- // A move acts on the whole selection when this file is part of it.
- onMove: () =>
- onPromptMoveFiles(
- selectedFileIds.has(file.id) ? Array.from(selectedFileIds) : [file.id],
- ),
- onDownload: onDownloadFile ? () => onDownloadFile(file) : undefined,
- onRename: onRenameFile ? () => onRenameFile(file) : undefined,
- onDuplicate: onDuplicateFile ? () => onDuplicateFile(file) : undefined,
- onSaveToServer: onSaveToServer ? () => onSaveToServer(file) : undefined,
- onVersionHistory: onVersionHistory
- ? () => onVersionHistory(file)
- : undefined,
- saveToServerDisabledReason,
- });
-}
-
-/** Per-file kebab handlers, shared by the card and row wrappers. */
-interface FileMenuHandlers {
- onRemove: () => void;
- onMove: () => void;
- onDownload?: () => void;
- onRename?: () => void;
- onDuplicate?: () => void;
- /** Kebab Save to server; only fires when file is local-only. */
- onSaveToServer?: () => void;
- /** Open the version-history modal; shown only when file has >1 version. */
- onVersionHistory?: () => void;
- /** When set, the kebab Save to server is disabled with this tooltip. */
- saveToServerDisabledReason?: string | null;
-}
-
-interface FileCardProps extends FileMenuHandlers {
+interface FileCardProps {
file: StirlingFileStub;
isSelected: boolean;
isInWorkspace: boolean;
/** Subtitle for search results outside current folder. */
parentPath?: string;
- selectedFileIds: Set<FileId>;
/** Shows the checkbox once 2+ files are selected. */
multiSelectActive: boolean;
- onClick: (e: React.MouseEvent) => void;
- onDoubleClick: () => void;
+ /** Download / rename / duplicate menu items offered. */
+ downloadAvailable: boolean;
+ renameAvailable: boolean;
+ duplicateAvailable: boolean;
+ /** Kebab Save to server offered; only fires when file is local-only. */
+ saveToServerAvailable: boolean;
+ /** Version-history menu item offered; shown only when file has >1 version. */
+ versionHistoryAvailable: boolean;
+ /** When set, the kebab Save to server is disabled with this tooltip. */
+ saveToServerDisabledReason?: string | null;
+ badges: FileItemPolicyRef[];
+ actions: FileGridActions;
}
-function FileCard({
+const FileCard = React.memo(function FileCard({
file,
parentPath,
isSelected,
isInWorkspace,
- selectedFileIds,
multiSelectActive,
- onClick,
- onDoubleClick,
- ...menuHandlers
+ downloadAvailable,
+ renameAvailable,
+ duplicateAvailable,
+ saveToServerAvailable,
+ versionHistoryAvailable,
+ saveToServerDisabledReason,
+ badges,
+ actions,
}: FileCardProps) {
const { t } = useTranslation();
const cardRef = useRef<HTMLDivElement>(null);
@@ -954,16 +988,25 @@ function FileCard({
[file.lastModified],
);
+ const onClick = useCallback(
+ (e: React.MouseEvent) =>
+ actions.selectFile(file.id, e.shiftKey, e.metaKey || e.ctrlKey),
+ [actions, file.id],
+ );
+ const onDoubleClick = useCallback(
+ () => actions.openFile(file),
+ [actions, file],
+ );
+
const handleDragStart = useCallback(
(e: React.DragEvent<HTMLDivElement>) => {
- const fileIds = isSelected ? Array.from(selectedFileIds) : [file.id];
e.dataTransfer.setData(
FILES_PAGE_DRAG_TYPE,
- serialiseFilesPageDragPayload({ kind: "files", fileIds }),
+ actions.fileDragPayload(file.id),
);
e.dataTransfer.effectAllowed = "move";
},
- [file.id, isSelected, selectedFileIds],
+ [actions, file.id],
);
const extension = file.name.split(".").pop()?.toUpperCase() ?? "";
@@ -1019,14 +1062,9 @@ function FileCard({
<Checkbox
checked={isSelected}
onClick={(e) => {
- // Synthesise ctrl-click so parent takes the toggle branch.
+ // Ctrl-click semantics: toggle this file in/out of the selection.
e.stopPropagation();
- onClick({
- ...e,
- shiftKey: false,
- ctrlKey: true,
- metaKey: true,
- });
+ actions.selectFile(file.id, false, true);
}}
onChange={() => {
/* handled by onClick */
@@ -1070,45 +1108,48 @@ function FileCard({
·
</span>
<span>{fileDate}</span>
- <PolicyBadges fileId={file.id} />
+ <PolicyBadgeRow policies={badges} />
</div>
</div>
<div className="files-page-card-actions">
<FileActionsMenu
file={file}
triggerRef={kebabRef}
- onOpen={onDoubleClick}
- {...menuHandlers}
+ downloadAvailable={downloadAvailable}
+ renameAvailable={renameAvailable}
+ duplicateAvailable={duplicateAvailable}
+ saveToServerAvailable={saveToServerAvailable}
+ versionHistoryAvailable={versionHistoryAvailable}
+ saveToServerDisabledReason={saveToServerDisabledReason}
+ actions={actions}
/>
</div>
</div>
);
-}
+});
-function ListView(
- props: FileGridProps & {
- sortMode?: FilesPageSortMode;
- onChangeSortMode?: (next: FilesPageSortMode) => void;
- },
-) {
- const {
- entries,
- selectedFileIds,
- activeWorkspaceFileIds,
- onSelectFile,
- onSetSelection,
- onOpenFolder,
- onOpenFile,
- onOpenDiskFile,
- onMoveFiles,
- onMoveFolder,
- onRenameFolder,
- onDeleteFolder,
- onChangeFolderAppearance,
- sortMode,
- onChangeSortMode,
- } = props;
- const menuHandlersFor = useFileMenuHandlers(props);
+function ListView({
+ entries,
+ selectedFileIds,
+ activeWorkspaceFileIds,
+ onSetSelection,
+ onSaveToServer,
+ onVersionHistory,
+ onDownloadFile,
+ onRenameFile,
+ onDuplicateFile,
+ saveToServerDisabledReason,
+ sortMode,
+ onChangeSortMode,
+ serverReachable,
+ actions,
+ policyBadges,
+}: FileGridProps & {
+ sortMode?: FilesPageSortMode;
+ onChangeSortMode?: (next: FilesPageSortMode) => void;
+ actions: FileGridActions;
+ policyBadges: Map<string, FileItemPolicyRef[]>;
+}) {
const { t } = useTranslation();
// Tri-state header checkbox state - computed from current entries.
@@ -1151,8 +1192,13 @@ function ListView(
},
});
+ const { range, padTop, padBottom, setContainer } = useVirtualFileRows(
+ entries.length,
+ rowHeightPx(false),
+ false,
+ );
return (
- <div className="files-page-list" role="grid">
+ <div className="files-page-list" role="grid" ref={setContainer}>
{/* Each direct child is a columnheader: a role="row" may only own cells, so
the sort controls and the select-all box have to sit inside one. */}
<div className="files-page-list-row is-header" role="row">
@@ -1197,7 +1243,14 @@ function ListView(
</span>
<span aria-hidden="true" />
</div>
- {entries.map((entry) => {
+ {padTop > 0 && (
+ <div
+ aria-hidden="true"
+ className="files-page-virtual-pad"
+ style={{ height: padTop }}
+ />
+ )}
+ {entries.slice(range.start, range.end).map((entry) => {
if (entry.kind === "folder" && entry.folder) {
return (
<FolderRow
@@ -1205,16 +1258,8 @@ function ListView(
folder={entry.folder}
fileCount={entry.folderFileCount ?? 0}
parentPath={entry.parentPath}
- onOpen={() => onOpenFolder(entry.folder!.id)}
- onRename={() => onRenameFolder(entry.folder!)}
- onDelete={() => onDeleteFolder(entry.folder!)}
- onChangeAppearance={(appearance) =>
- onChangeFolderAppearance(entry.folder!.id, appearance)
- }
- onDropFiles={(fileIds) => onMoveFiles(fileIds, entry.folder!.id)}
- onDropFolder={(folderId) =>
- onMoveFolder(folderId, entry.folder!.id)
- }
+ serverReachable={serverReachable ?? false}
+ actions={actions}
/>
);
}
@@ -1223,7 +1268,7 @@ function ListView(
<DiskFileRow
key={`disk-${entry.disk.path}`}
entry={entry.disk}
- onOpen={() => onOpenDiskFile?.(entry.disk!)}
+ actions={actions}
/>
);
}
@@ -1237,18 +1282,27 @@ function ListView(
isInWorkspace={
activeWorkspaceFileIds?.has(entry.file.id) ?? false
}
- selectedFileIds={selectedFileIds}
multiSelectActive={selectedFileIds.size >= 2}
- onClick={(e) =>
- onSelectFile(entry.file!.id, e.shiftKey, e.metaKey || e.ctrlKey)
- }
- onOpen={() => onOpenFile(entry.file!)}
- {...menuHandlersFor(entry.file)}
+ downloadAvailable={Boolean(onDownloadFile)}
+ renameAvailable={Boolean(onRenameFile)}
+ duplicateAvailable={Boolean(onDuplicateFile)}
+ saveToServerAvailable={Boolean(onSaveToServer)}
+ versionHistoryAvailable={Boolean(onVersionHistory)}
+ saveToServerDisabledReason={saveToServerDisabledReason}
+ badges={policyBadges.get(entry.file.id) ?? NO_BADGES}
+ actions={actions}
/>
);
}
return null;
})}
+ {padBottom > 0 && (
+ <div
+ aria-hidden="true"
+ className="files-page-virtual-pad"
+ style={{ height: padBottom }}
+ />
+ )}
</div>
);
}
@@ -1257,30 +1311,19 @@ interface FolderRowProps {
folder: FolderRecord;
fileCount: number;
parentPath?: string;
- onOpen: () => void;
- onRename: () => void;
- onDelete: () => void;
- onChangeAppearance: (appearance: {
- color?: string;
- icon?: string | null;
- }) => void;
- onDropFiles: (fileIds: FileId[]) => void | Promise<void>;
- onDropFolder: (folderId: FolderId) => void | Promise<void>;
+ serverReachable: boolean;
+ actions: FileGridActions;
}
-function FolderRow({
+const FolderRow = React.memo(function FolderRow({
folder,
fileCount,
parentPath,
- onOpen,
- onRename,
- onDelete,
- onChangeAppearance,
- onDropFiles,
- onDropFolder,
+ serverReachable,
+ actions,
}: FolderRowProps) {
const { t } = useTranslation();
- const { serverReachable, setError } = useFolders();
+ const onOpen = () => actions.openFolder(folder.id);
// Kinds gate the edit items, as in FolderCard.
const kind = folderKind(folder);
const originBadge = useFolderOriginBadge(folder);
@@ -1290,21 +1333,6 @@ function FolderRow({
"filesPage.offlineNoFolderEdits",
"Offline - folder changes are disabled.",
);
- const surfaceDrop = (err: unknown, label: string) => {
- console.error(`[FolderRow] ${label}`, err);
- setError(
- err instanceof Error
- ? t("filesPage.error.actionFailedDetail", {
- action: label,
- message: err.message,
- defaultValue: `Could not ${label}: ${err.message}`,
- })
- : t("filesPage.error.actionFailed", {
- action: label,
- defaultValue: `Could not ${label}.`,
- }),
- );
- };
const kebabRef = useRef<HTMLButtonElement>(null);
const { handlers: dropHandlers, isOver: isDropTarget } = useDropTarget({
dragType: FILES_PAGE_DRAG_TYPE,
@@ -1312,16 +1340,13 @@ function FolderRow({
const payload = parseFilesPageDragPayload(e.dataTransfer);
if (!payload) return;
if (payload.kind === "files") {
- Promise.resolve(onDropFiles(payload.fileIds)).catch((err) =>
- surfaceDrop(err, "move files into folder"),
- );
+ actions.dropFilesOnFolder(payload.fileIds, folder.id);
} else if (payload.kind === "folder") {
- Promise.resolve(onDropFolder(payload.folderId)).catch((err) =>
- surfaceDrop(err, "move folder"),
- );
+ actions.dropFolderOnFolder(payload.folderId, folder.id);
}
},
});
+
return (
<div
role="row"
@@ -1428,7 +1453,7 @@ function FolderRow({
<Menu.Item
color="red"
leftSection={<DeleteIcon fontSize="small" />}
- onClick={onDelete}
+ onClick={() => actions.deleteFolder(folder)}
>
{t(
"filesPage.removeLocalFolder",
@@ -1440,7 +1465,7 @@ function FolderRow({
<>
<Menu.Item
leftSection={<DriveFileRenameOutlineIcon fontSize="small" />}
- onClick={onRename}
+ onClick={() => actions.renameFolder(folder)}
disabled={editsDisabled}
title={editsDisabled ? offlineHint : undefined}
>
@@ -1452,14 +1477,16 @@ function FolderRow({
</Menu.Label>
<FolderAppearancePicker
folder={folder}
- onChange={onChangeAppearance}
+ onChange={(appearance) =>
+ actions.changeFolderAppearance(folder.id, appearance)
+ }
disabled={editsDisabled}
/>
<Menu.Divider />
<Menu.Item
color="red"
leftSection={<DeleteIcon fontSize="small" />}
- onClick={onDelete}
+ onClick={() => actions.deleteFolder(folder)}
disabled={editsDisabled}
title={editsDisabled ? offlineHint : undefined}
>
@@ -1472,30 +1499,43 @@ function FolderRow({
</span>
</div>
);
-}
+});
-interface FileRowProps extends FileMenuHandlers {
+interface FileRowProps {
file: StirlingFileStub;
isSelected: boolean;
isInWorkspace: boolean;
parentPath?: string;
- selectedFileIds: Set<FileId>;
/** Shows the checkbox once 2+ files are selected. */
multiSelectActive: boolean;
- onClick: (e: React.MouseEvent) => void;
- onOpen: () => void;
+ /** Download / rename / duplicate menu items offered. */
+ downloadAvailable: boolean;
+ renameAvailable: boolean;
+ duplicateAvailable: boolean;
+ /** Kebab Save to server offered; only fires when file is local-only. */
+ saveToServerAvailable: boolean;
+ /** Version-history menu item offered; shown only when file has >1 version. */
+ versionHistoryAvailable: boolean;
+ /** When set, the kebab Save to server is disabled with this tooltip. */
+ saveToServerDisabledReason?: string | null;
+ badges: FileItemPolicyRef[];
+ actions: FileGridActions;
}
-function FileRow({
+const FileRow = React.memo(function FileRow({
file,
isSelected,
isInWorkspace,
parentPath,
- selectedFileIds,
multiSelectActive,
- onClick,
- onOpen,
- ...menuHandlers
+ downloadAvailable,
+ renameAvailable,
+ duplicateAvailable,
+ saveToServerAvailable,
+ versionHistoryAvailable,
+ saveToServerDisabledReason,
+ badges,
+ actions,
}: FileRowProps) {
const { t } = useTranslation();
const kebabRef = useRef<HTMLButtonElement>(null);
@@ -1510,6 +1550,9 @@ function FileRow({
file.size,
file.thumbnailUrl,
);
+ const onClick = (e: React.MouseEvent) =>
+ actions.selectFile(file.id, e.shiftKey, e.metaKey || e.ctrlKey);
+ const onOpen = () => actions.openFile(file);
return (
<div
role="row"
@@ -1517,10 +1560,9 @@ function FileRow({
tabIndex={0}
draggable
onDragStart={(e) => {
- const fileIds = isSelected ? Array.from(selectedFileIds) : [file.id];
e.dataTransfer.setData(
FILES_PAGE_DRAG_TYPE,
- serialiseFilesPageDragPayload({ kind: "files", fileIds }),
+ actions.fileDragPayload(file.id),
);
e.dataTransfer.effectAllowed = "move";
}}
@@ -1549,12 +1591,7 @@ function FileRow({
onClick={(e) => {
// Toggle this file in/out of the selection without modifier keys.
e.stopPropagation();
- onClick({
- ...e,
- shiftKey: false,
- ctrlKey: true,
- metaKey: true,
- });
+ actions.selectFile(file.id, false, true);
}}
onChange={() => {
/* handled by onClick */
@@ -1621,7 +1658,7 @@ function FileRow({
)}
</span>
<FileOriginBadge origin={getFileOrigin(file)} compact />
- <PolicyBadges fileId={file.id} />
+ <PolicyBadgeRow policies={badges} />
{isInWorkspace && (
<span className="files-page-row-open-pill">
<span className="files-page-card-open-dot" />
@@ -1636,13 +1673,18 @@ function FileRow({
<FileActionsMenu
file={file}
triggerRef={kebabRef}
- onOpen={onOpen}
- {...menuHandlers}
+ downloadAvailable={downloadAvailable}
+ renameAvailable={renameAvailable}
+ duplicateAvailable={duplicateAvailable}
+ saveToServerAvailable={saveToServerAvailable}
+ versionHistoryAvailable={versionHistoryAvailable}
+ saveToServerDisabledReason={saveToServerDisabledReason}
+ actions={actions}
/>
</span>
</div>
);
-}
+});
// Re-export root constant for caller convenience
export { ROOT_FOLDER_ID };
@@ -1651,13 +1693,14 @@ export { ROOT_FOLDER_ID };
* No stub behind it, so no selection, move, rename or delete: the disk owns the
* file and the only affordance is adding it to the workspace.
*/
-function DiskFileCard({
+const DiskFileCard = React.memo(function DiskFileCard({
entry,
- onOpen,
+ actions,
}: {
entry: DiskFileEntry;
- onOpen: () => void;
+ actions: FileGridActions;
}) {
+ const onOpen = () => actions.openDiskFile(entry);
const { t } = useTranslation();
const thumbnail = useDiskThumbnail(entry);
const extension = entry.name.includes(".")
@@ -1735,16 +1778,17 @@ function DiskFileCard({
</div>
</div>
);
-}
+});
/** List-view sibling of {@link DiskFileCard}; same single affordance. */
-function DiskFileRow({
+const DiskFileRow = React.memo(function DiskFileRow({
entry,
- onOpen,
+ actions,
}: {
entry: DiskFileEntry;
- onOpen: () => void;
+ actions: FileGridActions;
}) {
+ const onOpen = () => actions.openDiskFile(entry);
const { t } = useTranslation();
const thumbnail = useDiskThumbnail(entry);
const ext = entry.name.includes(".")
@@ -1836,4 +1880,4 @@ function DiskFileRow({
</span>
</div>
);
-}
+});
diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
index 0952732599..774fbdb0a0 100644
--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
@@ -13,7 +13,6 @@ import {
Menu,
MultiSelect,
Select,
- Text,
TextInput,
Tooltip,
} from "@mantine/core";
@@ -25,7 +24,6 @@ import CloseIcon from "@mui/icons-material/Close";
import SearchIcon from "@mui/icons-material/Search";
import UploadFileIcon from "@mui/icons-material/UploadFile";
import QrCode2Icon from "@mui/icons-material/QrCode2";
-import CreateNewFolderIcon from "@mui/icons-material/CreateNewFolder";
import GridViewIcon from "@mui/icons-material/GridView";
import ViewListIcon from "@mui/icons-material/ViewList";
import DeleteIcon from "@mui/icons-material/Delete";
@@ -34,19 +32,18 @@ import OpenInNewIcon from "@mui/icons-material/OpenInNew";
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import KeyboardArrowRightIcon from "@mui/icons-material/KeyboardArrowRight";
-import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
-import DriveFolderUploadIcon from "@mui/icons-material/DriveFolderUpload";
-import CloudIcon from "@mui/icons-material/Cloud";
+import MoreHorizIcon from "@mui/icons-material/MoreHoriz";
import RefreshIcon from "@mui/icons-material/Refresh";
import { FilesToolbarBulkMenu } from "@app/components/filesPage/FilesToolbarBulkMenu";
import { FilesToolbarCount } from "@app/components/filesPage/FilesToolbarCount";
import { FilesToolbarFilterMenu } from "@app/components/filesPage/FilesToolbarFilterMenu";
import { FilesToolbarSortMenu } from "@app/components/filesPage/FilesToolbarSortMenu";
+import { NewFolderButton } from "@app/components/filesPage/NewFolderButton";
-import { stripBasePath } from "@app/constants/app";
import { useAuth } from "@app/auth/UseSession";
import { useSharingEnabled } from "@app/hooks/useSharingEnabled";
import { useFolders } from "@app/contexts/FolderContext";
+import { useOpenFolder } from "@app/components/filesPage/useOpenFolder";
import { useFileActions } from "@app/contexts/file/fileHooks";
import { useAllFiles } from "@app/contexts/FileContext";
import { useFileHandler } from "@app/hooks/useFileHandler";
@@ -66,7 +63,12 @@ import { getFileOrigin } from "@app/components/filesPage/fileOrigin";
import { FileId } from "@app/types/file";
import { StirlingFileStub } from "@app/types/fileContext";
-import { FolderId, ROOT_FOLDER_ID, folderKind } from "@app/types/folder";
+import {
+ FolderBreadcrumbEntry,
+ FolderId,
+ ROOT_FOLDER_ID,
+ folderKind,
+} from "@app/types/folder";
import { FileGrid, FilesPageEntry } from "@app/components/filesPage/FileGrid";
import SuperSearch from "@app/components/shared/superSearch/SuperSearch";
@@ -112,6 +114,7 @@ export default function FileManagerView() {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
+ const openFolder = useOpenFolder();
const searchScopes = useEditorSearchScopes();
// Hide Shared tab when storageSharingEnabled is false.
@@ -225,21 +228,37 @@ export default function FileManagerView() {
const foldersById = folders.foldersById;
const currentFolderId = folders.currentFolderId;
- // Sync the URL into FolderContext.
+ // The path selects the folder - see useOpenFolder - and this applies it, on arrival,
+ // on a deep link, and on back/forward alike. Re-runs as the folder map fills in.
useEffect(() => {
const match = location.pathname.match(/^\/files\/([^/]+)/);
const param = match?.[1] ?? null;
if (param === null) {
setCurrentFolderId(ROOT_FOLDER_ID);
- } else if (foldersById.has(param as FolderId)) {
+ return;
+ }
+ if (foldersById.has(param as FolderId)) {
setCurrentFolderId(param as FolderId);
- } else if (isDiskFolderId(param) && resolveDiskFolder(param as FolderId)) {
+ return;
+ }
+ if (isDiskFolderId(param) && resolveDiskFolder(param as FolderId)) {
// A mount subdirectory deep link: rebuilt from the id, mapped next render.
setCurrentFolderId(param as FolderId);
- } else {
+ return;
+ }
+ // Not known yet is not the same as not real: folders load asynchronously, and a
+ // mount's subdirectories arrive with the listing that finds them. Falling back to
+ // the root waits until the map can no longer turn up the folder named here.
+ if (!folders.loading) {
setCurrentFolderId(ROOT_FOLDER_ID);
}
- }, [location.pathname, foldersById, setCurrentFolderId, resolveDiskFolder]);
+ }, [
+ location.pathname,
+ foldersById,
+ setCurrentFolderId,
+ resolveDiskFolder,
+ folders.loading,
+ ]);
// Bounce off any share-related tab when sharing isn't enabled.
useEffect(() => {
@@ -251,17 +270,6 @@ export default function FileManagerView() {
}
}, [sharingEnabled, currentTab, setCurrentTab]);
- // Push folder selection into the URL while still on /files.
- useEffect(() => {
- const stripped = stripBasePath(window.location.pathname);
- if (!stripped.startsWith("/files")) return;
- const target =
- currentFolderId === null ? "/files" : `/files/${currentFolderId}`;
- if (stripped !== target) {
- navigate(target, { replace: true });
- }
- }, [currentFolderId, navigate]);
-
// ─── visible items (current folder + sort + search) ─────────────────────
/** currentFolderId + all descendants. Includes `null` when at root. */
@@ -290,7 +298,6 @@ export default function FileManagerView() {
const visibleFolders = useMemo(() => {
// Folders only appear in cloud-rooted tabs.
if (
- currentTab === "local" ||
currentTab === "recent" ||
currentTab === "shared" ||
currentTab === "sharedByMe"
@@ -301,6 +308,12 @@ export default function FileManagerView() {
const matched = folders.folders.filter((f) => {
// The Cloud tab is the server's view: browser folders and mounts aren't on it.
if (currentTab === "cloud" && folderKind(f) !== "server") return false;
+ // A folder answers to the source filter the way its files would: a server
+ // folder is cloud, a browser folder and a mount are both local.
+ if (originFilter !== "all") {
+ const folderOrigin = folderKind(f) === "server" ? "cloud" : "local";
+ if (folderOrigin !== originFilter) return false;
+ }
if (search) {
// Subtree-wide name match; exclude the current folder itself.
return (
@@ -315,18 +328,19 @@ export default function FileManagerView() {
return matched.sort((a, b) =>
a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
);
- }, [folders.folders, currentFolderId, search, currentTab, subtreeFolderIds]);
+ }, [
+ folders.folders,
+ currentFolderId,
+ search,
+ currentTab,
+ subtreeFolderIds,
+ originFilter,
+ ]);
// Files in current folder, pre-filter. Drives the type-filter dropdown.
const filesInCurrentFolder = useMemo(() => {
// Tab overrides folder navigation for Local/Recent/Shared.
switch (currentTab) {
- case "local":
- // Both halves: a local file inside a browser folder belongs to that folder,
- // not here as well.
- return allFiles.filter(
- (f) => f.remoteStorageId == null && (f.folderId ?? null) === null,
- );
case "cloud":
// Cloud bucket; search widens to subtree, else direct-folder match.
return allFiles.filter((f) => {
@@ -753,26 +767,40 @@ export default function FileManagerView() {
const proceed = async () => {
clearFilesPageReturnRoute();
+ // Already in the workspace: nothing to fetch or add, so just go to it. Sending
+ // it through materialize and add again has no reason to succeed - the bytes
+ // are already spoken for.
+ const alreadyOpen = stubs.filter((stub) =>
+ activeWorkspaceFileIdSet.has(stub.id as string),
+ );
+ const toOpen = stubs.filter(
+ (stub) => !activeWorkspaceFileIdSet.has(stub.id as string),
+ );
+
// Server-only stubs have no bytes in IDB; download + ingest first.
- const materialized = await materializeServerStubs(stubs, {
+ const materialized = await materializeServerStubs(toOpen, {
addFiles: fileActions.addFilesWithOptions,
updateStub: fileActions.updateStirlingFileStub,
});
- if (materialized.length !== stubs.length) {
+ if (materialized.length !== toOpen.length) {
// At least one server download failed; refresh so the grid
// reflects any successful ingests and the user can retry.
await refresh();
return;
}
- await fileActions.addStirlingFileStubs(materialized, {
- selectFiles: false,
- });
- // Branch on requested stubs so already-active files still activate.
- if (materialized.length === 1) {
- setActiveFileId(materialized[0].id);
+ if (materialized.length > 0) {
+ await fileActions.addStirlingFileStubs(materialized, {
+ selectFiles: false,
+ });
+ }
+
+ // Every file the user asked for, whether it arrived now or was already there.
+ const opened = [...alreadyOpen, ...materialized];
+ if (opened.length === 1) {
+ setActiveFileId(opened[0].id);
navActions.setWorkbench("viewer");
- } else if (materialized.length > 1) {
+ } else if (opened.length > 1) {
navActions.setWorkbench("fileEditor");
}
navigate(EDITOR_BASENAME);
@@ -790,6 +818,8 @@ export default function FileManagerView() {
navigate,
requestNavigation,
clearFilesPageReturnRoute,
+ activeWorkspaceFileIdSet,
+ refresh,
],
);
@@ -808,10 +838,10 @@ export default function FileManagerView() {
const handleOpenFolder = useCallback(
(id: FolderId) => {
- folders.setCurrentFolderId(id);
+ openFolder(id);
clearSelection();
},
- [folders, clearSelection],
+ [openFolder, clearSelection],
);
// ─── full-page drag-and-drop for OS uploads ─────────────────────────────
@@ -1094,14 +1124,12 @@ export default function FileManagerView() {
// disabled item's caption.
const serverFolderDisabledReason = useServerFolderBlock() ?? undefined;
- const { addLocalFolder, createFolderHere, createFolderHereBlockedReason } =
- useNewFolderFlow();
+ const { addLocalFolder } = useNewFolderFlow();
// null = New folder actionable; string = disabled tooltip reason.
const newFolderDisabledReason: string | null = useMemo(() => {
// Only All/Cloud render folders, so creating one elsewhere would look inert.
if (
- currentTab === "local" ||
currentTab === "recent" ||
currentTab === "shared" ||
currentTab === "sharedByMe"
@@ -1143,8 +1171,7 @@ export default function FileManagerView() {
<header className="files-page-header">
{/* Breadcrumb only for folder-rooted tabs. */}
{(currentTab === "all" || currentTab === "cloud") && <Breadcrumbs />}
- {(currentTab === "local" ||
- currentTab === "recent" ||
+ {(currentTab === "recent" ||
currentTab === "shared" ||
currentTab === "sharedByMe") && (
<div
@@ -1155,13 +1182,11 @@ export default function FileManagerView() {
color: "var(--c-text)",
}}
>
- {currentTab === "local"
- ? t("filesPage.tabName.local", "Local")
- : currentTab === "recent"
- ? t("filesPage.tabName.recent", "Recent")
- : currentTab === "shared"
- ? t("filesPage.tabName.shared", "Shared with me")
- : t("filesPage.tabName.sharedByMe", "Shared by me")}
+ {currentTab === "recent"
+ ? t("filesPage.tabName.recent", "Recent")
+ : currentTab === "shared"
+ ? t("filesPage.tabName.shared", "Shared with me")
+ : t("filesPage.tabName.sharedByMe", "Shared by me")}
</div>
)}
{(() => {
@@ -1223,89 +1248,15 @@ export default function FileManagerView() {
<RefreshIcon />
</ActionIcon>
</Tooltip>
- {newFolderDisabledReason ? (
- <Tooltip
- label={newFolderDisabledReason}
- withinPortal
- multiline
- w={220}
- >
- <span style={{ display: "inline-flex" }}>
- <Button
- variant="secondary"
- size="sm"
- leftSection={<CreateNewFolderIcon fontSize="small" />}
- disabled
- style={{ pointerEvents: "auto" }}
- >
- {t("filesPage.newFolder", "New folder")}
- </Button>
- </span>
- </Tooltip>
- ) : folders.currentFolderId !== null || !canPickDirectory ? (
- // Nothing to choose: a subfolder inherits its parent's kind, and on
- // the web everything lives on the server. Straight to the dialog.
- <Button
- variant="secondary"
- size="sm"
- leftSection={<CreateNewFolderIcon fontSize="small" />}
- onClick={() =>
- folders.currentFolderId !== null
- ? openNewFolderDialog()
- : openNewFolderDialog(null, "server")
- }
- >
- {t("filesPage.newFolder", "New folder")}
- </Button>
- ) : (
- // Desktop root: two peer destinations, so the button is the menu.
- <Menu shadow="md" position="bottom-end" withinPortal>
- <Menu.Target>
- <Button
- variant="secondary"
- size="sm"
- leftSection={<CreateNewFolderIcon fontSize="small" />}
- rightSection={<ArrowDropDownIcon fontSize="small" />}
- >
- {t("filesPage.newFolder", "New folder")}
- </Button>
- </Menu.Target>
- <Menu.Dropdown>
- <Menu.Item
- leftSection={
- <DriveFolderUploadIcon
- fontSize="small"
- style={{ marginRight: "0.3rem" }}
- />
- }
- onClick={() => void addLocalFolder()}
- >
- {t(
- "filesPage.newFolderMenu.addExisting",
- "Add local folder",
- )}
- </Menu.Item>
- <Menu.Item
- className="files-page-new-folder-option"
- leftSection={<CloudIcon fontSize="small" />}
- disabled={Boolean(serverFolderDisabledReason)}
- onClick={() => openNewFolderDialog(null, "server")}
- >
- {t(
- "filesPage.newFolderMenu.server",
- "New folder on the server",
- )}
- <Text size="xs" c="dimmed">
- {serverFolderDisabledReason ??
- t(
- "filesPage.newFolderMenu.serverHint",
- "Synced to your account, available wherever you sign in.",
- )}
- </Text>
- </Menu.Item>
- </Menu.Dropdown>
- </Menu>
- )}
+ <NewFolderButton
+ label={t("filesPage.newFolder", "New folder")}
+ disabledReason={newFolderDisabledReason}
+ serverDisabledReason={serverFolderDisabledReason}
+ currentFolderId={folders.currentFolderId}
+ canAddLocalFolder={canPickDirectory}
+ onAddLocalFolder={() => void addLocalFolder()}
+ onOpenDialog={openNewFolderDialog}
+ />
<Button
size="sm"
leftSection={<UploadFileIcon fontSize="small" />}
@@ -1902,6 +1853,7 @@ export default function FileManagerView() {
currentTab={currentTab}
searchActive={search.trim().length > 0}
serverReachable={folders.serverReachable}
+ onActionError={folders.setError}
selectedFileIds={selectedFileIds}
activeWorkspaceFileIds={activeWorkspaceFileIdSet}
viewMode={viewMode}
@@ -1944,11 +1896,17 @@ export default function FileManagerView() {
// (disabled tooltips, native file picker, dialog) is
// identical regardless of where the user clicks from.
onEmptyUpload={() => fileInputRef.current?.click()}
- onEmptyCreateFolder={createFolderHere}
- // A single-click shortcut, so it also blocks where it has nothing safe
- // to do, unlike the header button whose menu still offers the choices.
- newFolderDisabledReason={
- newFolderDisabledReason ?? createFolderHereBlockedReason
+ emptyNewFolderControl={
+ <NewFolderButton
+ label={t("filesPage.newFolder", "New folder")}
+ size="md"
+ disabledReason={newFolderDisabledReason}
+ serverDisabledReason={serverFolderDisabledReason}
+ currentFolderId={folders.currentFolderId}
+ canAddLocalFolder={canPickDirectory}
+ onAddLocalFolder={() => void addLocalFolder()}
+ onOpenDialog={openNewFolderDialog}
+ />
}
/>
{isDraggingExternal && (
@@ -2155,77 +2113,121 @@ function Breadcrumbs() {
const { t } = useTranslation();
const folders = useFolders();
const filesPage = useFilesPage();
+ const openFolder = useOpenFolder();
const trail = folders.breadcrumbs;
+
+ const reportFailure = (err: unknown, detailKey: string, plainKey: string) => {
+ folders.setError(
+ err instanceof Error
+ ? t(detailKey, {
+ message: err.message,
+ defaultValue: `Could not move: ${err.message}`,
+ })
+ : t(plainKey, "Could not move."),
+ );
+ };
+
+ /** A crumb is a drop target for the folder it names. */
+ const dropHandlers = (target: FolderBreadcrumbEntry) => ({
+ onDragOver: (e: React.DragEvent) => {
+ if (e.dataTransfer.types.includes(FILES_PAGE_DRAG_TYPE)) {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ }
+ },
+ onDrop: (e: React.DragEvent) => {
+ e.preventDefault();
+ const payload = parseFilesPageDragPayload(e.dataTransfer);
+ if (!payload) return;
+ if (payload.kind === "files") {
+ // Through moveFilesTo so the revision bumps and the grid refreshes, and a
+ // rejection reaches the banner rather than only the console.
+ void filesPage.moveFilesTo(payload.fileIds, target.id).catch((err) => {
+ console.error("[breadcrumb] drop failed", err);
+ reportFailure(
+ err,
+ "filesPage.error.moveFilesFailedDetail",
+ "filesPage.error.moveFilesFailed",
+ );
+ });
+ } else if (payload.kind === "folder") {
+ // Through moveFolderTo so the client-side cycle guard fires before the
+ // server call: dropping an ancestor on a descendant crumb has its own
+ // message, not the generic banner.
+ void filesPage
+ .moveFolderTo(payload.folderId, target.id)
+ .catch((err) => {
+ console.error("[breadcrumb] folder drop failed", err);
+ reportFailure(
+ err,
+ "filesPage.error.moveFolderFailedDetail",
+ "filesPage.error.moveFolderFailed",
+ );
+ });
+ }
+ },
+ });
+
+ // Two crumbs at most. Everything above them, the root included, moves into the
+ // overflow menu: a deep trail otherwise grows the bar it sits in, and the folder
+ // you are actually in is the one that scrolls out of sight.
+ const VISIBLE = 2;
+ const split = Math.max(0, trail.length - VISIBLE);
+ const hidden = trail.slice(0, split);
+ const shown = trail.slice(split);
+
return (
<nav
className="files-page-breadcrumbs"
aria-label={t("filesPage.breadcrumbs", "Folder path")}
>
- {trail.map((entry, idx) => {
- const isLast = idx === trail.length - 1;
+ {hidden.length > 0 && (
+ <>
+ <Menu shadow="md" position="bottom-start" withinPortal>
+ <Menu.Target>
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ className="files-page-breadcrumb-overflow"
+ aria-label={t(
+ "filesPage.breadcrumbsOverflow",
+ "Show parent folders",
+ )}
+ >
+ <MoreHorizIcon fontSize="small" />
+ </ActionIcon>
+ </Menu.Target>
+ <Menu.Dropdown>
+ {hidden.map((entry) => (
+ <Menu.Item
+ key={entry.id ?? "root"}
+ onClick={() => openFolder(entry.id)}
+ >
+ {entry.name}
+ </Menu.Item>
+ ))}
+ </Menu.Dropdown>
+ </Menu>
+ <KeyboardArrowRightIcon
+ className="files-page-breadcrumb-sep"
+ fontSize="small"
+ aria-hidden="true"
+ />
+ </>
+ )}
+ {shown.map((entry, idx) => {
+ const isLast = idx === shown.length - 1;
return (
<React.Fragment key={entry.id ?? "root"}>
- <Button
- variant="tertiary"
+ <button
+ type="button"
className={`files-page-breadcrumb${isLast ? " is-current" : ""}`}
- onClick={() => folders.setCurrentFolderId(entry.id)}
- onDragOver={(e) => {
- if (e.dataTransfer.types.includes(FILES_PAGE_DRAG_TYPE)) {
- e.preventDefault();
- e.dataTransfer.dropEffect = "move";
- }
- }}
- onDrop={(e) => {
- e.preventDefault();
- const payload = parseFilesPageDragPayload(e.dataTransfer);
- if (!payload) return;
- if (payload.kind === "files") {
- // Route through moveFilesTo (→ IndexedDBContext.moveFilesToFolder)
- // so the revision bumps and the grid refreshes. Surface
- // rejection via the banner - console-only was invisible
- // to non-dev users.
- void filesPage
- .moveFilesTo(payload.fileIds, entry.id)
- .catch((err) => {
- console.error("[breadcrumb] drop failed", err);
- folders.setError(
- err instanceof Error
- ? t("filesPage.error.moveFilesFailedDetail", {
- message: err.message,
- defaultValue: `Could not move files: ${err.message}`,
- })
- : t(
- "filesPage.error.moveFilesFailed",
- "Could not move files.",
- ),
- );
- });
- } else if (payload.kind === "folder") {
- // Route through moveFolderTo so the client-side cycle guard fires
- // before the server call - otherwise dragging an ancestor onto a
- // child crumb shows the generic banner instead of the localized
- // "Can't move a folder into one of its own subfolders." message.
- void filesPage
- .moveFolderTo(payload.folderId, entry.id)
- .catch((err) => {
- console.error("[breadcrumb] folder drop failed", err);
- folders.setError(
- err instanceof Error
- ? t("filesPage.error.moveFolderFailedDetail", {
- message: err.message,
- defaultValue: `Could not move folder: ${err.message}`,
- })
- : t(
- "filesPage.error.moveFolderFailed",
- "Could not move folder.",
- ),
- );
- });
- }
- }}
+ title={entry.name}
+ onClick={() => openFolder(entry.id)}
+ {...dropHandlers(entry)}
>
{entry.name}
- </Button>
+ </button>
{!isLast && (
<KeyboardArrowRightIcon
className="files-page-breadcrumb-sep"
diff --git a/frontend/editor/src/core/components/filesPage/FilesPage.css b/frontend/editor/src/core/components/filesPage/FilesPage.css
index b6e54bb15d..5900971bdb 100644
--- a/frontend/editor/src/core/components/filesPage/FilesPage.css
+++ b/frontend/editor/src/core/components/filesPage/FilesPage.css
@@ -65,15 +65,15 @@
display: flex;
align-items: center;
gap: 0.25rem;
- font-size: 0.95rem;
+ font-size: 0.8125rem;
min-width: 0;
- overflow-x: auto;
- scrollbar-width: none;
-}
-.files-page-breadcrumbs::-webkit-scrollbar {
- display: none;
+ /* Fixed, and never wrapping: the trail shares a row with the search and the
+ action buttons, and any growth here moves the grid below it. Length is handled
+ by showing fewer crumbs, not by taking more space. */
+ height: 2rem;
+ flex-wrap: nowrap;
+ overflow: hidden;
}
-
.files-page-breadcrumb {
background: none;
border: none;
@@ -87,10 +87,20 @@
background-color 0.12s ease,
color 0.12s ease;
white-space: nowrap;
- max-width: 18rem;
+ max-width: 14rem;
+ min-width: 0;
+ height: 1.5rem;
+ line-height: 1.5rem;
+ padding: 0 0.375rem;
overflow: hidden;
text-overflow: ellipsis;
}
+
+/* The parents that don't fit, root included. */
+.files-page-breadcrumb-overflow {
+ flex-shrink: 0;
+}
+
.files-page-breadcrumb:hover,
.files-page-breadcrumb.is-current {
background: var(--c-hover);
@@ -319,6 +329,14 @@
gap: 1rem;
}
+/* Stands in for the rows outside the rendered window, so the scrollbar reflects the
+ whole folder. Spans every column: in the grid a spacer sharing a row with cards
+ would be laid out beside them instead of above. */
+.files-page-virtual-pad {
+ grid-column: 1 / -1;
+ pointer-events: none;
+}
+
.files-page-list {
display: flex;
flex-direction: column;
@@ -333,6 +351,9 @@
grid-template-columns: 2.25rem minmax(0, 3fr) 1fr 1fr 1fr 2.5rem;
gap: 0.5rem;
align-items: center;
+ /* Same offscreen skip as .files-page-card. */
+ content-visibility: auto;
+ contain-intrinsic-size: auto 3rem;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--c-border-subtle);
cursor: pointer;
@@ -385,6 +406,11 @@
position: relative;
display: flex;
flex-direction: column;
+ /* Offscreen cards skip layout and paint — a 500-entry folder only pays
+ for the rows in view. The intrinsic size stands in for unrendered
+ cards so the scrollbar doesn't jump (auto: measured size once seen). */
+ content-visibility: auto;
+ contain-intrinsic-size: auto 13rem;
background: var(--c-surface);
border: 1px solid var(--c-border-subtle);
border-radius: 0.85rem;
diff --git a/frontend/editor/src/core/components/filesPage/FolderTreePanel.css b/frontend/editor/src/core/components/filesPage/FolderTreePanel.css
index 4a98babcbc..dd0a42571d 100644
--- a/frontend/editor/src/core/components/filesPage/FolderTreePanel.css
+++ b/frontend/editor/src/core/components/filesPage/FolderTreePanel.css
@@ -168,12 +168,27 @@
.files-page-tree-name {
flex: 1;
+ min-width: 0;
+ display: flex;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-left: 12px;
}
+/* Head elides, tail is kept whole: together they read as one name broken in the
+ middle, so both ends stay visible at any column width. */
+.files-page-tree-name-head {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.files-page-tree-name-tail {
+ flex-shrink: 0;
+ white-space: nowrap;
+}
+
.files-page-tree-count {
color: var(--c-text-subtle);
font-size: 12px;
diff --git a/frontend/editor/src/core/components/filesPage/FolderTreePanel.tsx b/frontend/editor/src/core/components/filesPage/FolderTreePanel.tsx
index b56915b757..76e8757255 100644
--- a/frontend/editor/src/core/components/filesPage/FolderTreePanel.tsx
+++ b/frontend/editor/src/core/components/filesPage/FolderTreePanel.tsx
@@ -1,6 +1,6 @@
/** Folder tree navigator panel rendered next to FileSidebar on /files. */
-import React, { useCallback, useEffect, useRef, useState } from "react";
+import React, { useCallback, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FolderTreeSidebar } from "@app/components/filesPage/FolderTreeSidebar";
@@ -39,15 +39,8 @@ export function FolderTreePanel({ active }: FolderTreePanelProps) {
const persisted = loadPersistedWidth();
return persisted ?? 256;
});
- const userSetRef = useRef<boolean>(loadPersistedWidth() !== null);
-
- // Auto-fit to the longest folder name on first render and whenever the
- // folder list grows; skipped once the user manually resizes.
- useEffect(() => {
- if (userSetRef.current) return;
- const auto = computeAutoFitWidth(folders.folders, rootLabel);
- setWidth(auto);
- }, [folders.folders, rootLabel]);
+ // The width is the user's, never the content's: a folder with a long name
+ // truncates in the row rather than widening the column it sits in.
const dragStateRef = useRef<{
startX: number;
@@ -69,7 +62,6 @@ export function FolderTreePanel({ active }: FolderTreePanelProps) {
document.removeEventListener("mouseup", onMouseUp);
document.body.style.removeProperty("cursor");
document.body.style.removeProperty("user-select");
- userSetRef.current = true;
setWidth((current) => {
savePersistedWidth(current);
return current;
@@ -98,7 +90,6 @@ export function FolderTreePanel({ active }: FolderTreePanelProps) {
else if (e.key === "End") next = MAX_WIDTH;
if (next === null) return;
e.preventDefault();
- userSetRef.current = true;
setWidth(next);
savePersistedWidth(next);
},
@@ -158,7 +149,6 @@ export function FolderTreePanel({ active }: FolderTreePanelProps) {
onKeyDown={onKeyDown}
onDoubleClick={() => {
const auto = computeAutoFitWidth(folders.folders, rootLabel);
- userSetRef.current = false;
setWidth(auto);
savePersistedWidth(auto);
}}
diff --git a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx
index 918dbe9880..63e8cf8841 100644
--- a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx
+++ b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx
@@ -28,6 +28,7 @@ import {
serialiseFilesPageDragPayload,
} from "@app/components/filesPage/dragDrop";
import { useDropTarget } from "@app/components/filesPage/useDropTarget";
+import { useOpenFolder } from "@app/components/filesPage/useOpenFolder";
/**
* Hard cap on folder-tree render depth. The backend already enforces an
@@ -63,6 +64,32 @@ interface FolderTreeSidebarProps {
// anyone re-wired the component into a non-embed surface they'd ship an
// always-enabled mutation button against a possibly-offline server.
// Deleted to remove the trap.
+/**
+ * A name that gives way in the middle when the row is too narrow for it, keeping both
+ * ends readable - folder names tend to differ at the end, where a plain end-ellipsis
+ * would cut. The split is fixed; the CSS decides whether the head actually elides.
+ */
+function MiddleTruncated({
+ text,
+ className,
+}: {
+ text: string;
+ className: string;
+}) {
+ const TAIL = 6;
+ if (text.length <= TAIL + 4) {
+ return <span className={className}>{text}</span>;
+ }
+ return (
+ <span className={className} title={text}>
+ <span className="files-page-tree-name-head">
+ {text.slice(0, text.length - TAIL)}
+ </span>
+ <span className="files-page-tree-name-tail">{text.slice(-TAIL)}</span>
+ </span>
+ );
+}
+
export function FolderTreeSidebar({
fileCounts,
onRequestNewFolder,
@@ -71,8 +98,15 @@ export function FolderTreeSidebar({
onMoveFilesIntoFolder,
}: FolderTreeSidebarProps) {
const { t } = useTranslation();
- const { tree, currentFolderId, setCurrentFolderId } = useFolders();
- const { currentTab, setCurrentTab, moveFolderTo } = useFilesPage();
+ const { tree, currentFolderId } = useFolders();
+ const openFolder = useOpenFolder();
+ const {
+ currentTab,
+ setCurrentTab,
+ moveFolderTo,
+ originFilter,
+ setOriginFilter,
+ } = useFilesPage();
return (
<div
@@ -92,15 +126,15 @@ export function FolderTreeSidebar({
if (currentTab !== "all" && currentTab !== "cloud") {
setCurrentTab("all");
}
- setCurrentFolderId(ROOT_FOLDER_ID);
+ openFolder(ROOT_FOLDER_ID);
}}
onDropFiles={(fileIds) =>
onMoveFilesIntoFolder(ROOT_FOLDER_ID, fileIds)
}
/>
<LocalRow
- isActive={currentTab === "local"}
- onSelect={() => setCurrentTab("local")}
+ isActive={originFilter === "local"}
+ onSelect={() => setOriginFilter("local")}
/>
{tree.map((node) => (
<TreeNodeRow
@@ -115,7 +149,7 @@ export function FolderTreeSidebar({
if (currentTab !== "all" && currentTab !== "cloud") {
setCurrentTab("all");
}
- setCurrentFolderId(id);
+ openFolder(id);
}}
onMoveFolder={async (folderId, newParentId) => {
// Route through filesPage.moveFolderTo so the cycle case
@@ -198,10 +232,9 @@ interface LocalRowProps {
}
/**
- * Pinned pseudo-folder row that selects the Local tab. Local files don't
- * belong to a folder (folders are a cloud concept) so this row is not a
- * drop target and has no count badge - the Local view scopes by predicate
- * (`remoteStorageId == null`), not by folderId.
+ * Sets the source filter to local, and nothing else: it narrows whatever view you
+ * are in rather than being a place of its own. Not a drop target and no count
+ * badge - a local file has no folder to be counted under.
*/
function LocalRow({ isActive, onSelect }: LocalRowProps) {
const { t } = useTranslation();
@@ -403,7 +436,10 @@ function TreeNodeRow({
<span className="files-page-tree-icon">
<FolderThumbnail color={node.folder.color} size="tree" />
</span>
- <span className="files-page-tree-name">{node.folder.name}</span>
+ <MiddleTruncated
+ className="files-page-tree-name"
+ text={node.folder.name}
+ />
<span className="files-page-tree-count">
{fileCounts.get(node.folder.id) ?? 0}
</span>
diff --git a/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx b/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx
new file mode 100644
index 0000000000..79de32b013
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/NewFolderButton.tsx
@@ -0,0 +1,126 @@
+import type { ReactNode } from "react";
+import { Menu, Text, Tooltip } from "@mantine/core";
+import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
+import CloudIcon from "@mui/icons-material/Cloud";
+import CreateNewFolderIcon from "@mui/icons-material/CreateNewFolder";
+import DriveFolderUploadIcon from "@mui/icons-material/DriveFolderUpload";
+import { useTranslation } from "react-i18next";
+
+import { Button } from "@app/ui/Button";
+import type { FolderId, FolderKind } from "@app/types/folder";
+
+export interface NewFolderButtonProps {
+ label: string;
+ size?: "sm" | "md";
+ /** Set when a folder cannot be created here at all; also the tooltip. */
+ disabledReason?: string | null;
+ /** Set when only the server destination is unavailable; also its tooltip. */
+ serverDisabledReason?: string | null;
+ /** A subfolder inherits its parent's kind, so inside one there is no choice. */
+ currentFolderId: FolderId | null;
+ /** Whether this build can put a directory on screen to be mounted. */
+ canAddLocalFolder: boolean;
+ onAddLocalFolder: () => void;
+ onOpenDialog: (parentId?: FolderId | null, kind?: FolderKind) => void;
+}
+
+/**
+ * New folder, in the three shapes the destinations allow: blocked with a reason, a
+ * plain button where only one destination exists, and a menu where two do. Shared by
+ * the header and the empty state, so one label cannot offer two different things.
+ */
+export function NewFolderButton({
+ label,
+ size = "sm",
+ disabledReason,
+ serverDisabledReason,
+ currentFolderId,
+ canAddLocalFolder,
+ onAddLocalFolder,
+ onOpenDialog,
+}: NewFolderButtonProps): ReactNode {
+ const { t } = useTranslation();
+
+ if (disabledReason) {
+ return (
+ <Tooltip label={disabledReason} withinPortal multiline w={260}>
+ {/* Wrapped so the tooltip still opens while the button is disabled. */}
+ <span style={{ display: "inline-flex" }}>
+ <Button
+ variant="secondary"
+ size={size}
+ leftSection={<CreateNewFolderIcon fontSize="small" />}
+ disabled
+ style={{ pointerEvents: "auto" }}
+ >
+ {label}
+ </Button>
+ </span>
+ </Tooltip>
+ );
+ }
+
+ // Inside a folder the kind is inherited, and on the web the server is the only
+ // place a folder can go.
+ if (currentFolderId !== null || !canAddLocalFolder) {
+ return (
+ <Button
+ variant="secondary"
+ size={size}
+ leftSection={<CreateNewFolderIcon fontSize="small" />}
+ onClick={() =>
+ currentFolderId !== null
+ ? onOpenDialog()
+ : onOpenDialog(null, "server")
+ }
+ >
+ {label}
+ </Button>
+ );
+ }
+
+ return (
+ <Menu shadow="md" position="bottom-end" withinPortal>
+ <Menu.Target>
+ <Button
+ variant="secondary"
+ size={size}
+ leftSection={<CreateNewFolderIcon fontSize="small" />}
+ rightSection={<ArrowDropDownIcon fontSize="small" />}
+ >
+ {label}
+ </Button>
+ </Menu.Target>
+ <Menu.Dropdown>
+ <Menu.Item
+ leftSection={
+ <DriveFolderUploadIcon
+ fontSize="small"
+ style={{ marginRight: "0.3rem" }}
+ />
+ }
+ onClick={onAddLocalFolder}
+ >
+ {t("filesPage.newFolderMenu.addExisting", "Add local folder")}
+ </Menu.Item>
+ <Menu.Item
+ className="files-page-new-folder-option"
+ leftSection={<CloudIcon fontSize="small" />}
+ disabled={Boolean(serverDisabledReason)}
+ onClick={() => onOpenDialog(null, "server")}
+ >
+ {t("filesPage.newFolderMenu.server", "New folder on the server")}
+ {/* The reason is the caption: a disabled item with no explanation
+ reads as broken rather than unavailable. */}
+ <Text size="xs" c="dimmed">
+ {serverDisabledReason ??
+ t(
+ "filesPage.newFolderMenu.serverHint",
+ "Synced to your account, available wherever you sign in.",
+ )}
+ </Text>
+ </Menu.Item>
+ </Menu.Dropdown>
+ </Menu>
+ );
+}
diff --git a/frontend/editor/src/core/components/filesPage/useOpenFolder.ts b/frontend/editor/src/core/components/filesPage/useOpenFolder.ts
new file mode 100644
index 0000000000..7da1feee54
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/useOpenFolder.ts
@@ -0,0 +1,20 @@
+import { useCallback } from "react";
+import { useNavigate } from "react-router-dom";
+
+import type { FolderId } from "@app/types/folder";
+
+/**
+ * Open a folder by putting it in the URL, which is what selects it: the library reads
+ * its current folder back out of the path. Selecting the folder state directly leaves
+ * the path to an effect that cannot tell such a selection from one the path itself
+ * made, which is why this is the only way in.
+ */
+export function useOpenFolder(): (id: FolderId | null) => void {
+ const navigate = useNavigate();
+ return useCallback(
+ (id: FolderId | null) => {
+ navigate(id === null ? "/files" : `/files/${id}`);
+ },
+ [navigate],
+ );
+}
diff --git a/frontend/editor/src/core/components/filesPage/useVirtualFileRows.ts b/frontend/editor/src/core/components/filesPage/useVirtualFileRows.ts
new file mode 100644
index 0000000000..65d82a2c6b
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/useVirtualFileRows.ts
@@ -0,0 +1,117 @@
+import { useCallback, useEffect, useState } from "react";
+import { useVirtualizer } from "@tanstack/react-virtual";
+
+/** Rows above and below the viewport kept mounted, so a fast scroll stays filled. */
+const OVERSCAN = 3;
+
+/**
+ * How many columns the grid is actually laying out. Read off the computed style
+ * rather than recomputed from a breakpoint, so `auto-fill` stays the one place the
+ * column count is decided.
+ */
+function useColumnCount(el: HTMLElement | null): number {
+ const [columns, setColumns] = useState(1);
+ useEffect(() => {
+ if (!el) return;
+ const read = () => {
+ const template = getComputedStyle(el).gridTemplateColumns;
+ const n =
+ template === "none" ? 1 : template.split(" ").filter(Boolean).length;
+ setColumns(Math.max(1, n));
+ };
+ read();
+ const ro = new ResizeObserver(read);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [el]);
+ return columns;
+}
+
+/** The scrolling ancestor the virtualiser measures against. */
+function useScrollParent(el: HTMLElement | null): HTMLElement | null {
+ const [parent, setParent] = useState<HTMLElement | null>(null);
+ useEffect(() => {
+ setParent(el?.closest<HTMLElement>(".files-page-content") ?? null);
+ }, [el]);
+ return parent;
+}
+
+interface VirtualFileRows {
+ /** The slice to render, or every index when virtualisation is standing down. */
+ range: { start: number; end: number };
+ /** Height to leave above and below the slice, keeping the scrollbar honest. */
+ padTop: number;
+ padBottom: number;
+ columns: number;
+ /** Ref for the element the rows live in. */
+ setContainer: (el: HTMLDivElement | null) => void;
+}
+
+/**
+ * Renders a window of a long file list instead of all of it, as a slice plus a
+ * spacer at each end. Spacers rather than absolute positioning so the grid keeps
+ * its own `auto-fill` layout and the list its own row flow.
+ *
+ * Stands down - every item rendered, no spacers - until there is a scrolling
+ * ancestor with a measured height. That covers a short list, the first paint
+ * before layout, and any environment without real geometry.
+ */
+export function useVirtualFileRows(
+ itemCount: number,
+ rowHeightEstimate: number,
+ isGrid: boolean,
+): VirtualFileRows {
+ const [container, setContainer] = useState<HTMLDivElement | null>(null);
+ const scrollParent = useScrollParent(container);
+ const measuredColumns = useColumnCount(isGrid ? container : null);
+ const columns = isGrid ? measuredColumns : 1;
+ const rowCount = Math.ceil(itemCount / columns);
+
+ const getScrollElement = useCallback(() => scrollParent, [scrollParent]);
+ const virtualizer = useVirtualizer({
+ count: rowCount,
+ getScrollElement,
+ estimateSize: () => rowHeightEstimate,
+ overscan: OVERSCAN,
+ });
+
+ const rows = virtualizer.getVirtualItems();
+ const active = Boolean(scrollParent) && rows.length > 0;
+
+ if (!active) {
+ return {
+ range: { start: 0, end: itemCount },
+ padTop: 0,
+ padBottom: 0,
+ columns,
+ setContainer,
+ };
+ }
+
+ const first = rows[0];
+ const last = rows[rows.length - 1];
+ return {
+ range: {
+ start: first.index * columns,
+ end: Math.min((last.index + 1) * columns, itemCount),
+ },
+ padTop: first.start,
+ padBottom: Math.max(0, virtualizer.getTotalSize() - last.end),
+ columns,
+ setContainer,
+ };
+}
+
+// Read once. The root font size is a layout read, and this is called on every render
+// of a list whose whole point is not doing needless work. A root restyled mid-session
+// keeps the first answer, which only shifts an estimate.
+let rootFontSizePx = 0;
+
+/** Card and row heights including their gap, matching contain-intrinsic-size. */
+export function rowHeightPx(isGrid: boolean): number {
+ if (rootFontSizePx === 0) {
+ rootFontSizePx =
+ parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
+ }
+ return isGrid ? 14 * rootFontSizePx : 3 * rootFontSizePx;
+}
diff --git a/frontend/editor/src/core/contexts/FilesPageContext.tsx b/frontend/editor/src/core/contexts/FilesPageContext.tsx
index 3a93653811..c64a9f1a54 100644
--- a/frontend/editor/src/core/contexts/FilesPageContext.tsx
+++ b/frontend/editor/src/core/contexts/FilesPageContext.tsx
@@ -55,13 +55,7 @@ export type FilesPageOriginFilter =
| "shared-with-me";
/** all|local|cloud|recent|shared filter presets. */
-export type FilesPageTab =
- | "all"
- | "local"
- | "cloud"
- | "recent"
- | "shared"
- | "sharedByMe";
+export type FilesPageTab = "all" | "cloud" | "recent" | "shared" | "sharedByMe";
export interface FolderNameDialogState {
mode: "new" | "rename" | null;
diff --git a/frontend/editor/src/core/contexts/FolderContext.test.tsx b/frontend/editor/src/core/contexts/FolderContext.test.tsx
index fa53a0240c..645f7166de 100644
--- a/frontend/editor/src/core/contexts/FolderContext.test.tsx
+++ b/frontend/editor/src/core/contexts/FolderContext.test.tsx
@@ -4,7 +4,12 @@ import { render, screen, waitFor, act } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { FolderProvider, useFolders } from "@app/contexts/FolderContext";
-import { createFolderId, FolderId, FolderRecord } from "@app/types/folder";
+import {
+ createFolderId,
+ diskFolderId,
+ FolderId,
+ FolderRecord,
+} from "@app/types/folder";
import { expectConsole } from "@app/tests/failOnConsole";
/**
@@ -105,13 +110,23 @@ vi.mock("@app/services/virtualFolderStorage", () => ({
},
}));
-vi.mock("@app/services/localFolderStorage", () => ({
- localFolderStorage: {
- getAllFolders: vi.fn(() => Promise.resolve([])),
- mountDirectory: vi.fn(),
- removeFolder: vi.fn(() => Promise.resolve()),
- },
+// `directoryKey` is a pure path normaliser that FolderContext imports from here, so
+// the mock keeps the real one - the disk-folder tests depend on its exact answers.
+const { mockLocal } = vi.hoisted(() => ({
+ mockLocal: { folders: [] as unknown[] },
}));
+vi.mock("@app/services/localFolderStorage", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@app/services/localFolderStorage")>();
+ return {
+ directoryKey: actual.directoryKey,
+ localFolderStorage: {
+ getAllFolders: vi.fn(() => Promise.resolve([...mockLocal.folders])),
+ mountDirectory: vi.fn(),
+ removeFolder: vi.fn(() => Promise.resolve()),
+ },
+ };
+});
vi.mock("@app/contexts/IndexedDBContext", () => ({
useIndexedDB: () => ({
@@ -420,3 +435,99 @@ describe("FolderContext stale-folder 404 cleanup", () => {
expect(screen.getByTestId("error").textContent).not.toBe("<null>");
});
});
+
+/**
+ * A mounted directory's subfolders are synthesised from the path rather than stored,
+ * so `resolveDiskFolder` is a setState reached from an effect that re-runs on every
+ * folder change. It has to be a no-op the second time or the pair spins until React
+ * gives up with "Maximum update depth exceeded".
+ */
+describe("FolderContext disk subfolder resolution", () => {
+ const MOUNT_DIR = "C:\\Users\\test\\Docs";
+
+ function mountRecord(): FolderRecord {
+ return {
+ id: diskFolderId(MOUNT_DIR),
+ kind: "local",
+ name: "Docs",
+ parentFolderId: null,
+ directory: MOUNT_DIR,
+ createdAt: 0,
+ updatedAt: 0,
+ } as FolderRecord;
+ }
+
+ type DiskProbeApi = {
+ resolveDiskFolder: (id: FolderId) => boolean;
+ knows: (id: FolderId) => boolean;
+ };
+
+ let renders = 0;
+
+ function DiskProbe(props: { onReady: (api: DiskProbeApi) => void }) {
+ const f = useFolders();
+ renders += 1;
+ React.useEffect(() => {
+ props.onReady({
+ resolveDiskFolder: f.resolveDiskFolder,
+ knows: (id) => f.foldersById.has(id),
+ });
+ }, [f, props]);
+ return <div data-testid="count">{f.folders.length}</div>;
+ }
+
+ async function setupWithMount(): Promise<{ current: DiskProbeApi }> {
+ mockList.mockResolvedValue([]);
+ mockLocal.folders = [mountRecord()];
+ const apiRef: { current: DiskProbeApi | null } = { current: null };
+ render(
+ <MemoryRouter>
+ <FolderProvider>
+ <DiskProbe onReady={(api) => (apiRef.current = api)} />
+ </FolderProvider>
+ </MemoryRouter>,
+ );
+ await waitFor(() =>
+ expect(screen.getByTestId("count").textContent).toBe("1"),
+ );
+ if (!apiRef.current) throw new Error("DiskProbe never reported ready");
+ return apiRef as { current: DiskProbeApi };
+ }
+
+ beforeEach(() => {
+ mockList.mockReset();
+ mockIdb.folders = [];
+ mockLocal.folders = [];
+ mockAuth.user = { id: "test-user", is_anonymous: false };
+ mockAuth.isAnonymous = false;
+ renders = 0;
+ });
+
+ test("resolving the same subdirectory twice renders once", async () => {
+ const api = await setupWithMount();
+ const childId = diskFolderId(`${MOUNT_DIR}\\Invoices`);
+
+ await act(async () => {
+ expect(api.current.resolveDiskFolder(childId)).toBe(true);
+ });
+ await waitFor(() => expect(api.current.knows(childId)).toBe(true));
+
+ const settled = renders;
+ await act(async () => {
+ expect(api.current.resolveDiskFolder(childId)).toBe(true);
+ });
+ expect(renders).toBe(settled);
+ });
+
+ test("a path that rebuilds to a different id is refused, not registered", async () => {
+ const api = await setupWithMount();
+ // Trailing separator: the id encodes the path verbatim, so the chain rebuilt
+ // from its segments can never carry this id.
+ const trailing = diskFolderId(`${MOUNT_DIR}\\Invoices\\`);
+
+ await act(async () => {
+ expect(api.current.resolveDiskFolder(trailing)).toBe(false);
+ });
+ expect(api.current.knows(trailing)).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/contexts/FolderContext.tsx b/frontend/editor/src/core/contexts/FolderContext.tsx
index 0c52c4b845..975a65ba07 100644
--- a/frontend/editor/src/core/contexts/FolderContext.tsx
+++ b/frontend/editor/src/core/contexts/FolderContext.tsx
@@ -971,15 +971,21 @@ export function FolderProvider({ children }: FolderProviderProps) {
additions.push([parentId, record]);
parentId = record.id;
}
+ // The rebuilt chain has to end at the id asked for: a path that normalises to
+ // a different one registers nothing the caller can find, leaving it to ask
+ // again on every folder change.
+ if (parentId !== id) return false;
setDiskSubfolders((prev) => {
- const next = new Map(prev);
+ let next: typeof prev | null = null;
for (const [parent, record] of additions) {
- const siblings = next.get(parent) ?? [];
- if (!siblings.some((f) => f.id === record.id)) {
- next.set(parent, [...siblings, record]);
- }
+ const siblings = (next ?? prev).get(parent) ?? [];
+ if (siblings.some((f) => f.id === record.id)) continue;
+ next = next ?? new Map(prev);
+ next.set(parent, [...siblings, record]);
}
- return next;
+ // Unchanged has to mean unchanged: a fresh Map rebuilds `folders`, which
+ // re-runs the effects that resolve a path - straight back into here.
+ return next ?? prev;
});
return true;
},
diff --git a/frontend/editor/src/core/hooks/useLazyThumbnail.ts b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
index 31d8d94bc2..8b8511a925 100644
--- a/frontend/editor/src/core/hooks/useLazyThumbnail.ts
+++ b/frontend/editor/src/core/hooks/useLazyThumbnail.ts
@@ -32,6 +32,32 @@ function drainLazyThumbQueue(): void {
});
}
+// Stub updates go through the file context, and each one re-renders every
+// consumer of the file list. A big folder filling in generates hundreds of
+// thumbnails over minutes; flushing them in windows turns that into a handful
+// of re-renders (React batches same-tick updates into one). The card itself
+// paints immediately from its local state — only the shared stub waits.
+const STUB_THUMB_FLUSH_MS = 500;
+const pendingStubThumbs = new Map<
+ FileId,
+ { thumbnail: string; apply: (id: FileId, thumbnail: string) => void }
+>();
+let stubThumbFlushTimer: ReturnType<typeof setTimeout> | null = null;
+
+function queueStubThumbUpdate(
+ fileId: FileId,
+ thumbnail: string,
+ apply: (id: FileId, thumbnail: string) => void,
+): void {
+ pendingStubThumbs.set(fileId, { thumbnail, apply });
+ stubThumbFlushTimer ??= setTimeout(() => {
+ stubThumbFlushTimer = null;
+ const batch = Array.from(pendingStubThumbs);
+ pendingStubThumbs.clear();
+ for (const [id, entry] of batch) entry.apply(id, entry.thumbnail);
+ }, STUB_THUMB_FLUSH_MS);
+}
+
/**
* Show the stub's thumbnail if present; otherwise pull bytes from IndexedDB,
* generate one, persist it, and update the stub. Server-only files with no
@@ -68,7 +94,9 @@ export function useLazyThumbnail(
if (cancelled || !thumbnail) return;
setThumb(thumbnail);
void indexedDB.updateThumbnail(fileId, thumbnail);
- updateStirlingFileStub(fileId, { thumbnailUrl: thumbnail });
+ queueStubThumbUpdate(fileId, thumbnail, (id, url) =>
+ updateStirlingFileStub(id, { thumbnailUrl: url }),
+ );
} catch {
// non-critical
}
diff --git a/frontend/editor/src/core/services/fileSyncService.ts b/frontend/editor/src/core/services/fileSyncService.ts
index 32e8ae32f1..599f397b12 100644
--- a/frontend/editor/src/core/services/fileSyncService.ts
+++ b/frontend/editor/src/core/services/fileSyncService.ts
@@ -485,6 +485,10 @@ export async function materializeServerStubs(
const primary = ingested[ingested.length - 1]!;
const newId = primary.fileId as FileId;
const remoteUpdates = {
+ // The ingest above made a new local file, which starts in no folder. Without
+ // carrying membership across, materialising a file to open it moves it to the
+ // library root - the copy is the file as far as the library is concerned.
+ folderId: stub.folderId ?? null,
remoteStorageId: stub.remoteStorageId,
remoteStorageUpdatedAt: stub.remoteStorageUpdatedAt,
remoteOwnerUsername: stub.remoteOwnerUsername,
diff --git a/frontend/editor/src/core/tests/stubbed/files-page.spec.ts b/frontend/editor/src/core/tests/stubbed/files-page.spec.ts
index 619712f9b0..5b20234bb1 100644
--- a/frontend/editor/src/core/tests/stubbed/files-page.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/files-page.spec.ts
@@ -8,12 +8,25 @@ interface SeedFile {
id: string;
name: string;
remoteStorageId: number | null;
+ folderId?: string;
versionNumber?: number;
toolHistory?: Array<{ toolId: string; timestamp: number }>;
}
/** Seed IDB + register the cloud entries with the server stub. */
-async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {
+interface SeedFolder {
+ id: string;
+ name: string;
+ parentFolderId?: string;
+}
+
+async function seedFiles(
+ page: Page,
+ files: SeedFile[],
+ // Browser-owned folders, seeded in the same open: a server folder needs an
+ // authenticated sync the stubbed app never runs.
+ virtualFolders: SeedFolder[] = [],
+): Promise<void> {
// Build the server-side view from the cloud entries so reconcileServerFiles
// sees them as still-existing on the server (otherwise they get detached).
const serverFiles = files
@@ -36,7 +49,7 @@ async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {
route.fulfill({ json: serverFiles }),
);
await page.addInitScript(
- ({ records, dbVersion }) => {
+ ({ records, vFolders, dbVersion }) => {
const open = window.indexedDB.open("stirling-pdf-files", dbVersion);
open.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
@@ -56,15 +69,36 @@ async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {
});
fStore.createIndex("name", "name", { unique: false });
}
+ if (!db.objectStoreNames.contains("virtual_folders")) {
+ const vStore = db.createObjectStore("virtual_folders", {
+ keyPath: "id",
+ });
+ vStore.createIndex("parentFolderId", "parentFolderId", {
+ unique: false,
+ });
+ }
+ if (!db.objectStoreNames.contains("local_folders")) {
+ db.createObjectStore("local_folders", { keyPath: "id" });
+ }
};
open.onsuccess = () => {
const db = open.result;
// Yield the connection if the app ever needs to upgrade, and drop it
// once the writes commit, so the seed never blocks the app's open.
db.onversionchange = () => db.close();
- const tx = db.transaction("files", "readwrite");
+ const tx = db.transaction(["files", "virtual_folders"], "readwrite");
const store = tx.objectStore("files");
const now = Date.now();
+ for (const folder of vFolders) {
+ tx.objectStore("virtual_folders").put({
+ id: folder.id,
+ kind: "virtual",
+ name: folder.name,
+ parentFolderId: folder.parentFolderId ?? null,
+ createdAt: now,
+ updatedAt: now,
+ });
+ }
for (const f of records) {
store.put({
id: f.id,
@@ -83,7 +117,7 @@ async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {
originalFileId: f.id,
parentFileId: null,
toolHistory: f.toolHistory ?? [],
- folderId: null,
+ folderId: f.folderId ?? null,
remoteStorageId: f.remoteStorageId,
remoteStorageUpdatedAt: f.remoteStorageId ? now : null,
remoteOwnerUsername: f.remoteStorageId ? "testuser" : null,
@@ -97,7 +131,11 @@ async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {
tx.oncomplete = () => db.close();
};
},
- { records: files, dbVersion: DATABASE_CONFIGS.FILES.version },
+ {
+ records: files,
+ vFolders: virtualFolders,
+ dbVersion: DATABASE_CONFIGS.FILES.version,
+ },
);
}
@@ -415,6 +453,48 @@ test.describe("Files page", () => {
});
});
+ test.describe("Opening a file already in the workspace", () => {
+ test.beforeEach(async ({ page }) => {
+ await stubStorageApis(page);
+ await seedFiles(page, [
+ { id: "dupe-test", name: "dupe-test.pdf", remoteStorageId: null },
+ ]);
+ });
+ test.use({ autoGoto: false });
+
+ /**
+ * Opening a file that is already open has nothing to fetch and nothing to add:
+ * sending it through materialize-and-add again has no reason to succeed twice.
+ */
+ test("opens it once, and opening it again neither duplicates nor throws", async ({
+ page,
+ }) => {
+ await gotoFilesPage(page);
+ const card = () =>
+ page
+ .locator(".files-page-card:not(.is-folder)")
+ .filter({ hasText: "dupe-test.pdf" });
+
+ await card().dblclick();
+ await expect(page).not.toHaveURL(/\/files/, { timeout: 5_000 });
+ await expect(page.locator(".file-sidebar-file-item")).toHaveCount(1, {
+ timeout: 10_000,
+ });
+
+ // Back to the library and open the same file again.
+ await page.goto("/files", { waitUntil: "domcontentloaded" });
+ await expect(card()).toBeVisible({ timeout: 10_000 });
+ await card().dblclick();
+ await expect(page).not.toHaveURL(/\/files/, { timeout: 5_000 });
+
+ // Still one: the workspace holds the file once, and the app is still up.
+ await expect(page.locator(".file-sidebar-file-item")).toHaveCount(1, {
+ timeout: 10_000,
+ });
+ await expect(page.getByText(/Something went wrong/i)).toHaveCount(0);
+ });
+ });
+
test.describe("Drag-and-drop wiring", () => {
test.beforeEach(async ({ page }) => {
await stubStorageApis(page);
@@ -499,7 +579,7 @@ test.describe("Files page", () => {
test.describe("Empty-state CTAs", () => {
test.use({ autoGoto: false });
- test("renders Upload + Create folder CTAs when grid is empty", async ({
+ test("renders Upload + New folder CTAs when grid is empty", async ({
page,
}) => {
await stubStorageApis(page);
@@ -519,15 +599,15 @@ test.describe("Files page", () => {
await expect(
page
.locator(".files-page-empty-actions")
- .getByRole("button", { name: /Create folder/i }),
+ .getByRole("button", { name: /New folder/i }),
).toBeVisible();
});
- test("Create folder CTA disabled when storage isn't reachable", async ({
+ test("New folder CTA is disabled when storage isn't reachable", async ({
page,
}) => {
- // Storage disabled - the New folder action is gated and the CTA
- // should mirror that gating with a disabled state.
+ // The CTA is the header's control, so it reports the same blocked reason
+ // rather than offering a click that cannot land.
await stubStorageApis(page, { storageEnabled: false });
await page.goto("/files", { waitUntil: "domcontentloaded" });
await expect(page.locator(".files-page-empty")).toBeVisible({
@@ -535,7 +615,7 @@ test.describe("Files page", () => {
});
const createCta = page
.locator(".files-page-empty-actions")
- .getByRole("button", { name: /Create folder/i });
+ .getByRole("button", { name: /New folder/i });
await expect(createCta).toBeVisible();
await expect(createCta).toBeDisabled();
});
@@ -856,4 +936,281 @@ test.describe("Files page", () => {
expect(after).toBeGreaterThanOrEqual(before + 24);
});
});
+
+ test.describe("Folder chrome stability", () => {
+ const CHROME_FOLDER = "11111111-2222-4333-8444-555555555561";
+ test.use({ autoGoto: false });
+
+ /** The column is sized by the user, not by its contents: a long name has to give
+ * way inside the row rather than push the panel wider. */
+ test("a long folder name does not widen the tree panel", async ({
+ page,
+ }) => {
+ await stubStorageApis(page);
+ await seedFiles(
+ page,
+ [{ id: "w-1", name: "w-1.pdf", remoteStorageId: null }],
+ [
+ {
+ id: CHROME_FOLDER,
+ name: "Quarterly reconciliation attachments 2024 final v3",
+ },
+ ],
+ );
+ await gotoFilesPage(page);
+
+ const panel = page.locator('.folder-tree-panel[data-active="true"]');
+ await expect(panel).toBeVisible({ timeout: 10_000 });
+ await expect(
+ page.getByRole("treeitem", { name: /Quarterly/i }),
+ ).toBeVisible();
+
+ const width = await panel.evaluate(
+ (el) => el.getBoundingClientRect().width,
+ );
+ expect(width).toBeLessThanOrEqual(280);
+ // Clipped inside the row rather than laid out at full length.
+ const clipped = await page
+ .locator(".files-page-tree-name-head")
+ .first()
+ .evaluate((el) => el.scrollWidth > el.clientWidth);
+ expect(clipped).toBe(true);
+ });
+
+ /** Depth is what grows the bar, so the trail has to stop showing more of it. */
+ test("a deep trail does not change the header height", async ({ page }) => {
+ const ids = [
+ "11111111-2222-4333-8444-555555555571",
+ "11111111-2222-4333-8444-555555555572",
+ "11111111-2222-4333-8444-555555555573",
+ "11111111-2222-4333-8444-555555555574",
+ ];
+ const names = [
+ "Client engagements and retainers",
+ "Quarterly reconciliation attachments",
+ "Supporting documentation bundle 2024",
+ "Signed originals awaiting countersignature",
+ ];
+ await stubStorageApis(page);
+ await seedFiles(
+ page,
+ [{ id: "d-1", name: "d-1.pdf", remoteStorageId: null }],
+ ids.map((id, i) => ({
+ id,
+ name: names[i],
+ parentFolderId: i === 0 ? undefined : ids[i - 1],
+ })),
+ );
+ await gotoFilesPage(page);
+
+ const header = page.locator(".files-page-header");
+ const atRoot = await header.evaluate(
+ (el) => el.getBoundingClientRect().height,
+ );
+
+ const tree = page.getByRole("tree", { name: /Folders/i });
+ for (let i = 0; i < names.length; i += 1) {
+ await tree
+ .getByRole("treeitem", {
+ name: new RegExp(names[i].slice(0, 12), "i"),
+ })
+ .first()
+ .click();
+ await expect(page).toHaveURL(new RegExp(ids[i]), { timeout: 5_000 });
+ }
+ const deep = await header.evaluate(
+ (el) => el.getBoundingClientRect().height,
+ );
+ expect(deep).toBe(atRoot);
+ // Two crumbs, whatever the depth; the rest live behind the overflow menu.
+ await expect(page.locator(".files-page-breadcrumb")).toHaveCount(2);
+ await expect(
+ page.locator(".files-page-breadcrumb-overflow"),
+ ).toBeVisible();
+ });
+
+ /** Walking into a folder must not resize the bar the breadcrumb sits in - the
+ * grid below it would jump by however much the header grew. */
+ test("entering a folder does not change the header height", async ({
+ page,
+ }) => {
+ await stubStorageApis(page);
+ await seedFiles(
+ page,
+ [{ id: "h-1", name: "h-1.pdf", remoteStorageId: null }],
+ [{ id: CHROME_FOLDER, name: "Invoices" }],
+ );
+ await gotoFilesPage(page);
+
+ const header = page.locator(".files-page-header");
+ const atRoot = await header.evaluate(
+ (el) => el.getBoundingClientRect().height,
+ );
+
+ await page.getByRole("treeitem", { name: /Invoices/i }).click();
+ await expect(page).toHaveURL(new RegExp(CHROME_FOLDER), {
+ timeout: 5_000,
+ });
+ const inFolder = await header.evaluate(
+ (el) => el.getBoundingClientRect().height,
+ );
+
+ expect(inFolder).toBe(atRoot);
+ });
+ });
+
+ test.describe("Folder navigation", () => {
+ const FOLDER_ID = "11111111-2222-4333-8444-555555555555";
+ test.beforeEach(async ({ page }) => {
+ await stubStorageApis(page);
+ await seedFiles(
+ page,
+ [
+ { id: "nav-outside", name: "nav-outside.pdf", remoteStorageId: null },
+ {
+ id: "nav-inside",
+ name: "nav-inside.pdf",
+ remoteStorageId: null,
+ folderId: FOLDER_ID,
+ },
+ ],
+ [{ id: FOLDER_ID, name: "Invoices" }],
+ );
+ });
+ test.use({ autoGoto: false });
+
+ const intoFolder = async (page: Page) => {
+ const tree = page.getByRole("tree", { name: /Folders/i });
+ await expect(tree).toBeVisible({ timeout: 10_000 });
+ await tree.getByRole("treeitem", { name: /Invoices/i }).click();
+ await expect(page).toHaveURL(new RegExp(`/files/${FOLDER_ID}`), {
+ timeout: 5_000,
+ });
+ };
+
+ /**
+ * A breadcrumb is a plain jump to an ancestor. Everything the selection change
+ * drives - the listing, the folder filters, the path write - has to survive it.
+ */
+ test("clicking a breadcrumb returns to the root without throwing", async ({
+ page,
+ }) => {
+ await page.goto("/files", { waitUntil: "domcontentloaded" });
+ await intoFolder(page);
+
+ const crumbs = page.getByRole("navigation", { name: /Folder path/i });
+ await expect(crumbs).toBeVisible({ timeout: 5_000 });
+ await crumbs.getByRole("button", { name: /All files/i }).click();
+
+ await expect(page).toHaveURL(/\/files\/?$/, { timeout: 5_000 });
+ await expect(page.getByText(/Something went wrong/i)).toHaveCount(0);
+ // Still a working library, not a husk.
+ await expect(page.getByRole("tree", { name: /Folders/i })).toBeVisible();
+ });
+
+ /**
+ * Back walks up one level per press, and lands where it says it does. Anything
+ * that writes the path in response to the selection can push the folder being
+ * left back on top of the entry just landed on, which reads as a press that did
+ * nothing.
+ */
+ test("back steps up one folder per press", async ({ page }) => {
+ const NESTED = "11111111-2222-4333-8444-555555555556";
+ await seedFiles(
+ page,
+ [
+ {
+ id: "nav-nested",
+ name: "nav-nested.pdf",
+ remoteStorageId: null,
+ folderId: NESTED,
+ },
+ ],
+ [
+ { id: FOLDER_ID, name: "Invoices" },
+ { id: NESTED, name: "Paid", parentFolderId: FOLDER_ID },
+ ],
+ );
+ await page.goto("/files", { waitUntil: "domcontentloaded" });
+
+ const tree = page.getByRole("tree", { name: /Folders/i });
+ await expect(tree).toBeVisible({ timeout: 10_000 });
+ await tree.getByRole("treeitem", { name: /Invoices/i }).click();
+ await expect(page).toHaveURL(new RegExp(FOLDER_ID), { timeout: 5_000 });
+ await tree.getByRole("treeitem", { name: /Paid/i }).click();
+ await expect(page).toHaveURL(new RegExp(NESTED), { timeout: 5_000 });
+
+ await page.goBack();
+ await expect(page).toHaveURL(new RegExp(FOLDER_ID), { timeout: 5_000 });
+ await page.goBack();
+ await expect(page).toHaveURL(/\/files\/?$/, { timeout: 5_000 });
+ await expect(page.getByText(/Something went wrong/i)).toHaveCount(0);
+ });
+
+ /** Each folder is its own history entry, so Back walks up the tree rather than
+ * out of the library, and Forward returns to the folder. */
+ test("back leaves the folder rather than the library, and forward returns", async ({
+ page,
+ }) => {
+ await page.goto("/files", { waitUntil: "domcontentloaded" });
+ await intoFolder(page);
+ const deep = page.url();
+
+ await page.goBack();
+ await expect(page).toHaveURL(/\/files\/?$/, { timeout: 5_000 });
+ await expect(page.getByText(/Something went wrong/i)).toHaveCount(0);
+
+ await page.goForward();
+ await expect(page).toHaveURL(deep, { timeout: 5_000 });
+ await expect(page.getByText(/Something went wrong/i)).toHaveCount(0);
+ });
+ });
+
+ test.describe("Long lists", () => {
+ test.use({ autoGoto: false });
+
+ /**
+ * A folder can hold thousands of files, so the grid renders a window of them plus
+ * a spacer at each end rather than the whole list. Needs a real browser: without
+ * layout the window stands down and everything renders, which is the intended
+ * fallback but proves nothing about the windowing.
+ */
+ test("renders a window of a long list, not all of it", async ({ page }) => {
+ const COUNT = 400;
+ await stubStorageApis(page);
+ await seedFiles(
+ page,
+ Array.from({ length: COUNT }, (_, i) => ({
+ id: `bulk-${i}`,
+ name: `bulk-${String(i).padStart(4, "0")}.pdf`,
+ remoteStorageId: null,
+ })),
+ );
+ await gotoFilesPage(page);
+
+ const cards = page.locator(
+ ".files-page-card:not(.files-page-skeleton-card)",
+ );
+ const rendered = await cards.count();
+ expect(rendered).toBeGreaterThan(0);
+ expect(rendered).toBeLessThan(COUNT / 2);
+
+ // The spacers stand in for the rest, so the scroll height still reflects the
+ // whole folder rather than only what is mounted.
+ const scroller = page.locator(".files-page-content");
+ const metrics = await scroller.evaluate((el) => ({
+ scrollHeight: el.scrollHeight,
+ clientHeight: el.clientHeight,
+ }));
+ expect(metrics.scrollHeight).toBeGreaterThan(metrics.clientHeight * 3);
+
+ // Scrolling to the end swaps the window rather than growing it.
+ const firstBefore = await cards.first().textContent();
+ await scroller.evaluate((el) => el.scrollTo({ top: el.scrollHeight }));
+ await expect
+ .poll(async () => cards.first().textContent(), { timeout: 5_000 })
+ .not.toBe(firstBefore);
+ expect(await cards.count()).toBeLessThan(COUNT / 2);
+ });
+ });
});
diff --git a/frontend/editor/src/desktop/services/localFolderContents.ts b/frontend/editor/src/desktop/services/localFolderContents.ts
index 1d071b74bb..3241b97b8e 100644
--- a/frontend/editor/src/desktop/services/localFolderContents.ts
+++ b/frontend/editor/src/desktop/services/localFolderContents.ts
@@ -36,10 +36,6 @@ async function isWithinMount(path: string): Promise<boolean> {
);
}
-/** Caps the listing; past the cap the freshest files win, which is what is wanted
- * in a Downloads-like directory. */
-const LIST_CAP = 500;
-
/**
* Every stat is a webview-to-Rust round trip, so listing cost is IPC latency, not disk
* speed.
@@ -100,7 +96,7 @@ export async function listDirectory(
}
}
files.sort((a, b) => b.lastModified - a.lastModified);
- return { files: files.slice(0, LIST_CAP), directories };
+ return { files, directories };
}
export async function makeDiskDirectory(