Open source CapCut alternative.
TypeScript
feat(site): share multi-select right-click and delete across project and library grids
David Le15ca2ea994cf
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 89bd7ad4..f08b0a07 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -15,22 +15,9 @@ import {X,} from "lucide-react";import { Button } from "@/components/ui/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,-} from "@/components/ui/dropdown-menu";+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";+import { useDeleteKey } from "@/cut/hooks/useDeleteKey";import { useElapsed } from "@/cut/hooks/useElapsed";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/components/ui/alert-dialog";import {Dialog,DialogContent,@@ -98,6 +85,7 @@ 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";// 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.@@ -105,6 +93,10 @@ const LIBRARY_MOVE_MIME = "application/x-cut-library-move";// A dragged folder tile, filed into another folder or back out to a crumb.const LIBRARY_FOLDER_MOVE_MIME = "application/x-cut-library-folder";+/** A saved arrangement among the media a pick can carry off the shelf. */+const isTemplate = (x: LibraryAsset | LibraryTemplateItem): x is LibraryTemplateItem =>+ "layers" in x;+/** 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. */@@ -390,10 +382,8 @@ 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[] | null>(null);- // The right-click menu over a card, anchored to the pointer, with the ids it- // acts on.- const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null);+ const [deleting, setDeleting] = useState<(LibraryAsset | LibraryTemplateItem)[] | 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// enter/leave noise as the cursor crosses child tiles).@@ -427,12 +417,6 @@ export function LibraryView() {await renameTemplate(r, id, name).catch(() => void reload());};- const removeTpl = async (r: Residency, id: string) => {- if (!live(r)) return;- patch((d) => ({ ...d, templates: d.templates.filter((t) => t.id !== id) }));- await deleteTemplate(r, id).catch(() => void reload());- };-// Track one arrival from its first moment to its last: the tile goes up// before any bytes move, follows the work, and comes down when the asset// itself takes its place. A failure leaves the tile up with the reason.@@ -634,11 +618,19 @@ export function LibraryView() {const taking = deleting.filter((a) => live(a.residency));if (taking.length === 0) return;const gone = new Set(taking.map((a) => a.id));- patch((d) => ({ ...d, assets: d.assets.filter((a) => !gone.has(a.id)) }));+ patch((d) => ({+ ...d,+ assets: d.assets.filter((a) => !gone.has(a.id)),+ templates: d.templates.filter((t) => !gone.has(t.id)),+ }));setSelected(new Set());- for (const a of taking) if (isLinkedType(a.type)) forgetLinkedCopy(a.id);+ for (const a of taking) if (!isTemplate(a) && isLinkedType(a.type)) forgetLinkedCopy(a.id);try {- await Promise.all(taking.map((a) => deleteFromLibrary(a.residency, a.id)));+ await Promise.all(+ taking.map((a) =>+ isTemplate(a) ? deleteTemplate(a.residency, a.id) : deleteFromLibrary(a.residency, a.id),+ ),+ );} catch {void reload();}@@ -762,27 +754,31 @@ export function LibraryView() {const bothShelves = listed.length > 1;const shown = all.filter((a) => (a.folderId ?? null) === openFolder);+ const shownTemplates = templates.filter(+ (t) => (t.folderId ?? null) === openFolder,+ );// 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));- // A card inside the pick carries the whole set, the rule its drag and ⌘C- // follow.- const setOf = (a: LibraryAsset) => (selected.has(a.id) ? pickedRun : [a]);-- // Right-click over a card: the selection menu, with the card joining the- // pick if it wasn't in it. The browser's own media menu never shows here.+ // The whole pick, templates leading the way the grid lays them out.+ const picked: (LibraryAsset | LibraryTemplateItem)[] = [+ ...shownTemplates.filter((t) => selected.has(t.id)),+ ...pickedRun,+ ];+ // 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),+ });+ // 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) => {- const t = e.target as HTMLElement;- if (t.closest("button,a,input,textarea,[role='button'],[role='menuitem'],[data-no-marquee]"))- return;- const card = t.closest<HTMLElement>("[data-sel-id]");- if (!card) return;- const id = card.dataset.selId!;- if (!shown.some((a) => a.id === id)) return;- e.preventDefault();- const ids = selected.has(id) ? [id, ...[...selected].filter((x) => x !== id)] : [id];- if (!selected.has(id)) setSelected(new Set([id]));- setCtxMenu({ x: e.clientX, y: e.clientY, ids });+ if (!ctx.onContextMenu(e) && (e.target as HTMLElement).closest("video,img"))+ e.preventDefault();};// Similar-shape tiles get their own band of wrapped rows, so a wide tile// never shares a row with a tall one; audio and unmeasured assets band as@@ -811,9 +807,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;- 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]);@@ -844,6 +837,7 @@ export function LibraryView() {return (<div+ ref={rootRef}className={cn("min-h-full",fileOver &&@@ -1032,7 +1026,7 @@ export function LibraryView() {}onDelete={live(t.residency)- ? () => void removeTpl(t.residency, t.id)+ ? () => setDeleting(setOf(t)): undefined}/>@@ -1130,65 +1124,42 @@ export function LibraryView() {</DialogContent></Dialog>- {/* The right-click menu, anchored to the pointer. */}- <DropdownMenu open={ctxMenu !== null} onOpenChange={(o) => !o && setCtxMenu(null)}>- {ctxMenu && (- <DropdownMenuContent- className="w-48"- sideOffset={0}- anchor={{- getBoundingClientRect: () => new DOMRect(ctxMenu.x, ctxMenu.y, 0, 0),+ <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 });}}- finalFocus={false}>- {ctxMenu.ids.length === 1 && <DropdownMenuItem onClick={() => {- const asset = shown.find((a) => a.id === ctxMenu.ids[0]);- if (asset && live(asset.residency)) setSharing({ kind: "asset", id: asset.id, residency: asset.residency });- setCtxMenu(null);- }}><Share2 /> Share</DropdownMenuItem>}- <DropdownMenuItem- variant="destructive"- onClick={() => {- setDeleting(shown.filter((a) => ctxMenu.ids.includes(a.id)));- setCtxMenu(null);- }}- >- <Trash2 /> Delete- </DropdownMenuItem>- </DropdownMenuContent>+ <Share2 /> Share+ </DropdownMenuItem>)}- </DropdownMenu>+ <DropdownMenuItem+ variant="destructive"+ onClick={() =>+ setDeleting(+ [...shownTemplates, ...shown].filter((a) => ctx.menu!.ids.includes(a.id)),+ )+ }+ >+ <Trash2 /> Delete+ </DropdownMenuItem>+ </SelectionMenu>- <AlertDialog+ <DeleteConfirmopen={!!deleting}- onOpenChange={(o) => !o && setDeleting(null)}- >- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>- {deleting && deleting.length > 1- ? `Delete ${deleting.length} items?`- : `Delete “${deleting?.[0]?.name}”?`}- </AlertDialogTitle>- <AlertDialogDescription>- Projects that already use {deleting && deleting.length > 1 ? "them" : "it"} keep- their own copy.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- className="bg-destructive/10 text-destructive hover:bg-destructive/20"- onClick={(e) => {- e.preventDefault();- void remove();- }}- >- Remove- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ title={+ deleting && deleting.length > 1+ ? `Delete ${deleting.length} items?`+ : `Delete “${deleting?.[0]?.name}”?`+ }+ description={`Projects that already use ${deleting && deleting.length > 1 ? "them" : "it"} keep their own copy.`}+ action="Remove"+ onClose={() => setDeleting(null)}+ onConfirm={() => void remove()}+ />{sharing && library.data && <LibraryShareDialogkey={`${sharing.kind}:${sharing.id}`}diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex 4135d4e3..93ae3933 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -26,16 +26,6 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/components/ui/alert-dialog";import {DropdownMenu,DropdownMenuContent,@@ -70,6 +60,7 @@ import {type ProjectsSection,type Residency,} from "@/cut/lib/queries";+import { useDeleteKey } from "@/cut/hooks/useDeleteKey";import { useInView } from "@/cut/hooks/useInView";import { useNewProjectTarget } from "@/cut/lib/newProject";import { NewProjectButton } from "@/cut/components/NewProjectButton";@@ -94,6 +85,7 @@ import { setObjectDragImage } from "@/cut/lib/assetDrag";import { childrenOf, folderTrail, folderWithin, parentOf } from "@/cut/lib/folderTree";import { PICKED_RING } from "@/cut/lib/assetPick";import { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";+import { DeleteConfirm, SelectionMenu, useSelectionMenu } from "./selectionMenu";import { formatBytes } from "@/lib/bytes";type View = "gallery" | "list";@@ -296,9 +288,12 @@ export function ProjectsHome() {const [renaming, setRenaming] = useState<{ project: ProjectSummary; residency: Residency } | null>(null);- const [deleting, setDeleting] = useState<{ project: ProjectSummary; residency: Residency } | null>(- null- );+ // 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 rootRef = useRef<HTMLDivElement>(null);const [name, setName] = useState("");const [busy, setBusy] = useState(false);// One line of feedback when a cross-residency duplicate fails.@@ -579,25 +574,30 @@ 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.+ useGenScene.getState().killProject(id);+ useGenerate.getState().cancelForOwner({ projectId: id });+ clearProjectThreads(id);+ dropCachedDoc(id, residency);+ if (residency === "cloud") void dropLocalProjectCopy(id);+ patch(residency, (s) => ({ ...s, projects: s.projects.filter((p) => p.id !== id) }));+ };+const remove = async () => {if (!deleting) return;- const { project, residency } = deleting;- if (!live(residency)) return setDeleting(null);+ // A shelf that isn't answering keeps its projects.+ const taking = deleting.filter(({ residency }) => live(residency));+ if (taking.length === 0) return setDeleting(null);setBusy(true);- const id = project.id;try {- 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.- useGenScene.getState().killProject(id);- useGenerate.getState().cancelForOwner({ projectId: id });- clearProjectThreads(id);- dropCachedDoc(id, residency);- if (residency === "cloud") void dropLocalProjectCopy(id);- patch(residency, (s) => ({ ...s, projects: s.projects.filter((p) => p.id !== id) }));+ await Promise.all(taking.map(({ project, residency }) => removeOne(project.id, residency)));+ setSelected(new Set());setDeleting(null);} finally {setBusy(false);@@ -637,6 +637,37 @@ export function ProjectsHome() {).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.+ 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);+ })(),+ }))+ : [];+// Begin a project drag. Dragging a member of the current selection carries the// whole selection; dragging anything else drags (and selects) just that item.const onProjectDragStart = (e: React.DragEvent, p: ProjectSummary) => {@@ -765,7 +796,7 @@ export function ProjectsHome() {onDuplicate={() => void duplicate(r, p)}moveTo={moveDests(r).map((d) => ({ target: d, run: () => void moveAcross(r, d, p) }))}- onDelete={() => setDeleting({ project: p, residency: r })}+ onDelete={() => setDeleting(setOf(p, r))}/>)}</div>@@ -847,7 +878,7 @@ export function ProjectsHome() {onDuplicate={() => void duplicate(r, p)}moveTo={moveDests(r).map((d) => ({ target: d, run: () => void moveAcross(r, d, p) }))}- onDelete={() => setDeleting({ project: p, residency: r })}+ onDelete={() => setDeleting(setOf(p, r))}/>) : (<span />@@ -877,11 +908,13 @@ export function ProjectsHome() {return (<div+ ref={rootRef}className={cn("min-h-full",fileOver &&"rounded-3xl outline-2 outline-dashed outline-offset-[-10px] outline-[#0a84ff]/60")}+ onContextMenu={ctx.onContextMenu}onDragEnter={(e) => {if (!isFileDrag(e)) return;e.preventDefault();@@ -1070,30 +1103,43 @@ export function ProjectsHome() {</DialogContent></Dialog>- <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Delete “{deleting?.project.name}”?</AlertDialogTitle>- <AlertDialogDescription>- This deletes the whole project folder, including its media files- and exports. This can’t be undone.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel>- <AlertDialogAction- disabled={busy}- className="bg-destructive/10 text-destructive hover:bg-destructive/20"- onClick={(e) => {- e.preventDefault();- void remove();- }}- >- Delete project- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ {/* 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 })))}+ />+ </SelectionMenu>++ <DeleteConfirm+ open={!!deleting}+ title={+ deleting && deleting.length > 1+ ? `Delete ${deleting.length} projects?`+ : `Delete “${deleting?.[0]?.project.name}”?`+ }+ 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."+ }+ action={deleting && deleting.length > 1 ? "Delete projects" : "Delete project"}+ busy={busy}+ onClose={() => setDeleting(null)}+ onConfirm={() => void remove()}+ /></div></div>);@@ -1275,6 +1321,49 @@ const MOVE_DEST: Record<Residency, { Icon: typeof Cloud; label: string }> = {browser: { Icon: Laptop, label: "Move to Local" },};+/** The actions on a project, or on a set of them: Rename and Duplicate take+ * one project, so a set offers only the moves every member can make and+ * Delete. */+function ProjectMenuItems({+ onRename,+ onDuplicate,+ moveTo,+ onDelete,+}: {+ onRename?: () => void;+ onDuplicate?: () => void;+ /** The other live residencies this project can move to. */+ moveTo?: { target: Residency; run: () => void }[];+ onDelete: () => void;+}) {+ return (+ <>+ {onRename && (+ <DropdownMenuItem onClick={onRename}>+ <Pencil /> Rename+ </DropdownMenuItem>+ )}+ {onDuplicate && (+ <DropdownMenuItem onClick={onDuplicate}>+ <Copy /> Duplicate+ </DropdownMenuItem>+ )}+ {moveTo?.map(({ target, run }) => {+ const { Icon, label } = MOVE_DEST[target];+ return (+ <DropdownMenuItem key={target} onClick={run}>+ <Icon /> {label}+ </DropdownMenuItem>+ );+ })}+ {(onRename || onDuplicate || (moveTo?.length ?? 0) > 0) && <DropdownMenuSeparator />}+ <DropdownMenuItem variant="destructive" onClick={onDelete}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </>+ );+}+function ProjectMenu({className,onRename,@@ -1305,24 +1394,12 @@ function ProjectMenu({<MoreHorizontal /></DropdownMenuTrigger><DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>- <DropdownMenuItem onClick={onRename}>- <Pencil /> Rename- </DropdownMenuItem>- <DropdownMenuItem onClick={onDuplicate}>- <Copy /> Duplicate- </DropdownMenuItem>- {moveTo?.map(({ target, run }) => {- const { Icon, label } = MOVE_DEST[target];- return (- <DropdownMenuItem key={target} onClick={run}>- <Icon /> {label}- </DropdownMenuItem>- );- })}- <DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" onClick={onDelete}>- <Trash2 /> Delete- </DropdownMenuItem>+ <ProjectMenuItems+ onRename={onRename}+ onDuplicate={onDuplicate}+ moveTo={moveTo}+ onDelete={onDelete}+ /></DropdownMenuContent></DropdownMenu>);diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 0c7b3eee..29ed7a4e 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -122,6 +122,7 @@ 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 { TemplateCard } from "./TemplateCard";import { GenerateVideoPanel } from "./GeneratePanel";import { ImageGenPanel } from "./ImageGenPanel";@@ -817,10 +818,8 @@ function ProjectFilesPanel({// folder the moment its name is committed.const [creatingIds, setCreatingIds] = useState<string[] | null>(null);// The right-click menu at the cursor: `ids` carries the selection it acts- // on, null means the empty-space menu (just "New folder").- const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number; ids: string[] | null } | null>(- null- );+ // 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 [deletingIds, setDeletingIds] = useState<string[] | null>(null);@@ -947,24 +946,9 @@ function ProjectFilesPanel({// Right-click: over a card, the selection menu (the card joins the pick if// it wasn't in it); over empty panel space at the root, the New-folder menu.const onPanelContextMenu = (e: React.MouseEvent) => {- if (readOnly) return;- const t = e.target as HTMLElement;- // Controls, folder tiles, and the crumb keep their own menus and clicks.- if (t.closest("button,a,input,textarea,[role='button'],[role='menuitem'],[data-no-marquee]"))- return;- const card = t.closest<HTMLElement>("[data-sel-id]");- if (card) {- const id = card.dataset.selId!;- if (!shown.some((a) => a.id === id)) return;- e.preventDefault();- const ids = picked.has(id) ? [id, ...pickedIds.filter((x) => x !== id)] : [id];- if (!picked.has(id)) setPicked(new Set([id]));- setCtxMenu({ x: e.clientX, y: e.clientY, ids });- return;- }- if (openFolder !== null) return;+ if (readOnly || ctx.onContextMenu(e) || openFolder !== null) return;e.preventDefault();- setCtxMenu({ x: e.clientX, y: e.clientY, ids: null });+ ctx.openAt(e, []);};return (@@ -1251,87 +1235,47 @@ function ProjectFilesPanel({</AlertDialogContent></AlertDialog>- {/* The right-click menu: the same dropdown the cards' "…" button uses,- anchored to the pointer. */}- <DropdownMenu open={ctxMenu !== null} onOpenChange={(o) => !o && setCtxMenu(null)}>- {ctxMenu && (- <DropdownMenuContent- className="w-48"- sideOffset={0}- anchor={{- getBoundingClientRect: () => new DOMRect(ctxMenu.x, ctxMenu.y, 0, 0),- }}- // No focus return on close — there is no trigger to go back to,- // and reclaiming focus would blur the folder-name field the "New- // folder" items open, whose blur cancels the creation.- finalFocus={false}- >- {ctxMenu.ids === null ? (- <DropdownMenuItem- onClick={() => {- setCreatingIds([]);- setCtxMenu(null);- }}- >- <FolderPlus /> New folder- </DropdownMenuItem>- ) : (- <>- <DropdownMenuItem- onClick={() => {- // The name field opens on the root shelf; the picked ids- // file into the folder when the name is committed.- setCreatingIds(ctxMenu.ids);- setOpenFolder(null);- setCtxMenu(null);- }}- >- <FolderPlus /> New folder- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- onClick={() => {- removeMany(ctxMenu.ids!);- setCtxMenu(null);- }}- >- <Trash2 /> Delete- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- )}- </DropdownMenu>-- <AlertDialog open={deletingIds !== null} onOpenChange={(o) => !o && setDeletingIds(null)}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>- {deletingIds !== null && deletingIds.length > 1- ? `Remove ${deletingIds.length} files from the project?`- : "Remove this file from the project?"}- </AlertDialogTitle>- <AlertDialogDescription>- Timeline clips made from them are removed too.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- className="bg-destructive/10 text-destructive hover:bg-destructive/20"- onClick={(e) => {- e.preventDefault();- const s = useEditor.getState();- for (const id of deletingIds ?? []) s.removeAsset(id);- setDeletingIds(null);+ <SelectionMenu menu={ctx.menu} onClose={ctx.close}>+ {ctx.menu?.ids.length === 0 ? (+ <DropdownMenuItem onClick={() => setCreatingIds([])}>+ <FolderPlus /> New folder+ </DropdownMenuItem>+ ) : (+ <>+ <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);}}>- Remove- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ <FolderPlus /> New folder+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={() => removeMany(ctx.menu!.ids)}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </>+ )}+ </SelectionMenu>++ <DeleteConfirm+ open={deletingIds !== null}+ title={+ deletingIds !== null && deletingIds.length > 1+ ? `Remove ${deletingIds.length} files from the project?`+ : "Remove this file from the project?"+ }+ description="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);+ setDeletingIds(null);+ }}+ /></div>);}@@ -1651,9 +1595,6 @@ 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);- // The right-click menu over a card, anchored to the pointer, with the ids it- // acts on.- const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number; ids: string[] } | null>(null);const [uploading, setUploading] = useState(0);// Where an asset shows: phone recordings gather in the derived Camera Roll@@ -1795,22 +1736,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {// 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]);-- // Right-click over a card: the selection menu, with the card joining the- // pick if it wasn't in it. The browser's own media menu never shows here.- const onShelfContextMenu = (e: React.MouseEvent) => {- const t = e.target as HTMLElement;- if (t.closest("button,a,input,textarea,[role='button'],[role='menuitem'],[data-no-marquee]"))- return;- const card = t.closest<HTMLElement>("[data-sel-id]");- if (!card) return;- const id = card.dataset.selId!;- if (!shown.some((a) => a.id === id)) return;- e.preventDefault();- const ids = picked.has(id) ? [id, ...[...picked].filter((x) => x !== id)] : [id];- if (!picked.has(id)) setPicked(new Set([id]));- setCtxMenu({ x: e.clientX, y: e.clientY, ids });- };+ 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@@ -1877,7 +1803,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {dropActive &&"rounded-xl bg-[#0a84ff]/5 outline-2 outline-dashed outline-offset-[-4px] outline-[#0a84ff]/60")}- onContextMenu={onShelfContextMenu}+ onContextMenu={ctx.onContextMenu}>{!loaded ? (<div className="grid flex-1 place-items-center text-muted-foreground">@@ -2053,57 +1979,27 @@ function LibraryPanel({ projectId }: { projectId: string }) {</ScrollArea>)}- {/* The right-click menu, anchored to the pointer. */}- <DropdownMenu open={ctxMenu !== null} onOpenChange={(o) => !o && setCtxMenu(null)}>- {ctxMenu && (- <DropdownMenuContent- className="w-48"- sideOffset={0}- anchor={{- getBoundingClientRect: () => new DOMRect(ctxMenu.x, ctxMenu.y, 0, 0),- }}- finalFocus={false}- >- <DropdownMenuItem- variant="destructive"- onClick={() => {- setDeleting(shown.filter((a) => ctxMenu.ids.includes(a.id)));- setCtxMenu(null);- }}- >- <Trash2 /> Delete- </DropdownMenuItem>- </DropdownMenuContent>- )}- </DropdownMenu>-- <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>- {deleting && deleting.length > 1- ? `Delete ${deleting.length} items?`- : `Delete “${deleting?.[0]?.name}”?`}- </AlertDialogTitle>- <AlertDialogDescription>- Projects that already use {deleting && deleting.length > 1 ? "them" : "it"} keep- their own copy.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- className="bg-destructive/10 text-destructive hover:bg-destructive/20"- onClick={(e) => {- e.preventDefault();- void remove();- }}- >- Remove- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ <SelectionMenu menu={ctx.menu} onClose={ctx.close}>+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleting(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}”?`+ }+ description={`Projects that already use ${deleting && deleting.length > 1 ? "them" : "it"} keep their own copy.`}+ action="Remove"+ onClose={() => setDeleting(null)}+ onConfirm={() => void remove()}+ /></div>);}diff --git a/site/src/cut/components/selectionMenu.tsx b/site/src/cut/components/selectionMenu.tsxnew file mode 100644index 00000000..df647bdf--- /dev/null+++ b/site/src/cut/components/selectionMenu.tsx@@ -0,0 +1,137 @@+"use client";++import { useState, type ReactNode } from "react";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu";++/** The right-click menu over a grid of tiles: where it opened, and the ids it+ * 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.+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`.+ */+export function useSelectionMenu({+ picked,+ setPicked,+ shown,+}: {+ picked: Set<string>;+ setPicked: (s: Set<string>) => void;+ /** The ids on screen; a tile that isn't among them opens nothing. */+ shown: readonly string[];+}) {+ const [menu, setMenu] = useState<SelectionMenuAt | null>(null);+ const openAt = (e: { clientX: number; clientY: number }, ids: string[]) =>+ setMenu({ x: e.clientX, y: e.clientY, ids });+ // True when a tile or a control claimed the press, whether or not a menu+ // 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]");+ if (!card) return false;+ const id = card.dataset.selId!;+ if (!shown.includes(id)) return true;+ e.preventDefault();+ const ids = picked.has(id) ? [id, ...[...picked].filter((x) => x !== id)] : [id];+ if (!picked.has(id)) setPicked(new Set([id]));+ openAt(e, ids);+ return true;+ };+ return { menu, onContextMenu, openAt, close: () => setMenu(null) };+}++/** The menu `useSelectionMenu` opens, anchored to the pointer. Any entry+ * clicked closes it. */+export function SelectionMenu({+ menu,+ onClose,+ children,+}: {+ menu: SelectionMenuAt | null;+ onClose: () => void;+ children: ReactNode;+}) {+ return (+ <DropdownMenu open={menu !== null} onOpenChange={(o) => !o && onClose()}>+ {menu && (+ <DropdownMenuContent+ className="w-48"+ sideOffset={0}+ anchor={{+ getBoundingClientRect: () => new DOMRect(menu.x, menu.y, 0, 0),+ }}+ // No focus return on close — there is no trigger to go back to,+ // and reclaiming focus would blur a name field an entry opens,+ // whose blur cancels the creation.+ finalFocus={false}+ onClick={onClose}+ >+ {children}+ </DropdownMenuContent>+ )}+ </DropdownMenu>+ );+}++/** 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({+ open,+ title,+ description,+ action = "Delete",+ busy = false,+ onClose,+ onConfirm,+}: {+ open: boolean;+ title: ReactNode;+ description: ReactNode;+ action?: string;+ busy?: boolean;+ onClose: () => void;+ onConfirm: () => void;+}) {+ return (+ <AlertDialog open={open} onOpenChange={(o) => !o && onClose()}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{title}</AlertDialogTitle>+ <AlertDialogDescription>{description}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ disabled={busy}+ className="bg-destructive/10 text-destructive hover:bg-destructive/20"+ onClick={(e) => {+ e.preventDefault();+ onConfirm();+ }}+ >+ {action}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/site/src/cut/hooks/useDeleteKey.ts b/site/src/cut/hooks/useDeleteKey.tsnew file mode 100644index 00000000..63c1c8d6--- /dev/null+++ b/site/src/cut/hooks/useDeleteKey.ts@@ -0,0 +1,32 @@+"use client";++import { useEffect, useRef, type RefObject } from "react";+import { dialogOnTop, isDeleteKey, isTextEntry, menuOnTop } from "@/cut/lib/shortcutGate";++/**+ * ⌫ or Delete over a page of tiles asks for the pick to go. The page keeps+ * the keystroke only while it is the one on screen — the router leaves a page+ * you navigated away from mounted and hidden — and stands aside for a text+ * field, a dialog, or an open menu. `onDelete` is null while nothing is+ * picked.+ */+export function useDeleteKey(+ root: RefObject<HTMLElement | null>,+ onDelete: (() => void) | null+): void {+ const latest = useRef(onDelete);+ useEffect(() => {+ latest.current = onDelete;+ });+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (!latest.current || e.defaultPrevented || !isDeleteKey(e)) return;+ if (isTextEntry(e.target) || dialogOnTop() || menuOnTop()) return;+ if (!root.current?.checkVisibility()) return;+ e.preventDefault();+ latest.current();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [root]);+}diff --git a/site/src/cut/lib/shortcutGate.ts b/site/src/cut/lib/shortcutGate.tsindex 9d16132b..bb973f86 100644--- a/site/src/cut/lib/shortcutGate.ts+++ b/site/src/cut/lib/shortcutGate.ts@@ -96,7 +96,17 @@ export const popupOnTop = (el: Popup): boolean =>/** Whether a dialog stands over the editor, which owns the keyboard while it* is open. */export function dialogOnTop(): boolean {- for (const el of document.querySelectorAll('[data-slot="dialog-content"]')) {+ for (const el of document.querySelectorAll(+ '[data-slot="dialog-content"],[data-slot="alert-dialog-content"]'+ )) {+ if (popupOnTop(el)) return true;+ }+ return false;+}++/** Whether a menu is open, which owns the keyboard while it is up. */+export function menuOnTop(): boolean {+ for (const el of document.querySelectorAll('[role="menu"]')) {if (popupOnTop(el)) return true;}return false;