Skip to content

Open source CapCut alternative.

TypeScript

feat(site): library and project folders nest on every shelf [rebuild]

David Led48042fdd5f0
diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.ts
index 11c17ab8..2121f465 100644
--- a/site/src/cut/components/LibraryView.tools.ts
+++ b/site/src/cut/components/LibraryView.tools.ts
@@ -12,7 +12,7 @@ export const LIBRARY_TOOLS = [
{
name: "library_list",
description:
- "List the shared Library — reusable media saved across projects: folders, assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). An asset's `origin` says it came from the user's iOS app: \"camera\" is a clip they recorded on their phone (their Camera Roll), \"inspiration\" a reference they saved to the Inspiration folder. Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",
+ "List the shared Library — reusable media saved across projects: folders (nested; a folder's parentId names the folder it sits in), assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). An asset's `origin` says it came from the user's iOS app: \"camera\" is a clip they recorded on their phone (their Camera Roll), \"inspiration\" a reference they saved to the Inspiration folder. Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",
inputSchema: obj({}),
},
{
@@ -57,15 +57,16 @@ export const LIBRARY_TOOLS = [
{
name: "library_organize",
description:
- "Organize the shared Library: create_folder / rename_folder / delete_folder (a deleted folder's items drop to the root), move_asset files an asset or template into a folder (omit folder_id for the root), delete_asset / delete_template remove an item. Deletes are permanent — projects keep their own copies, but delete only what the user explicitly asked to remove. Deleting an asset with origin \"camera\" or \"inspiration\" takes it off the user's phone as well.",
+ "Organize the shared Library. Folders nest: create_folder makes one at the root or inside parent_id, rename_folder renames, move_folder files a folder under another (omit parent_id for the root; never into itself or a folder inside it), delete_folder removes one (what it held — items and folders — moves up one level). move_asset files an asset or template into a folder (omit folder_id for the root), delete_asset / delete_template remove an item. Deletes are permanent — projects keep their own copies, but delete only what the user explicitly asked to remove. Deleting an asset with origin \"camera\" or \"inspiration\" takes it off the user's phone as well.",
inputSchema: obj({
action: {
type: "string",
- enum: ["create_folder", "rename_folder", "delete_folder", "move_asset", "delete_asset", "delete_template"],
+ enum: ["create_folder", "rename_folder", "move_folder", "delete_folder", "move_asset", "delete_asset", "delete_template"],
description: "The organize operation",
},
name: str("Folder name (create_folder, rename_folder)"),
- folder_id: str("Folder id (rename_folder, delete_folder, move_asset destination — omit for root)"),
+ folder_id: str("Folder id (rename_folder, move_folder, delete_folder, move_asset destination — omit for root)"),
+ parent_id: str("The folder to file a folder inside (create_folder, move_folder) — omit for the root"),
id: str("Library asset or template id (move_asset, delete_asset, delete_template)"),
}, ["action"]),
},
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 25fc5f80..211c23a9 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
@@ -78,7 +78,7 @@ import {
carryAssetTo,
carryTemplateTo,
moveLibraryItem,
- renameLibraryFolder,
+ updateLibraryFolder,
renameTemplate,
uploadToLibrary,
type ImportStage,
@@ -124,6 +124,7 @@ import {
SPECIMEN_META,
} from "@/cut/lib/fontSpecimen";
import { AudioCardFace } from "./AudioPanel";
+import { childrenOf, folderTrail, folderWithin, parentOf } from "@/cut/lib/folderTree";
import { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";
import { formatBytes } from "@/lib/bytes";
import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";
@@ -131,6 +132,8 @@ import { useMediaFileSize } from "@/cut/hooks/useMediaFileSize";
// 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.
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";
/** 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
@@ -366,7 +369,8 @@ export function LibraryView() {
// Phone camera recordings have their own home tab (Camera Roll); the
// Library grid lists everything else.
const all = (library.data?.assets ?? []).filter((a) => a.origin !== "camera");
- const folders = library.data?.folders ?? [];
+ const folderList = library.data?.folders;
+ const folders = useMemo(() => folderList ?? [], [folderList]);
const templates = library.data?.templates ?? [];
const patch = useCallback(
(fn: (prev: LibraryData) => LibraryData) => patchLibrary(client, fn),
@@ -636,6 +640,35 @@ export function LibraryView() {
).catch(() => void reload());
};
+ // 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.
+ const moveFolders = async (ids: string[], parentId: string | null) => {
+ const target = parentId
+ ? folders.find((f) => f.id === parentId)?.residency
+ : null;
+ if (parentId && !target) return;
+ const moving = folders.filter(
+ (f) =>
+ ids.includes(f.id) &&
+ live(f.residency) &&
+ (!target || f.residency === target) &&
+ parentOf(f) !== parentId &&
+ !folderWithin(folders, parentId, f.id),
+ );
+ if (moving.length === 0) return;
+ const idset = new Set(moving.map((f) => f.id));
+ patch((d) => ({
+ ...d,
+ folders: d.folders.map((f) =>
+ idset.has(f.id) ? { ...f, parentId } : f,
+ ),
+ }));
+ await Promise.all(
+ moving.map((f) => updateLibraryFolder(f.residency, f.id, { parentId })),
+ ).catch(() => void reload());
+ };
+
// 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.
@@ -688,7 +721,23 @@ export function LibraryView() {
const shownTemplates = templates.filter(
(t) => (t.folderId ?? null) === openFolder,
);
- const openFolderName = folders.find((f) => f.id === openFolder)?.name;
+ // 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.
+ const openOwner = openFolder
+ ? folders.find((f) => f.id === openFolder)?.residency
+ : null;
+ const newShelf = openOwner && live(openOwner) ? openOwner : target;
+ const newParent = openOwner === newShelf ? openFolder : null;
+ // A folder the URL names and no shelf answers for — deleted elsewhere —
+ // goes back to the top level.
+ const staleFolder = !!openFolder && !!library.data && trail.length === 0;
+ useEffect(() => {
+ if (staleFolder) router.replace(homeHref(base, "library"));
+ }, [staleFolder, router, base]);
const hasContent =
all.length > 0 ||
folders.length > 0 ||
@@ -741,14 +790,16 @@ export function LibraryView() {
) : (
<FolderCrumb
root="Library"
- trail={[{ id: openFolder, name: openFolderName ?? "Folder" }]}
+ trail={trail}
mime={LIBRARY_MOVE_MIME}
- onGo={() => gotoFolder(null)}
- onDrop={(ids) => void moveItems(ids, null)}
+ folderMime={LIBRARY_FOLDER_MOVE_MIME}
+ onGo={gotoFolder}
+ onDrop={(ids, id) => void moveItems(ids, id)}
+ onDropFolders={(ids, id) => void moveFolders(ids, id)}
/>
)}
<div className="flex items-center gap-2">
- {openFolder === null && (
+ {(openFolder === null || newParent) && (
<Button variant="outline" onClick={() => setFolderCreating(true)}>
<FolderPlus data-icon="inline-start" /> New folder
</Button>
@@ -773,18 +824,20 @@ export function LibraryView() {
/>
</div>
- {/* Folders live at the root and nowhere else, so an open folder shows
- only what is filed in it. */}
- {openFolder === null && (folders.length > 0 || folderCreating) ? (
+ {/* The folders filed at this level, at the top and inside any folder
+ alike. A new one is made here and a dropped one is filed here. */}
+ {shownFolders.length > 0 || folderCreating ? (
<FolderShelf
- folders={folders}
+ folders={shownFolders}
mime={LIBRARY_MOVE_MIME}
+ folderMime={LIBRARY_FOLDER_MOVE_MIME}
creating={folderCreating}
onCreatingChange={setFolderCreating}
statOf={(id) => ({
count:
all.filter((a) => (a.folderId ?? null) === id).length +
- templates.filter((t) => (t.folderId ?? null) === id).length,
+ templates.filter((t) => (t.folderId ?? null) === id).length +
+ childrenOf(folders, id).length,
})}
badgeOf={(id) => {
const r = folders.find((f) => f.id === id)?.residency;
@@ -794,8 +847,8 @@ export function LibraryView() {
}}
onOpen={gotoFolder}
onCreate={async (name) => {
- if (!live(target)) return;
- const f = await createLibraryFolder(name, target);
+ if (!live(newShelf)) return;
+ const f = await createLibraryFolder(name, newShelf, newParent);
patch((d) => ({ ...d, folders: [...d.folders, f] }));
}}
onRename={async (id, name) => {
@@ -807,24 +860,29 @@ export function LibraryView() {
f.id === id ? { ...f, name } : f,
),
}));
- await renameLibraryFolder(r, id, name).catch(() => void reload());
+ await updateLibraryFolder(r, id, { name }).catch(() => void reload());
}}
onDelete={async (id) => {
- const r = folders.find((f) => f.id === id)?.residency;
- if (!r || !live(r)) return;
+ // 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),
+ 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: null } : a,
+ a.folderId === id ? { ...a, folderId: up } : a,
),
templates: d.templates.map((t) =>
- t.folderId === id ? { ...t, folderId: null } : t,
+ t.folderId === id ? { ...t, folderId: up } : t,
),
}));
- if (openFolder === id) router.replace(homeHref(base, "library"));
- await deleteLibraryFolder(r, id).catch(() => void reload());
+ await deleteLibraryFolder(gone.residency, id).catch(() => void reload());
}}
onDropIds={(ids, fid) => void moveItems(ids, fid)}
+ onDropFolders={(ids, fid) => void moveFolders(ids, fid)}
onDropFiles={(files, fid) => void upload(files, fid)}
/>
) : null}
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index 68c574c4..dbfb4ef8 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -90,6 +90,7 @@ 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 { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";
import { formatBytes } from "@/lib/bytes";
@@ -117,6 +118,8 @@ type SectionData = {
// 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";
+// A dragged folder tile, filed into another folder or back out to a crumb.
+const PROJECT_FOLDER_MIME = "application/x-cut-project-folder";
// The badge marks where one project lives, so it says that outright rather
// than repeating the shelf heading it sits under. A local project the Donkey
@@ -267,6 +270,10 @@ export function ProjectsHome() {
// The open folder lives in the URL (?folder=…) so project URLs can point
// back into it and the browser's back button steps folder → root.
const openFolder = useSearchParams().get("folder");
+ // Which section owns the open folder — in dual mode only that section shows.
+ 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, setView] = useState<View>("gallery");
// The residency the pending creation was launched for; null when the naming
@@ -295,6 +302,14 @@ export function ProjectsHome() {
if (saved === "list" || saved === "gallery") setView(saved);
}, []);
+ // A folder the URL names and no listed shelf answers for — deleted
+ // elsewhere — goes back to the top level.
+ const allSettled = residencies.every((r) => data[r].projects !== null || data[r].error);
+ const staleFolder = !!openFolder && allSettled && !folderOwner;
+ useEffect(() => {
+ if (staleFolder) router.replace(homeHref(base, "projects"));
+ }, [staleFolder, router, base]);
+
const switchView = (v: View) => {
setView(v);
localStorage.setItem("cut-projects-view", v);
@@ -303,12 +318,12 @@ export function ProjectsHome() {
// Each mutation below opens with the same guard: a shelf that isn't
// answering takes no changes, and an optimistic patch would paint a rename
// that never happened and then take it back on reconnect.
- const createFolder = async (r: Residency, fname: string) => {
+ const createFolder = async (r: Residency, fname: string, parentId: string | null) => {
if (!live(r)) return;
const res = await backendFor(r).fetch("/api/cut/projects/folders", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: fname }),
+ body: JSON.stringify({ name: fname, parentId }),
});
if (res.ok) {
const f = (await res.json()) as ProjectFolder;
@@ -339,18 +354,51 @@ export function ProjectsHome() {
router.push(homeHref(base, "projects", id));
};
+ // What a deleted folder held comes up one level, the way the shelf files it.
const deleteFolder = async (r: Residency, id: string) => {
if (!live(r)) return;
+ const up = parentOf(data[r].folders.find((f) => f.id === id) ?? { id });
patch(r, (s) => ({
- folders: s.folders.filter((f) => f.id !== id),
- projects: s.projects.map((p) => (p.folderId === id ? { ...p, folderId: null } : p)),
+ 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)),
}));
- if (openFolder === id) router.replace(homeHref(base, "projects"));
await backendFor(r)
.fetch(`/api/cut/projects/folders/${id}`, { method: "DELETE" })
.catch(() => void refresh(r));
};
+ // 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. Each shelf moves its own.
+ const moveFolders = async (ids: string[], parentId: string | null) => {
+ for (const r of residencies) {
+ if (!live(r)) continue;
+ const own = data[r].folders;
+ if (parentId && !own.some((f) => f.id === parentId)) continue;
+ const moving = own.filter(
+ (f) =>
+ ids.includes(f.id) && parentOf(f) !== parentId && !folderWithin(own, parentId, f.id)
+ );
+ if (moving.length === 0) continue;
+ const idset = new Set(moving.map((f) => f.id));
+ patch(r, (s) => ({
+ ...s,
+ folders: s.folders.map((f) => (idset.has(f.id) ? { ...f, parentId } : f)),
+ }));
+ await Promise.all(
+ moving.map((f) =>
+ backendFor(r).fetch(`/api/cut/projects/folders/${f.id}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ parentId }),
+ })
+ )
+ ).catch(() => void refresh(r));
+ }
+ };
+
// Move a collection of projects into a folder (or out to the root, folderId
// null). Optimistic; reconciles from disk on any failure. A dragged
// selection can span sections, so a backend only ever moves its own.
@@ -544,13 +592,8 @@ export function ProjectsHome() {
}
};
- // Which section owns the open folder — in dual mode only that section shows.
- const folderOwner: Residency | null = openFolder
- ? (residencies.find((r) => data[r].folders.some((f) => f.id === openFolder)) ?? null)
- : null;
- const openFolderName = folderOwner
- ? data[folderOwner].folders.find((f) => f.id === openFolder)?.name
- : undefined;
+ // The way down to the open folder, for the crumb.
+ const trail = folderOwner ? folderTrail(data[folderOwner].folders, openFolder) : [];
// A folder pins where a new project lands, but only a shelf that answers can
// take one: inside a folder on an unreachable shelf, New project goes where
// the picker points instead.
@@ -565,9 +608,15 @@ export function ProjectsHome() {
// One flat surface: every residency's folders on one shelf and projects in
// one grid, newest edits first — the per-card badge says where each lives.
+ // Inside a folder, the shelf holds the folders filed there, on its shelf.
const residencyOfFolder = (id: string): Residency =>
residencies.find((r) => data[r].folders.some((f) => f.id === id)) ?? homeMode;
- const mergedFolders = residencies.flatMap((r) => data[r].folders);
+ const shownFolders =
+ openFolder === null
+ ? residencies.flatMap((r) => childrenOf(data[r].folders, null))
+ : folderOwner
+ ? childrenOf(data[folderOwner].folders, openFolder)
+ : [];
const mergedShown = residencies
.flatMap((r) =>
(data[r].projects ?? [])
@@ -598,23 +647,33 @@ export function ProjectsHome() {
// PROJECT_MIME and are handled by the folder tiles and breadcrumb instead.
const isFileDrag = (e: React.DragEvent) => Array.from(e.dataTransfer.types).includes("Files");
+ // Where a new folder goes: the open folder's shelf, or the picker's at the
+ // top level — the same shelf a new project would land on.
+ const folderTarget = pinnedTarget ?? target;
const renderShelf = () => (
<FolderShelf
- folders={mergedFolders}
+ folders={shownFolders}
mime={PROJECT_MIME}
+ folderMime={PROJECT_FOLDER_MIME}
creating={folderCreating !== null}
- onCreatingChange={(c) => setFolderCreating(c ? (folderCreating ?? target) : null)}
+ onCreatingChange={(c) => setFolderCreating(c ? (folderCreating ?? folderTarget) : null)}
statOf={(id) => {
- const items = (data[residencyOfFolder(id)].projects ?? []).filter(
- (p) => (p.folderId ?? null) === id
- );
- return { count: items.length, size: items.reduce((n, p) => n + (p.sizeBytes ?? 0), 0) };
+ const r = residencyOfFolder(id);
+ const items = (data[r].projects ?? []).filter((p) => (p.folderId ?? null) === id);
+ return {
+ count: items.length + childrenOf(data[r].folders, id).length,
+ size: items.reduce((n, p) => n + (p.sizeBytes ?? 0), 0),
+ };
}}
onOpen={gotoFolder}
- onCreate={(n) => void createFolder(folderCreating ?? target, n)}
+ 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)}
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
// can receive the files themselves; drops on another residency's folder
// land at the root, like drops on the page surface.
@@ -854,17 +913,23 @@ export function ProjectsHome() {
) : (
<FolderCrumb
root="Projects"
- trail={[{ id: openFolder, name: openFolderName ?? "Folder" }]}
+ trail={trail}
mime={PROJECT_MIME}
- onGo={() => gotoFolder(null)}
- onDrop={(ids) => void moveProjects(folderOwner ?? r0, ids, null)}
+ folderMime={PROJECT_FOLDER_MIME}
+ onGo={gotoFolder}
+ onDrop={(ids, id) =>
+ void moveProjects(id ? residencyOfFolder(id) : (folderOwner ?? r0), ids, id)
+ }
+ onDropFolders={(ids, id) => void moveFolders(ids, id)}
/>
)}
<div className="flex items-center gap-2">
{/* A folder lands where a project would: New project owns that
- choice for the whole page, so this asks nothing of its own. */}
- {openFolder === null && (
- <Button variant="outline" onClick={() => setFolderCreating(target)}>
+ choice for the whole page, so this asks nothing of its own.
+ Inside a folder it lands there, so the folder's shelf has to
+ be answering. */}
+ {(openFolder === null || pinnedTarget) && (
+ <Button variant="outline" onClick={() => setFolderCreating(folderTarget)}>
<FolderPlus data-icon="inline-start" /> New folder
</Button>
)}
@@ -940,9 +1005,7 @@ export function ProjectsHome() {
</p>
)
)}
- {openFolder === null &&
- (mergedFolders.length > 0 || folderCreating !== null) &&
- renderShelf()}
+ {(shownFolders.length > 0 || folderCreating !== null) && renderShelf()}
{view === "gallery" ? renderGallery(mergedShown) : renderList(mergedShown)}
</>
)}
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 6dbc3966..bb0aeade 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -69,7 +69,7 @@ import {
importTemplateToProject,
libraryMediaUrl,
moveLibraryItem,
- renameLibraryFolder,
+ updateLibraryFolder,
renameTemplate,
saveAssetToLibrary,
saveTemplate,
@@ -121,6 +121,7 @@ import { useRevealEffect, useRevealFlash } from "@/cut/lib/refReveal";
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 { TemplateCard } from "./TemplateCard";
import { GenerateVideoPanel } from "./GeneratePanel";
@@ -138,6 +139,8 @@ import { SubTabs } from "./SubTabs";
// Drag a library clip onto a folder tile to file it (side panel, single card).
const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
+// A dragged folder row, filed into another folder or back out to a crumb.
+const LIBRARY_FOLDER_MOVE_MIME = "application/x-cut-library-folder";
// A Project Files selection dragged onto a folder tile or the crumb: the
// payload is the picked asset ids, so one drop files the whole selection.
const MEDIA_MOVE_MIME = "application/x-cut-media-move";
@@ -1684,24 +1687,49 @@ function LibraryPanel({ projectId }: { projectId: string }) {
const bothShelves = availableResidencies().length > 1;
const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);
- // The Camera Roll tile leads the shelf while the phone has synced anything.
+ // The shelf at this level: the folders filed here. At the top the Camera
+ // Roll tile leads it while the phone has synced anything; the roll itself
+ // holds no folders.
+ const cameraRoll: LibraryFolder & { locked?: boolean } = {
+ id: CAMERA_ROLL_FOLDER,
+ name: "Camera Roll",
+ createdAt: 0,
+ residency: "cloud",
+ locked: true,
+ };
const shelfFolders: (LibraryFolder & { locked?: boolean })[] =
- cameraCount > 0
- ? [
- {
- id: CAMERA_ROLL_FOLDER,
- name: "Camera Roll",
- createdAt: 0,
- residency: "cloud",
- locked: true,
- },
- ...folders,
- ]
- : folders;
- const openFolderName =
- openFolder === CAMERA_ROLL_FOLDER
- ? "Camera Roll"
- : folders.find((f) => f.id === openFolder)?.name;
+ openFolder === null
+ ? [...(cameraCount > 0 ? [cameraRoll] : []), ...childrenOf(folders, null)]
+ : openFolder === CAMERA_ROLL_FOLDER
+ ? []
+ : childrenOf(folders, openFolder);
+ const trail =
+ openFolder === CAMERA_ROLL_FOLDER ? [cameraRoll] : folderTrail(folders, openFolder);
+
+ // 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.
+ const moveFolders = async (ids: string[], parentId: string | null) => {
+ if (parentId === CAMERA_ROLL_FOLDER) return;
+ const target = parentId ? folders.find((f) => f.id === parentId)?.residency : null;
+ if (parentId && !target) return;
+ const moving = folders.filter(
+ (f) =>
+ ids.includes(f.id) &&
+ (!target || f.residency === target) &&
+ parentOf(f) !== parentId &&
+ !folderWithin(folders, parentId, f.id)
+ );
+ if (moving.length === 0) return;
+ const idset = new Set(moving.map((f) => f.id));
+ patch((d) => ({
+ ...d,
+ folders: d.folders.map((f) => (idset.has(f.id) ? { ...f, parentId } : f)),
+ }));
+ await Promise.all(
+ moving.map((f) => updateLibraryFolder(f.residency, f.id, { parentId }))
+ ).catch(() => void reload());
+ };
return (
<div
@@ -1718,23 +1746,27 @@ function LibraryPanel({ projectId }: { projectId: string }) {
<FolderCrumb
className="text-sm"
root="Library"
- trail={[{ id: openFolder, name: openFolderName ?? "Folder" }]}
+ trail={trail}
mime={LIBRARY_MOVE_MIME}
- onGo={() => setOpenFolder(null)}
- onDrop={(ids) => ids.forEach((id) => void move(id, null))}
+ folderMime={LIBRARY_FOLDER_MOVE_MIME}
+ onGo={setOpenFolder}
+ onDrop={(ids, id) => ids.forEach((fid) => void move(fid, id))}
+ onDropFolders={(ids, id) => void moveFolders(ids, id)}
/>
</div>
)}
- {openFolder === null && shelfFolders.length > 0 ? (
+ {shelfFolders.length > 0 ? (
<div className="shrink-0 px-3.5">
<FolderShelf
rows
folders={shelfFolders}
mime={LIBRARY_MOVE_MIME}
+ folderMime={LIBRARY_FOLDER_MOVE_MIME}
statOf={(id) => ({
count:
all.filter((a) => folderOf(a) === id).length +
- templates.filter((t) => (t.folderId ?? null) === id).length,
+ templates.filter((t) => (t.folderId ?? null) === id).length +
+ childrenOf(folders, id).length,
})}
badgeOf={(id) => {
const r = folders.find((f) => f.id === id)?.residency;
@@ -1748,24 +1780,29 @@ function LibraryPanel({ projectId }: { projectId: string }) {
...d,
folders: d.folders.map((f) => (f.id === id ? { ...f, name } : f)),
}));
- await renameLibraryFolder(r, id, name).catch(() => void reload());
+ await updateLibraryFolder(r, id, { name }).catch(() => void reload());
}}
onDelete={async (id) => {
- const r = folders.find((f) => f.id === id)?.residency;
- if (!r) return;
+ // 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),
+ 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: null } : a
+ a.folderId === id ? { ...a, folderId: up } : a
),
templates: d.templates.map((t) =>
- t.folderId === id ? { ...t, folderId: null } : t
+ t.folderId === id ? { ...t, folderId: up } : t
),
}));
- if (openFolder === id) setOpenFolder(null);
- await deleteLibraryFolder(r, id).catch(() => void reload());
+ await deleteLibraryFolder(gone.residency, id).catch(() => void reload());
}}
onDropIds={(ids, fid) => ids.forEach((id) => void move(id, fid))}
+ onDropFolders={(ids, fid) => void moveFolders(ids, fid)}
onRefDrop={(ref, fid) => {
// Project media dropped on a folder tile (a Media card or a
// timeline clip): save it to the library, filed in that folder.
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 3190fff4..37c36b73 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -63,6 +63,7 @@ import { refFromAsset, refFromStockVideo, type AssetRef } from "./assetRef";
import { chatOwner, tagChatAsset } from "./chatAssets";
import { applyOwnership, useGenerate, type VideoAttempt, type VideoGenOptions } from "./generate";
import { useGenScene } from "./genScene";
+import { folderWithin } from "./folderTree";
import { anchorRefused } from "./genvideo/shotAttempts";
import {
addProjectTemplateToTimeline,
@@ -74,7 +75,7 @@ import {
fetchLibrary,
importLibraryAsset,
moveLibraryItem,
- renameLibraryFolder,
+ updateLibraryFolder,
saveAssetToLibrary,
} from "./library";
import { fetchNotes } from "./notes";
@@ -2844,7 +2845,11 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
library_list: async () => {
const lib = await fetchLibrary();
return {
- folders: lib.folders.map((f) => ({ id: f.id, name: f.name })),
+ folders: lib.folders.map((f) => ({
+ id: f.id,
+ name: f.name,
+ ...(f.parentId ? { parentId: f.parentId } : {}),
+ })),
assets: lib.assets.map((a) => ({
id: a.id,
name: a.name,
@@ -2875,7 +2880,11 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const folderName = new Map(folders.map((f) => [f.id, f.name]));
const labelName = new Map(labels.map((l) => [l.id, l.name]));
return {
- folders: folders.map((f) => ({ id: f.id, name: f.name })),
+ folders: folders.map((f) => ({
+ id: f.id,
+ name: f.name,
+ ...(f.parentId ? { parentId: f.parentId } : {}),
+ })),
labels: labels.map((l) => l.name),
notes: notes.map((n) => {
const worn = n.labelIds
@@ -2983,8 +2992,13 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
case "create_folder": {
const name = String(input.name ?? "").trim();
if (!name) throw new ToolError("A folder name is required.");
- const f = await createLibraryFolder(name);
- return { folderId: f.id, name: f.name };
+ // Inside a parent, the folder lands on the parent's shelf.
+ const parentId =
+ typeof input.parent_id === "string" && input.parent_id ? input.parent_id : null;
+ const r = parentId ? folderShelf(parentId) : undefined;
+ if (parentId && !r) throw new ToolError(`No library folder with id ${parentId}.`);
+ const f = await createLibraryFolder(name, r, parentId);
+ return { folderId: f.id, name: f.name, ...(f.parentId ? { parentId: f.parentId } : {}) };
}
case "rename_folder": {
const name = String(input.name ?? "").trim();
@@ -2992,15 +3006,30 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const id = String(input.folder_id ?? "");
const r = folderShelf(id);
if (!r) throw new ToolError(`No library folder with id ${id}.`);
- await renameLibraryFolder(r, id, name);
+ await updateLibraryFolder(r, id, { name });
return { renamed: true, name };
}
+ case "move_folder": {
+ const id = String(input.folder_id ?? "");
+ const r = folderShelf(id);
+ if (!r) throw new ToolError(`No library folder with id ${id}.`);
+ const parentId =
+ typeof input.parent_id === "string" && input.parent_id ? input.parent_id : null;
+ if (parentId && folderShelf(parentId) !== r) {
+ throw new ToolError("That folder is on a different library shelf.");
+ }
+ if (parentId && folderWithin(lib.folders, parentId, id)) {
+ throw new ToolError("A folder can't move into itself or a folder inside it.");
+ }
+ const moved = await updateLibraryFolder(r, id, { parentId });
+ return { moved: true, parentId: moved.parentId ?? null };
+ }
case "delete_folder": {
const id = String(input.folder_id ?? "");
const r = folderShelf(id);
if (!r) throw new ToolError(`No library folder with id ${id}.`);
await deleteLibraryFolder(r, id);
- return { deleted: true, note: "Its assets moved to the Library root." };
+ return { deleted: true, note: "What it held moved up one level." };
}
case "move_asset": {
const folderId =
diff --git a/site/src/cut/lib/backend/browser/library.ts b/site/src/cut/lib/backend/browser/library.ts
index c3d92b43..d9e1251f 100644
--- a/site/src/cut/lib/backend/browser/library.ts
+++ b/site/src/cut/lib/backend/browser/library.ts
@@ -11,6 +11,7 @@
// video off a link, so that import runs on the cloud worker and the bytes are
// adopted afterwards (`lib/library.ts`); those paths fall through to the
// hosted twin.
+import { resolveParent, settleParents } from "../../folderTree";
import type {
AssetType,
LibraryTemplate,
@@ -54,7 +55,14 @@ type StoredAsset = {
posterFile?: string;
};
-type StoredFolder = { id: string; name: string; createdAt: number };
+type StoredFolder = {
+ id: string;
+ name: string;
+ /** The folder this one is filed in; null (or absent, from before nesting)
+ * is the top level. */
+ parentId?: string | null;
+ createdAt: number;
+};
type LibraryIndex = {
version: 1;
@@ -142,7 +150,7 @@ async function list(): Promise<Response> {
}
return json({
assets: [...idx.assets].sort((a, b) => b.addedAt - a.addedAt),
- folders: [...idx.folders].sort((a, b) => a.createdAt - b.createdAt),
+ folders: settleParents(idx.folders).sort((a, b) => a.createdAt - b.createdAt),
templates: [...idx.templates].sort((a, b) => b.addedAt - a.addedAt),
});
}
@@ -280,48 +288,68 @@ async function move(req: Request): Promise<Response> {
async function createFolder(req: Request): Promise<Response> {
try {
- const { name } = (await req.json()) as { name?: string };
+ const { name, parentId } = (await req.json()) as {
+ name?: string;
+ parentId?: string | null;
+ };
const trimmed = (name ?? "").trim();
if (!trimmed) return err("Folder name required.", 500);
- const folder: StoredFolder = {
- id: crypto.randomUUID().slice(0, 8),
- name: trimmed.slice(0, 80),
- createdAt: Date.now(),
- };
- await mutateIndex((idx) => {
- idx.folders.push(folder);
- });
- return json(folder);
+ const id = crypto.randomUUID().slice(0, 8);
+ return json(
+ await mutateIndex((idx) => {
+ const folder: StoredFolder = {
+ id,
+ name: trimmed.slice(0, 80),
+ parentId: resolveParent(idx.folders, id, parentId),
+ createdAt: Date.now(),
+ };
+ idx.folders.push(folder);
+ return folder;
+ }),
+ );
} catch (e) {
return caught(e, "Could not create folder.");
}
}
-async function renameFolder(req: Request, id: string): Promise<Response> {
+/** Rename a folder, file it under another (null for the top level), or
+ * both; a key left out keeps what the folder has. */
+async function updateFolder(req: Request, id: string): Promise<Response> {
try {
- const { name } = (await req.json()) as { name?: string };
- const trimmed = (name ?? "").trim();
- if (!trimmed) return err("Folder name required.", 500);
+ const { name, parentId } = (await req.json()) as {
+ name?: string;
+ parentId?: string | null;
+ };
+ const trimmed = name?.trim();
+ if (name !== undefined && !trimmed) return err("Folder name required.", 500);
return json(
await mutateIndex((idx) => {
const folder = idx.folders.find((f) => f.id === id);
if (!folder) throw new Error("Folder not found.");
- folder.name = trimmed.slice(0, 80);
+ if (trimmed) folder.name = trimmed.slice(0, 80);
+ if (parentId !== undefined) {
+ folder.parentId = resolveParent(idx.folders, id, parentId);
+ }
return folder;
}),
);
} catch (e) {
- return caught(e, "Could not rename folder.");
+ return caught(e, "Could not update folder.");
}
}
+/** Delete a folder. What it held — its items and the folders inside it —
+ * comes up one level, filed where the folder was. */
async function deleteFolder(id: string): Promise<Response> {
try {
await mutateIndex((idx) => {
+ const gone = idx.folders.find((f) => f.id === id);
+ if (!gone) return;
+ const up = gone.parentId ?? null;
idx.folders = idx.folders.filter((f) => f.id !== id);
- // Items in the folder fall back to ungrouped rather than vanishing.
- for (const a of idx.assets) if (a.folderId === id) a.folderId = null;
- for (const t of idx.templates) if (t.folderId === id) t.folderId = null;
+ for (const f of idx.folders) if ((f.parentId ?? null) === id) f.parentId = up;
+ for (const a of idx.assets) if (a.folderId === id) a.folderId = up;
+ for (const t of idx.templates) if (t.folderId === id) t.folderId = up;
});
return json({ ok: true });
} catch (e) {
@@ -624,7 +652,7 @@ export async function dispatchLibraryRoute(
if (rest[0] === "folders") {
if (rest.length === 1 && method === "POST") return createFolder(req());
if (rest.length === 2 && method === "PUT")
- return renameFolder(req(), rest[1]);
+ return updateFolder(req(), rest[1]);
if (rest.length === 2 && method === "DELETE") return deleteFolder(rest[1]);
return err("Not found.", 404);
}
diff --git a/site/src/cut/lib/backend/browser/router.ts b/site/src/cut/lib/backend/browser/router.ts
index be61da42..f69e58cc 100644
--- a/site/src/cut/lib/backend/browser/router.ts
+++ b/site/src/cut/lib/backend/browser/router.ts
@@ -6,6 +6,7 @@
// Owned here: projects CRUD + folders, media bytes, image import, presign-get
// (answered with blob URLs), exports, the export-jobs feed, and the library
// shelf (./library.ts). Everything else is the driver's cloud proxy.
+import { resolveParent, settleParents } from "../../folderTree";
import { normalizeAspect, type ProjectDoc, type ProjectFolder } from "../../types";
import {
getBrowserExportJob,
@@ -156,50 +157,72 @@ async function moveProject(req: Request, id: string): Promise<Response> {
async function createFolder(req: Request): Promise<Response> {
try {
- const { name } = (await req.json()) as { name?: string };
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
const trimmed = (name ?? "").trim();
if (!trimmed) return err("Folder name required.", 500);
- const folder: ProjectFolder = {
- id: crypto.randomUUID().slice(0, 8),
- name: trimmed.slice(0, 80),
- createdAt: Date.now(),
- };
- await store.updateIndex((idx) => ({ ...idx, folders: [...idx.folders, folder] }));
+ const id = crypto.randomUUID().slice(0, 8);
+ let folder: ProjectFolder | null = null;
+ await store.updateIndex((idx) => {
+ folder = {
+ id,
+ name: trimmed.slice(0, 80),
+ parentId: resolveParent(idx.folders, id, parentId),
+ createdAt: Date.now(),
+ };
+ return { ...idx, folders: [...idx.folders, folder] };
+ });
return json(folder);
} catch (e) {
return caught(e, "Could not create folder.");
}
}
-async function renameFolder(req: Request, fid: string): Promise<Response> {
+/** Rename a folder, file it under another (null for the top level), or
+ * both; a key left out keeps what the folder has. */
+async function updateFolder(req: Request, fid: string): Promise<Response> {
try {
- const { name } = (await req.json()) as { name?: string };
- const trimmed = (name ?? "").trim();
- if (!trimmed) return err("Folder name required.", 500);
- let renamed: ProjectFolder | null = null;
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
+ const trimmed = name?.trim();
+ if (name !== undefined && !trimmed) return err("Folder name required.", 500);
+ let updated: ProjectFolder | null = null;
await store.updateIndex((idx) => ({
...idx,
folders: idx.folders.map((f) =>
- f.id === fid ? (renamed = { ...f, name: trimmed.slice(0, 80) }) : f
+ f.id === fid
+ ? (updated = {
+ ...f,
+ ...(trimmed ? { name: trimmed.slice(0, 80) } : {}),
+ ...(parentId !== undefined
+ ? { parentId: resolveParent(idx.folders, fid, parentId) }
+ : {}),
+ })
+ : f
),
}));
- return renamed ? json(renamed) : err("Folder not found.", 500);
+ return updated ? json(updated) : err("Folder not found.", 500);
} catch (e) {
- return caught(e, "Could not rename folder.");
+ return caught(e, "Could not update folder.");
}
}
+/** Delete a folder. What it held — its projects and the folders inside it —
+ * comes up one level, filed where the folder was. */
async function deleteFolder(fid: string): Promise<Response> {
try {
- await store.updateIndex((idx) => ({
- ...idx,
- folders: idx.folders.filter((f) => f.id !== fid),
- }));
- // Projects in the folder fall back to ungrouped rather than disappearing.
+ let up: string | null = null;
+ await store.updateIndex((idx) => {
+ up = idx.folders.find((f) => f.id === fid)?.parentId ?? null;
+ return {
+ ...idx,
+ folders: idx.folders
+ .filter((f) => f.id !== fid)
+ .map((f) => ((f.parentId ?? null) === fid ? { ...f, parentId: up } : f)),
+ };
+ });
for (const id of await store.listProjectIds()) {
const doc = await store.readDoc(id);
if (doc?.folderId === fid) {
- doc.folderId = null;
+ doc.folderId = up;
await store.writeDoc(id, doc);
}
}
@@ -343,13 +366,13 @@ export async function dispatchBrowserRoute(
if (rest.length === 2) {
if (method === "GET") {
const { folders } = await store.readIndex();
- return json([...folders].sort((a, b) => a.createdAt - b.createdAt));
+ return json(settleParents(folders).sort((a, b) => a.createdAt - b.createdAt));
}
if (method === "POST") return createFolder(req());
return err("Method not allowed.", 405);
}
if (rest.length === 3) {
- if (method === "PUT") return renameFolder(req(), rest[2]);
+ if (method === "PUT") return updateFolder(req(), rest[2]);
if (method === "DELETE") return deleteFolder(rest[2]);
return err("Method not allowed.", 405);
}
diff --git a/site/src/cut/lib/folderTree.ts b/site/src/cut/lib/folderTree.ts
new file mode 100644
index 00000000..4376a0d6
--- /dev/null
+++ b/site/src/cut/lib/folderTree.ts
@@ -0,0 +1,80 @@
+/**
+ * Folders that file into folders. Every folder table — project folders,
+ * library folders, note folders, on every shelf — carries `parentId`, null
+ * for the top level, and these are the rules they all share: a folder never
+ * files under itself, what a deleted folder held comes up one level, and a
+ * parent nothing answers for reads as the top level.
+ */
+
+export interface TreeFolder {
+ id: string;
+ parentId?: string | null;
+}
+
+export const parentOf = (f: TreeFolder): string | null => f.parentId ?? null;
+
+/** Whether `folderId` is `ancestorId` or filed somewhere under it. */
+export function folderWithin(
+ folders: readonly TreeFolder[],
+ folderId: string | null,
+ ancestorId: string,
+): boolean {
+ const parents = new Map(folders.map((f) => [f.id, parentOf(f)]));
+ let cur = folderId;
+ for (let steps = 0; cur && steps <= folders.length; steps++) {
+ if (cur === ancestorId) return true;
+ cur = parents.get(cur) ?? null;
+ }
+ return false;
+}
+
+/** The folders from the top level down to `folderId`, the open one last.
+ * Empty when nothing answers for the id. */
+export function folderTrail<F extends TreeFolder>(
+ folders: readonly F[],
+ folderId: string | null,
+): F[] {
+ const byId = new Map(folders.map((f) => [f.id, f]));
+ const trail: F[] = [];
+ let cur = folderId ? byId.get(folderId) : undefined;
+ while (cur && trail.length <= folders.length) {
+ trail.unshift(cur);
+ const up = parentOf(cur);
+ cur = up ? byId.get(up) : undefined;
+ }
+ return trail;
+}
+
+/** The parent folder `id` may be filed under: one of `folders` that is
+ * neither `id` itself nor anything filed under it, or the top level. An id
+ * naming nothing files the folder at the top level rather than failing the
+ * write — the parent may have been deleted elsewhere while this side was
+ * offline — and so does one that would close a loop, which two devices
+ * moving folders into each other offline can ask for. */
+export function resolveParent(
+ folders: readonly TreeFolder[],
+ id: string,
+ parentId: unknown,
+): string | null {
+ if (typeof parentId !== "string" || !parentId || parentId === id) return null;
+ if (!folders.some((f) => f.id === parentId)) return null;
+ if (folderWithin(folders, parentId, id)) return null;
+ return parentId;
+}
+
+/** The folders filed right under `parentId` (null for the top level). */
+export function childrenOf<F extends TreeFolder>(
+ folders: readonly F[],
+ parentId: string | null,
+): F[] {
+ return folders.filter((f) => parentOf(f) === parentId);
+}
+
+/** A listing with every parent the listing does not name read as the top
+ * level, so nothing hangs off a folder nobody can open. */
+export function settleParents<F extends TreeFolder>(folders: readonly F[]): F[] {
+ const known = new Set(folders.map((f) => f.id));
+ return folders.map((f) =>
+ f.parentId && !known.has(f.parentId) ? { ...f, parentId: null } : f,
+ );
+}
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 08884c7e..143b005d 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -77,6 +77,9 @@ export interface LibraryAsset {
export interface LibraryFolder {
id: string;
name: string;
+ /** The folder this one is filed in; null is the top level. Folders nest
+ * only within their own shelf. */
+ parentId?: string | null;
createdAt: number;
residency: Residency;
}
@@ -415,36 +418,44 @@ async function importUrlThroughCloud(
return landed;
}
+/** Make a folder on a shelf, filed under `parentId` there (null for the
+ * top level). */
export async function createLibraryFolder(
name: string,
residency: Residency = activeResidency(),
+ parentId: string | null = null,
): Promise<LibraryFolder> {
const res = await backendFor(residency).fetch("/api/cut/library/folders", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name }),
+ body: JSON.stringify({ name, parentId }),
});
const body = await apiJson<LibraryFolder>(res);
if (!res.ok) throw new Error(body.error ?? "Could not create folder.");
return { ...body, residency };
}
-export async function renameLibraryFolder(
+/** Rename a folder, move it under another (null for the top level), or
+ * both. A key left out keeps what the folder has. The shelf answers with the
+ * folder as stored: a parent it could not honor reads back as the top level. */
+export async function updateLibraryFolder(
residency: Residency,
id: string,
- name: string,
-): Promise<void> {
+ patch: { name?: string; parentId?: string | null },
+): Promise<LibraryFolder> {
const res = await backendFor(residency).fetch(
`/api/cut/library/folders/${id}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name }),
+ body: JSON.stringify(patch),
},
);
- if (!res.ok) throw new Error("Could not rename folder.");
+ if (!res.ok) throw new Error("Could not update folder.");
+ return { ...((await res.json()) as Omit<LibraryFolder, "residency">), residency };
}
+/** Delete a folder. What it held comes up one level. */
export async function deleteLibraryFolder(
residency: Residency,
id: string,
diff --git a/site/src/cut/lib/notes.ts b/site/src/cut/lib/notes.ts
index b88afaa8..adc79963 100644
--- a/site/src/cut/lib/notes.ts
+++ b/site/src/cut/lib/notes.ts
@@ -12,8 +12,11 @@
* offline, and the one PUT creates, renames and moves.
*/
+import { settleParents } from "./folderTree";
import { backendFor } from "./residency";
+export { folderTrail, folderWithin } from "./folderTree";
+
export interface CutNote {
id: string;
title: string;
@@ -80,48 +83,13 @@ export async function fetchNotes(): Promise<NotesData> {
const res = await notesFetch("/api/cut/notes");
if (!res.ok) throw new Error("Could not load notes.");
const body = (await res.json()) as Partial<NotesData>;
- const folders = body.folders ?? [];
- const known = new Set(folders.map((f) => f.id));
return {
notes: (body.notes ?? []).filter((n) => n.deletedAt === null),
- folders: folders.map((f) => ({
- ...f,
- parentId: f.parentId && known.has(f.parentId) ? f.parentId : null,
- })),
+ folders: settleParents(body.folders ?? []),
labels: body.labels ?? [],
};
}
-/** Whether `folderId` is `ancestorId` or filed somewhere under it. */
-export function folderWithin(
- folders: readonly CutNoteFolder[],
- folderId: string | null,
- ancestorId: string,
-): boolean {
- const parentOf = new Map(folders.map((f) => [f.id, f.parentId]));
- let cur = folderId;
- for (let steps = 0; cur && steps <= folders.length; steps++) {
- if (cur === ancestorId) return true;
- cur = parentOf.get(cur) ?? null;
- }
- return false;
-}
-
-/** The folders from the top level down to `folderId`, the open one last. */
-export function folderTrail(
- folders: readonly CutNoteFolder[],
- folderId: string | null,
-): CutNoteFolder[] {
- const byId = new Map(folders.map((f) => [f.id, f]));
- const trail: CutNoteFolder[] = [];
- let cur = folderId ? byId.get(folderId) : undefined;
- while (cur && trail.length <= folders.length) {
- trail.unshift(cur);
- cur = cur.parentId ? byId.get(cur.parentId) : undefined;
- }
- return trail;
-}
-
/** Write one note. The server answers with the winning version — this write,
* or a newer one from the phone. */
export async function saveNote(note: {
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 72881247..7b3748b4 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -1476,10 +1476,13 @@ export interface RenderRecord {
assetId?: string;
}
-/** A named group of projects on the home screen. */
+/** A named group of projects on the home screen. Folders file into folders
+ * through `parentId`; null (or absent, on an index from before nesting) is
+ * the top level. */
export interface ProjectFolder {
id: string;
name: string;
+ parentId?: string | null;
createdAt: number;
}
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index dd67e3d0..5a4a8d6b 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -379,7 +379,7 @@ The Library is shared across every project: folders, reusable assets, and templa
- library_list browses it; library_add copies an asset into the project (the import step "library"-scope attachments need); template_add re-materializes a template; save_template saves timeline items as one.
- Assets from the user's iOS app carry an origin: "camera" is a clip they recorded on their phone (their Camera Roll — "the video I shot on my phone" lives here), "inspiration" a reference saved into the Library's Inspiration folder. library_add imports either like any other asset. A camera clip's name is the clock it was shot on; its title, when it has one, was read off the clip itself and is what the user sees on the card — match a request like "the one about the launch" against the title.
- notes_list reads the user's synced notes (written on their phone or the Notes tab) with the folders they are filed in and the labels they carry — the place to look when they point at "my note", or name a folder or label, for a script, caption, or voiceover text.
-- library_organize handles folders (create/rename/delete), filing (move_asset), and deletes (permanent — explicit ask only).
+- library_organize handles folders (create/rename/move/delete — folders nest, and a folder's parentId in library_list says where it sits), filing (move_asset), and deletes (permanent — explicit ask only).
- import_url reads any URL (TikTok, YouTube, Instagram, an X post or Article, a web page, direct links): a page comes back as its article text and its pictures, a post as its video or photos, and a source that is only words as sourceText alone. When the user asks for the sound alone — a song, a soundtrack — pass audio_only and the audio track lands as an audio asset. Media lands as a card in the chat with that text quoted beside it; the user drags a card to the timeline, Media, or the Library. Place it with add_clip only when they asked for it in the cut.
Attachments: media files dropped on the chat import into project media by themselves; library attachments wait for library_add.`,
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index 6243a772..65cda454 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -11,6 +11,7 @@ import type {
TemplateLayer,
TemplateMedia,
} from "../library";
+import { resolveParent } from "@/cut/lib/folderTree";
import type { StoredAsset } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
@@ -282,6 +283,18 @@ async function deleteLibraryObject(userId: string, fileName: string) {
await del([row.r2Key]);
}
+const libraryFolderView = (row: {
+ id: string;
+ name: string;
+ parentId: string | null;
+ createdAt: Date;
+}): LibraryFolder => ({
+ id: row.id,
+ name: row.name,
+ parentId: row.parentId,
+ createdAt: row.createdAt.getTime(),
+});
+
export const libraryCloud = {
/** The shelf. `?deleted=1` adds the tombstoned ids — the phone asks for
* them to mirror a delete made here onto its Camera Roll, and it is the
@@ -321,11 +334,7 @@ export const libraryCloud = {
return obj ? assetView(r, obj) : null;
})
.filter((a): a is LibraryAsset => a !== null);
- const folders: LibraryFolder[] = folderRows.map((f) => ({
- id: f.id,
- name: f.name,
- createdAt: f.createdAt.getTime(),
- }));
+ const folders: LibraryFolder[] = folderRows.map(libraryFolderView);
const templates = templateRows.map(templateView);
// Assets someone deleted, for a client that holds its own copy of them:
// the iOS app deletes the matching clip on the phone.
@@ -679,55 +688,79 @@ export const libraryCloud = {
async createFolder(userId: string, req: Request) {
try {
- const { name } = (await req.json()) as { name?: string };
+ const { name, parentId } = (await req.json()) as {
+ name?: string;
+ parentId?: string | null;
+ };
const trimmed = (name ?? "").trim();
if (!trimmed) throw new Error("Folder name required.");
- const row = await prisma.cutFolder.create({
- data: { userId, name: trimmed.slice(0, 80), scope: "library" },
+ const folders = await prisma.cutFolder.findMany({
+ where: { userId, scope: "library" },
+ select: { id: true, parentId: true },
});
- return Response.json({
- id: row.id,
- name: row.name,
- createdAt: row.createdAt.getTime(),
+ const row = await prisma.cutFolder.create({
+ data: {
+ userId,
+ name: trimmed.slice(0, 80),
+ scope: "library",
+ parentId: resolveParent(folders, "", parentId),
+ },
});
+ return Response.json(libraryFolderView(row));
} catch (e) {
return caught(e, "Could not create folder.");
}
},
- async renameFolder(userId: string, id: string, req: Request) {
+ /** Rename a folder, file it under another (null for the top level), or
+ * both; a key left out keeps what the folder has. */
+ async updateFolder(userId: string, id: string, req: Request) {
try {
- const { name } = (await req.json()) as { name?: string };
- const trimmed = (name ?? "").trim();
- if (!trimmed) throw new Error("Folder name required.");
- const row = await prisma.cutFolder.findFirst({
- where: { id, userId, scope: "library" },
+ const { name, parentId } = (await req.json()) as {
+ name?: string;
+ parentId?: string | null;
+ };
+ const trimmed = name?.trim();
+ if (name !== undefined && !trimmed) throw new Error("Folder name required.");
+ const folders = await prisma.cutFolder.findMany({
+ where: { userId, scope: "library" },
+ select: { id: true, parentId: true },
});
- if (!row) throw new Error("Folder not found.");
+ if (!folders.some((f) => f.id === id)) throw new Error("Folder not found.");
const updated = await prisma.cutFolder.update({
where: { id },
- data: { name: trimmed.slice(0, 80) },
- });
- return Response.json({
- id: updated.id,
- name: updated.name,
- createdAt: updated.createdAt.getTime(),
+ data: {
+ ...(trimmed ? { name: trimmed.slice(0, 80) } : {}),
+ ...(parentId !== undefined
+ ? { parentId: resolveParent(folders, id, parentId) }
+ : {}),
+ },
});
+ return Response.json(libraryFolderView(updated));
} catch (e) {
- return caught(e, "Could not rename folder.");
+ return caught(e, "Could not update folder.");
}
},
+ /** Delete a folder. What it held — its items and the folders inside it —
+ * comes up one level, filed where the folder was. */
async deleteFolder(userId: string, id: string) {
try {
await prisma.$transaction(async (tx) => {
- await tx.cutFolder.deleteMany({
+ const gone = await tx.cutFolder.findFirst({
where: { id, userId, scope: "library" },
+ select: { parentId: true },
+ });
+ if (!gone) return;
+ const up = gone.parentId;
+ await tx.cutFolder.delete({ where: { id } });
+ await tx.cutFolder.updateMany({
+ where: { userId, scope: "library", parentId: id },
+ data: { parentId: up },
});
- // Items in the folder fall back to ungrouped rather than vanishing.
await tx.cutLibraryAsset.updateMany({
where: { userId, folderId: id },
- data: { folderId: null },
+ data: { folderId: up },
});
const templates = await tx.cutTemplate.findMany({ where: { userId } });
for (const t of templates) {
@@ -735,7 +768,7 @@ export const libraryCloud = {
if (doc.folderId === id) {
await tx.cutTemplate.update({
where: { id: t.id },
- data: { doc: asJson({ ...doc, folderId: null }) },
+ data: { doc: asJson({ ...doc, folderId: up }) },
});
}
}
diff --git a/site/src/cut/server/cloud/notes.ts b/site/src/cut/server/cloud/notes.ts
index 47e5a171..789db7c4 100644
--- a/site/src/cut/server/cloud/notes.ts
+++ b/site/src/cut/server/cloud/notes.ts
@@ -8,6 +8,7 @@
// client-generated like note ids, so a phone can make one offline and push it
// under the id it already filed notes against. Folders file into folders the
// same way, through `parentId`; the top level is null.
+import { resolveParent } from "@/cut/lib/folderTree";
import { NOTE_LABELS_MAX } from "@/cut/lib/types";
import { prisma } from "@/lib/prisma";
import { caught, err } from "./util";
@@ -103,27 +104,15 @@ async function resolveFolder(userId: string, folderId: unknown): Promise<string
return row?.id ?? null;
}
-/** The folder a folder may be filed in: one of this account's note folders
- * that is neither the folder itself nor anything filed under it, or the top
- * level. An id naming nothing files the folder at the top level rather than
- * failing the write — the parent may have been deleted on the other device
- * while this one was offline — and so does one that would close a loop, which
- * two devices moving folders into each other offline can ask for. */
-async function resolveParent(userId: string, id: string, parentId: unknown): Promise<string | null> {
- if (typeof parentId !== "string" || !parentId || parentId === id) return null;
+/** The folder a note folder may be filed in, by the rules every folder table
+ * shares (folderTree.ts), against this account's note folders. */
+async function resolveNoteParent(userId: string, id: string, parentId: unknown): Promise<string | null> {
+ if (typeof parentId !== "string" || !parentId) return null;
const folders = await prisma.cutFolder.findMany({
where: { userId, scope: "note" },
select: { id: true, parentId: true },
});
- const parentOf = new Map(folders.map((f) => [f.id, f.parentId]));
- if (!parentOf.has(parentId)) return null;
- // Walk up from the asked parent; reaching `id` means the move would loop.
- let cur: string | null | undefined = parentId;
- for (let steps = 0; cur && steps <= folders.length; steps++) {
- if (cur === id) return null;
- cur = parentOf.get(cur);
- }
- return parentId;
+ return resolveParent(folders, id, parentId);
}
/** The labels a note may carry: the ids among `labelIds` that name one of
@@ -253,7 +242,7 @@ export const notesCloud = {
const parentId =
body.parentId === undefined
? (existing?.parentId ?? null)
- : await resolveParent(userId, id, body.parentId);
+ : await resolveNoteParent(userId, id, body.parentId);
if (!existing) {
const row = await prisma.cutFolder.create({
data: { id, userId, name, parentId, scope: "note" },
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index 225f1f29..422c0a2a 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -1,5 +1,6 @@
// Cloud twin of the engine's project CRUD (server/projects.ts + http/projects.ts):
// docs and metadata in Postgres, media bytes in R2. Every query scopes by userId.
+import { resolveParent } from "@/cut/lib/folderTree";
import { normalizeAspect, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
@@ -9,6 +10,18 @@ import { del, deletePrefix, projectExportKey, projectHlsRoot, projectMediaKey }
import { addUsage } from "./usage";
import { caught, decodeFileParam, err, redirect } from "./util";
+const projectFolderView = (row: {
+ id: string;
+ name: string;
+ parentId: string | null;
+ createdAt: Date;
+}): ProjectFolder => ({
+ id: row.id,
+ name: row.name,
+ parentId: row.parentId,
+ createdAt: row.createdAt.getTime(),
+});
+
type ProjectRow = {
id: string;
userId: string;
@@ -282,56 +295,77 @@ export const projectsCloud = {
where: { userId, scope: "project" },
orderBy: { createdAt: "asc" },
});
- const folders: ProjectFolder[] = rows.map((f) => ({
- id: f.id,
- name: f.name,
- createdAt: f.createdAt.getTime(),
- }));
- return Response.json(folders);
+ return Response.json(rows.map(projectFolderView));
},
async createFolder(userId: string, req: Request) {
try {
- const { name } = (await req.json()) as { name?: string };
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
const trimmed = (name ?? "").trim();
if (!trimmed) return err("Folder name required.", 500);
+ const folders = await prisma.cutFolder.findMany({
+ where: { userId, scope: "project" },
+ select: { id: true, parentId: true },
+ });
const row = await prisma.cutFolder.create({
- data: { userId, name: trimmed.slice(0, 80), scope: "project" },
+ data: {
+ userId,
+ name: trimmed.slice(0, 80),
+ scope: "project",
+ parentId: resolveParent(folders, "", parentId),
+ },
});
- return Response.json({ id: row.id, name: row.name, createdAt: row.createdAt.getTime() });
+ return Response.json(projectFolderView(row));
} catch (e) {
return caught(e, "Could not create folder.");
}
},
- async renameFolder(userId: string, id: string, req: Request) {
+ /** Rename a folder, file it under another (null for the top level), or
+ * both; a key left out keeps what the folder has. */
+ async updateFolder(userId: string, id: string, req: Request) {
try {
- const { name } = (await req.json()) as { name?: string };
- const trimmed = (name ?? "").trim();
- if (!trimmed) return err("Folder name required.", 500);
- const row = await prisma.cutFolder.findFirst({ where: { id, userId, scope: "project" } });
- if (!row) return err("Folder not found.", 500);
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
+ const trimmed = name?.trim();
+ if (name !== undefined && !trimmed) return err("Folder name required.", 500);
+ const folders = await prisma.cutFolder.findMany({
+ where: { userId, scope: "project" },
+ select: { id: true, parentId: true },
+ });
+ if (!folders.some((f) => f.id === id)) return err("Folder not found.", 500);
const updated = await prisma.cutFolder.update({
where: { id },
- data: { name: trimmed.slice(0, 80) },
- });
- return Response.json({
- id: updated.id,
- name: updated.name,
- createdAt: updated.createdAt.getTime(),
+ data: {
+ ...(trimmed ? { name: trimmed.slice(0, 80) } : {}),
+ ...(parentId !== undefined ? { parentId: resolveParent(folders, id, parentId) } : {}),
+ },
});
+ return Response.json(projectFolderView(updated));
} catch (e) {
- return caught(e, "Could not rename folder.");
+ return caught(e, "Could not update folder.");
}
},
+ /** Delete a folder. What it held — its projects and the folders inside it —
+ * comes up one level, filed where the folder was. */
async deleteFolder(userId: string, id: string) {
try {
- await prisma.$transaction([
- prisma.cutFolder.deleteMany({ where: { id, userId, scope: "project" } }),
- // Projects in the folder fall back to ungrouped rather than disappearing.
- prisma.cutProject.updateMany({ where: { userId, folderId: id }, data: { folderId: null } }),
- ]);
+ await prisma.$transaction(async (tx) => {
+ const gone = await tx.cutFolder.findFirst({
+ where: { id, userId, scope: "project" },
+ select: { parentId: true },
+ });
+ if (!gone) return;
+ await tx.cutFolder.delete({ where: { id } });
+ await tx.cutProject.updateMany({
+ where: { userId, folderId: id },
+ data: { folderId: gone.parentId },
+ });
+ await tx.cutFolder.updateMany({
+ where: { userId, scope: "project", parentId: id },
+ data: { parentId: gone.parentId },
+ });
+ });
return Response.json({ ok: true });
} catch (e) {
return caught(e, "Could not delete folder.");
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index 94af1d5e..bca19119 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -38,7 +38,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "POST", path: "/api/cut-cloud/projects", handler: (r, u) => projectsCloud.create(u, r) },
{ method: "GET", path: "/api/cut-cloud/projects/folders", handler: (_r, u) => projectsCloud.folders(u) },
{ method: "POST", path: "/api/cut-cloud/projects/folders", handler: (r, u) => projectsCloud.createFolder(u, r) },
- { method: "PUT", path: "/api/cut-cloud/projects/folders/:id", handler: (r, u, p) => projectsCloud.renameFolder(u, p.id, r) },
+ { method: "PUT", path: "/api/cut-cloud/projects/folders/:id", handler: (r, u, p) => projectsCloud.updateFolder(u, p.id, r) },
{ method: "DELETE", path: "/api/cut-cloud/projects/folders/:id", handler: (_r, u, p) => projectsCloud.deleteFolder(u, p.id) },
{ method: "POST", path: "/api/cut-cloud/projects/:id/move", handler: (r, u, p) => projectsCloud.move(u, p.id, r) },
{ method: "GET", path: "/api/cut-cloud/projects/:id", handler: (_r, u, p) => projectsCloud.get(u, p.id) },
@@ -84,7 +84,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "DELETE", path: "/api/cut-cloud/library/templates/:id", handler: (_r, u, p) => libraryCloud.removeTemplate(u, p.id) },
{ method: "POST", path: "/api/cut-cloud/library/import-url", handler: (r, u) => jobsCloud.importUrlToLibrary(u, r) },
{ method: "POST", path: "/api/cut-cloud/library/folders", handler: (r, u) => libraryCloud.createFolder(u, r) },
- { method: "PUT", path: "/api/cut-cloud/library/folders/:id", handler: (r, u, p) => libraryCloud.renameFolder(u, p.id, r) },
+ { method: "PUT", path: "/api/cut-cloud/library/folders/:id", handler: (r, u, p) => libraryCloud.updateFolder(u, p.id, r) },
{ method: "DELETE", path: "/api/cut-cloud/library/folders/:id", handler: (_r, u, p) => libraryCloud.deleteFolder(u, p.id) },
{ method: "GET", path: "/api/cut-cloud/library/media/:file", handler: (r, u, p) => libraryCloud.serveMedia(u, p.file, wantsDownload(r)) },
{ method: "DELETE", path: "/api/cut-cloud/library/:id", handler: (_r, u, p) => libraryCloud.remove(u, p.id) },
diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.ts
index 29b7960d..0c162168 100644
--- a/site/src/cut/server/http/library.ts
+++ b/site/src/cut/server/http/library.ts
@@ -12,7 +12,7 @@ import {
listTemplates,
moveItem,
removeAsset,
- renameFolder,
+ updateFolder,
renameTemplate,
saveTemplate,
useInProject,
@@ -123,19 +123,20 @@ export const libraryApi = {
async createFolder(req: Request) {
try {
- const { name } = (await req.json()) as { name?: string };
- return Response.json(await createFolder(name ?? ""));
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
+ return Response.json(await createFolder(name ?? "", parentId ?? null));
} catch (e) {
return caught(e, "Could not create folder.");
}
},
- async renameFolder(req: Request, { id }: { id: string }) {
+ /** Rename a folder, move it under another, or both. */
+ async updateFolder(req: Request, { id }: { id: string }) {
try {
- const { name } = (await req.json()) as { name?: string };
- return Response.json(await renameFolder(id, name ?? ""));
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
+ return Response.json(await updateFolder(id, { name, parentId }));
} catch (e) {
- return caught(e, "Could not rename folder.");
+ return caught(e, "Could not update folder.");
}
},
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 14d6055a..10626ec8 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -17,7 +17,7 @@ import {
moveProjectToFolder,
previewPath,
readProject,
- renameProjectFolder,
+ updateProjectFolder,
saveMedia,
sweepOrphanMedia,
writeProject,
@@ -45,19 +45,20 @@ export const projectsApi = {
async createFolder(req: Request) {
try {
- const { name } = (await req.json()) as { name?: string };
- return Response.json(await createProjectFolder(name ?? ""));
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
+ return Response.json(await createProjectFolder(name ?? "", parentId ?? null));
} catch (e) {
return caught(e, "Could not create folder.");
}
},
- async renameFolder(req: Request, { id }: { id: string }) {
+ /** Rename a folder, move it under another, or both. */
+ async updateFolder(req: Request, { id }: { id: string }) {
try {
- const { name } = (await req.json()) as { name?: string };
- return Response.json(await renameProjectFolder(id, name ?? ""));
+ const { name, parentId } = (await req.json()) as { name?: string; parentId?: string | null };
+ return Response.json(await updateProjectFolder(id, { name, parentId }));
} catch (e) {
- return caught(e, "Could not rename folder.");
+ return caught(e, "Could not update folder.");
}
},
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
index 785b5d4b..516c486f 100644
--- a/site/src/cut/server/http/routes.ts
+++ b/site/src/cut/server/http/routes.ts
@@ -28,7 +28,7 @@ export const CUT_ROUTES: CutRoute[] = [
{ method: "POST", path: "/api/cut/projects", handler: (req) => projectsApi.create(req) },
{ method: "GET", path: "/api/cut/projects/folders", handler: () => projectsApi.folders() },
{ method: "POST", path: "/api/cut/projects/folders", handler: (req) => projectsApi.createFolder(req) },
- { method: "PUT", path: "/api/cut/projects/folders/:id", handler: (req, p) => projectsApi.renameFolder(req, { id: p.id }) },
+ { method: "PUT", path: "/api/cut/projects/folders/:id", handler: (req, p) => projectsApi.updateFolder(req, { id: p.id }) },
{ method: "DELETE", path: "/api/cut/projects/folders/:id", handler: (req, p) => projectsApi.deleteFolder(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/move", handler: (req, p) => projectsApi.move(req, { id: p.id }) },
{ method: "GET", path: "/api/cut/projects/:id", handler: (req, p) => projectsApi.get(req, { id: p.id }) },
@@ -66,7 +66,7 @@ export const CUT_ROUTES: CutRoute[] = [
{ method: "PUT", path: "/api/cut/library/templates/:id", handler: (req, p) => libraryApi.renameTemplate(req, { id: p.id }) },
{ method: "DELETE", path: "/api/cut/library/templates/:id", handler: (req, p) => libraryApi.removeTemplate(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/library/folders", handler: (req) => libraryApi.createFolder(req) },
- { method: "PUT", path: "/api/cut/library/folders/:id", handler: (req, p) => libraryApi.renameFolder(req, { id: p.id }) },
+ { method: "PUT", path: "/api/cut/library/folders/:id", handler: (req, p) => libraryApi.updateFolder(req, { id: p.id }) },
{ method: "DELETE", path: "/api/cut/library/folders/:id", handler: (req, p) => libraryApi.deleteFolder(req, { id: p.id }) },
{ method: "GET", path: "/api/cut/library/media/:file", handler: (req, p) => libraryApi.serveMedia(req, { file: p.file }) },
{ method: "DELETE", path: "/api/cut/library/:id", handler: (req, p) => libraryApi.remove(req, { id: p.id }) },
diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.ts
index 68918e26..8c747be7 100644
--- a/site/src/cut/server/library.ts
+++ b/site/src/cut/server/library.ts
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import type { ClipSound } from "@donkeycut/effects-kit";
+import { resolveParent, settleParents } from "@/cut/lib/folderTree";
import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
import { mediaPath as projectMediaPath, readProject } from "./projects";
@@ -45,6 +46,9 @@ export interface LibraryAsset {
export interface LibraryFolder {
id: string;
name: string;
+ /** The folder this one is filed in; null (or absent, from before nesting)
+ * is the top level. */
+ parentId?: string | null;
createdAt: number;
}
@@ -374,48 +378,64 @@ export function getAsset(id: string) {
return readIndex().then((idx) => idx.assets.find((a) => a.id === id));
}
-// --- Folders: a flat set of named groups; assets carry a folderId. ---
+// --- Folders: named groups that file into each other; assets carry a
+// folderId, folders a parentId. ---
export async function listFolders(): Promise<LibraryFolder[]> {
const idx = await readIndex();
- return (idx.folders ?? []).slice().sort((a, b) => a.createdAt - b.createdAt);
+ return settleParents(idx.folders ?? []).sort((a, b) => a.createdAt - b.createdAt);
}
-export async function createFolder(name: string): Promise<LibraryFolder> {
+export async function createFolder(
+ name: string,
+ parentId: string | null = null,
+): Promise<LibraryFolder> {
const trimmed = name.trim();
if (!trimmed) throw new Error("Folder name required.");
- const folder: LibraryFolder = {
- id: crypto.randomUUID().slice(0, 8),
- name: trimmed.slice(0, 80),
- createdAt: Date.now(),
- };
- await mutateIndex((idx) => {
+ const id = crypto.randomUUID().slice(0, 8);
+ return mutateIndex((idx) => {
+ const folder: LibraryFolder = {
+ id,
+ name: trimmed.slice(0, 80),
+ parentId: resolveParent(idx.folders ?? [], id, parentId),
+ createdAt: Date.now(),
+ };
idx.folders = [...(idx.folders ?? []), folder];
+ return folder;
});
- return folder;
}
-export async function renameFolder(
+/** Rename a folder, file it under another (null for the top level), or
+ * both; a key left undefined keeps what the folder has. */
+export async function updateFolder(
id: string,
- name: string,
+ patch: { name?: string; parentId?: string | null },
): Promise<LibraryFolder> {
- const trimmed = name.trim();
- if (!trimmed) throw new Error("Folder name required.");
+ const trimmed = patch.name?.trim();
+ if (patch.name !== undefined && !trimmed) throw new Error("Folder name required.");
return mutateIndex((idx) => {
const folder = (idx.folders ?? []).find((f) => f.id === id);
if (!folder) throw new Error("Folder not found.");
- folder.name = trimmed.slice(0, 80);
+ if (trimmed) folder.name = trimmed.slice(0, 80);
+ if (patch.parentId !== undefined) {
+ folder.parentId = resolveParent(idx.folders ?? [], id, patch.parentId);
+ }
return folder;
});
}
+/** Delete a folder. What it held — its items and the folders inside it —
+ * comes up one level, filed where the folder was. */
export async function deleteFolder(id: string) {
await mutateIndex((idx) => {
+ const gone = (idx.folders ?? []).find((f) => f.id === id);
+ if (!gone) return;
+ const up = gone.parentId ?? null;
idx.folders = (idx.folders ?? []).filter((f) => f.id !== id);
- // Items in the folder fall back to ungrouped rather than vanishing.
- for (const a of idx.assets) if (a.folderId === id) a.folderId = null;
+ for (const f of idx.folders) if ((f.parentId ?? null) === id) f.parentId = up;
+ for (const a of idx.assets) if (a.folderId === id) a.folderId = up;
for (const t of idx.templates ?? [])
- if (t.folderId === id) t.folderId = null;
+ if (t.folderId === id) t.folderId = up;
});
}
diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.ts
index f916ca24..2952f273 100644
--- a/site/src/cut/server/projects.ts
+++ b/site/src/cut/server/projects.ts
@@ -1,6 +1,7 @@
import fsSync from "node:fs";
import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
+import { resolveParent, settleParents } from "@/cut/lib/folderTree";
import type { Aspect, ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";
import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
@@ -444,8 +445,8 @@ async function summarize(id: string, doc: ProjectDoc): Promise<ProjectSummary> {
};
}
-// --- Project folders: a flat set of named groups; each project's doc carries
-// its folderId, so grouping travels with the project. ---
+// --- Project folders: named groups that file into each other; each project's
+// doc carries its folderId, so grouping travels with the project. ---
async function readFolders(): Promise<ProjectFolder[]> {
try {
@@ -462,39 +463,60 @@ async function writeFolders(folders: ProjectFolder[]) {
}
export async function listProjectFolders(): Promise<ProjectFolder[]> {
- return (await readFolders()).sort((a, b) => a.createdAt - b.createdAt);
+ return settleParents(await readFolders()).sort((a, b) => a.createdAt - b.createdAt);
}
-export async function createProjectFolder(name: string): Promise<ProjectFolder> {
+export async function createProjectFolder(
+ name: string,
+ parentId: string | null = null
+): Promise<ProjectFolder> {
const trimmed = name.trim();
if (!trimmed) throw new Error("Folder name required.");
+ const folders = await readFolders();
+ const id = crypto.randomUUID().slice(0, 8);
const folder: ProjectFolder = {
- id: crypto.randomUUID().slice(0, 8),
+ id,
name: trimmed.slice(0, 80),
+ parentId: resolveParent(folders, id, parentId),
createdAt: Date.now(),
};
- await writeFolders([...(await readFolders()), folder]);
+ await writeFolders([...folders, folder]);
return folder;
}
-export async function renameProjectFolder(id: string, name: string): Promise<ProjectFolder> {
- const trimmed = name.trim();
- if (!trimmed) throw new Error("Folder name required.");
+/** Rename a folder, file it under another (null for the top level), or
+ * both; a key left undefined keeps what the folder has. */
+export async function updateProjectFolder(
+ id: string,
+ patch: { name?: string; parentId?: string | null }
+): Promise<ProjectFolder> {
+ const trimmed = patch.name?.trim();
+ if (patch.name !== undefined && !trimmed) throw new Error("Folder name required.");
const folders = await readFolders();
const folder = folders.find((f) => f.id === id);
if (!folder) throw new Error("Folder not found.");
- folder.name = trimmed.slice(0, 80);
+ if (trimmed) folder.name = trimmed.slice(0, 80);
+ if (patch.parentId !== undefined) folder.parentId = resolveParent(folders, id, patch.parentId);
await writeFolders(folders);
return folder;
}
+/** Delete a folder. What it held — its projects and the folders inside it —
+ * comes up one level, filed where the folder was. */
export async function deleteProjectFolder(id: string) {
- await writeFolders((await readFolders()).filter((f) => f.id !== id));
- // Projects in the folder fall back to ungrouped rather than disappearing.
+ const folders = await readFolders();
+ const gone = folders.find((f) => f.id === id);
+ if (!gone) return;
+ const up = gone.parentId ?? null;
+ await writeFolders(
+ folders
+ .filter((f) => f.id !== id)
+ .map((f) => ((f.parentId ?? null) === id ? { ...f, parentId: up } : f))
+ );
await Promise.all(
(await readProjectEntries()).map(async ({ id: projectId, doc }) => {
if (doc.folderId === id) {
- doc.folderId = null;
+ doc.folderId = up;
await writeProject(projectId, doc);
}
})