Skip to content

Open source CapCut alternative.

TypeScript

feat(site): multi-select folders alongside tiles in project and library grids

David Lefa06e1b4cdbf
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index f08b0a07..eb9f692b 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -44,6 +44,7 @@ import {
deleteLibraryFolder,
deleteTemplate,
estimatedShape,
+ folderDeleteTakes,
importUrlToLibrary,
libraryMediaUrl,
carryAssetTo,
@@ -54,9 +55,11 @@ import {
uploadToLibrary,
type ImportStage,
type LibraryAsset,
+ type LibraryFolder,
type LibraryTemplateItem,
type LibraryData,
} from "@/cut/lib/library";
+import { additiveClick } from "@/cut/lib/hostKeys";
import { linkFromText, normalizeLink } from "@/cut/lib/link";
import { dialogOnTop, isPasteTarget } from "@/cut/lib/shortcutGate";
import { lightboxItemFromLibrary, useLightbox } from "@/cut/lib/lightbox";
@@ -72,7 +75,7 @@ import { TabStatus } from "./TabStatus";
import { TemplateCard } from "./TemplateCard";
import { homeHref, useCutBase } from "@/cut/lib/nav";
import {
- forgetLinkedCopy,
+ forgetLinkedCopies,
expandLinkedFiles,
isLinkedFile,
linkedAccept,
@@ -84,8 +87,23 @@ import { shapeBand } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { AudioCardFace } from "./AudioPanel";
import { childrenOf, folderTrail, folderWithin, parentOf } from "@/cut/lib/folderTree";
-import { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";
-import { DeleteConfirm, SelectionMenu, useSelectionMenu } from "./selectionMenu";
+import {
+ FolderCrumb,
+ FolderMenuItems,
+ FolderShelf,
+ Marquee,
+ folderSelId,
+ splitPick,
+ useTilePicks,
+} from "./desktopFolders";
+import {
+ DeleteConfirm,
+ SelectionMenu,
+ foldersGoNote,
+ phoneGoNote,
+ pickLabel,
+ useSelectionMenu,
+} from "./selectionMenu";
// A dragged library selection travels as a JSON array of asset ids, so a whole
// marquee-selected collection can be dropped onto a folder at once.
@@ -97,6 +115,10 @@ const LIBRARY_FOLDER_MOVE_MIME = "application/x-cut-library-folder";
const isTemplate = (x: LibraryAsset | LibraryTemplateItem): x is LibraryTemplateItem =>
"layers" in x;
+/** What a delete is about to take: folders and items, picked together. */
+type DeleteSet = { folders: LibraryFolder[]; items: (LibraryAsset | LibraryTemplateItem)[] };
+const NO_PICK: DeleteSet = { folders: [], items: [] };
+
/** What an arriving item is doing right now. An upload is one push from this
* browser; a link is fetched by whichever shelf is taking it, and comes down
* in stages. */
@@ -356,6 +378,7 @@ export function LibraryView() {
const folderList = library.data?.folders;
const folders = useMemo(() => folderList ?? [], [folderList]);
const templates = library.data?.templates ?? [];
+ const listing: LibraryData = { assets: library.data?.assets ?? [], folders, templates };
const patch = useCallback(
(fn: (prev: LibraryData) => LibraryData) => patchLibrary(client, fn),
[client],
@@ -364,7 +387,6 @@ export function LibraryView() {
// The open folder lives in the URL (?folder=…) so the browser's back button
// steps folder → root and the location survives reloads.
const openFolder = useSearchParams().get("folder");
- const [selected, setSelected] = useState<Set<string>>(new Set());
// Media on its way in — an upload or a link — each one a tile in the grid
// from the moment it starts, so the library shows the work rather than the
// dialog holding it.
@@ -382,7 +404,9 @@ export function LibraryView() {
const [folderCreating, setFolderCreating] = useState(false);
// What a delete is about to take: the pick when the card is in it, else
// the one card. Null while nothing is being asked.
- const [deleting, setDeleting] = useState<(LibraryAsset | LibraryTemplateItem)[] | null>(null);
+ const [deleting, setDeleting] = useState<DeleteSet | null>(null);
+ // The folder whose name field is open, when the right-click menu opened it.
+ const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
// Whether an OS-file drag is hovering the surface (a depth counter tames
@@ -611,30 +635,53 @@ export function LibraryView() {
return () => window.removeEventListener("paste", onPaste);
}, []);
- const remove = async () => {
- if (!deleting) return;
+ // Delete a set. A folder takes everything under it — the folders filed
+ // there, however deep, and every item they hold — the way the shelf deletes
+ // it; an item filed in one of those needs no delete of its own. A camera
+ // clip filed there stays in Camera Roll, unfiled.
+ const remove = async (set: DeleteSet) => {
setDeleting(null);
// A shelf that isn't answering keeps its items.
- const taking = deleting.filter((a) => live(a.residency));
- if (taking.length === 0) return;
- const gone = new Set(taking.map((a) => a.id));
+ const goneFolders = set.folders.filter((f) => live(f.residency));
+ const takes = folderDeleteTakes(listing, goneFolders);
+ const inTree = (x: { folderId?: string | null }) => !!x.folderId && takes.tree.has(x.folderId);
+ const goneItems = set.items.filter((a) => live(a.residency) && !inTree(a));
+ if (goneFolders.length + goneItems.length === 0) return;
+ const gone = new Set([...goneItems, ...takes.assets, ...takes.templates].map((a) => a.id));
+ forgetLinkedCopies([...goneItems.filter((a): a is LibraryAsset => !isTemplate(a)), ...takes.assets]);
patch((d) => ({
...d,
- assets: d.assets.filter((a) => !gone.has(a.id)),
+ folders: d.folders.filter((f) => !takes.tree.has(f.id)),
+ assets: d.assets
+ .filter((a) => !gone.has(a.id))
+ .map((a) => (inTree(a) ? { ...a, folderId: null } : a)),
templates: d.templates.filter((t) => !gone.has(t.id)),
}));
setSelected(new Set());
- for (const a of taking) if (!isTemplate(a) && isLinkedType(a.type)) forgetLinkedCopy(a.id);
try {
- await Promise.all(
- taking.map((a) =>
+ await Promise.all([
+ ...goneItems.map((a) =>
isTemplate(a) ? deleteTemplate(a.residency, a.id) : deleteFromLibrary(a.residency, a.id),
),
- );
+ ...goneFolders.map((f) => deleteLibraryFolder(f.residency, f.id)),
+ ]);
} catch {
void reload();
}
};
+ // How many items the folders hold between them, however deep — what the
+ // confirm counts beside them.
+ const heldBy = (fs: LibraryFolder[]) => {
+ const takes = folderDeleteTakes(listing, fs);
+ return takes.assets.length + takes.templates.length;
+ };
+ // How many of the items a delete takes were synced from the phone, which
+ // takes them off the phone too.
+ const phoneSynced = (set: DeleteSet) =>
+ [
+ ...set.items.filter((a): a is LibraryAsset => !isTemplate(a)),
+ ...folderDeleteTakes(listing, set.folders).assets,
+ ].filter((a) => !!a.origin).length;
// Open a folder (or the root, id null) by navigating, so the location is
// shareable and back-button friendly.
@@ -730,6 +777,7 @@ export function LibraryView() {
idset.has(f.id) ? { ...f, parentId } : f,
),
}));
+ setSelected(new Set());
await Promise.all(
moving.map((f) => updateLibraryFolder(f.residency, f.id, { parentId })),
).catch(() => void reload());
@@ -737,16 +785,20 @@ export function LibraryView() {
// Carry the current selection (or just this card) as a folder-move payload,
// with a ghost — alongside the timeline-drag payload the card already sets.
- // A single card drags as itself; a multi-selection keeps the counted stack.
+ // A single card drags as itself; a multi-selection keeps the counted stack,
+ // the folders in it riding under their own MIME.
const dragSelection = (e: React.DragEvent, id: string): string[] => {
- const ids =
- selected.has(id) && selected.size > 0 ? Array.from(selected) : [id];
- if (!selected.has(id)) setSelected(new Set([id]));
- e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(ids));
+ const inPick = selected.has(id);
+ const { folders: pickedFolders, items } = inPick
+ ? splitPick(selected)
+ : { folders: [], items: [id] };
+ if (!inPick) setSelected(new Set([id]));
+ e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(items));
+ if (pickedFolders.length)
+ e.dataTransfer.setData(LIBRARY_FOLDER_MOVE_MIME, JSON.stringify(pickedFolders));
e.dataTransfer.effectAllowed = "copyMove";
- return ids;
+ return [id, ...items.filter((x) => x !== id), ...pickedFolders.map(folderSelId)];
};
-
const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {
const ids = dragSelection(e, a.id);
setObjectDragImage(e, ids.length, ids, () => setSelected(new Set()));
@@ -757,23 +809,46 @@ export function LibraryView() {
const shownTemplates = templates.filter(
(t) => (t.folderId ?? null) === openFolder,
);
+ // The way down to the open folder, and what is filed right here.
+ const trail = useMemo(() => folderTrail(folders, openFolder), [folders, openFolder]);
+ const shownFolders = useMemo(() => childrenOf(folders, openFolder), [folders, openFolder]);
+ // What can be picked at this level, in the order a ⇧-range runs: the
+ // shelf's folders, then the grid with templates leading.
+ const order = [
+ ...shownFolders.map((f) => folderSelId(f.id)),
+ ...[...shownTemplates, ...shown].map((a) => a.id),
+ ];
+ const { picked: selected, setPicked: setSelected, pick: pickTile } = useTilePicks(order);
// The picked run, built once for the whole grid: every card hands the same
// array to its drag and its ⌘C.
const pickedRun = shown.filter((a) => selected.has(a.id));
- // The whole pick, templates leading the way the grid lays them out.
- const picked: (LibraryAsset | LibraryTemplateItem)[] = [
- ...shownTemplates.filter((t) => selected.has(t.id)),
- ...pickedRun,
- ];
+ // The whole pick: the folders on the shelf, and the items with templates
+ // leading the way the grid lays them out.
+ const pick: DeleteSet = {
+ folders: shownFolders.filter((f) => selected.has(folderSelId(f.id))),
+ items: [...shownTemplates.filter((t) => selected.has(t.id)), ...pickedRun],
+ };
+ const pickSize = pick.folders.length + pick.items.length;
// A card inside the pick carries the whole set, the rule its drag, its ⌘C
// and its delete follow.
- const setOf = (a: LibraryAsset | LibraryTemplateItem) => (selected.has(a.id) ? picked : [a]);
- useDeleteKey(rootRef, picked.length > 0 ? () => setDeleting(picked) : null);
- const ctx = useSelectionMenu({
- picked: selected,
- setPicked: setSelected,
- shown: [...shownTemplates, ...shown].map((a) => a.id),
- });
+ const setOf = (a: LibraryAsset | LibraryTemplateItem): DeleteSet =>
+ selected.has(a.id) ? pick : { ...NO_PICK, items: [a] };
+ useDeleteKey(rootRef, pickSize > 0 ? () => setDeleting(pick) : null);
+ const ctx = useSelectionMenu({ picked: selected, setPicked: setSelected, shown: order });
+ // What the open right-click menu acts on.
+ const ctxSet: DeleteSet = ctx.menu
+ ? {
+ folders: shownFolders.filter((f) => ctx.menu!.ids.includes(folderSelId(f.id))),
+ items: [...shownTemplates, ...shown].filter((a) => ctx.menu!.ids.includes(a.id)),
+ }
+ : NO_PICK;
+ // A menu over one folder offers the folder's own actions.
+ const ctxFolder =
+ ctxSet.folders.length === 1 && ctxSet.items.length === 0 ? ctxSet.folders[0] : null;
+ // What the open confirm counts: the items the folders hold, and everything
+ // going in all.
+ const deletingHeld = deleting ? heldBy(deleting.folders) : 0;
+ const deletingTotal = (deleting?.items.length ?? 0) + deletingHeld;
// Right-click over a card: the selection menu. An arrival's preview is the
// one other media here, and the browser's own menu never shows over it.
const onPageContextMenu = (e: React.MouseEvent) => {
@@ -807,9 +882,6 @@ export function LibraryView() {
// Sound tiles are 70% of the shared tile's width and height.
const TILE_AREA = LIBRARY_TILE_AREA;
const audioArea = LIBRARY_AUDIO_TILE_AREA;
- // The way down to the open folder, and what is filed right here.
- const trail = useMemo(() => folderTrail(folders, openFolder), [folders, openFolder]);
- const shownFolders = useMemo(() => childrenOf(folders, openFolder), [folders, openFolder]);
// Where a new folder goes: inside the open folder on its shelf, or at the
// top level of the shelf new items go to — the rule `landing` applies to
// items, spelled out here so the render stays pure.
@@ -934,6 +1006,10 @@ export function LibraryView() {
<ShelfBadge residency={r} offline={!live(r)} />
) : null;
}}
+ picked={selected}
+ onPick={(e, id) => pickTile(e, folderSelId(id), order)}
+ renaming={renamingFolder}
+ onRenamingChange={setRenamingFolder}
onOpen={gotoFolder}
onShare={shareFolder}
onCreate={async (name) => {
@@ -952,24 +1028,13 @@ export function LibraryView() {
}));
await updateLibraryFolder(r, id, { name }).catch(() => void reload());
}}
- onDelete={async (id) => {
- // What the folder held comes up one level, the way the shelf
- // files it.
- const gone = folders.find((f) => f.id === id);
- if (!gone || !live(gone.residency)) return;
- const up = parentOf(gone);
- patch((d) => ({
- folders: d.folders
- .filter((f) => f.id !== id)
- .map((f) => (parentOf(f) === id ? { ...f, parentId: up } : f)),
- assets: d.assets.map((a) =>
- a.folderId === id ? { ...a, folderId: up } : a,
- ),
- templates: d.templates.map((t) =>
- t.folderId === id ? { ...t, folderId: up } : t,
- ),
- }));
- await deleteLibraryFolder(gone.residency, id).catch(() => void reload());
+ // A folder in a pick with others takes the pick to the confirm;
+ // alone, itself.
+ onDelete={(id) => {
+ const f = shownFolders.find((x) => x.id === id);
+ if (!f) return;
+ if (selected.has(folderSelId(id)) && pickSize > 1) setDeleting(pick);
+ else setDeleting({ ...NO_PICK, folders: [f] });
}}
onDropIds={(ids, fid) => void moveItems(ids, fid)}
onDropFolders={(ids, fid) => void moveFolders(ids, fid)}
@@ -998,7 +1063,8 @@ export function LibraryView() {
</button>
) : shown.length === 0 &&
shownPending.length === 0 &&
- shownTemplates.length === 0 ? null : (
+ shownTemplates.length === 0 &&
+ shownFolders.length === 0 ? null : (
<Marquee
className="flex min-h-[40vh] flex-col content-start gap-8"
selected={selected}
@@ -1060,14 +1126,14 @@ export function LibraryView() {
// can only remember is the moment something is actually
// blocked, so that is when the gate's banner — and the way
// out of it — comes up.
- onClick={
- live(a.residency)
- ? () =>
- useLightbox
- .getState()
- .open(lightboxItemFromLibrary(a, true))
- : () => setNeedsApp(true)
- }
+ onClick={(e) => {
+ if (additiveClick(e)) {
+ e.preventDefault();
+ pickTile(e, a.id, order);
+ } else if (live(a.residency))
+ useLightbox.getState().open(lightboxItemFromLibrary(a, true));
+ else setNeedsApp(true);
+ }}
onDelete={
live(a.residency) ? () => setDeleting(setOf(a)) : undefined
}
@@ -1125,40 +1191,41 @@ export function LibraryView() {
</Dialog>
<SelectionMenu menu={ctx.menu} onClose={ctx.close}>
- {ctx.menu?.ids.length === 1 && shown.some((a) => a.id === ctx.menu!.ids[0]) && (
- <DropdownMenuItem
- onClick={() => {
- const asset = shown.find((a) => a.id === ctx.menu!.ids[0]);
- if (asset && live(asset.residency))
- setSharing({ kind: "asset", id: asset.id, residency: asset.residency });
- }}
- >
- <Share2 /> Share
- </DropdownMenuItem>
+ {ctxFolder ? (
+ <FolderMenuItems
+ onShare={() => shareFolder(ctxFolder.id)}
+ onRename={() => setRenamingFolder(ctxFolder.id)}
+ onDelete={() => setDeleting({ ...NO_PICK, folders: [ctxFolder] })}
+ />
+ ) : (
+ <>
+ {ctxSet.folders.length === 0 && ctxSet.items.length === 1 && shown.some((a) => a.id === ctxSet.items[0].id) && (
+ <DropdownMenuItem
+ onClick={() => {
+ const asset = ctxSet.items[0];
+ if (live(asset.residency))
+ setSharing({ kind: "asset", id: asset.id, residency: asset.residency });
+ }}
+ >
+ <Share2 /> Share
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem variant="destructive" onClick={() => setDeleting(ctxSet)}>
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ </>
)}
- <DropdownMenuItem
- variant="destructive"
- onClick={() =>
- setDeleting(
- [...shownTemplates, ...shown].filter((a) => ctx.menu!.ids.includes(a.id)),
- )
- }
- >
- <Trash2 /> Delete
- </DropdownMenuItem>
</SelectionMenu>
<DeleteConfirm
open={!!deleting}
title={
- deleting && deleting.length > 1
- ? `Delete ${deleting.length} items?`
- : `Delete “${deleting?.[0]?.name}”?`
+ deleting ? `Delete ${pickLabel(deleting.folders, deleting.items, ["item", "items"], deletingHeld)}?` : ""
}
- description={`Projects that already use ${deleting && deleting.length > 1 ? "them" : "it"} keep their own copy.`}
+ description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}Projects that already use ${deletingTotal === 1 ? "it" : "them"} keep their own copy.`}
action="Remove"
onClose={() => setDeleting(null)}
- onConfirm={() => void remove()}
+ onConfirm={() => deleting && void remove(deleting)}
/>
{sharing && library.data && <LibraryShareDialog
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index 93ae3933..6883f7c9 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -43,6 +43,7 @@ import {
import { additiveClick } from "@/cut/lib/hostKeys";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { capturePosterWhenReady, readPoster } from "@/cut/lib/posterCache";
+import { apiJson } from "@/cut/lib/api";
import { quotaErrorMessage } from "@/cut/lib/backend/cloud";
import {
useCloudUsage,
@@ -82,10 +83,24 @@ import {
} from "@/cut/lib/types";
import { cn } from "@/lib/utils";
import { setObjectDragImage } from "@/cut/lib/assetDrag";
-import { childrenOf, folderTrail, folderWithin, parentOf } from "@/cut/lib/folderTree";
+import { childrenOf, folderTrail, folderWithin, parentOf, subtreeOf } from "@/cut/lib/folderTree";
import { PICKED_RING } from "@/cut/lib/assetPick";
-import { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";
-import { DeleteConfirm, SelectionMenu, useSelectionMenu } from "./selectionMenu";
+import {
+ FolderCrumb,
+ FolderMenuItems,
+ FolderShelf,
+ Marquee,
+ folderSelId,
+ splitPick,
+ useTilePicks,
+} from "./desktopFolders";
+import {
+ DeleteConfirm,
+ SelectionMenu,
+ foldersGoNote,
+ pickLabel,
+ useSelectionMenu,
+} from "./selectionMenu";
import { formatBytes } from "@/lib/bytes";
type View = "gallery" | "list";
@@ -120,6 +135,17 @@ type SectionData = {
error: boolean;
};
+/** What a delete is about to take: folders and projects, picked together. */
+type DeleteSet = {
+ folders: ProjectFolder[];
+ projects: { project: ProjectSummary; residency: Residency }[];
+};
+const NO_PICK: DeleteSet = { folders: [], projects: [] };
+
+// What a shelf's refusal says, when it says anything.
+const errorOf = async (res: Response | null) =>
+ res ? (await apiJson<object>(res)).error : undefined;
+
// A dragged selection is carried as a JSON array of project ids, so one drag can
// move a whole marquee-selected collection into a folder.
const PROJECT_MIME = "application/x-cut-project";
@@ -279,7 +305,6 @@ export function ProjectsHome() {
const folderOwner: Residency | null = openFolder
? (residencies.find((r) => data[r].folders.some((f) => f.id === openFolder)) ?? null)
: null;
- const [selected, setSelected] = useState<Set<string>>(new Set());
const view = useSyncExternalStore(subscribeView, readView, serverView);
// The residency the pending creation was launched for; null when the naming
// dialog is closed.
@@ -290,9 +315,9 @@ export function ProjectsHome() {
);
// What a delete is about to take: the pick when the card is in it, else
// the one card. Null while nothing is being asked.
- const [deleting, setDeleting] = useState<
- { project: ProjectSummary; residency: Residency }[] | null
- >(null);
+ const [deleting, setDeleting] = useState<DeleteSet | null>(null);
+ // The folder whose name field is open, when the right-click menu opened it.
+ const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
@@ -357,20 +382,36 @@ export function ProjectsHome() {
router.push(homeHref(base, "projects", id));
};
- // What a deleted folder held comes up one level, the way the shelf files it.
+ // A deleted folder takes everything under it: the folders filed there,
+ // however deep, and every project they hold. The shelf deletes each project
+ // the way its own delete goes; once it has, this side purges what it keeps
+ // for them. A shelf that refuses gets its list back.
const deleteFolder = async (r: Residency, id: string) => {
if (!live(r)) return;
- const up = parentOf(data[r].folders.find((f) => f.id === id) ?? { id });
+ const tree = new Set(subtreeOf(data[r].folders, id));
+ const inTree = (p: ProjectSummary) => !!p.folderId && tree.has(p.folderId);
+ const held = (data[r].projects ?? []).filter(inTree);
patch(r, (s) => ({
- folders: s.folders
- .filter((f) => f.id !== id)
- .map((f) => (parentOf(f) === id ? { ...f, parentId: up } : f)),
- projects: s.projects.map((p) => (p.folderId === id ? { ...p, folderId: up } : p)),
+ folders: s.folders.filter((f) => !tree.has(f.id)),
+ projects: s.projects.filter((p) => !inTree(p)),
}));
- await backendFor(r)
+ const res = await backendFor(r)
.fetch(`/api/cut/projects/folders/${id}`, { method: "DELETE" })
- .catch(() => void refresh(r));
+ .catch(() => null);
+ if (!res?.ok) {
+ void refresh(r);
+ throw new Error((await errorOf(res)) ?? "Could not delete the folder.");
+ }
+ for (const p of held) purgeProject(p.id, r);
};
+ // How many projects the folders hold between them, however deep — what
+ // the confirm counts beside them.
+ const heldBy = (fs: ProjectFolder[]) =>
+ fs.reduce((n, f) => {
+ const r = residencyOfFolder(f.id);
+ const tree = new Set(subtreeOf(data[r].folders, f.id));
+ return n + (data[r].projects ?? []).filter((p) => !!p.folderId && tree.has(p.folderId)).length;
+ }, 0);
// File folders under a folder (or out to the root, parentId null). A folder
// files only beside itself: under a folder on its own shelf, never under
@@ -390,6 +431,7 @@ export function ProjectsHome() {
...s,
folders: s.folders.map((f) => (idset.has(f.id) ? { ...f, parentId } : f)),
}));
+ setSelected(new Set());
await Promise.all(
moving.map((f) =>
backendFor(r).fetch(`/api/cut/projects/folders/${f.id}`, {
@@ -574,32 +616,47 @@ export function ProjectsHome() {
}
};
- const removeOne = async (id: string, residency: Residency) => {
- await backendFor(residency).fetch(`/api/cut/projects/${id}`, { method: "DELETE" });
- // The doc, media, and exports go with the folder on the server. Purge the
- // client-side residue keyed to this project so nothing survives it: a live
- // scene run, its in-flight renders, its chat history (whose ids the
- // render-resume guard reads to keep a deleted thread's render from
- // landing), and the cached copy of its document.
+ // The doc, media, and exports go with the folder on the server. Purge the
+ // client-side residue keyed to this project so nothing survives it: a live
+ // scene run, its in-flight renders, its chat history (whose ids the
+ // render-resume guard reads to keep a deleted thread's render from
+ // landing), and the cached copy of its document.
+ const purgeProject = (id: string, residency: Residency) => {
useGenScene.getState().killProject(id);
useGenerate.getState().cancelForOwner({ projectId: id });
clearProjectThreads(id);
dropCachedDoc(id, residency);
if (residency === "cloud") void dropLocalProjectCopy(id);
+ };
+
+ const removeOne = async (id: string, residency: Residency) => {
+ const res = await backendFor(residency).fetch(`/api/cut/projects/${id}`, { method: "DELETE" });
+ if (!res.ok) throw new Error((await errorOf(res)) ?? "Could not delete the project.");
+ purgeProject(id, residency);
patch(residency, (s) => ({ ...s, projects: s.projects.filter((p) => p.id !== id) }));
};
const remove = async () => {
if (!deleting) return;
- // A shelf that isn't answering keeps its projects.
- const taking = deleting.filter(({ residency }) => live(residency));
- if (taking.length === 0) return setDeleting(null);
+ // A shelf that isn't answering keeps its projects. A project filed under
+ // a folder in the set goes with the folder.
+ const folders = deleting.folders.filter((f) => live(residencyOfFolder(f.id)));
+ const trees = new Set(folders.flatMap((f) => subtreeOf(data[residencyOfFolder(f.id)].folders, f.id)));
+ const projects = deleting.projects.filter(
+ ({ project, residency }) => live(residency) && !(project.folderId && trees.has(project.folderId))
+ );
+ if (folders.length + projects.length === 0) return setDeleting(null);
setBusy(true);
try {
- await Promise.all(taking.map(({ project, residency }) => removeOne(project.id, residency)));
+ await Promise.all([
+ ...projects.map(({ project, residency }) => removeOne(project.id, residency)),
+ ...folders.map((f) => deleteFolder(residencyOfFolder(f.id), f.id)),
+ ]);
setSelected(new Set());
- setDeleting(null);
+ } catch (e) {
+ setDupError(e instanceof Error && e.message ? e.message : "Could not delete.");
} finally {
+ setDeleting(null);
setBusy(false);
}
};
@@ -636,56 +693,72 @@ export function ProjectsHome() {
.map((p) => ({ p, r }))
)
.sort((a, b) => (b.p.updatedAt ?? 0) - (a.p.updatedAt ?? 0));
-
- // The picked run, built once for the whole grid, on the shelves that answer.
- // A card inside the pick carries the whole set, the rule its ⋯ menu, the
- // right-click menu and ⌫ follow.
- const pickedRun = mergedShown
- .filter(({ p, r }) => selected.has(p.id) && live(r))
- .map(({ p, r }) => ({ project: p, residency: r }));
- const setOf = (p: ProjectSummary, r: Residency) =>
- selected.has(p.id) ? pickedRun : [{ project: p, residency: r }];
- useDeleteKey(rootRef, pickedRun.length > 0 ? () => setDeleting(pickedRun) : null);
- const ctx = useSelectionMenu({
- picked: selected,
- setPicked: setSelected,
- shown: mergedShown.map(({ p }) => p.id),
- });
- // What the open right-click menu acts on: the live projects among its ids,
- // and where the whole set can move — a place every one of them can go.
+ // What can be picked at this level, in the order a ⇧-range runs: the
+ // shelf's folders, then the grid.
+ const order = [...shownFolders.map((f) => folderSelId(f.id)), ...mergedShown.map(({ p }) => p.id)];
+ const { picked: selected, setPicked: setSelected, pick: pickTile } = useTilePicks(order);
+
+ // The pick, built once for the whole grid, on the shelves that answer: the
+ // folders on the shelf and the projects in the grid. A card inside the
+ // pick carries the whole set, the rule its ⋯ menu, the right-click menu
+ // and ⌫ follow.
+ const pick: DeleteSet = {
+ folders: shownFolders.filter(
+ (f) => selected.has(folderSelId(f.id)) && live(residencyOfFolder(f.id))
+ ),
+ projects: mergedShown
+ .filter(({ p, r }) => selected.has(p.id) && live(r))
+ .map(({ p, r }) => ({ project: p, residency: r })),
+ };
+ const pickSize = pick.folders.length + pick.projects.length;
+ const setOf = (p: ProjectSummary, r: Residency): DeleteSet =>
+ selected.has(p.id) ? pick : { ...NO_PICK, projects: [{ project: p, residency: r }] };
+ useDeleteKey(rootRef, pickSize > 0 ? () => setDeleting(pick) : null);
+ const ctx = useSelectionMenu({ picked: selected, setPicked: setSelected, shown: order });
+ // What the open right-click menu acts on: the live folders and projects
+ // among its ids, and where the projects can move — a place every one of
+ // them can go, offered while no folder is along.
const ctxSet = ctx.menu
? mergedShown.filter(({ p, r }) => ctx.menu!.ids.includes(p.id) && live(r))
: [];
- const ctxMoveTo = ctxSet.length
- ? moveDests(ctxSet[0].r)
- .filter((d) => ctxSet.every(({ r }) => moveDests(r).includes(d)))
- .map((d) => ({
- target: d,
- run: () =>
- void (async () => {
- for (const { p, r } of ctxSet) await moveAcross(r, d, p);
- })(),
- }))
+ const ctxFolders = ctx.menu
+ ? shownFolders.filter(
+ (f) => ctx.menu!.ids.includes(folderSelId(f.id)) && live(residencyOfFolder(f.id))
+ )
: [];
+ // A menu over one folder offers the folder's own actions.
+ const ctxFolder = ctxFolders.length === 1 && ctxSet.length === 0 ? ctxFolders[0] : null;
+ // What the open confirm counts: the projects the folders hold, and
+ // everything going in all.
+ const deletingHeld = deleting ? heldBy(deleting.folders) : 0;
+ const deletingTotal = (deleting?.projects.length ?? 0) + deletingHeld;
+ const ctxMoveTo =
+ ctxSet.length && ctxFolders.length === 0
+ ? moveDests(ctxSet[0].r)
+ .filter((d) => ctxSet.every(({ r }) => moveDests(r).includes(d)))
+ .map((d) => ({
+ target: d,
+ run: () =>
+ void (async () => {
+ for (const { p, r } of ctxSet) await moveAcross(r, d, p);
+ })(),
+ }))
+ : [];
// Begin a project drag. Dragging a member of the current selection carries the
- // whole selection; dragging anything else drags (and selects) just that item.
+ // whole selection, the folders in it under their own MIME; dragging anything
+ // else drags (and selects) just that item.
const onProjectDragStart = (e: React.DragEvent, p: ProjectSummary) => {
- const ids = selected.has(p.id) && selected.size > 0 ? Array.from(selected) : [p.id];
- if (!selected.has(p.id)) setSelected(new Set([p.id]));
- e.dataTransfer.setData(PROJECT_MIME, JSON.stringify(ids));
+ const inPick = selected.has(p.id);
+ const { folders, items } = inPick ? splitPick(selected) : { folders: [], items: [p.id] };
+ if (!inPick) setSelected(new Set([p.id]));
+ e.dataTransfer.setData(PROJECT_MIME, JSON.stringify(items));
+ if (folders.length) e.dataTransfer.setData(PROJECT_FOLDER_MIME, JSON.stringify(folders));
e.dataTransfer.effectAllowed = "move";
+ const ids = [p.id, ...items.filter((x) => x !== p.id), ...folders.map(folderSelId)];
setObjectDragImage(e, ids.length, ids, () => setSelected(new Set()));
};
- const toggleSelect = (id: string) =>
- setSelected((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
-
// Only OS-file drags are drop targets here; internal project drags carry
// PROJECT_MIME and are handled by the folder tiles and breadcrumb instead.
const isFileDrag = (e: React.DragEvent) => Array.from(e.dataTransfer.types).includes("Files");
@@ -708,13 +781,24 @@ export function ProjectsHome() {
size: items.reduce((n, p) => n + (p.sizeBytes ?? 0), 0),
};
}}
+ picked={selected}
+ onPick={(e, id) => pickTile(e, folderSelId(id), order)}
+ renaming={renamingFolder}
+ onRenamingChange={setRenamingFolder}
onOpen={gotoFolder}
onCreate={(n) => {
const r = folderCreating ?? folderTarget;
void createFolder(r, n, r === folderOwner ? openFolder : null);
}}
onRename={(id, n) => void renameFolder(residencyOfFolder(id), id, n)}
- onDelete={(id) => void deleteFolder(residencyOfFolder(id), id)}
+ // A folder in a pick with others takes the pick to the confirm; alone,
+ // itself.
+ onDelete={(id) => {
+ const f = shownFolders.find((x) => x.id === id);
+ if (!f) return;
+ if (selected.has(folderSelId(id)) && pickSize > 1) setDeleting(pick);
+ else setDeleting({ ...NO_PICK, folders: [f] });
+ }}
onDropIds={(ids, fid) => void moveProjects(residencyOfFolder(fid), ids, fid)}
onDropFolders={(ids, fid) => void moveFolders(ids, fid)}
// File imports run on the globally bound backend, so only its folders
@@ -759,7 +843,7 @@ export function ProjectsHome() {
onClick={(e) => {
if (additiveClick(e)) {
e.preventDefault();
- toggleSelect(p.id);
+ pickTile(e, p.id, order);
return;
}
router.push(projectHref(base, p.id, "projects", openFolder));
@@ -843,7 +927,7 @@ export function ProjectsHome() {
onClick={(e) => {
if (additiveClick(e)) {
e.preventDefault();
- toggleSelect(p.id);
+ pickTile(e, p.id, order);
return;
}
router.push(projectHref(base, p.id, "projects", openFolder));
@@ -1104,38 +1188,64 @@ export function ProjectsHome() {
</Dialog>
{/* A shelf that isn't answering takes no changes, so a pick with none
- of its projects live opens no menu. */}
- <SelectionMenu menu={ctxSet.length > 0 ? ctx.menu : null} onClose={ctx.close}>
- <ProjectMenuItems
- onRename={
- ctxSet.length === 1
- ? () => {
- setName(ctxSet[0].p.name);
- setRenaming({ project: ctxSet[0].p, residency: ctxSet[0].r });
- }
- : undefined
- }
- onDuplicate={
- ctxSet.length === 1 ? () => void duplicate(ctxSet[0].r, ctxSet[0].p) : undefined
- }
- moveTo={ctxMoveTo}
- onDelete={() => setDeleting(ctxSet.map(({ p, r }) => ({ project: p, residency: r })))}
- />
+ of its projects or folders live opens no menu. */}
+ <SelectionMenu menu={ctxSet.length + ctxFolders.length > 0 ? ctx.menu : null} onClose={ctx.close}>
+ {ctxFolder ? (
+ <FolderMenuItems
+ onRename={() => setRenamingFolder(ctxFolder.id)}
+ onDelete={() => setDeleting({ ...NO_PICK, folders: [ctxFolder] })}
+ />
+ ) : (
+ <ProjectMenuItems
+ onRename={
+ ctxSet.length === 1 && ctxFolders.length === 0
+ ? () => {
+ setName(ctxSet[0].p.name);
+ setRenaming({ project: ctxSet[0].p, residency: ctxSet[0].r });
+ }
+ : undefined
+ }
+ onDuplicate={
+ ctxSet.length === 1 && ctxFolders.length === 0
+ ? () => void duplicate(ctxSet[0].r, ctxSet[0].p)
+ : undefined
+ }
+ moveTo={ctxMoveTo}
+ onDelete={() =>
+ setDeleting({
+ folders: ctxFolders,
+ projects: ctxSet.map(({ p, r }) => ({ project: p, residency: r })),
+ })
+ }
+ />
+ )}
</SelectionMenu>
<DeleteConfirm
open={!!deleting}
title={
- deleting && deleting.length > 1
- ? `Delete ${deleting.length} projects?`
- : `Delete “${deleting?.[0]?.project.name}”?`
+ deleting
+ ? `Delete ${pickLabel(deleting.folders, deleting.projects.map((x) => x.project), ["project", "projects"], deletingHeld)}?`
+ : ""
}
- description={
- deleting && deleting.length > 1
- ? "This deletes each project’s whole folder, including its media files and exports. This can’t be undone."
- : "This deletes the whole project folder, including its media files and exports. This can’t be undone."
+ description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${
+ deletingTotal === 0
+ ? deleting?.folders.length === 1
+ ? "The folder is empty."
+ : "The folders are empty."
+ : deletingTotal === 1
+ ? "This deletes the whole project folder, including its media files and exports."
+ : "This deletes each project’s whole folder, including its media files and exports."
+ } This can’t be undone.`}
+ action={
+ !deleting || deleting.folders.length === 0
+ ? deleting && deleting.projects.length > 1
+ ? "Delete projects"
+ : "Delete project"
+ : deleting.projects.length === 0 && deleting.folders.length === 1
+ ? "Delete folder"
+ : "Delete"
}
- action={deleting && deleting.length > 1 ? "Delete projects" : "Delete project"}
busy={busy}
onClose={() => setDeleting(null)}
onConfirm={() => void remove()}
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 29ed7a4e..98e7dd92 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -65,6 +65,7 @@ import {
deleteFromLibrary,
deleteLibraryFolder,
deleteTemplate,
+ folderDeleteTakes,
importLibraryAsset,
importTemplateToProject,
libraryMediaUrl,
@@ -89,7 +90,7 @@ import { isSoundPresetTemplate } from "@/cut/lib/soundPresets";
import { isStylePresetTemplate } from "@/cut/lib/stylePresets";
import { retryUpload } from "@/cut/lib/importQueue";
import {
- forgetLinkedCopy,
+ forgetLinkedCopies,
expandLinkedFiles,
isLinkedFile,
linkedAccept,
@@ -121,8 +122,23 @@ import { usePanelRequestEffect } from "@/cut/lib/panelRequest";
import { CopyNameLabel } from "./AssetRefs";
import { AudioCardFace, AudioPanel } from "./AudioPanel";
import { childrenOf, folderTrail, folderWithin, parentOf } from "@/cut/lib/folderTree";
-import { FolderCrumb, FolderShelf, Marquee, useTilePicks } from "./desktopFolders";
-import { DeleteConfirm, SelectionMenu, useSelectionMenu } from "./selectionMenu";
+import {
+ FolderCrumb,
+ FolderMenuItems,
+ FolderShelf,
+ Marquee,
+ folderSelId,
+ splitPick,
+ useTilePicks,
+} from "./desktopFolders";
+import {
+ DeleteConfirm,
+ SelectionMenu,
+ foldersGoNote,
+ phoneGoNote,
+ pickLabel,
+ useSelectionMenu,
+} from "./selectionMenu";
import { TemplateCard } from "./TemplateCard";
import { GenerateVideoPanel } from "./GeneratePanel";
import { ImageGenPanel } from "./ImageGenPanel";
@@ -808,21 +824,39 @@ function ProjectFilesPanel({
? null
: storedFolder;
const shown = assets.filter((a) => (a.folderId ?? null) === openFolder);
+ const readOnly = useEditor((s) => s.readOnly);
+ // The shelf's folders join the pick at the root, while the project takes
+ // changes; a shared view's folders only open.
+ const shelfFolders = openFolder === null ? folders : [];
+ const order = [
+ ...(readOnly ? [] : shelfFolders).map((f) => folderSelId(f.id)),
+ ...shown.map((a) => a.id),
+ ];
// Which tiles are picked, so a sweep or a ⇧-click can hand the timeline a
// run of media in one drag. Anything that leaves the grid leaves the pick.
- const { picked, setPicked, pick } = useTilePicks(shown.map((a) => a.id));
- // Built once for the whole grid; each card hands the same array on.
- const pickedIds = [...picked];
+ const { picked, setPicked, pick } = useTilePicks(order);
+ // Built once for the whole grid; each card hands the same array on. The
+ // folders in the pick stay on the shelf: nothing drags them.
+ const pickedIds = splitPick(picked).items;
// The name field of a folder being made: [] from the empty-space menu, the
// picked ids when the selection menu starts one — those file into the
// folder the moment its name is committed.
const [creatingIds, setCreatingIds] = useState<string[] | null>(null);
+ // The folder whose name field is open, when the right-click menu opened it.
+ const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
// The right-click menu at the cursor: `ids` carries the selection it acts
// on, empty over empty space (just "New folder").
- const ctx = useSelectionMenu({ picked, setPicked, shown: shown.map((a) => a.id) });
- // A selection delete that would also take timeline clips waits on this
- // confirm; ids whose media is unused delete without one.
+ const ctx = useSelectionMenu({ picked, setPicked, shown: order });
+ // A delete that would also take timeline clips, or a folder with files in
+ // it, waits on this confirm; unused media and an empty folder go without
+ // one. The ids are the pick's, folders and files alike.
const [deletingIds, setDeletingIds] = useState<string[] | null>(null);
+ const deletingSet = splitPick(deletingIds ?? []);
+ const deletingFolders = folders.filter((f) => deletingSet.folders.includes(f.id));
+ const deletingFiles = assets.filter((a) => deletingSet.items.includes(a.id));
+ const deletingHeld = assets.filter(
+ (a) => !!a.folderId && deletingSet.folders.includes(a.folderId)
+ ).length;
const templates = useEditor((s) => s.templates);
const exportOpen = useEditor((s) => s.exportOpen);
// A render that finishes in the background (dialog closed) drops a new file in
@@ -846,7 +880,6 @@ function ProjectFilesPanel({
// and that render carries its progress on a local row; the engine's feed
// alone showed nothing at all while it ran.
const exporting = useExportRows(projectId).filter(exportInFlight);
- const readOnly = useEditor((s) => s.readOnly);
// The whole panel takes drops: OS files import into this project and stay off
// the timeline, and a project asset made elsewhere (a generation, a
// recording) dropped here moves into Media. It lights up for both.
@@ -931,16 +964,26 @@ function ProjectFilesPanel({
if (preview && !list.some((e) => e.file === preview.file)) setPreview(null);
};
- // The selection menu's delete: unused media goes straight away; media on
- // the timeline waits on the confirm below, which names what goes with it.
+ // Delete a pick, folders and files. A folder takes every file in it with
+ // it: unused media and an empty folder go straight away; media on the
+ // timeline, or a folder with files in it, waits on the confirm below,
+ // which names what goes.
const removeMany = (ids: string[]) => {
const s = useEditor.getState();
- const gone = new Set(ids);
+ const { folders: goneFolders, items } = splitPick(ids);
+ const held = s.assets.filter((a) => !!a.folderId && goneFolders.includes(a.folderId));
+ const gone = new Set([...items, ...held.map((a) => a.id)]);
const uses =
s.clips.filter((c) => gone.has(c.assetId)).length +
s.audioClips.filter((c) => gone.has(c.assetId)).length;
- if (uses > 0) setDeletingIds(ids);
- else for (const id of ids) s.removeAsset(id);
+ if (uses > 0 || held.length > 0) setDeletingIds(ids);
+ else deleteNow(ids);
+ };
+ const deleteNow = (ids: string[]) => {
+ const s = useEditor.getState();
+ const { folders: goneFolders, items } = splitPick(ids);
+ for (const id of goneFolders) s.removeMediaFolder(id);
+ for (const id of items) s.removeAsset(id);
};
// Right-click: over a card, the selection menu (the card joins the pick if
@@ -1004,44 +1047,54 @@ function ProjectFilesPanel({
/>
</div>
)}
- {openFolder === null && (folders.length > 0 || creatingIds !== null) && (
- <div className="shrink-0 px-3.5">
- <FolderShelf
- rows
- folders={readOnly ? folders.map((f) => ({ ...f, locked: true })) : folders}
- mime={MEDIA_MOVE_MIME}
- statOf={(id) => ({ count: assets.filter((a) => a.folderId === id).length })}
- onOpen={(id) => setOpenFolder(id)}
- onCreate={(name) => {
- useEditor.getState().addMediaFolder(name, creatingIds ?? undefined);
- }}
- onRename={(id, name) => useEditor.getState().renameMediaFolder(id, name)}
- onDelete={(id) => useEditor.getState().removeMediaFolder(id)}
- onDropIds={(ids, fid) => useEditor.getState().moveAssetsToMediaFolder(ids, fid)}
- onDropFiles={
- readOnly
- ? undefined
- : (files, fid) => onImport(files, { mediaOnly: true, folderId: fid })
- }
- onRefDrop={(ref, fid) => {
- // Media made elsewhere — a generation, a recording, a timeline
- // clip's asset — dropped on a folder tile joins Media filed there.
- if (ref.scope !== "project") return;
- useEditor.getState().updateAsset(ref.id, {
- origin: undefined,
- chatId: undefined,
- folderId: fid,
- });
- }}
- creating={creatingIds !== null}
- onCreatingChange={(c) => {
- if (!c) setCreatingIds(null);
- }}
- />
- </div>
- )}
-
+ {/* The shelf scrolls with the grid, so one sweep reaches both. */}
<ScrollArea className="min-h-0 flex-1" contentClassName="pt-1 pb-3.5">
+ {openFolder === null && (folders.length > 0 || creatingIds !== null) && (
+ <div className="shrink-0 px-3.5">
+ <FolderShelf
+ rows
+ folders={readOnly ? folders.map((f) => ({ ...f, locked: true })) : folders}
+ mime={MEDIA_MOVE_MIME}
+ picked={picked}
+ onPick={(e, id) => pick(e, folderSelId(id), order)}
+ renaming={renamingFolder}
+ onRenamingChange={setRenamingFolder}
+ statOf={(id) => ({ count: assets.filter((a) => a.folderId === id).length })}
+ onOpen={(id) => setOpenFolder(id)}
+ onCreate={(name) => {
+ useEditor.getState().addMediaFolder(name, creatingIds ?? undefined);
+ }}
+ onRename={(id, name) => useEditor.getState().renameMediaFolder(id, name)}
+ // A folder in a pick with others takes the pick; alone, itself.
+ onDelete={(id) =>
+ removeMany(
+ picked.has(folderSelId(id)) && picked.size > 1 ? [...picked] : [folderSelId(id)]
+ )
+ }
+ onDropIds={(ids, fid) => useEditor.getState().moveAssetsToMediaFolder(ids, fid)}
+ onDropFiles={
+ readOnly
+ ? undefined
+ : (files, fid) => onImport(files, { mediaOnly: true, folderId: fid })
+ }
+ onRefDrop={(ref, fid) => {
+ // Media made elsewhere — a generation, a recording, a timeline
+ // clip's asset — dropped on a folder tile joins Media filed there.
+ if (ref.scope !== "project") return;
+ useEditor.getState().updateAsset(ref.id, {
+ origin: undefined,
+ chatId: undefined,
+ folderId: fid,
+ });
+ }}
+ creating={creatingIds !== null}
+ onCreatingChange={(c) => {
+ if (!c) setCreatingIds(null);
+ }}
+ />
+ </div>
+ )}
+
{openFolder === null && templates.length > 0 && (
<div className="flex flex-col gap-1.5 px-3.5 pb-3">
{templates.map((t) => (
@@ -1066,7 +1119,7 @@ function ProjectFilesPanel({
))}
</div>
)}
- {shown.length === 0 && !importing ? (
+ {order.length === 0 && !importing ? (
openFolder !== null ? (
<div className="px-3.5 py-6 text-center text-xs text-muted-foreground">
Empty folder
@@ -1095,7 +1148,7 @@ function ProjectFilesPanel({
asset={a}
projectId={projectId}
selected={picked.has(a.id)}
- onSelect={(e) => pick(e, a.id, shown.map((x) => x.id))}
+ onSelect={(e) => pick(e, a.id, order)}
dragGroup={pickedIds}
onDragLanded={() => setPicked(new Set())}
/>
@@ -1240,19 +1293,31 @@ function ProjectFilesPanel({
<DropdownMenuItem onClick={() => setCreatingIds([])}>
<FolderPlus /> New folder
</DropdownMenuItem>
+ ) : ctx.menu && splitPick(ctx.menu.ids).folders.length === 1 && ctx.menu.ids.length === 1 ? (
+ // A menu over one folder offers the folder's own actions.
+ <FolderMenuItems
+ onRename={() => setRenamingFolder(splitPick(ctx.menu!.ids).folders[0])}
+ onDelete={() => removeMany(ctx.menu!.ids)}
+ />
) : (
<>
- <DropdownMenuItem
- onClick={() => {
- // The name field opens on the root shelf; the picked ids
- // file into the folder when the name is committed.
- setCreatingIds(ctx.menu!.ids);
- setOpenFolder(null);
- }}
- >
- <FolderPlus /> New folder
- </DropdownMenuItem>
- <DropdownMenuSeparator />
+ {/* Folders file into nothing here, so a pick holding one makes
+ no new folder. */}
+ {ctx.menu && splitPick(ctx.menu.ids).folders.length === 0 && (
+ <>
+ <DropdownMenuItem
+ onClick={() => {
+ // The name field opens on the root shelf; the picked ids
+ // file into the folder when the name is committed.
+ setCreatingIds(ctx.menu!.ids);
+ setOpenFolder(null);
+ }}
+ >
+ <FolderPlus /> New folder
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
<DropdownMenuItem variant="destructive" onClick={() => removeMany(ctx.menu!.ids)}>
<Trash2 /> Delete
</DropdownMenuItem>
@@ -1263,16 +1328,15 @@ function ProjectFilesPanel({
<DeleteConfirm
open={deletingIds !== null}
title={
- deletingIds !== null && deletingIds.length > 1
- ? `Remove ${deletingIds.length} files from the project?`
- : "Remove this file from the project?"
+ deletingFolders.length === 0 && deletingFiles.length === 1
+ ? "Remove this file from the project?"
+ : `Remove ${pickLabel(deletingFolders, deletingFiles, ["file", "files"], deletingHeld)} from the project?`
}
- description="Timeline clips made from them are removed too."
+ description={`${foldersGoNote(deletingFolders.length, deletingHeld)}Timeline clips made from them are removed too.`}
action="Remove"
onClose={() => setDeletingIds(null)}
onConfirm={() => {
- const s = useEditor.getState();
- for (const id of deletingIds ?? []) s.removeAsset(id);
+ deleteNow(deletingIds ?? []);
setDeletingIds(null);
}}
/>
@@ -1582,6 +1646,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
const templates = (library.data?.templates ?? []).filter(
(t) => reachable(t.residency) && !isStylePresetTemplate(t) && !isSoundPresetTemplate(t)
);
+ const listing: LibraryData = { assets, folders, templates };
const patch = useCallback(
(fn: (prev: LibraryData) => LibraryData) => patchLibrary(client, fn),
[client]
@@ -1594,7 +1659,9 @@ function LibraryPanel({ projectId }: { projectId: string }) {
);
// What a delete is about to take: the pick when the card is in it, else
// the one card. Null while nothing is being asked.
- const [deleting, setDeleting] = useState<LibraryAsset[] | null>(null);
+ const [deleting, setDeleting] = useState<LibraryDeleteSet | null>(null);
+ // The folder whose name field is open, when the right-click menu opened it.
+ const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
const [uploading, setUploading] = useState(0);
// Where an asset shows: phone recordings gather in the derived Camera Roll
@@ -1637,20 +1704,48 @@ function LibraryPanel({ projectId }: { projectId: string }) {
await renameTemplate(r, id, name).catch(() => void reload());
};
- const remove = async () => {
- if (!deleting) return;
- const gone = new Set(deleting.map((a) => a.id));
- patch((d) => ({ ...d, assets: d.assets.filter((a) => !gone.has(a.id)) }));
+ // Delete a set. A folder takes everything under it — the folders filed
+ // there, however deep, and every asset and template they hold — the way
+ // the shelf deletes it; an asset filed in one of those needs no delete of
+ // its own. A camera clip filed there stays in Camera Roll, unfiled.
+ const remove = async (set: LibraryDeleteSet) => {
setDeleting(null);
+ const takes = folderDeleteTakes(listing, set.folders);
+ const inTree = (x: { folderId?: string | null }) => !!x.folderId && takes.tree.has(x.folderId);
+ const goneAssets = set.items.filter((a) => !inTree(a));
+ const gone = new Set([...goneAssets, ...takes.assets, ...takes.templates].map((a) => a.id));
+ forgetLinkedCopies([...goneAssets, ...takes.assets]);
+ patch((d) => ({
+ ...d,
+ folders: d.folders.filter((f) => !takes.tree.has(f.id)),
+ assets: d.assets
+ .filter((a) => !gone.has(a.id))
+ .map((a) => (inTree(a) ? { ...a, folderId: null } : a)),
+ templates: d.templates.filter((t) => !gone.has(t.id)),
+ }));
setPicked(new Set());
- for (const a of deleting) if (isLinkedType(a.type)) forgetLinkedCopy(a.id);
try {
- await Promise.all(deleting.map((a) => deleteFromLibrary(a.residency, a.id)));
+ await Promise.all([
+ ...goneAssets.map((a) => deleteFromLibrary(a.residency, a.id)),
+ ...set.folders.map((f) => deleteLibraryFolder(f.residency, f.id)),
+ ]);
} catch {
// Server delete failed; pull a fresh list so the UI stays truthful.
void reload();
}
};
+ // How many items the folders hold between them, however deep — what the
+ // confirm counts beside them: what shows inside them, so a camera clip
+ // filed there, which shows in Camera Roll, is left out.
+ const heldBy = (fs: LibraryFolder[]) => {
+ const takes = folderDeleteTakes(listing, fs);
+ return takes.assets.length + takes.templates.length;
+ };
+ // How many of the items a delete takes were synced from the phone, which
+ // takes them off the phone too.
+ const phoneSynced = (set: LibraryDeleteSet) =>
+ [...set.items, ...folderDeleteTakes(listing, set.folders).assets].filter((a) => !!a.origin)
+ .length;
// Every item carries its shelf; a folder belongs to one, so an item only
// files into a folder on the same shelf.
@@ -1727,27 +1822,6 @@ function LibraryPanel({ projectId }: { projectId: string }) {
const all = assets;
const shown = all.filter((a) => folderOf(a) === openFolder);
- // Which cards are picked, so a sweep or a ⇧-click hands the timeline (or a
- // folder tile) a run of clips in one drag. Only what the open folder shows
- // can be picked, so walking into another folder leaves its selection behind.
- const { picked, setPicked, pick } = useTilePicks(shown.map((a) => a.id));
- // Built once for the whole grid; each card hands the same array on.
- const pickedRun = shown.filter((a) => picked.has(a.id));
- // A card inside the pick carries the whole set, the rule its drag and ⌘C
- // follow.
- const setOf = (a: LibraryAsset) => (picked.has(a.id) ? pickedRun : [a]);
- const ctx = useSelectionMenu({ picked, setPicked, shown: shown.map((a) => a.id) });
-
- // Let a clip be dragged onto a folder tile to file it (alongside the timeline
- // drag payload the card already sets). The ghost is the card's picture, and
- // it hands over to the timeline's segment preview.
- const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {
- const ids = picked.has(a.id) ? [a.id, ...[...picked].filter((id) => id !== a.id)] : [a.id];
- e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(ids));
- e.dataTransfer.effectAllowed = "copyMove";
- setObjectDragImage(e, ids.length, ids, () => setPicked(new Set()));
- };
-
const bothShelves = availableResidencies().length > 1;
const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);
// The shelf at this level: the folders filed here. At the top the Camera
@@ -1769,6 +1843,59 @@ function LibraryPanel({ projectId }: { projectId: string }) {
const trail =
openFolder === CAMERA_ROLL_FOLDER ? [cameraRoll] : folderTrail(folders, openFolder);
+ // Which cards are picked, so a sweep or a ⇧-click hands the timeline (or a
+ // folder tile) a run of clips in one drag. Only what the open folder shows
+ // can be picked — the shelf's folders and the grid's cards — so walking into
+ // another folder leaves its selection behind.
+ const order = [
+ ...shelfFolders.filter((f) => !f.locked).map((f) => folderSelId(f.id)),
+ ...shown.map((a) => a.id),
+ ];
+ const { picked, setPicked, pick } = useTilePicks(order);
+ // Built once for the whole grid; each card hands the same array on.
+ const pickedRun = shown.filter((a) => picked.has(a.id));
+ const pickSet: LibraryDeleteSet = {
+ folders: shelfFolders.filter((f) => !f.locked && picked.has(folderSelId(f.id))),
+ items: pickedRun,
+ };
+ // A card inside the pick carries the whole set, the rule its drag and ⌘C
+ // follow.
+ const setOf = (a: LibraryAsset): LibraryDeleteSet =>
+ picked.has(a.id) ? pickSet : { folders: [], items: [a] };
+ const ctx = useSelectionMenu({ picked, setPicked, shown: order });
+ // What the open right-click menu acts on.
+ const ctxSet: LibraryDeleteSet = ctx.menu
+ ? {
+ folders: shelfFolders.filter(
+ (f) => !f.locked && ctx.menu!.ids.includes(folderSelId(f.id))
+ ),
+ items: shown.filter((a) => ctx.menu!.ids.includes(a.id)),
+ }
+ : { folders: [], items: [] };
+ // A menu over one folder offers the folder's own actions.
+ const ctxFolder =
+ ctxSet.folders.length === 1 && ctxSet.items.length === 0 ? ctxSet.folders[0] : null;
+ // What the open confirm counts: the items the folders hold, and everything
+ // going in all.
+ const deletingHeld = deleting ? heldBy(deleting.folders) : 0;
+ const deletingTotal = (deleting?.items.length ?? 0) + deletingHeld;
+
+ // Let a clip be dragged onto a folder tile to file it (alongside the timeline
+ // drag payload the card already sets), the folders in the pick riding under
+ // their own MIME. The ghost is the card's picture, and it hands over to the
+ // timeline's segment preview.
+ const onCardDragExtra = (e: React.DragEvent, a: LibraryAsset) => {
+ const { folders: pickedFolders, items } = picked.has(a.id)
+ ? splitPick(picked)
+ : { folders: [], items: [a.id] };
+ e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify(items));
+ if (pickedFolders.length)
+ e.dataTransfer.setData(LIBRARY_FOLDER_MOVE_MIME, JSON.stringify(pickedFolders));
+ e.dataTransfer.effectAllowed = "copyMove";
+ const ids = [a.id, ...items.filter((id) => id !== a.id), ...pickedFolders.map(folderSelId)];
+ setObjectDragImage(e, ids.length, ids, () => setPicked(new Set()));
+ };
+
// File folders under a folder (or out to the root, parentId null). A folder
// files only beside itself: under a folder on its own shelf, never under
// itself or anything inside it.
@@ -1789,6 +1916,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
...d,
folders: d.folders.map((f) => (idset.has(f.id) ? { ...f, parentId } : f)),
}));
+ setPicked(new Set());
await Promise.all(
moving.map((f) => updateLibraryFolder(f.residency, f.id, { parentId }))
).catch(() => void reload());
@@ -1844,6 +1972,10 @@ function LibraryPanel({ projectId }: { projectId: string }) {
const r = folders.find((f) => f.id === id)?.residency;
return bothShelves && r ? <ShelfBadge residency={r} /> : null;
}}
+ picked={picked}
+ onPick={(e, id) => pick(e, folderSelId(id), order)}
+ renaming={renamingFolder}
+ onRenamingChange={setRenamingFolder}
onOpen={(id) => setOpenFolder(id)}
onRename={async (id, name) => {
const r = folders.find((f) => f.id === id)?.residency;
@@ -1854,24 +1986,14 @@ function LibraryPanel({ projectId }: { projectId: string }) {
}));
await updateLibraryFolder(r, id, { name }).catch(() => void reload());
}}
- onDelete={async (id) => {
- // What the folder held comes up one level, the way the shelf
- // files it.
- const gone = folders.find((f) => f.id === id);
- if (!gone) return;
- const up = parentOf(gone);
- patch((d) => ({
- folders: d.folders
- .filter((f) => f.id !== id)
- .map((f) => (parentOf(f) === id ? { ...f, parentId: up } : f)),
- assets: d.assets.map((a) =>
- a.folderId === id ? { ...a, folderId: up } : a
- ),
- templates: d.templates.map((t) =>
- t.folderId === id ? { ...t, folderId: up } : t
- ),
- }));
- await deleteLibraryFolder(gone.residency, id).catch(() => void reload());
+ // A folder in a pick with others takes the pick to the
+ // confirm; alone, itself.
+ onDelete={(id) => {
+ const f = folders.find((x) => x.id === id);
+ if (!f) return;
+ const size = pickSet.folders.length + pickSet.items.length;
+ if (picked.has(folderSelId(id)) && size > 1) setDeleting(pickSet);
+ else setDeleting({ folders: [f], items: [] });
}}
onDropIds={(ids, fid) => ids.forEach((id) => void move(id, fid))}
onDropFolders={(ids, fid) => void moveFolders(ids, fid)}
@@ -1929,7 +2051,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
</div>
</div>
)}
- {shown.length === 0 && uploading === 0 ? (
+ {order.length === 0 && uploading === 0 ? (
// At the root, filed-away assets, folders, and templates all count as
// content — the invitation is only for a truly empty library.
openFolder !== null ? (
@@ -1956,7 +2078,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
asset={a}
mention
selected={picked.has(a.id)}
- onClick={(e) => pick(e, a.id, shown.map((x) => x.id))}
+ onClick={(e) => pick(e, a.id, order)}
dragGroup={pickedRun}
// A font is used from the font menu; there is nothing to place.
onUse={
@@ -1980,30 +2102,36 @@ function LibraryPanel({ projectId }: { projectId: string }) {
)}
<SelectionMenu menu={ctx.menu} onClose={ctx.close}>
- <DropdownMenuItem
- variant="destructive"
- onClick={() => setDeleting(shown.filter((a) => ctx.menu!.ids.includes(a.id)))}
- >
- <Trash2 /> Delete
- </DropdownMenuItem>
+ {ctxFolder ? (
+ <FolderMenuItems
+ onRename={() => setRenamingFolder(ctxFolder.id)}
+ onDelete={() => setDeleting({ folders: [ctxFolder], items: [] })}
+ />
+ ) : (
+ <DropdownMenuItem variant="destructive" onClick={() => setDeleting(ctxSet)}>
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ )}
</SelectionMenu>
<DeleteConfirm
open={!!deleting}
title={
- deleting && deleting.length > 1
- ? `Delete ${deleting.length} items?`
- : `Delete “${deleting?.[0]?.name}”?`
+ deleting ? `Delete ${pickLabel(deleting.folders, deleting.items, ["item", "items"], deletingHeld)}?` : ""
}
- description={`Projects that already use ${deleting && deleting.length > 1 ? "them" : "it"} keep their own copy.`}
+ description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}Projects that already use ${deletingTotal === 1 ? "it" : "them"} keep their own copy.`}
action="Remove"
onClose={() => setDeleting(null)}
- onConfirm={() => void remove()}
+ onConfirm={() => deleting && void remove(deleting)}
/>
</div>
);
}
+/** What a library delete is about to take: folders and assets, picked
+ * together. */
+type LibraryDeleteSet = { folders: LibraryFolder[]; items: LibraryAsset[] };
+
function CopyChip({ text, label }: { text: string; label: string }) {
const [copied, setCopied] = useState(false);
return (
diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsx
index 1e50479a..246afdb9 100644
--- a/site/src/cut/components/desktopFolders.tsx
+++ b/site/src/cut/components/desktopFolders.tsx
@@ -12,6 +12,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { setObjectDragImage } from "@/cut/lib/assetDrag";
+import { PICKED_RING } from "@/cut/lib/assetPick";
import { additiveClick } from "@/cut/lib/hostKeys";
import type { AssetRef } from "@/cut/lib/assetRef";
import { formatBytes } from "@/lib/bytes";
@@ -32,6 +33,21 @@ export interface DeskFolder {
locked?: boolean;
}
+// A folder sits in the grid's pick beside the items, under an id of its own
+// shape, so a folder and an item never collide in the one Set.
+const FOLDER_SEL = "folder:";
+export const folderSelId = (id: string) => FOLDER_SEL + id;
+
+/** A pick taken apart: the folder ids and the item ids it holds. */
+export function splitPick(ids: Iterable<string>): { folders: string[]; items: string[] } {
+ const folders: string[] = [];
+ const items: string[] = [];
+ for (const id of ids)
+ if (id.startsWith(FOLDER_SEL)) folders.push(id.slice(FOLDER_SEL.length));
+ else items.push(id);
+ return { folders, items };
+}
+
export function readDragIds(e: React.DragEvent, mime: string): string[] {
const raw = e.dataTransfer.getData(mime);
if (!raw) return [];
@@ -104,8 +120,9 @@ const MARQUEE_SKIP =
/** Rubber-band selection like a desktop: press-drag on empty space to sweep a
* rectangle, and every tile (marked `data-sel-id`) it touches is selected. Armed
* off the whole `<main>` arena — so it starts anywhere in the content area, not
- * just over the grid — while the left sidebar is left alone. ⇧/⌘ keeps the prior
- * selection; a plain click on empty space clears it. */
+ * just over the grid — while the left sidebar is left alone. The sweep reaches
+ * every tile in the arena, so the folder shelf above the grid is swept with it.
+ * ⇧/⌘ keeps the prior selection; a plain click on empty space clears it. */
export function Marquee({
className,
rootClassName = "relative min-h-[68vh] flex-1",
@@ -162,7 +179,7 @@ export function Marquee({
};
setRect(r);
const hit = new Set(base);
- ref.current?.querySelectorAll<HTMLElement>("[data-sel-id]").forEach((el) => {
+ arena.querySelectorAll<HTMLElement>("[data-sel-id]").forEach((el) => {
const b = el.getBoundingClientRect();
const overlaps =
b.left < r.left + r.width && b.right > r.left && b.top < r.top + r.height && b.bottom > r.top;
@@ -240,11 +257,13 @@ function CrumbStep({
onDropFolders?: (ids: string[]) => void;
}) {
const [over, setOver] = useState(false);
+ // A pick that holds both drags both payloads, and the step takes each.
const carried = (e: React.DragEvent) => {
const types = Array.from(e.dataTransfer.types);
- if (types.includes(mime)) return "items";
- if (folderMime && onDropFolders && types.includes(folderMime)) return "folders";
- return null;
+ return {
+ items: types.includes(mime),
+ folders: !!folderMime && !!onDropFolders && types.includes(folderMime),
+ };
};
return (
<button
@@ -254,7 +273,8 @@ function CrumbStep({
)}
onClick={onGo}
onDragOver={(e) => {
- if (!carried(e)) return;
+ const kind = carried(e);
+ if (!kind.items && !kind.folders) return;
e.preventDefault();
e.dataTransfer.dropEffect = "move";
setOver(true);
@@ -262,11 +282,11 @@ function CrumbStep({
onDragLeave={() => setOver(false)}
onDrop={(e) => {
const kind = carried(e);
- if (!kind) return;
+ if (!kind.items && !kind.folders) return;
e.preventDefault();
setOver(false);
- if (kind === "folders") onDropFolders?.(readDragIds(e, folderMime!));
- else onDrop(readDragIds(e, mime));
+ if (kind.folders) onDropFolders?.(readDragIds(e, folderMime!));
+ if (kind.items) onDrop(readDragIds(e, mime));
}}
>
{label}
@@ -336,6 +356,34 @@ export function FolderCrumb({
);
}
+/** The actions on a folder, shared by its ⋯ button and the grid's right-click
+ * menu. `deleteLabel` says what Delete takes: the folder, or the pick it is
+ * in. */
+export function FolderMenuItems({
+ onShare,
+ onRename,
+ onDelete,
+ deleteLabel = "Delete folder",
+}: {
+ onShare?: () => void;
+ onRename: () => void;
+ onDelete: () => void;
+ deleteLabel?: string;
+}) {
+ return (
+ <>
+ {onShare && <DropdownMenuItem onClick={onShare}><Share2 /> Share</DropdownMenuItem>}
+ <DropdownMenuItem onClick={onRename}>
+ <Pencil /> Rename
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 /> {deleteLabel}
+ </DropdownMenuItem>
+ </>
+ );
+}
+
/** The desktop-style folder shelf: each folder as a blue folder icon and a
* drop target for dragged items. Folder creation is driven by the host (e.g.
* a header button) through `creating`/`onCreatingChange`. A host that nests
@@ -347,6 +395,10 @@ export function FolderShelf<F extends DeskFolder>({
badgeOf,
mime,
folderMime,
+ picked,
+ onPick,
+ renaming,
+ onRenamingChange,
onOpen,
onCreate,
onRename,
@@ -368,9 +420,23 @@ export function FolderShelf<F extends DeskFolder>({
mime: string;
/** The MIME a dragged folder tile carries its id under. */
folderMime?: string;
+ /** The grid's pick, when folder tiles join it: a tile is marked for the
+ * marquee and the selection menu under `folderSelId`, wears the ring while
+ * picked, and hands a ⌘/⇧ click to `onPick`; a plain click opens it. A
+ * picked tile drags the whole pick — the folders under `folderMime`, the
+ * items under `mime`. A locked folder stays out of the pick. */
+ picked?: Set<string>;
+ onPick?: (e: React.MouseEvent, id: string) => void;
+ /** The folder whose name is being edited, when the host drives that (its
+ * right-click menu offers Rename); unset, the tile keeps it itself. */
+ renaming?: string | null;
+ onRenamingChange?: (id: string | null) => void;
onOpen: (id: string) => void;
onCreate?: (name: string) => void | Promise<void>;
onRename: (id: string, name: string) => void | Promise<void>;
+ /** Delete from the tile's ⋯ menu. The host decides what a picked folder's
+ * Delete takes: the tile labels it "Delete" when the folder is in a pick
+ * with others. */
onDelete: (id: string) => void | Promise<void>;
onShare?: (id: string) => void;
onDropIds: (ids: string[], folderId: string) => void;
@@ -399,8 +465,13 @@ export function FolderShelf<F extends DeskFolder>({
dragTypes(e).includes(mime) ||
(nests && dragTypes(e).includes(folderMime) && dragging !== target) ||
(!!onDropFiles && dragTypes(e).includes("Files"));
- const [editingId, setEditingId] = useState<string | null>(null);
+ const [ownEditing, setOwnEditing] = useState<string | null>(null);
+ const editingId = renaming ?? ownEditing;
+ const setEditingId = onRenamingChange ?? setOwnEditing;
const [draft, setDraft] = useState("");
+ // The rename field opens on the folder's own name, whoever opened it, and
+ // holds the draft only once it has been typed in.
+ const [draftFor, setDraftFor] = useState<string | null>(null);
const [over, setOver] = useState<string | null>(null);
// Every close path clears the draft, so the next create opens with an empty
// name field.
@@ -410,6 +481,7 @@ export function FolderShelf<F extends DeskFolder>({
};
const closeRename = () => {
setDraft("");
+ setDraftFor(null);
setEditingId(null);
};
@@ -426,34 +498,51 @@ export function FolderShelf<F extends DeskFolder>({
{folders.map((f) => {
const s = statOf(f.id);
const isOver = over === f.id;
- if (editingId === f.id)
+ if (editingId === f.id) {
+ const text = draftFor === f.id ? draft : f.name;
return (
<div key={f.id} className={editRowClass}>
<FolderGlyph className={editGlyphClass} />
<Input
autoFocus
- value={draft}
+ value={text}
className={cn("h-6 text-[11px]", rows ? "flex-1" : "w-full")}
- onChange={(e) => setDraft(e.target.value)}
+ onChange={(e) => {
+ setDraftFor(f.id);
+ setDraft(e.target.value);
+ }}
onBlur={closeRename}
onKeyDown={(e) => {
- if (e.key === "Enter" && draft.trim()) {
- void onRename(f.id, draft.trim());
+ if (e.key === "Enter" && text.trim()) {
+ void onRename(f.id, text.trim());
closeRename();
} else if (e.key === "Escape") closeRename();
}}
/>
</div>
);
+ }
+ const sel = folderSelId(f.id);
+ const pickable = !!picked && !!onPick && !f.locked;
+ const isPicked = pickable && picked.has(sel);
+ // The pick this tile drags: itself first, then the rest of the
+ // folders, with the items riding under their own MIME.
+ const carried = isPicked ? splitPick(picked) : { folders: [], items: [] };
+ const carriedFolders = [f.id, ...carried.folders.filter((id) => id !== f.id)];
const interact = {
- onClick: () => onOpen(f.id),
+ ...(pickable ? { "data-sel-id": sel } : {}),
+ onClick: (e: React.MouseEvent) => {
+ if (pickable && additiveClick(e)) {
+ e.preventDefault();
+ onPick(e, f.id);
+ return;
+ }
+ onOpen(f.id);
+ },
...(f.locked
? {}
: {
- onDoubleClick: () => {
- setDraft(f.name);
- setEditingId(f.id);
- },
+ onDoubleClick: () => setEditingId(f.id),
onDragOver: (e: React.DragEvent) => {
if (!accepts(e, f.id)) return;
e.preventDefault();
@@ -472,22 +561,29 @@ export function FolderShelf<F extends DeskFolder>({
onDropFiles(e.dataTransfer.files, f.id);
return;
}
- if (nests && dragTypes(e).includes(folderMime)) {
+ // A pick that holds both drops both: the folders file in,
+ // then the items.
+ if (nests && dragTypes(e).includes(folderMime))
onDropFolders(readDragIds(e, folderMime), f.id);
- return;
- }
- onDropIds(readDragIds(e, mime), f.id);
+ if (dragTypes(e).includes(mime)) onDropIds(readDragIds(e, mime), f.id);
},
// The tile itself is what a nesting host drags: its own id,
- // with the glyph as the ghost.
+ // with the glyph as the ghost — and the rest of the pick
+ // when it is in one.
...(nests
? {
draggable: true,
onDragStart: (e: React.DragEvent) => {
- e.dataTransfer.setData(folderMime, JSON.stringify([f.id]));
+ e.dataTransfer.setData(folderMime, JSON.stringify(carriedFolders));
+ if (carried.items.length)
+ e.dataTransfer.setData(mime, JSON.stringify(carried.items));
e.dataTransfer.effectAllowed = "move";
setDragging(f.id);
- setObjectDragImage(e, 1, [f.id]);
+ setObjectDragImage(
+ e,
+ carriedFolders.length + carried.items.length,
+ [...carriedFolders.map(folderSelId), ...carried.items]
+ );
},
onDragEnd: () => setDragging(null),
}
@@ -515,19 +611,12 @@ export function FolderShelf<F extends DeskFolder>({
<MoreHorizontal className="size-3.5" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" onClick={(e) => e.stopPropagation()}>
- {onShare && <DropdownMenuItem onClick={() => onShare(f.id)}><Share2 /> Share</DropdownMenuItem>}
- <DropdownMenuItem
- onClick={() => {
- setDraft(f.name);
- setEditingId(f.id);
- }}
- >
- <Pencil /> Rename
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem variant="destructive" onClick={() => void onDelete(f.id)}>
- <Trash2 /> Delete folder
- </DropdownMenuItem>
+ <FolderMenuItems
+ onShare={onShare && (() => onShare(f.id))}
+ onRename={() => setEditingId(f.id)}
+ onDelete={() => void onDelete(f.id)}
+ deleteLabel={isPicked && picked.size > 1 ? "Delete" : "Delete folder"}
+ />
</DropdownMenuContent>
</DropdownMenu>
);
@@ -535,7 +624,8 @@ export function FolderShelf<F extends DeskFolder>({
<div
className={cn(
"group/f flex cursor-pointer items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-muted/60",
- isOver && "bg-primary/10"
+ isOver && "bg-primary/10",
+ isPicked && PICKED_RING
)}
{...interact}
>
@@ -558,7 +648,10 @@ export function FolderShelf<F extends DeskFolder>({
</div>
) : (
<div
- className="group/f relative flex w-[92px] cursor-pointer flex-col items-start rounded-xl px-2 py-1.5 text-left transition-colors hover:bg-muted/60"
+ className={cn(
+ "group/f relative flex w-[92px] cursor-pointer flex-col items-start rounded-xl px-2 py-1.5 text-left transition-colors hover:bg-muted/60",
+ isPicked && PICKED_RING
+ )}
{...interact}
>
<div
diff --git a/site/src/cut/components/selectionMenu.test.ts b/site/src/cut/components/selectionMenu.test.ts
new file mode 100644
index 00000000..12ebaf34
--- /dev/null
+++ b/site/src/cut/components/selectionMenu.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, test } from "bun:test";
+import { foldersGoNote, phoneGoNote, pickLabel } from "./selectionMenu";
+
+const folder = { name: "Shoot day" };
+const item = { name: "clip.mp4" };
+
+describe("what a confirm calls a pick", () => {
+ test("one folder by name, with what it holds in the grid's own word", () => {
+ expect(pickLabel([folder], [], ["project", "projects"], 3)).toBe(
+ "“Shoot day” and its 3 projects",
+ );
+ expect(pickLabel([folder], [], ["file", "files"], 1)).toBe("“Shoot day” and its 1 file");
+ expect(pickLabel([folder], [], ["item", "items"], 0)).toBe("“Shoot day”");
+ });
+
+ test("one item by name", () => {
+ expect(pickLabel([], [item], ["file", "files"], 0)).toBe("“clip.mp4”");
+ });
+
+ test("counts otherwise, the held count in the same word", () => {
+ expect(pickLabel([folder, folder], [item, item, item], ["project", "projects"], 19)).toBe(
+ "2 folders (19 projects) and 3 projects",
+ );
+ expect(pickLabel([folder], [item], ["item", "items"], 0)).toBe("1 folder and 1 item");
+ });
+});
+
+describe("the sentences a confirm opens with", () => {
+ test("a folder note only while the folders hold something", () => {
+ expect(foldersGoNote(1, 0)).toBe("");
+ expect(foldersGoNote(0, 4)).toBe("");
+ expect(foldersGoNote(1, 4)).toBe("Everything inside the folder goes with it. ");
+ expect(foldersGoNote(2, 4)).toBe("Everything inside the folders goes with them. ");
+ });
+
+ test("a phone note only while something synced from the phone goes", () => {
+ expect(phoneGoNote(0, 3)).toBe("");
+ expect(phoneGoNote(1, 1)).toBe("It was synced from your phone and is removed there too. ");
+ expect(phoneGoNote(1, 3)).toBe("One of them was synced from your phone and is removed there too. ");
+ expect(phoneGoNote(2, 3)).toBe("2 of them were synced from your phone and are removed there too. ");
+ });
+});
diff --git a/site/src/cut/components/selectionMenu.tsx b/site/src/cut/components/selectionMenu.tsx
index df647bdf..1cd2ba67 100644
--- a/site/src/cut/components/selectionMenu.tsx
+++ b/site/src/cut/components/selectionMenu.tsx
@@ -17,16 +17,16 @@ import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu
* acts on, the clicked tile first. Empty ids is a menu over empty space. */
export type SelectionMenuAt = { x: number; y: number; ids: string[] };
-// Controls, folder tiles, and the crumb keep their own menus and clicks.
+// Controls and the crumb keep their own menus and clicks.
const OWN_MENU = "button,a,input,textarea,[role='button'],[role='menuitem'],[data-no-marquee]";
/**
* The mechanics every tile grid shares — the projects home, the Library page,
* and the editor's Media panel and Library shelf. A right-click over a tile
- * (marked `data-sel-id`, the mark `Marquee` sweeps) opens the selection menu
- * at the pointer, with the tile joining the pick if it wasn't in it, so the
- * browser's own media menu never shows over a tile. Each grid draws its own
- * entries inside `SelectionMenu`.
+ * (marked `data-sel-id`, the mark `Marquee` sweeps; a folder tile carries one
+ * too) opens the selection menu at the pointer, with the tile joining the
+ * pick if it wasn't in it, so the browser's own media menu never shows over a
+ * tile. Each grid draws its own entries inside `SelectionMenu`.
*/
export function useSelectionMenu({
picked,
@@ -45,10 +45,12 @@ export function useSelectionMenu({
// opened; a press over empty space is left to the grid.
const onContextMenu = (e: React.MouseEvent): boolean => {
const t = e.target as HTMLElement;
- if (t.closest(OWN_MENU)) return true;
- const card = t.closest<HTMLElement>("[data-sel-id]");
+ // The nearest of the two decides: a tile inside the folder shelf is a
+ // tile, a control inside a tile is a control.
+ const card = t.closest<HTMLElement>(`[data-sel-id],${OWN_MENU}`);
if (!card) return false;
- const id = card.dataset.selId!;
+ const id = card.dataset.selId;
+ if (id === undefined) return true;
if (!shown.includes(id)) return true;
e.preventDefault();
const ids = picked.has(id) ? [id, ...[...picked].filter((x) => x !== id)] : [id];
@@ -92,6 +94,49 @@ export function SelectionMenu({
);
}
+/** What a confirm calls a pick: the one thing by name, with what a folder
+ * holds counted beside it; or the counts — "2 folders (19 projects) and 3
+ * projects". `noun` is the grid's word for an item, singular and plural, the
+ * word for what the folders hold too; `held` is how many of those the
+ * folders hold between them, however deep. */
+export function pickLabel(
+ folders: readonly { name: string }[],
+ items: readonly { name: string }[],
+ noun: [string, string],
+ held: number,
+): string {
+ const count = (n: number, [one, many]: [string, string]) => `${n} ${n === 1 ? one : many}`;
+ const inside = held > 0 ? ` (${count(held, noun)})` : "";
+ if (folders.length === 1 && items.length === 0)
+ return `“${folders[0].name}”${held > 0 ? ` and its ${count(held, noun)}` : ""}`;
+ if (folders.length === 0 && items.length === 1) return `“${items[0].name}”`;
+ const parts: string[] = [];
+ if (folders.length) parts.push(count(folders.length, ["folder", "folders"]) + inside);
+ if (items.length) parts.push(count(items.length, noun));
+ return parts.join(" and ");
+}
+
+/** The sentence a confirm opens with while the pick holds folders with
+ * something in them: a folder goes with everything inside it. Empty when the
+ * folders hold nothing, or there are none. */
+export function foldersGoNote(folders: number, held: number): string {
+ if (folders === 0 || held === 0) return "";
+ return folders === 1
+ ? "Everything inside the folder goes with it. "
+ : "Everything inside the folders goes with them. ";
+}
+
+/** The sentence a Library confirm adds while what goes includes items synced
+ * from the phone: those leave the phone too. `synced` counts them among the
+ * `total` items going. Empty without one. */
+export function phoneGoNote(synced: number, total: number): string {
+ if (synced === 0) return "";
+ if (total === 1) return "It was synced from your phone and is removed there too. ";
+ return synced === 1
+ ? "One of them was synced from your phone and is removed there too. "
+ : `${synced} of them were synced from your phone and are removed there too. `;
+}
+
/** The confirm before a pick is deleted. The grid words it: what goes, what
* it takes with it, and what the button says. */
export function DeleteConfirm({