Skip to content

Open source CapCut alternative.

TypeScript

feat(site): note folders nest, with folder tiles that drag

David Le460bfbcbf26a
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prisma
index b2a0524b..a40102c8 100644
--- a/site/prisma/Cut.prisma
+++ b/site/prisma/Cut.prisma
@@ -61,6 +61,8 @@ model CutFolder {
userId String
name String
scope String @default("project") // project | library | note
+ // The folder this one is filed in; null is the top level. Note folders nest.
+ parentId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 8bf3db76..25fc5f80 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -741,10 +741,10 @@ export function LibraryView() {
) : (
<FolderCrumb
root="Library"
- name={openFolderName ?? "Folder"}
+ trail={[{ id: openFolder, name: openFolderName ?? "Folder" }]}
mime={LIBRARY_MOVE_MIME}
- onBack={() => gotoFolder(null)}
- onDropOut={(ids) => void moveItems(ids, null)}
+ onGo={() => gotoFolder(null)}
+ onDrop={(ids) => void moveItems(ids, null)}
/>
)}
<div className="flex items-center gap-2">
diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsx
index 6ec6ad60..60ccd2be 100644
--- a/site/src/cut/components/NotesView.tsx
+++ b/site/src/cut/components/NotesView.tsx
@@ -9,11 +9,14 @@ import {
deleteNote,
deleteNoteFolder,
deleteNoteLabel,
+ folderTrail,
+ folderWithin,
noteColor,
saveNote,
saveNoteFolder,
saveNoteLabel,
type CutNote,
+ type CutNoteFolder,
} from "@/cut/lib/notes";
import { homeHref, useCutBase } from "@/cut/lib/nav";
import { notesKey, patchNotes, useNotes } from "@/cut/lib/queries";
@@ -28,6 +31,8 @@ const NOTE_INK = "#201a0d";
// A dragged selection of notes, the same shape the library and the projects
// home carry: a JSON array of ids under this page's own MIME type.
const NOTES_MOVE_MIME = "application/x-donkey-notes";
+// A dragged folder tile, filed into another folder or back out to a crumb.
+const NOTE_FOLDERS_MOVE_MIME = "application/x-donkey-note-folders";
/** Write a note out. The list shows it the moment it is written, and the
* server's answer — this write, or a newer one from the phone — replaces it.
@@ -110,7 +115,9 @@ const draftOf = (n: CutNote): NoteDraft => ({
/** Synced notes: written on the phone or here, merged by last writer wins.
* The phone reads these into its teleprompter, so a script drafted at the
* desk is on the camera by the time the phone is in hand. Notes file into
- * folders on the desktop-style shelf the library uses. */
+ * folders on the desktop-style shelf the library uses, and folders file into
+ * folders: every level has the shelf, the New folder button and the grid the
+ * top level has. */
export function NotesView() {
const client = useQueryClient();
const base = useCutBase();
@@ -137,7 +144,10 @@ export function NotesView() {
const params = useSearchParams();
const openFolder = params.get("folder");
const openNoteId = params.get("note");
- const openFolderName = folders.find((f) => f.id === openFolder)?.name;
+ // The way down to the open folder, for the crumb; and what is filed right
+ // here: the folders and the notes this level holds.
+ const trail = folderTrail(folders, openFolder);
+ const shownFolders = folders.filter((f) => f.parentId === openFolder);
const shown = list.filter((n) => (n.folderId ?? null) === openFolder);
// What the composer shows: the buffer while it belongs to the note the URL
// names, and the stored note otherwise. A note nobody has typed into has no
@@ -337,6 +347,43 @@ export function NotesView() {
}));
};
+ /** File a set of folders into a folder (or back to the top level). A folder
+ * never files into itself or into anything under it; the shelf and the
+ * crumb only ever offer siblings and ancestors, and this is the check
+ * behind them. */
+ const moveFolders = async (ids: string[], parentId: string | null) => {
+ const moving = folders.filter(
+ (f) =>
+ ids.includes(f.id) &&
+ f.parentId !== parentId &&
+ !folderWithin(folders, parentId, f.id),
+ );
+ if (moving.length === 0) return;
+ const movingIds = new Set(moving.map((f) => f.id));
+ patchNotes(client, (prev) => ({
+ ...prev,
+ folders: prev.folders.map((f) => (movingIds.has(f.id) ? { ...f, parentId } : f)),
+ }));
+ await Promise.all([...movingIds, parentId].map(settleFolder));
+ const saved = await Promise.all(
+ moving.map((f) =>
+ saveNoteFolder(f.id, { name: f.name, parentId }).catch(() => null),
+ ),
+ );
+ const landed = saved.filter((f): f is CutNoteFolder => f !== null);
+ if (landed.length !== moving.length) {
+ reload();
+ return;
+ }
+ // The server answers with where each folder is filed, so a parent that
+ // is gone shows its folders back at the top level right away.
+ const byId = new Map(landed.map((f) => [f.id, f]));
+ patchNotes(client, (prev) => ({
+ ...prev,
+ folders: prev.folders.map((f) => byId.get(f.id) ?? f),
+ }));
+ };
+
// The same write, reachable from the listeners below, which outlive any one
// render.
const closing = useRef<() => void>(() => {});
@@ -367,12 +414,18 @@ export function NotesView() {
}, []);
// A note the URL names and nothing answers for — deleted from another
- // device, or a reload of one never written — leaves the list behind.
+ // device, or a reload of one never written — leaves the list behind. A
+ // folder the URL names and nothing answers for goes back to the top level.
const stale = !!openNoteId && !draft && !!notes.data;
const listHref = notesHref(openFolder);
useEffect(() => {
if (stale) window.history.replaceState(null, "", listHref);
}, [stale, listHref]);
+ const staleFolder = !!openFolder && !!notes.data && trail.length === 0;
+ const rootHref = homeHref(base, "notes");
+ useEffect(() => {
+ if (staleFolder) window.history.replaceState(null, "", rootHref);
+ }, [staleFolder, rootHref]);
// Carry the selection (or just this card) as a folder-move payload, with a
// ghost for a multi-note drag.
@@ -416,40 +469,44 @@ export function NotesView() {
) : (
<FolderCrumb
root="Notes"
- name={openFolderName ?? "Folder"}
+ trail={trail}
mime={NOTES_MOVE_MIME}
- onBack={() => gotoFolder(null)}
- onDropOut={(ids) => void moveNotes(ids, null)}
+ folderMime={NOTE_FOLDERS_MOVE_MIME}
+ onGo={gotoFolder}
+ onDrop={(ids, id) => void moveNotes(ids, id)}
+ onDropFolders={(ids, id) => void moveFolders(ids, id)}
/>
)}
<div className="flex items-center gap-2">
- {openFolder === null && (
- <Button variant="outline" onClick={() => setFolderCreating(true)}>
- <FolderPlus data-icon="inline-start" /> New folder
- </Button>
- )}
+ <Button variant="outline" onClick={() => setFolderCreating(true)}>
+ <FolderPlus data-icon="inline-start" /> New folder
+ </Button>
<Button onClick={openNew}>
<Plus data-icon="inline-start" /> New note
</Button>
</div>
</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={NOTES_MOVE_MIME}
+ folderMime={NOTE_FOLDERS_MOVE_MIME}
creating={folderCreating}
onCreatingChange={setFolderCreating}
statOf={(id) => ({
- count: list.filter((n) => (n.folderId ?? null) === id).length,
+ count:
+ list.filter((n) => (n.folderId ?? null) === id).length +
+ folders.filter((f) => f.parentId === id).length,
})}
onOpen={gotoFolder}
onCreate={async (name) => {
- const folder = {
+ const folder: CutNoteFolder = {
id: crypto.randomUUID(),
name,
+ parentId: openFolder,
updatedAt: Date.now(),
createdAt: Date.now(),
};
@@ -457,7 +514,11 @@ export function NotesView() {
...prev,
folders: [...prev.folders, folder],
}));
- const write = saveNoteFolder(folder.id, name).catch(() => reload());
+ // The parent's own write may still be in flight; it lands first,
+ // so the server knows it by the time this one names it.
+ const write = settleFolder(openFolder)
+ .then(() => saveNoteFolder(folder.id, { name, parentId: openFolder }))
+ .catch(() => reload());
folderWrites.current.set(folder.id, write);
try {
await write;
@@ -466,25 +527,32 @@ export function NotesView() {
}
}}
onRename={async (id, name) => {
+ const parentId = folders.find((f) => f.id === id)?.parentId ?? null;
patchNotes(client, (prev) => ({
...prev,
folders: prev.folders.map((f) => (f.id === id ? { ...f, name } : f)),
}));
- await saveNoteFolder(id, name).catch(() => reload());
+ await settleFolder(id);
+ await saveNoteFolder(id, { name, parentId }).catch(() => reload());
}}
onDelete={async (id) => {
+ // What the folder held comes up one level, the way the server
+ // files it.
+ const parentId = folders.find((f) => f.id === id)?.parentId ?? null;
patchNotes(client, (prev) => ({
...prev,
- folders: prev.folders.filter((f) => f.id !== id),
+ folders: prev.folders
+ .filter((f) => f.id !== id)
+ .map((f) => (f.parentId === id ? { ...f, parentId } : f)),
notes: prev.notes.map((n) =>
- n.folderId === id ? { ...n, folderId: null } : n,
+ n.folderId === id ? { ...n, folderId: parentId } : n,
),
}));
- if (openFolder === id)
- window.history.replaceState(null, "", homeHref(base, "notes"));
+ await settleFolder(id);
await deleteNoteFolder(id).catch(() => reload());
}}
onDropIds={(ids, folderId) => void moveNotes(ids, folderId)}
+ onDropFolders={(ids, folderId) => void moveFolders(ids, folderId)}
/>
) : null}
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index e3ad9588..68c574c4 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -854,10 +854,10 @@ export function ProjectsHome() {
) : (
<FolderCrumb
root="Projects"
- name={openFolderName ?? "Folder"}
+ trail={[{ id: openFolder, name: openFolderName ?? "Folder" }]}
mime={PROJECT_MIME}
- onBack={() => gotoFolder(null)}
- onDropOut={(ids) => void moveProjects(folderOwner ?? r0, ids, null)}
+ onGo={() => gotoFolder(null)}
+ onDrop={(ids) => void moveProjects(folderOwner ?? r0, ids, null)}
/>
)}
<div className="flex items-center gap-2">
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 1c7481ed..6dbc3966 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -900,10 +900,12 @@ function ProjectFilesPanel({
<FolderCrumb
className="text-sm"
root="Project Files"
- name={folders.find((f) => f.id === openFolder)?.name ?? "Folder"}
+ trail={[
+ { id: openFolder, name: folders.find((f) => f.id === openFolder)?.name ?? "Folder" },
+ ]}
mime={MEDIA_MOVE_MIME}
- onBack={() => setOpenFolder(null)}
- onDropOut={(ids) => useEditor.getState().moveAssetsToMediaFolder(ids, null)}
+ onGo={() => setOpenFolder(null)}
+ onDrop={(ids) => useEditor.getState().moveAssetsToMediaFolder(ids, null)}
/>
</div>
)}
@@ -1716,10 +1718,10 @@ function LibraryPanel({ projectId }: { projectId: string }) {
<FolderCrumb
className="text-sm"
root="Library"
- name={openFolderName ?? "Folder"}
+ trail={[{ id: openFolder, name: openFolderName ?? "Folder" }]}
mime={LIBRARY_MOVE_MIME}
- onBack={() => setOpenFolder(null)}
- onDropOut={(ids) => ids.forEach((id) => void move(id, null))}
+ onGo={() => setOpenFolder(null)}
+ onDrop={(ids) => ids.forEach((id) => void move(id, null))}
/>
</div>
)}
diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsx
index 38dbd858..81f99345 100644
--- a/site/src/cut/components/desktopFolders.tsx
+++ b/site/src/cut/components/desktopFolders.tsx
@@ -11,6 +11,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
+import { setObjectDragImage } from "@/cut/lib/assetDrag";
import type { AssetRef } from "@/cut/lib/assetRef";
import { formatBytes } from "@/lib/bytes";
import { RefDropZone } from "./RefDropZone";
@@ -42,8 +43,10 @@ export function readDragIds(e: React.DragEvent, mime: string): string[] {
}
/** Folder tile glyph: the Lucide folder, filled blue. */
-export function FolderGlyph({ className }: { className?: string }) {
- return <Folder className={cn("fill-[#8cc5ff] text-[#8cc5ff]", className)} aria-hidden="true" />;
+export function FolderGlyph({ className, ...rest }: { className?: string } & Record<string, unknown>) {
+ return (
+ <Folder className={cn("fill-[#8cc5ff] text-[#8cc5ff]", className)} aria-hidden="true" {...rest} />
+ );
}
/**
@@ -217,69 +220,138 @@ export function Marquee({
);
}
-/** Root breadcrumb shown while a folder is open. The root label is itself a drop
- * target, so a selection can be dragged back out to the top level. */
+/** One step of the breadcrumb that can be gone back to: a button, and a drop
+ * target for an item selection under `mime` and, when the host nests folders,
+ * for folders under `folderMime`. */
+function CrumbStep({
+ label,
+ mime,
+ folderMime,
+ onGo,
+ onDrop,
+ onDropFolders,
+}: {
+ label: string;
+ mime: string;
+ folderMime?: string;
+ onGo: () => void;
+ onDrop: (ids: string[]) => void;
+ onDropFolders?: (ids: string[]) => void;
+}) {
+ const [over, setOver] = useState(false);
+ const carried = (e: React.DragEvent) => {
+ const types = Array.from(e.dataTransfer.types);
+ if (types.includes(mime)) return "items";
+ if (folderMime && onDropFolders && types.includes(folderMime)) return "folders";
+ return null;
+ };
+ return (
+ <button
+ className={cn(
+ "rounded-md px-1.5 py-0.5 text-muted-foreground transition-colors hover:text-foreground",
+ over && "bg-primary/15 text-primary"
+ )}
+ onClick={onGo}
+ onDragOver={(e) => {
+ if (!carried(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ setOver(true);
+ }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => {
+ const kind = carried(e);
+ if (!kind) return;
+ e.preventDefault();
+ setOver(false);
+ if (kind === "folders") onDropFolders?.(readDragIds(e, folderMime!));
+ else onDrop(readDragIds(e, mime));
+ }}
+ >
+ {label}
+ </button>
+ );
+}
+
+/** The breadcrumb shown while a folder is open: the root, then every folder
+ * on the way down to the open one. Each step above the open folder is a
+ * button and a drop target, so a selection can be dragged back out to any
+ * level. `id` is null for the root. */
export function FolderCrumb({
root,
- name,
+ trail,
mime,
- onBack,
- onDropOut,
+ folderMime,
+ onGo,
+ onDrop,
+ onDropFolders,
className,
}: {
root: string;
- name: string;
+ /** The folders from the top level down to the open one, the open one last. */
+ trail: { id: string; name: string }[];
mime: string;
- onBack: () => void;
- onDropOut: (ids: string[]) => void;
+ /** Set when folders themselves are dragged; steps then take those drops too. */
+ folderMime?: string;
+ onGo: (id: string | null) => void;
+ onDrop: (ids: string[], id: string | null) => void;
+ onDropFolders?: (ids: string[], id: string | null) => void;
className?: string;
}) {
- const [over, setOver] = useState(false);
+ const open = trail[trail.length - 1];
return (
<div
- className={cn("flex items-center gap-2 text-lg font-semibold tracking-tight", className)}
+ className={cn("flex min-w-0 items-center gap-2 text-lg font-semibold tracking-tight", className)}
data-no-marquee
>
- <button
- className={cn(
- "rounded-md px-1.5 py-0.5 text-muted-foreground transition-colors hover:text-foreground",
- over && "bg-primary/15 text-primary"
- )}
- onClick={onBack}
- onDragOver={(e) => {
- if (!Array.from(e.dataTransfer.types).includes(mime)) return;
- e.preventDefault();
- e.dataTransfer.dropEffect = "move";
- setOver(true);
- }}
- onDragLeave={() => setOver(false)}
- onDrop={(e) => {
- e.preventDefault();
- setOver(false);
- onDropOut(readDragIds(e, mime));
- }}
- >
- {root}
- </button>
- <span className="text-muted-foreground/50">/</span>
- <span className="truncate">{name}</span>
+ <CrumbStep
+ label={root}
+ mime={mime}
+ folderMime={folderMime}
+ onGo={() => onGo(null)}
+ onDrop={(ids) => onDrop(ids, null)}
+ onDropFolders={onDropFolders && ((ids) => onDropFolders(ids, null))}
+ />
+ {trail.slice(0, -1).map((f) => (
+ <Fragment key={f.id}>
+ <span className="text-muted-foreground/50">/</span>
+ <CrumbStep
+ label={f.name}
+ mime={mime}
+ folderMime={folderMime}
+ onGo={() => onGo(f.id)}
+ onDrop={(ids) => onDrop(ids, f.id)}
+ onDropFolders={onDropFolders && ((ids) => onDropFolders(ids, f.id))}
+ />
+ </Fragment>
+ ))}
+ {open && (
+ <>
+ <span className="text-muted-foreground/50">/</span>
+ <span className="truncate">{open.name}</span>
+ </>
+ )}
</div>
);
}
-/** The desktop-style folder shelf at the root: each folder as a blue folder
- * icon and a drop target for dragged items. Folder creation is driven by the
- * host (e.g. a header button) through `creating`/`onCreatingChange`. */
+/** The desktop-style folder shelf: each folder as a blue folder icon and a
+ * drop target for dragged items. Folder creation is driven by the host (e.g.
+ * a header button) through `creating`/`onCreatingChange`. A host that nests
+ * folders passes `folderMime`; tiles are then draggable, carrying their own
+ * id under it, and every other tile takes that drop. */
export function FolderShelf<F extends DeskFolder>({
folders,
statOf,
badgeOf,
mime,
+ folderMime,
onOpen,
onCreate,
onRename,
onDelete,
onDropIds,
+ onDropFolders,
onDropFiles,
onRefDrop,
creating = false,
@@ -292,11 +364,15 @@ export function FolderShelf<F extends DeskFolder>({
* a folder is on. */
badgeOf?: (id: string) => React.ReactNode;
mime: string;
+ /** The MIME a dragged folder tile carries its id under. */
+ folderMime?: string;
onOpen: (id: string) => void;
onCreate?: (name: string) => void | Promise<void>;
onRename: (id: string, name: string) => void | Promise<void>;
onDelete: (id: string) => void | Promise<void>;
onDropIds: (ids: string[], folderId: string) => void;
+ /** Folders dropped onto a folder tile — filed inside it. */
+ onDropFolders?: (ids: string[], folderId: string) => void;
/** Desktop files dropped onto a folder tile — dropped straight into it. */
onDropFiles?: (files: FileList, folderId: string) => void;
/** When set, folder tiles also take media drops from cards and timeline
@@ -308,11 +384,18 @@ export function FolderShelf<F extends DeskFolder>({
* subtext — for narrow panels; default is the desktop tile grid. */
rows?: boolean;
}) {
- // A folder tile accepts both an internal selection (its MIME) and, when the
- // host wires it up, OS files dragged from the desktop.
+ // A folder tile accepts an internal selection (its MIME), another folder
+ // tile when the host nests folders, and, when the host wires it up, OS
+ // files dragged from the desktop.
const dragTypes = (e: React.DragEvent) => Array.from(e.dataTransfer.types);
- const accepts = (e: React.DragEvent) =>
- dragTypes(e).includes(mime) || (!!onDropFiles && dragTypes(e).includes("Files"));
+ const nests = !!folderMime && !!onDropFolders;
+ // The tile being dragged, so it does not light up as its own target. The
+ // payload is drop-only, which is why the id is held here.
+ const [dragging, setDragging] = useState<string | null>(null);
+ const accepts = (e: React.DragEvent, target: string) =>
+ dragTypes(e).includes(mime) ||
+ (nests && dragTypes(e).includes(folderMime) && dragging !== target) ||
+ (!!onDropFiles && dragTypes(e).includes("Files"));
const [editingId, setEditingId] = useState<string | null>(null);
const [draft, setDraft] = useState("");
const [over, setOver] = useState<string | null>(null);
@@ -369,14 +452,14 @@ export function FolderShelf<F extends DeskFolder>({
setEditingId(f.id);
},
onDragOver: (e: React.DragEvent) => {
- if (!accepts(e)) return;
+ if (!accepts(e, f.id)) return;
e.preventDefault();
- e.dataTransfer.dropEffect = dragTypes(e).includes(mime) ? "move" : "copy";
+ e.dataTransfer.dropEffect = dragTypes(e).includes("Files") ? "copy" : "move";
setOver(f.id);
},
onDragLeave: () => setOver((o: string | null) => (o === f.id ? null : o)),
onDrop: (e: React.DragEvent) => {
- if (!accepts(e)) return;
+ if (!accepts(e, f.id)) return;
e.preventDefault();
setOver(null);
// Files land in this folder; stop the drop bubbling to the page's
@@ -386,8 +469,26 @@ export function FolderShelf<F extends DeskFolder>({
onDropFiles(e.dataTransfer.files, f.id);
return;
}
+ if (nests && dragTypes(e).includes(folderMime)) {
+ onDropFolders(readDragIds(e, folderMime), f.id);
+ return;
+ }
onDropIds(readDragIds(e, mime), f.id);
},
+ // The tile itself is what a nesting host drags: its own id,
+ // with the glyph as the ghost.
+ ...(nests
+ ? {
+ draggable: true,
+ onDragStart: (e: React.DragEvent) => {
+ e.dataTransfer.setData(folderMime, JSON.stringify([f.id]));
+ e.dataTransfer.effectAllowed = "move";
+ setDragging(f.id);
+ setObjectDragImage(e, 1, [f.id]);
+ },
+ onDragEnd: () => setDragging(null),
+ }
+ : {}),
}),
};
const menu = f.locked ? null : (
@@ -439,6 +540,7 @@ export function FolderShelf<F extends DeskFolder>({
"size-7 shrink-0 drop-shadow-sm transition-transform",
isOver && "scale-105 brightness-110"
)}
+ data-drag-object
/>
<div className="min-w-0 flex-1">
<div className="truncate text-xs font-medium">{f.name}</div>
@@ -455,7 +557,10 @@ export function FolderShelf<F extends DeskFolder>({
className="group/f relative flex w-[92px] cursor-pointer flex-col items-start rounded-xl px-2 py-1.5 text-left transition-colors hover:bg-muted/60"
{...interact}
>
- <div className={cn("grid place-items-center transition-transform", isOver && "scale-105")}>
+ <div
+ className={cn("grid place-items-center transition-transform", isOver && "scale-105")}
+ data-drag-object
+ >
<FolderGlyph className={cn("size-[40px] drop-shadow-sm", isOver && "brightness-110")} />
</div>
<span className="mt-0.5 line-clamp-2 max-w-full text-xs font-medium leading-tight">
diff --git a/site/src/cut/lib/notes.ts b/site/src/cut/lib/notes.ts
index 48354973..b88afaa8 100644
--- a/site/src/cut/lib/notes.ts
+++ b/site/src/cut/lib/notes.ts
@@ -7,9 +7,9 @@
* version is newer (last writer wins). Deletes leave tombstones; the list is
* filtered here so the UI only ever sees live notes.
*
- * Notes file into folders, the same way the library's do. Folder ids are
- * client-generated so the phone can make one offline, and the one PUT both
- * creates and renames.
+ * Notes file into folders, the same way the library's do, and folders file
+ * into folders. Folder ids are client-generated so the phone can make one
+ * offline, and the one PUT creates, renames and moves.
*/
import { backendFor } from "./residency";
@@ -29,6 +29,8 @@ export interface CutNote {
export interface CutNoteFolder {
id: string;
name: string;
+ /** The folder this one is filed in; null is the top level. */
+ parentId: string | null;
updatedAt: number;
createdAt: number;
}
@@ -71,18 +73,55 @@ const json = (body: unknown): RequestInit => ({
});
/** Every live note, newest first, with the folders they file into. Tombstones
- * are the phone's concern; the desktop just drops them. */
+ * are the phone's concern; the desktop just drops them. A folder whose parent
+ * the listing does not name reads as top level, so nothing on screen hangs
+ * off a folder nobody can open. */
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: body.folders ?? [],
+ folders: folders.map((f) => ({
+ ...f,
+ parentId: f.parentId && known.has(f.parentId) ? f.parentId : null,
+ })),
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: {
@@ -108,18 +147,23 @@ export async function deleteNote(id: string): Promise<void> {
if (!res.ok) throw new Error("Could not delete the note.");
}
-/** Create or rename a folder under `id`. A create mints the id here so the
- * new folder is on screen before the write returns. */
-export async function saveNoteFolder(id: string, name: string): Promise<CutNoteFolder> {
+/** Create, rename or move a folder under `id`. A create mints the id here so
+ * the new folder is on screen before the write returns. The server answers
+ * with the folder as stored: a parent it could not honor reads back as the
+ * top level. */
+export async function saveNoteFolder(
+ id: string,
+ folder: { name: string; parentId: string | null },
+): Promise<CutNoteFolder> {
const res = await notesFetch(
`/api/cut/notes/folders/${encodeURIComponent(id)}`,
- json({ name }),
+ json(folder),
);
if (!res.ok) throw new Error("Could not save the folder.");
return (await res.json()) as CutNoteFolder;
}
-/** Delete a folder. Its notes come back to the top level. */
+/** Delete a folder. What it held comes up one level. */
export async function deleteNoteFolder(id: string): Promise<void> {
const res = await notesFetch(`/api/cut/notes/folders/${encodeURIComponent(id)}`, {
method: "DELETE",
diff --git a/site/src/cut/server/cloud/notes.ts b/site/src/cut/server/cloud/notes.ts
index 5b5b32f5..47e5a171 100644
--- a/site/src/cut/server/cloud/notes.ts
+++ b/site/src/cut/server/cloud/notes.ts
@@ -6,7 +6,8 @@
// Notes file into folders — CutFolder rows with scope "note", the same table
// the library and the projects home keep their folders in. Folder ids are
// client-generated like note ids, so a phone can make one offline and push it
-// under the id it already filed notes against.
+// under the id it already filed notes against. Folders file into folders the
+// same way, through `parentId`; the top level is null.
import { NOTE_LABELS_MAX } from "@/cut/lib/types";
import { prisma } from "@/lib/prisma";
import { caught, err } from "./util";
@@ -26,6 +27,7 @@ export interface NoteView {
export interface NoteFolderView {
id: string;
name: string;
+ parentId: string | null;
updatedAt: number;
createdAt: number;
}
@@ -62,11 +64,13 @@ const view = (row: {
const folderView = (row: {
id: string;
name: string;
+ parentId: string | null;
updatedAt: Date;
createdAt: Date;
}): NoteFolderView => ({
id: row.id,
name: row.name,
+ parentId: row.parentId,
updatedAt: row.updatedAt.getTime(),
createdAt: row.createdAt.getTime(),
});
@@ -99,6 +103,29 @@ 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;
+ 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;
+}
+
/** The labels a note may carry: the ids among `labelIds` that name one of
* this account's labels. An id naming nothing is dropped rather than failing
* the write — the label may have been deleted on the other device while this
@@ -208,38 +235,57 @@ export const notesCloud = {
// --- Folders (scope "note") ---
- /** Create or rename one folder under a client-chosen id. One call serves
- * both, so a phone that made the folder offline pushes it with the request
- * a rename uses. */
+ /** Create, rename or move one folder under a client-chosen id. One call
+ * serves all three, so a phone that made the folder offline pushes it with
+ * the request a rename uses. A write that says nothing about `parentId`
+ * keeps the parent the folder has; the response is the folder as stored,
+ * which is where a parent the server could not honor shows up. */
async putFolder(userId: string, id: string, req: Request) {
try {
if (!NOTE_ID.test(id)) return err("Invalid folder id.", 400);
- const body = (await req.json()) as { name?: string };
+ const body = (await req.json()) as { name?: string; parentId?: string | null };
const name = String(body.name ?? "").trim().slice(0, 120);
if (!name) return err("Folder name required.", 400);
const existing = await prisma.cutFolder.findFirst({
where: { id, userId, scope: "note" },
- select: { id: true },
+ select: { id: true, parentId: true },
});
+ const parentId =
+ body.parentId === undefined
+ ? (existing?.parentId ?? null)
+ : await resolveParent(userId, id, body.parentId);
if (!existing) {
- const row = await prisma.cutFolder.create({ data: { id, userId, name, scope: "note" } });
+ const row = await prisma.cutFolder.create({
+ data: { id, userId, name, parentId, scope: "note" },
+ });
return Response.json(folderView(row));
}
- const row = await prisma.cutFolder.update({ where: { id }, data: { name } });
+ const row = await prisma.cutFolder.update({ where: { id }, data: { name, parentId } });
return Response.json(folderView(row));
} catch (e) {
return caught(e, "Could not save the folder.");
}
},
- /** Delete one folder. Its notes fall back to the top level rather than
- * going with it. */
+ /** Delete one folder. What it held — its notes and the folders inside it —
+ * comes up one level, filed where the folder was. */
async removeFolder(userId: string, id: string) {
try {
await prisma.$transaction(async (tx) => {
- const { count } = await tx.cutFolder.deleteMany({ where: { id, userId, scope: "note" } });
- if (!count) return;
- await tx.cutNote.updateMany({ where: { userId, folderId: id }, data: { folderId: null } });
+ const gone = await tx.cutFolder.findFirst({
+ where: { id, userId, scope: "note" },
+ select: { parentId: true },
+ });
+ if (!gone) return;
+ await tx.cutFolder.delete({ where: { id } });
+ await tx.cutNote.updateMany({
+ where: { userId, folderId: id },
+ data: { folderId: gone.parentId },
+ });
+ await tx.cutFolder.updateMany({
+ where: { userId, scope: "note", parentId: id },
+ data: { parentId: gone.parentId },
+ });
});
return Response.json({ ok: true });
} catch (e) {