The VS Code of video editing, built for agents.
TypeScript
feat: enhance asset and folder item components to support multiple selections and context menu actions
konstantin-paulus7760cb569d26
diff --git a/apps/web/src/components/sidebar-left/asset-item.tsx b/apps/web/src/components/sidebar-left/asset-item.tsxindex 8dbec3c9..50a98011 100644--- a/apps/web/src/components/sidebar-left/asset-item.tsx+++ b/apps/web/src/components/sidebar-left/asset-item.tsx@@ -3,10 +3,8 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { createSignal, onMount, onCleanup, Show, createMemo } from "solid-js";-import { toast } from "somoto";-import { useWorld } from "@diffusionstudio/koota-solid";import { assetName } from "@diffusionstudio/assets";-import { insertAssetAtPlayhead, replaceAssetSource, saveAssetAs } from "@/engine/asset-actions";+import { replaceAssetSource, saveAssetAs } from "@/engine/asset-actions";import {ContextMenu,ContextMenuContent,@@ -20,21 +18,27 @@ import { AssetThumbnail } from "../ui/asset-thumbnail";import { MiddleEllipsis } from "../ui/middle-ellipsis";import { formatAssetDuration } from "@/utils";import { useLibrary } from "@/engine/library";-import { ASSET_DRAG_TYPE } from "./folder-item";import type { Asset } from "@diffusionstudio/assets";export type LazyAssetItemProps = {asset: Asset;selected: boolean;- onSelect(): void;+ /** Selected along with other items: the menu then acts on all of them. */+ multiple: boolean;+ onSelect(event: MouseEvent): void;+ onContextSelect(): void;+ onDragStart(event: DragEvent): void;+ /** Inserts the selection at the playhead. */+ onInsert(): void;+ /** Deletes the selection. */+ onDelete(): void;};/*** A lazy loaded asset item. Clears the buffer when not visible.*/export function LazyAssetItem(props: LazyAssetItemProps) {- const world = useWorld();const library = useLibrary();const [isVisible, setIsVisible] = createSignal(false);@@ -56,18 +60,6 @@ export function LazyAssetItem(props: LazyAssetItemProps) {onCleanup(() => observer.disconnect());});- const handleDeleteAsset = async () => {- try {- await library()?.remove([props.asset]);- } catch (e) {- toast.error("Failed to delete", { description: (e as Error).message });- }- };-- const handleDragStart = (event: DragEvent) => {- event.dataTransfer?.setData(ASSET_DRAG_TYPE, props.asset.id);- };-const commitRename = (nextName: string) => {if (!isRenaming()) return;setIsRenaming(false);@@ -100,7 +92,6 @@ export function LazyAssetItem(props: LazyAssetItemProps) {};const handleSaveAs = () => saveAssetAs(props.asset);- const handleInsertToTimeline = () => insertAssetAtPlayhead(world, props.asset);return (<ContextMenu>@@ -109,9 +100,9 @@ export function LazyAssetItem(props: LazyAssetItemProps) {class="flex flex-col gap-1 text-left"data-asset-id={props.asset.id}draggable={true}- onDragStart={handleDragStart}- onClick={props.onSelect}- onContextMenu={props.onSelect}>+ onDragStart={(event: DragEvent) => props.onDragStart(event)}+ onClick={(event: MouseEvent) => props.onSelect(event)}+ onContextMenu={() => props.onContextSelect()}><divref={ref}data-selected={props.selected}@@ -158,21 +149,23 @@ export function LazyAssetItem(props: LazyAssetItemProps) {</ContextMenuTrigger><ContextMenuPortal><ContextMenuContent class="w-[180px]">- <ContextMenuItem onSelect={handleInsertToTimeline}>+ <ContextMenuItem onSelect={props.onInsert}>Insert at playhead</ContextMenuItem>+ <Show when={!props.multiple}>+ <ContextMenuSeparator />+ <ContextMenuItem onSelect={() => setIsRenaming(true)}>+ Rename+ </ContextMenuItem>+ <ContextMenuItem onSelect={handleReplaceMedia}>+ Replace+ </ContextMenuItem>+ <ContextMenuItem onSelect={handleSaveAs}>+ Save as+ </ContextMenuItem>+ </Show><ContextMenuSeparator />- <ContextMenuItem onSelect={() => setIsRenaming(true)}>- Rename- </ContextMenuItem>- <ContextMenuItem onSelect={handleReplaceMedia}>- Replace- </ContextMenuItem>- <ContextMenuItem onSelect={handleSaveAs}>- Save as- </ContextMenuItem>- <ContextMenuSeparator />- <ContextMenuItem onSelect={handleDeleteAsset}>+ <ContextMenuItem onSelect={props.onDelete}>Delete<ContextMenuShortcut>⌫</ContextMenuShortcut></ContextMenuItem>diff --git a/apps/web/src/components/sidebar-left/assets.tsx b/apps/web/src/components/sidebar-left/assets.tsxindex 9703d3c2..ac581c27 100644--- a/apps/web/src/components/sidebar-left/assets.tsx+++ b/apps/web/src/components/sidebar-left/assets.tsx@@ -5,7 +5,8 @@import { basename, dirname } from "@diffusionstudio/assets";import { usePromptInput } from "@/context/prompt-input";import { restoreConfig } from "@/components/genai/saved-config";-import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js";+import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show, untrack } from "solid-js";+import { useWorld } from "@diffusionstudio/koota-solid";import { SidebarTabs } from "@/agent-chat";import { Button } from "../ui/button";import { Icon } from "../ui/icon";@@ -31,12 +32,21 @@ import { LazyAssetItem } from "./asset-item";import { FolderItem, handleFolderDrop, isAssetOrFolderDrag, ASSET_DRAG_TYPE, FOLDER_DRAG_TYPE } from "./folder-item";import { useLibrary } from "@/engine/library";import { useAssetSelection } from "@/engine/hooks";-import { droppedFiles, importFiles, pickAndImport } from "@/engine/asset-actions";+import { droppedFiles, importFiles, insertAssetsAtPlayhead, pickAndImport } from "@/engine/asset-actions";import { isInputTarget } from "@/utils";import type { AssetLibrary } from "@diffusionstudio/assets";/** The ancestors of a folder path, root excluded, nearest last. */+/**+ * A grid item's selection key: an asset id or a folder path, told apart by+ * prefix so the two kinds can share one ordered list.+ */+const assetKey = (id: string) => `asset:${id}`;+const folderKey = (path: string) => `folder:${path}`;+const isAssetKey = (key: string) => key.startsWith("asset:");+const keyValue = (key: string) => key.slice(key.indexOf(":") + 1);+function ancestorsOf(path: string): string[] {const chain: string[] = [];for (let folder = path; folder; folder = dirname(folder)) chain.unshift(folder);@@ -45,10 +55,12 @@ function ancestorsOf(path: string): string[] {export function Assets() {let root: HTMLDivElement | undefined;+ let scroller: HTMLDivElement | undefined;let dragCounter = 0;+ const world = useWorld();const library = useLibrary();- const { id: selectedAssetId, select: setSelectedAssetId } = useAssetSelection();+ const assetSelection = useAssetSelection();const { openPromptInput } = usePromptInput();const [query, setQuery] = createSignal("");const [assetFilter, setAssetFilter] = createSignal<AssetFilter>("ALL");@@ -86,6 +98,171 @@ export function Assets() {const itemCount = createMemo(() => visibleFolders().length + filteredAssets().length);+ /** The items in the grid, in its order: folders first, then assets. */+ const visibleKeys = createMemo(() => [+ ...visibleFolders().map(folderKey),+ ...filteredAssets().map((asset) => assetKey(asset.id)),+ ]);++ const selectedKeys = createMemo(() => new Set([+ ...assetSelection.folders().map(folderKey),+ ...assetSelection.ids().map(assetKey),+ ]));++ const setSelection = (keys: Iterable<string>) => {+ const unique = [...new Set(keys)];+ assetSelection.set({+ ids: unique.filter(isAssetKey).map(keyValue),+ folders: unique.filter((key) => !isAssetKey(key)).map(keyValue),+ });+ };++ // Finder's selection, as the dashboard's project grid has it: where a+ // Shift range starts, where Shift-arrows move from, and what was selected+ // before the range — the range is added to that.+ let anchor: string | null = null;+ let lead: string | null = null;+ let base: ReadonlySet<string> = new Set();++ const selectOnly = (key: string) => {+ setSelection([key]);+ anchor = lead = key;+ base = new Set();+ };++ const toggleSelected = (key: string) => {+ const next = new Set(selectedKeys());+ if (!next.delete(key)) next.add(key);+ setSelection(next);+ anchor = lead = key;+ base = new Set([...next].filter((entry) => entry !== key));+ };++ /** Selects anchor through `key` on top of `base`, or just `key` when the anchor is off the grid. */+ const selectRangeTo = (key: string) => {+ const keys = visibleKeys();+ const from = anchor === null ? -1 : keys.indexOf(anchor);+ const to = keys.indexOf(key);+ if (from < 0 || to < 0) return selectOnly(key);++ setSelection([...base, ...keys.slice(Math.min(from, to), Math.max(from, to) + 1)]);+ lead = key;+ };++ const selectAll = () => {+ const keys = visibleKeys();+ setSelection(keys);+ anchor = keys[0] ?? null;+ lead = keys.at(-1) ?? null;+ base = new Set();+ };++ const clearSelection = () => {+ setSelection([]);+ anchor = lead = null;+ base = new Set();+ };++ // Items that leave the grid (another folder opened, filtered out, moved or+ // deleted) leave the selection, so keys never act on what is not in view.+ createEffect(() => {+ const visible = new Set(visibleKeys());+ const selected = untrack(selectedKeys);+ const kept = [...selected].filter((key) => visible.has(key));+ if (kept.length !== selected.size) setSelection(kept);+ });++ const handleItemClick = (key: string, event: MouseEvent) => {+ if (event.shiftKey) selectRangeTo(key);+ else if (event.metaKey || event.ctrlKey) toggleSelected(key);+ else selectOnly(key);+ root?.focus();+ };++ /** A right-click keeps a selection it lands in, like Finder; elsewhere it selects the item alone. */+ const handleItemContextMenu = (key: string) => {+ if (!selectedKeys().has(key)) selectOnly(key);+ root?.focus();+ };++ /** Drags the whole selection when the item is part of it, the item alone otherwise. */+ const handleItemDragStart = (key: string, event: DragEvent) => {+ const keys = selectedKeys().has(key) ? [...selectedKeys()] : [key];+ const assetIds = keys.filter(isAssetKey).map(keyValue);+ const folders = keys.filter((entry) => !isAssetKey(entry)).map(keyValue);+ if (assetIds.length) event.dataTransfer?.setData(ASSET_DRAG_TYPE, assetIds.join(","));+ if (folders.length) event.dataTransfer?.setData(FOLDER_DRAG_TYPE, folders.join("\n"));+ if (keys.length > 1) setSelectionDragImage(keys, event);+ };++ /**+ * Shows every dragged item under the pointer, where it sits in the grid, as+ * Finder does: copies of the items in view, laid out as they are, become the+ * drag image. Items scrolled out of view are left out, their thumbnails are+ * not loaded.+ */+ const setSelectionDragImage = (keys: string[], event: DragEvent) => {+ const viewport = scroller?.getBoundingClientRect();+ if (!event.dataTransfer || !viewport) return;++ const items = keys+ .map((key) => itemElement(key))+ .filter((element) => element !== null)+ .map((element) => ({ element, rect: element.getBoundingClientRect() }))+ .filter(({ rect }) => rect.bottom > viewport.top && rect.top < viewport.bottom);+ if (items.length < 2) return;++ const left = Math.min(...items.map(({ rect }) => rect.left));+ const top = Math.min(...items.map(({ rect }) => rect.top));++ // Off screen: the browser takes its picture of the element while it is in+ // the document, and it can go once the drag has begun.+ const image = document.createElement("div");+ image.style.cssText = "position: fixed; left: -10000px; top: 0; pointer-events: none;";+ for (const { element, rect } of items) {+ const copy = element.cloneNode(true) as HTMLElement;+ copy.removeAttribute("id");+ copy.style.cssText = `position: absolute; left: ${rect.left - left}px; top: ${rect.top - top}px; width: ${rect.width}px; height: ${rect.height}px;`;+ image.append(copy);+ }+ document.body.append(image);+ event.dataTransfer.setDragImage(image, event.clientX - left, event.clientY - top);+ setTimeout(() => image.remove());+ };++ const selectedAssets = () => {+ const lib = library();+ if (!lib) return [];+ return assetSelection.ids().map((id) => lib.get(id)).filter((asset) => asset !== undefined);+ };++ const insertSelection = () => insertAssetsAtPlayhead(world, selectedAssets());++ const deleteSelection = async () => {+ const lib = library();+ if (!lib) return;+ const assets = selectedAssets();+ const folders = assetSelection.folders();+ try {+ if (assets.length) await lib.remove(assets);+ // A folder inside another selected folder is gone with it.+ for (const folder of folders) {+ if (lib.folders().has(folder)) await lib.deleteFolder(folder);+ }+ } catch (e) {+ toast.error("Failed to delete", { description: (e as Error).message });+ }+ };++ const itemElement = (key: string) => {+ const attribute = isAssetKey(key) ? "data-asset-id" : "data-folder-path";+ return root?.querySelector<HTMLElement>(`[${attribute}="${CSS.escape(keyValue(key))}"]`) ?? null;+ };++ const scrollToItem = (key: string) => {+ itemElement(key)?.scrollIntoView({ block: "nearest" });+ };+// Deep paths collapse like the breadcrumbs docs example:// All assets / … / parent / current, with the hidden folders in a dropdown.const folderPath = createMemo(() => ancestorsOf(currentFolder()));@@ -107,9 +284,9 @@ export function Assets() {if (currentFolder()) openFolder(dirname(currentFolder()));};- const getAssetIdFromTarget = (target: EventTarget | null) => {+ const isItemTarget = (target: EventTarget | null) => {const element = target instanceof Element ? target : null;- return element?.closest("[data-asset-id]")?.getAttribute("data-asset-id") ?? null;+ return element?.closest("[data-asset-id], [data-folder-path]") != null;};// A folder that went away (deleted, moved) closes to the nearest one left.@@ -180,35 +357,42 @@ export function Assets() {};- const handleSelectAsset = (assetId: string) => {- setSelectedAssetId(assetId);- root?.focus();- };-- const moveSelection = (delta: number) => {- const items = Array.from(- root?.querySelectorAll<HTMLElement>("[data-asset-id]") ?? []- );- if (items.length === 0) return;-- const currentId = selectedAssetId();- const currentIndex = currentId- ? items.findIndex(item => item.dataset.assetId === currentId)- : -1;- const baseIndex = currentIndex === -1 ? 0 : currentIndex;- const nextIndex = Math.min(- items.length - 1,- Math.max(0, baseIndex + delta)- );+ /** Moves the lead an item over, or a row up or down, as Finder's icon view does. */+ const moveSelection = (arrow: string, extend: boolean) => {+ const keys = visibleKeys();+ if (keys.length === 0) return;- const nextItem = items[nextIndex];- const nextId = nextItem?.dataset.assetId;- if (!nextId) return;+ const columns = 2;+ const count = keys.length;+ const current = lead === null ? -1 : keys.indexOf(lead);++ let index: number;+ if (current < 0) {+ index = 0;+ } else {+ if (arrow === "ArrowLeft") index = current - 1;+ else if (arrow === "ArrowRight") index = current + 1;+ else if (arrow === "ArrowUp") index = current - columns;+ // Down from a row above a short last row lands on its last item.+ else if (current + columns < count) index = current + columns;+ else if (Math.floor(current / columns) < Math.floor((count - 1) / columns)) index = count - 1;+ else return;++ if (index < 0 || index >= count) return;+ }- setSelectedAssetId(nextId);- nextItem.scrollIntoView({ block: "nearest" });+ const key = keys[index];+ if (extend && anchor !== null) selectRangeTo(key);+ else selectOnly(key);+ scrollToItem(key);};+ /**+ * Finder's keys for the grid: arrows move the selection and Shift-arrows+ * grow it, ⌘A selects every item in view and ⌥⌘A or Escape none, ⌘↓ opens+ * the selected folder and ⌘↑ goes up, ⌫ deletes the selection. Handled keys+ * stop here, so the canvas does not act on them too.+ */const handleKeyDown = (event: KeyboardEvent) => {const target = event.target as HTMLElement | null;if (@@ -219,13 +403,13 @@ export function Assets() {return;}+ const command = event.metaKey || event.ctrlKey;+if (event.key === "Backspace" || event.key === "Delete") {- const selected = selectedAssetId();- const entry = selected ? library()?.get(selected) : undefined;- if (entry) {+ if (selectedKeys().size > 0) {event.preventDefault();event.stopPropagation();- void library()?.remove([entry]);+ void deleteSelection();return;}@@ -237,24 +421,38 @@ export function Assets() {return;}- const columns = 2;- const deltaByKey: Record<string, number> = {- ArrowUp: -columns,- ArrowDown: columns,- ArrowLeft: -1,- ArrowRight: 1,- };- const delta = deltaByKey[event.key];- if (delta === undefined) return;+ // By code: ⌥ turns the A of ⌥⌘A into another character on a Mac.+ if (command && event.code === "KeyA") {+ event.preventDefault();+ event.stopPropagation();+ if (event.altKey) clearSelection();+ else selectAll();+ return;+ }+ if (event.key === "Escape" && selectedKeys().size > 0) {+ event.preventDefault();+ event.stopPropagation();+ clearSelection();+ return;+ }++ if (!event.key.startsWith("Arrow")) return;event.preventDefault();- moveSelection(delta);+ event.stopPropagation();++ if (command && event.key === "ArrowDown") {+ const folders = assetSelection.folders();+ if (folders.length === 1 && assetSelection.ids().length === 0) openFolder(folders[0]);+ } else if (command && event.key === "ArrowUp") {+ handleGoToParent();+ } else if (!command && !event.altKey) {+ moveSelection(event.key, event.shiftKey);+ }};const handleBackgroundClick = (event: MouseEvent) => {- if (!getAssetIdFromTarget(event.target)) {- setSelectedAssetId(null);- }+ if (!isItemTarget(event.target)) clearSelection();};const hasAssets = () => allAssets().length > 0;@@ -478,6 +676,7 @@ export function Assets() {</div></Show><div+ ref={scroller}class="flex-1 min-h-0 overflow-y-auto p-4 pt-3"onClick={handleBackgroundClick}>@@ -515,9 +714,15 @@ export function Assets() {<FolderItempath={folder}renaming={renamingFolder() === folder}+ selected={selectedKeys().has(folderKey(folder))}+ multiple={selectedKeys().size > 1 && selectedKeys().has(folderKey(folder))}+ onSelect={(event) => handleItemClick(folderKey(folder), event)}+ onContextSelect={() => handleItemContextMenu(folderKey(folder))}+ onDragStart={(event) => handleItemDragStart(folderKey(folder), event)}onRenameStart={() => setRenamingFolder(folder)}onRenameEnd={() => setRenamingFolder(null)}onOpen={() => openFolder(folder)}+ onDelete={deleteSelection}/>)}</For>@@ -525,8 +730,13 @@ export function Assets() {{(asset) => (<LazyAssetItemasset={asset}- selected={selectedAssetId() === asset.id}- onSelect={() => handleSelectAsset(asset.id)}+ selected={selectedKeys().has(assetKey(asset.id))}+ multiple={selectedKeys().size > 1 && selectedKeys().has(assetKey(asset.id))}+ onSelect={(event) => handleItemClick(assetKey(asset.id), event)}+ onContextSelect={() => handleItemContextMenu(assetKey(asset.id))}+ onDragStart={(event) => handleItemDragStart(assetKey(asset.id), event)}+ onInsert={insertSelection}+ onDelete={deleteSelection}/>)}</For>diff --git a/apps/web/src/components/sidebar-left/folder-item.tsx b/apps/web/src/components/sidebar-left/folder-item.tsxindex 2bc354d7..52c412ca 100644--- a/apps/web/src/components/sidebar-left/folder-item.tsx+++ b/apps/web/src/components/sidebar-left/folder-item.tsx@@ -19,7 +19,7 @@ import { useLibrary } from "@/engine/library";import type { AssetLibrary } from "@diffusionstudio/assets";-/** Drag payloads: comma-separated asset ids, or one folder path. */+/** Drag payloads: comma-separated asset ids, and newline-separated folder paths. */export const ASSET_DRAG_TYPE = "application/x-asset-id";export const FOLDER_DRAG_TYPE = "application/x-folder-path";@@ -36,14 +36,16 @@ export function handleFolderDrop(library: AssetLibrary | undefined, event: DragEif (!library) return false;const assetIds = event.dataTransfer?.getData(ASSET_DRAG_TYPE)?.split(",").filter(Boolean) ?? [];- const folder = event.dataTransfer?.getData(FOLDER_DRAG_TYPE);- if (!assetIds.length && !folder) return false;+ const folders = event.dataTransfer?.getData(FOLDER_DRAG_TYPE)?.split("\n").filter(Boolean) ?? [];+ if (!assetIds.length && !folders.length) return false;const assets = assetIds.map((id) => library.get(id)).filter((asset) => asset !== undefined);if (assets.length) library.move(assets, target);- if (folder && folder !== target) {- if (target === folder || target.startsWith(`${folder}/`)) {+ for (const folder of folders) {+ // A selected folder dropped on itself stays put; the rest of the selection goes in.+ if (folder === target) continue;+ if (target.startsWith(`${folder}/`)) {toast("Cannot move a folder into itself");} else {library.moveFolder(folder, target);@@ -56,9 +58,17 @@ export type FolderItemProps = {/** The folder's library path. */path: string;renaming: boolean;+ selected: boolean;+ /** Selected along with other items: the menu then acts on all of them. */+ multiple: boolean;+ onSelect(event: MouseEvent): void;+ onContextSelect(): void;+ onDragStart(event: DragEvent): void;onRenameStart(): void;onRenameEnd(): void;onOpen(): void;+ /** Deletes the selection. */+ onDelete(): void;};export function FolderItem(props: FolderItemProps) {@@ -71,10 +81,6 @@ export function FolderItem(props: FolderItemProps) {return children ? children.folders.length + children.assets.length : 0;});- const handleDragStart = (event: DragEvent) => {- event.dataTransfer?.setData(FOLDER_DRAG_TYPE, props.path);- };-const handleDragOver = (event: DragEvent) => {if (!isAssetOrFolderDrag(event)) return;event.preventDefault();@@ -116,14 +122,6 @@ export function FolderItem(props: FolderItemProps) {});};- const handleDelete = async () => {- try {- await library()?.deleteFolder(props.path);- } catch (e) {- toast.error("Failed to delete", { description: (e as Error).message });- }- };-return (<ContextMenu><ContextMenuTrigger@@ -131,15 +129,18 @@ export function FolderItem(props: FolderItemProps) {class="flex flex-col gap-1 text-left"data-folder-path={props.path}draggable={true}- onDragStart={handleDragStart}+ onDragStart={(event: DragEvent) => props.onDragStart(event)}on:dragover={handleDragOver}on:dragleave={() => setIsDropTarget(false)}on:drop={handleDrop}- onClick={props.onOpen}+ onClick={(event: MouseEvent) => props.onSelect(event)}+ onDblClick={() => props.onOpen()}+ onContextMenu={() => props.onContextSelect()}><divdata-drop-target={isDropTarget()}- class="relative aspect-video w-full rounded bg-muted flex items-center justify-center after:pointer-events-none after:absolute after:-inset-px after:rounded-[5px] after:opacity-0 after:ring-2 after:ring-inset after:ring-ring after:z-10 data-[drop-target=true]:after:opacity-100"+ data-selected={props.selected}+ class="relative aspect-video w-full rounded bg-muted flex items-center justify-center after:pointer-events-none after:absolute after:-inset-px after:rounded-[5px] after:opacity-0 after:ring-2 after:ring-inset after:ring-ring after:z-10 data-[drop-target=true]:after:opacity-100 data-[selected=true]:after:opacity-100"><Icon name="folder-thumbnail" class="w-8 h-6 text-muted-foreground pointer-events-none" /><Show when={childCount() > 0}>@@ -150,7 +151,13 @@ export function FolderItem(props: FolderItemProps) {</div><Showwhen={props.renaming}- fallback={<MiddleEllipsis text={name()} class="text-xs text-center text-muted-foreground select-none" />}+ fallback={+ <MiddleEllipsis+ text={name()}+ data-selected={props.selected}+ class="text-xs text-center text-muted-foreground select-none data-[selected=true]:text-foreground"+ />+ }><inputref={handleFocusElement}@@ -169,11 +176,13 @@ export function FolderItem(props: FolderItemProps) {</ContextMenuTrigger><ContextMenuPortal><ContextMenuContent class="w-[220px]">- <ContextMenuItem onSelect={props.onOpen}>Open</ContextMenuItem>- <ContextMenuSeparator />- <ContextMenuItem onSelect={props.onRenameStart}>Rename</ContextMenuItem>- <ContextMenuSeparator />- <ContextMenuItem onSelect={handleDelete}>Delete</ContextMenuItem>+ <Show when={!props.multiple}>+ <ContextMenuItem onSelect={props.onOpen}>Open</ContextMenuItem>+ <ContextMenuSeparator />+ <ContextMenuItem onSelect={props.onRenameStart}>Rename</ContextMenuItem>+ <ContextMenuSeparator />+ </Show>+ <ContextMenuItem onSelect={props.onDelete}>Delete</ContextMenuItem></ContextMenuContent></ContextMenuPortal></ContextMenu>diff --git a/apps/web/src/engine/asset-actions.ts b/apps/web/src/engine/asset-actions.tsindex b79e238d..157ba086 100644--- a/apps/web/src/engine/asset-actions.ts+++ b/apps/web/src/engine/asset-actions.ts@@ -69,8 +69,16 @@ export async function replaceAssetSource(library: AssetLibrary, asset: Asset): P/** Inserts `asset` at the playhead of the active scene; tells the user when there is nowhere to put it. */export function insertAssetAtPlayhead(world: World, asset: Asset): void {- if (!insertAsset(world, asset)) {- toast("Nothing to insert into", { description: "Open a project first." });+ insertAssetsAtPlayhead(world, [asset]);+}++/** Inserts each of `assets` at the playhead, all starting there. */+export function insertAssetsAtPlayhead(world: World, assets: ReadonlyArray<Asset>): void {+ for (const asset of assets) {+ if (!insertAsset(world, asset)) {+ toast("Nothing to insert into", { description: "Open a project first." });+ return;+ }}}diff --git a/apps/web/src/engine/editor.ts b/apps/web/src/engine/editor.tsindex 5ed64ff7..57f120c1 100644--- a/apps/web/src/engine/editor.ts+++ b/apps/web/src/engine/editor.ts@@ -391,8 +391,9 @@ export class DocumentEditor {public select(entities: Entity | Entity[], options: { extend?: boolean } = {}): void {const next = new Set(Array.isArray(entities) ? entities : [entities]);- if (this.world.has(AssetSelection) && this.world.get(AssetSelection)?.id !== null) {- this.world.set(AssetSelection, { id: null });+ const assetSelection = this.world.get(AssetSelection);+ if (assetSelection && (assetSelection.ids.length || assetSelection.folders.length)) {+ this.world.set(AssetSelection, { ids: [], folders: [] });}if (!options.extend) {diff --git a/apps/web/src/engine/hooks/use-asset-selection.ts b/apps/web/src/engine/hooks/use-asset-selection.tsindex 3362d59b..6e52d9cb 100644--- a/apps/web/src/engine/hooks/use-asset-selection.ts+++ b/apps/web/src/engine/hooks/use-asset-selection.ts@@ -11,29 +11,39 @@ import { useLibrary } from '../library';import type { Asset } from '@diffusionstudio/assets';/**- * Reactive read and write of the AssetSelection trait: the one asset the- * assets panel has picked and the inspector describes. Shared between the two- * sidebars, so it lives on the world rather than in either panel.+ * Reactive read and write of the AssetSelection trait: the assets and folders+ * the assets panel has picked, and the one asset the inspector describes.+ * Shared between the two sidebars, so it lives on the world rather than in+ * either panel.*/export function useAssetSelection() {const world = useWorld();const library = useLibrary();const selection = useTrait(world, AssetSelection);- const id = () => selection()?.id ?? null;+ const ids = () => selection()?.ids ?? [];+ const folders = () => selection()?.folders ?? [];- // `list()` is the library's signal, so a removed or relinked asset drops- // out here without the panel having to watch for it.+ // The asset the inspector describes: the selection, when it is one asset+ // alone. `list()` is the library's signal, so a removed or relinked asset+ // drops out here without the panel having to watch for it.const asset = createMemo(() => {const lib = library();- const current = id();- if (!lib || !current) return undefined;- return lib.list().find((entry) => entry.id === current);+ const current = ids();+ if (!lib || current.length !== 1 || folders().length) return undefined;+ return lib.list().find((entry) => entry.id === current[0]);});+ /** Selects one asset alone, or nothing. */const select = (next: Asset | string | null) => {- world.set(AssetSelection, { id: typeof next === 'string' ? next : (next?.id ?? null) });+ const id = typeof next === 'string' ? next : next?.id;+ world.set(AssetSelection, { ids: id ? [id] : [], folders: [] });};- return { id, asset, select };+ /** Replaces the selection with these assets and folders. */+ const set = (next: { ids: string[]; folders: string[] }) => {+ world.set(AssetSelection, next);+ };++ return { ids, folders, asset, select, set };}diff --git a/apps/web/src/engine/traits.ts b/apps/web/src/engine/traits.tsindex 3cb606dd..f2c0c47e 100644--- a/apps/web/src/engine/traits.ts+++ b/apps/web/src/engine/traits.ts@@ -142,12 +142,13 @@ export const PathEditor = trait({export const PointerEvents = trait({ queue: () => [] as CanvasPointerEvent[] });/**- * The library asset picked in the assets panel, by id (null for none). The- * inspector shows its information; a click on empty canvas clears it, like- * it clears the node selection. Not a document property: which asset is- * being looked at is editor state, not something the JSX says.+ * The library items picked in the assets panel: asset ids and folder paths.+ * The inspector shows the information of a lone selected asset; a click on+ * empty canvas clears it, like it clears the node selection. Not a document+ * property: which assets are being looked at is editor state, not something+ * the JSX says.*/-export const AssetSelection = trait({ id: null as string | null });+export const AssetSelection = trait({ ids: () => [] as string[], folders: () => [] as string[] });/*** The config of the project on disk (its package.json `diffusion` field),