Open source CapCut alternative.
TypeScript
feat(site): notes file into folders and open as a full page [rebuild]
David Lebaeafe8c9a1f
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 88550633..13e383b0 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -78,7 +78,7 @@ Every client call goes through a backend seam (`site/src/cut/lib/backend/`): theThe library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up. Filing an item into a folder on another shelf crosses the same way — the bytes come down and go back up, a file with its cover and a template with its own media, and the copy left behind comes off.-The phone feeds the cloud shelf. Clips recorded in the iOS app upload themselves to it, marked as camera footage; that marker gives the desktop its Camera Roll — a tab of phone clips kept out of the main Library grid, and a locked Camera Roll folder in the editor's library panel so the footage drops into any project. Inspiration saved on the phone lands in an Inspiration folder on the same shelf, links riding the same worker import every shelf uses. Notes are the one thing that flows both ways: the phone and the desktop's Notes tab edit the same set, the newer edit winning, deletes carrying across. Every request from the app carries a client marker, the server remembers accounts it has seen it from, and only those accounts get the phone tabs — a desktop-only account's sidebar never changes. The app's own guide covers the phone side: [The iOS App](../ios-app.md).+The phone feeds the cloud shelf. Clips recorded in the iOS app upload themselves to it, marked as camera footage; that marker gives the desktop its Camera Roll — a tab of phone clips kept out of the main Library grid, and a locked Camera Roll folder in the editor's library panel so the footage drops into any project. Inspiration saved on the phone lands in an Inspiration folder on the same shelf, links riding the same worker import every shelf uses. Notes are the one thing that flows both ways: the phone and the desktop's Notes tab edit the same set, the newer edit winning, deletes carrying across. Notes file into folders of their own, on the shelf's folder table: the desktop files them by dragging onto the same folder tiles the Library uses, the phone by a folder list it opens like any other, and a folder made on either side is on the other by the next pass. Every request from the app carries a client marker, the server remembers accounts it has seen it from, and only those accounts get the phone tabs — a desktop-only account's sidebar never changes. The app's own guide covers the phone side: [The iOS App](../ios-app.md).Some of what the Library holds is lent. Most items are copied when they are used — a clip's bytes become the project's own — but a font is pointed at: every title set in it names it, and the file stays on the shelf where every project can reach it. Lent items follow three rules. They are identified by their bytes, so the same file on two shelves is one entry in the menu and one id in a document. A new one lands on the shelf every surface can read, whenever it is small and the account has room. And a project moving to the cloud takes what it points at with it, so a title keeps its typeface when it starts rendering there — since the id is the bytes, not a word of the document changes. Fonts are the first of these; a .ttf, .otf, .woff or .woff2 dropped on the Library is filed in folders, deleted, and counted against storage like anything else, and every project offers it for titles and captions. A font download arrives as a zip, so the zip is droppable: the faces come out of it and the licence text stays behind, and a family of eighteen weights becomes a single entry. The file is checked by installing it through the renderer's font seam before any bytes move, so what lands is what a preview and an export can draw with, and the family name comes off the font's own metadata. That same moment draws the specimen the shelf keeps as the file's cover, so a font card shows the alphabet in its own face whether or not the page looking at it has that face installed. A new account starts with an empty Fonts folder to say the shelf takes them; it is an ordinary folder and can be deleted. A render job reaches the cloud shelf alone, which is what those rules are for. A font filed into a folder belongs to that folder's shelf like anything else, and a full account keeps its font on the shelf it was working from: it draws in the tab, is marked in the font menu as living on this device, and falls back to the base face in a render job. A title set in a font that is later deleted falls back too, so nothing in a document has to be rewritten.diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismaindex 7768b396..b1970b1a 100644--- a/site/prisma/Cut.prisma+++ b/site/prisma/Cut.prisma@@ -60,7 +60,7 @@ model CutFolder {id String @id @default(cuid())userId Stringname String- scope String @default("project") // project | library+ scope String @default("project") // project | library | notecreatedAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -143,6 +143,8 @@ model CutNote {title String @default("")body String @default("")colorIndex Int @default(0)+ // The CutFolder (scope "note") this note is filed in; null is the top level.+ folderId String?updatedAt DateTimedeletedAt DateTime?createdAt DateTime @default(now())diff --git a/site/prisma/migrations/20260821124635/migration.sql b/site/prisma/migrations/20260821124635/migration.sqlnew file mode 100644index 00000000..bfbb7afb--- /dev/null+++ b/site/prisma/migrations/20260821124635/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "CutNote" ADD COLUMN "folderId" TEXT;diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex 38d377da..0c67cfd0 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -18,7 +18,7 @@ export const LIBRARY_TOOLS = [{name: "notes_list",description:- "List the user's synced notes — short scripts and ideas written in the Donkey Cut iOS app or the desktop Notes tab. Read them when the user points at \"my note(s)\" for a script, caption, or voiceover text; quote a note's body verbatim when they ask for its words.",+ "List the user's synced notes — short scripts and ideas written in the Donkey Cut iOS app or the desktop Notes tab — with the folders they are filed in. Read them when the user points at \"my note(s)\" for a script, caption, or voiceover text, and when they name a folder (\"the scripts folder\") match it against `folders` and read the notes carrying that folder. Quote a note's body verbatim when they ask for its words.",inputSchema: obj({}),},{diff --git a/site/src/cut/components/NoteComposer.tsx b/site/src/cut/components/NoteComposer.tsxnew file mode 100644index 00000000..9adbb70a--- /dev/null+++ b/site/src/cut/components/NoteComposer.tsx@@ -0,0 +1,174 @@+"use client";++import { useEffect, useRef } from "react";+import { ArrowLeft, Check, ChevronDown, Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { NOTE_COLORS, noteColor } from "@/cut/lib/notes";++// The note paper's ink, matching the iOS app.+const NOTE_INK = "#201a0d";++export interface NoteDraft {+ id: string;+ title: string;+ body: string;+ colorIndex: number;+ folderId: string | null;+ isNew: boolean;+ /** What the note held when it opened. A draft that still matches closes+ * without a write, so opening a note to read it leaves the list alone. */+ saved: { title: string; body: string; colorIndex: number };+}++/** True when the draft holds something the stored note does not. */+export const noteChanged = (d: NoteDraft) =>+ d.title.trim() !== d.saved.title ||+ d.body.trim() !== d.saved.body ||+ d.colorIndex !== d.saved.colorIndex;++/** A text box that grows with what is written, so the page scrolls as one+ * sheet of paper. */+function useAutoGrow(value: string) {+ const ref = useRef<HTMLTextAreaElement>(null);+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ el.style.height = "auto";+ el.style.height = `${el.scrollHeight}px`;+ }, [value]);+ return ref;+}++/** The note itself, filling the window: a page of paper with a title, a body+ * that runs as long as it needs to, and the paper's color on a menu. Closing+ * it — the back arrow, Done, or Escape — hands the draft back to be saved. */+export function NoteComposer({+ draft,+ onChange,+ onClose,+ onDelete,+}: {+ draft: NoteDraft;+ onChange: (draft: NoteDraft) => void;+ onClose: () => void;+ onDelete: () => void;+}) {+ const paper = noteColor(draft.colorIndex);+ const titleRef = useAutoGrow(draft.title);+ const bodyRef = useAutoGrow(draft.body);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape" || ((e.metaKey || e.ctrlKey) && e.key === "Enter")) {+ e.preventDefault();+ onClose();+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ return (+ <div+ className="flex min-h-full flex-col"+ style={{ backgroundColor: paper.background, color: NOTE_INK }}+ >+ <header+ className="sticky top-0 z-10 flex items-center gap-2 px-6 py-3"+ style={{ backgroundColor: paper.background }}+ >+ <Button+ variant="ghost"+ className="hover:bg-black/5 hover:text-current"+ style={{ color: NOTE_INK }}+ onClick={onClose}+ >+ <ArrowLeft data-icon="inline-start" /> All notes+ </Button>+ <div className="flex-1" />+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ aria-label="Note color"+ className="hover:bg-black/5 hover:text-current"+ style={{ color: NOTE_INK }}+ />+ }+ >+ <span+ className="size-3.5 rounded-full border border-black/10"+ style={{ backgroundColor: paper.accent }}+ />+ {paper.name}+ <ChevronDown className="size-3.5 opacity-60" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-40">+ {NOTE_COLORS.map((c, i) => (+ <DropdownMenuItem+ key={c.name}+ className="gap-2"+ onClick={() => onChange({ ...draft, colorIndex: i })}+ >+ <span+ className="size-3.5 rounded-full border border-black/10"+ style={{ backgroundColor: c.accent }}+ />+ <span className="flex-1">{c.name}</span>+ {i === draft.colorIndex && <Check className="size-4 opacity-70" />}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ {!draft.isNew && (+ <Button+ variant="ghost"+ aria-label="Delete note"+ className="text-destructive hover:bg-black/5 hover:text-destructive"+ onClick={onDelete}+ >+ <Trash2 data-icon="inline-start" /> Delete+ </Button>+ )}+ <Button className="bg-black/80 text-white hover:bg-black" onClick={onClose}>+ Done+ </Button>+ </header>++ <div className="mx-auto flex w-full max-w-3xl flex-1 flex-col gap-4 px-8 pt-6 pb-32">+ <textarea+ ref={titleRef}+ autoFocus+ rows={1}+ value={draft.title}+ placeholder="Untitled"+ className="resize-none overflow-hidden bg-transparent text-4xl leading-tight font-semibold tracking-tight outline-none placeholder:opacity-30"+ style={{ color: NOTE_INK }}+ onChange={(e) => onChange({ ...draft, title: e.target.value.replace(/\n/g, "") })}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ bodyRef.current?.focus();+ }+ }}+ />+ <textarea+ ref={bodyRef}+ rows={1}+ value={draft.body}+ placeholder="Write your note…"+ className="min-h-[50vh] flex-1 resize-none overflow-hidden bg-transparent text-lg leading-8 outline-none placeholder:opacity-40"+ style={{ color: NOTE_INK }}+ onChange={(e) => onChange({ ...draft, body: e.target.value })}+ />+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsxindex 4c2852ea..4562f303 100644--- a/site/src/cut/components/NotesView.tsx+++ b/site/src/cut/components/NotesView.tsx@@ -1,81 +1,120 @@"use client";-import { useState } from "react";+import { useEffect, useRef, useState } from "react";+import { useRouter, useSearchParams } from "next/navigation";import { useQueryClient } from "@tanstack/react-query";-import { Loader2, Plus, StickyNote, Trash2 } from "lucide-react";+import { FolderPlus, Loader2, Plus, StickyNote } from "lucide-react";import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";import {deleteNote,- NOTE_COLORS,+ deleteNoteFolder,noteColor,saveNote,+ saveNoteFolder,type CutNote,} from "@/cut/lib/notes";+import { homeHref, useCutBase } from "@/cut/lib/nav";import { notesKey, patchNotes, useNotes } from "@/cut/lib/queries";import { cn } from "@/lib/utils";+import { buildDragGhost, FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";+import { NoteComposer, noteChanged, type NoteDraft } from "./NoteComposer";// The note paper's ink, matching the iOS app.const NOTE_INK = "#201a0d";-interface Draft {- id: string;- title: string;- body: string;- colorIndex: number;- isNew: boolean;-}+// 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";/** 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. */+ * 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. */export function NotesView() {const client = useQueryClient();+ const router = useRouter();+ const base = useCutBase();const notes = useNotes();- const [draft, setDraft] = useState<Draft | null>(null);+ const [draft, setDraft] = useState<NoteDraft | null>(null);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [folderCreating, setFolderCreating] = useState(false);++ const list = notes.data?.notes ?? [];+ const folders = notes.data?.folders ?? [];+ // The open folder lives in the URL (?folder=…) so the browser's back button+ // steps folder → root and the location survives reloads.+ const openFolder = useSearchParams().get("folder");+ const openFolderName = folders.find((f) => f.id === openFolder)?.name;+ const shown = list.filter((n) => (n.folderId ?? null) === openFolder);++ const reload = () => void client.invalidateQueries({ queryKey: notesKey });+ const gotoFolder = (id: string | null) =>+ router.push(homeHref(base, "notes", id));const openNew = () =>- setDraft({ id: crypto.randomUUID(), title: "", body: "", colorIndex: 0, isNew: true });+ setDraft({+ id: crypto.randomUUID(),+ title: "",+ body: "",+ colorIndex: 0,+ // A note written inside a folder is filed there.+ folderId: openFolder,+ isNew: true,+ saved: { title: "", body: "", colorIndex: 0 },+ });const openNote = (n: CutNote) =>- setDraft({ id: n.id, title: n.title, body: n.body, colorIndex: n.colorIndex, isNew: false });+ setDraft({+ id: n.id,+ title: n.title,+ body: n.body,+ colorIndex: n.colorIndex,+ folderId: n.folderId ?? null,+ isNew: false,+ saved: { title: n.title, body: n.body, colorIndex: n.colorIndex },+ });- const commit = async () => {- if (!draft) return;- const { id, title, body, colorIndex } = draft;+ /** Save the draft and close the composer. A note that was only read closes+ * untouched, so the list keeps the order it had. */+ const commit = async (d: NoteDraft | null = draft) => {+ if (!d) return;+ const { id, title, body, colorIndex, folderId } = d;setDraft(null);if (!title.trim() && !body.trim()) return;+ if (!noteChanged(d)) return;const now = Date.now();const optimistic: CutNote = {id,title: title.trim() || "Untitled",body: body.trim(),colorIndex,+ folderId,updatedAt: now,deletedAt: null,createdAt: now,};patchNotes(client, (prev) => {- const rest = prev.filter((n) => n.id !== id);- const existing = prev.find((n) => n.id === id);- return [{ ...optimistic, createdAt: existing?.createdAt ?? now }, ...rest];+ const rest = prev.notes.filter((n) => n.id !== id);+ const existing = prev.notes.find((n) => n.id === id);+ return {+ ...prev,+ notes: [{ ...optimistic, createdAt: existing?.createdAt ?? now }, ...rest],+ };});const saved = await saveNote({id,title: optimistic.title,body: optimistic.body,colorIndex,+ folderId,}).catch(() => null);// The server answers with the winning version — this write, or a newer// one from the phone.- if (saved) patchNotes(client, (prev) => prev.map((n) => (n.id === id ? saved : n)));- else void client.invalidateQueries({ queryKey: notesKey });+ if (saved)+ patchNotes(client, (prev) => ({+ ...prev,+ notes: prev.notes.map((n) => (n.id === id ? saved : n)),+ }));+ else reload();};const remove = async () => {@@ -83,26 +122,149 @@ export function NotesView() {const { id, isNew } = draft;setDraft(null);if (isNew) return;- patchNotes(client, (prev) => prev.filter((n) => n.id !== id));- await deleteNote(id).catch(() => void client.invalidateQueries({ queryKey: notesKey }));+ patchNotes(client, (prev) => ({+ ...prev,+ notes: prev.notes.filter((n) => n.id !== id),+ }));+ await deleteNote(id).catch(() => reload());+ };++ /** File a set of notes into a folder (or back to the top level). Each note+ * is its own write, carrying its own last-writer-wins stamp. */+ const moveNotes = async (ids: string[], folderId: string | null) => {+ const moving = list.filter((n) => ids.includes(n.id));+ if (moving.length === 0) return;+ patchNotes(client, (prev) => ({+ ...prev,+ notes: prev.notes.map((n) => (ids.includes(n.id) ? { ...n, folderId } : n)),+ }));+ setSelected(new Set());+ await Promise.all(+ moving.map((n) =>+ saveNote({+ id: n.id,+ title: n.title,+ body: n.body,+ colorIndex: n.colorIndex,+ folderId,+ }).catch(() => reload()),+ ),+ );};- const list = notes.data ?? [];+ // Leaving the page (the sidebar, the back button) closes the composer the+ // same way its own Done does, so an open draft is never dropped.+ const closing = useRef<() => void>(() => {});+ useEffect(() => {+ closing.current = () => void commit(draft);+ });+ useEffect(() => () => closing.current(), []);++ // Carry the selection (or just this card) as a folder-move payload, with a+ // ghost for a multi-note drag.+ const onCardDragStart = (e: React.DragEvent, id: string) => {+ const ids = selected.has(id) && selected.size > 0 ? Array.from(selected) : [id];+ if (!selected.has(id)) setSelected(new Set([id]));+ e.dataTransfer.setData(NOTES_MOVE_MIME, JSON.stringify(ids));+ e.dataTransfer.effectAllowed = "move";+ if (ids.length > 1) {+ const ghost = buildDragGhost(ids.length, `${ids.length} notes`);+ document.body.appendChild(ghost);+ e.dataTransfer.setDragImage(ghost, 18, 16);+ setTimeout(() => ghost.remove(), 0);+ }+ };++ const hasContent = list.length > 0 || folders.length > 0;++ // The composer takes the whole page: one note, filling the window.+ if (draft)+ return (+ <NoteComposer+ draft={draft}+ onChange={setDraft}+ onClose={() => void commit()}+ onDelete={() => void remove()}+ />+ );return (<div className="mx-auto w-full max-w-6xl px-10 py-9"><div className="mb-5 flex items-center justify-between gap-4">- <h1 className="text-lg font-semibold tracking-tight">Notes</h1>- <Button onClick={openNew}>- <Plus data-icon="inline-start" /> New note- </Button>+ {openFolder === null ? (+ <h1 className="text-lg font-semibold tracking-tight">Notes</h1>+ ) : (+ <FolderCrumb+ root="Notes"+ name={openFolderName ?? "Folder"}+ mime={NOTES_MOVE_MIME}+ onBack={() => gotoFolder(null)}+ onDropOut={(ids) => void moveNotes(ids, null)}+ />+ )}+ <div className="flex items-center gap-2">+ {openFolder === null && (+ <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) ? (+ <FolderShelf+ folders={folders}+ mime={NOTES_MOVE_MIME}+ creating={folderCreating}+ onCreatingChange={setFolderCreating}+ statOf={(id) => ({+ count: list.filter((n) => (n.folderId ?? null) === id).length,+ })}+ onOpen={gotoFolder}+ onCreate={async (name) => {+ const folder = {+ id: crypto.randomUUID(),+ name,+ updatedAt: Date.now(),+ createdAt: Date.now(),+ };+ patchNotes(client, (prev) => ({+ ...prev,+ folders: [...prev.folders, folder],+ }));+ await saveNoteFolder(folder.id, name).catch(() => reload());+ }}+ onRename={async (id, name) => {+ patchNotes(client, (prev) => ({+ ...prev,+ folders: prev.folders.map((f) => (f.id === id ? { ...f, name } : f)),+ }));+ await saveNoteFolder(id, name).catch(() => reload());+ }}+ onDelete={async (id) => {+ patchNotes(client, (prev) => ({+ folders: prev.folders.filter((f) => f.id !== id),+ notes: prev.notes.map((n) =>+ n.folderId === id ? { ...n, folderId: null } : n,+ ),+ }));+ if (openFolder === id) router.replace(homeHref(base, "notes"));+ await deleteNoteFolder(id).catch(() => reload());+ }}+ onDropIds={(ids, folderId) => void moveNotes(ids, folderId)}+ />+ ) : null}+{!notes.data && notes.isPending ? (<div className="grid place-items-center py-24 text-muted-foreground"><Loader2 className="size-5 animate-spin" /></div>- ) : list.length === 0 ? (+ ) : !hasContent ? (<buttonclassName="grid w-full cursor-pointer place-items-center rounded-2xl py-24"onClick={openNew}@@ -117,11 +279,21 @@ export function NotesView() {</div></button>) : (- <div className="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-3">- {list.map((n) => (+ <Marquee+ className="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-3"+ selected={selected}+ setSelected={setSelected}+ >+ {shown.map((n) => (<buttonkey={n.id}- className="flex min-h-40 cursor-pointer flex-col gap-1.5 rounded-2xl p-4 text-left shadow-sm transition-transform hover:-translate-y-0.5"+ data-sel-id={n.id}+ draggable+ onDragStart={(e) => onCardDragStart(e, n.id)}+ className={cn(+ "flex min-h-40 cursor-pointer flex-col gap-1.5 rounded-2xl p-4 text-left shadow-sm transition-transform hover:-translate-y-0.5",+ selected.has(n.id) && "ring-2 ring-[#0a84ff]",+ )}style={{ backgroundColor: noteColor(n.colorIndex).background, color: NOTE_INK }}onClick={() => openNote(n)}>@@ -129,76 +301,8 @@ export function NotesView() {<div className="line-clamp-6 text-sm whitespace-pre-wrap opacity-80">{n.body}</div></button>))}- </div>+ </Marquee>)}-- <Dialog open={!!draft} onOpenChange={(o) => (o ? undefined : void commit())}>- <DialogContent- className="sm:max-w-lg"- style={- draft- ? { backgroundColor: noteColor(draft.colorIndex).background, color: NOTE_INK }- : undefined- }- >- <DialogHeader>- <DialogTitle className="sr-only">{draft?.isNew ? "New note" : "Edit note"}</DialogTitle>- </DialogHeader>- {draft && (- <div className="flex flex-col gap-3">- <Input- autoFocus- value={draft.title}- placeholder="Title"- className="border-none bg-transparent px-0 text-base font-semibold shadow-none focus-visible:ring-0 dark:bg-transparent"- style={{ color: NOTE_INK }}- onChange={(e) => setDraft({ ...draft, title: e.target.value })}- />- <textarea- value={draft.body}- placeholder="Write your note…"- rows={10}- className="resize-none bg-transparent text-sm outline-none placeholder:opacity-50"- style={{ color: NOTE_INK }}- onChange={(e) => setDraft({ ...draft, body: e.target.value })}- />- <DialogFooter className="flex-row items-center sm:justify-between">- <div className="flex items-center gap-1.5">- {NOTE_COLORS.map((c, i) => (- <button- key={c.background}- aria-label={`Note color ${i + 1}`}- className={cn(- "size-5 cursor-pointer rounded-full border",- draft.colorIndex === i ? "border-black/50" : "border-black/15"- )}- style={{ backgroundColor: c.accent }}- onClick={() => setDraft({ ...draft, colorIndex: i })}- />- ))}- </div>- <div className="flex items-center gap-2">- {!draft.isNew && (- <Button- variant="ghost"- className="text-destructive hover:bg-black/5 hover:text-destructive"- onClick={() => void remove()}- >- <Trash2 data-icon="inline-start" /> Delete- </Button>- )}- <Button- className="bg-black/80 text-white hover:bg-black"- onClick={() => void commit()}- >- Done- </Button>- </div>- </DialogFooter>- </div>- )}- </DialogContent>- </Dialog></div>);}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex c325cbba..0bbaecde 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -2426,12 +2426,15 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {},notes_list: async () => {- const notes = await fetchNotes();+ const { notes, folders } = await fetchNotes();+ const folderName = new Map(folders.map((f) => [f.id, f.name]));return {+ folders: folders.map((f) => ({ id: f.id, name: f.name })),notes: notes.map((n) => ({id: n.id,title: n.title,body: n.body,+ ...(n.folderId ? { folder: folderName.get(n.folderId) ?? n.folderId } : {}),updatedAt: new Date(n.updatedAt).toISOString(),})),};diff --git a/site/src/cut/lib/notes.ts b/site/src/cut/lib/notes.tsindex a10b4b95..b73a2665 100644--- a/site/src/cut/lib/notes.ts+++ b/site/src/cut/lib/notes.ts@@ -6,6 +6,10 @@* write carries its own `updatedAt` stamp and the server keeps whichever* 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.*/import { backendFor } from "./residency";@@ -15,19 +19,32 @@ export interface CutNote {title: string;body: string;colorIndex: number;+ folderId: string | null;updatedAt: number;deletedAt: number | null;createdAt: number;}+export interface CutNoteFolder {+ id: string;+ name: string;+ updatedAt: number;+ createdAt: number;+}++export interface NotesData {+ notes: CutNote[];+ folders: CutNoteFolder[];+}+/** The note paper palette, shared with the iOS app (NoteColor). Index into it* with `colorIndex`. */export const NOTE_COLORS = [- { background: "#faefb6", accent: "#f2c94c" }, // butter- { background: "#fbd8d4", accent: "#ef8b80" }, // blush- { background: "#d5e8fb", accent: "#7fb2ef" }, // sky- { background: "#d9f3d6", accent: "#82cf7a" }, // mint- { background: "#e6dcf7", accent: "#a988e0" }, // lilac+ { name: "Butter", background: "#faefb6", accent: "#f2c94c" },+ { name: "Blush", background: "#fbd8d4", accent: "#ef8b80" },+ { name: "Sky", background: "#d5e8fb", accent: "#7fb2ef" },+ { name: "Mint", background: "#d9f3d6", accent: "#82cf7a" },+ { name: "Lilac", background: "#e6dcf7", accent: "#a988e0" },] as const;export const noteColor = (index: number) =>@@ -36,13 +53,22 @@ export const noteColor = (index: number) =>const notesFetch = (path: string, init?: RequestInit) =>backendFor("cloud").fetch(path, init);-/** Every live note, newest first. Tombstones are the phone's concern; the- * desktop just drops them. */-export async function fetchNotes(): Promise<CutNote[]> {+const json = (body: unknown): RequestInit => ({+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+});++/** Every live note, newest first, with the folders they file into. Tombstones+ * are the phone's concern; the desktop just drops them. */+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 { notes?: CutNote[] };- return (body.notes ?? []).filter((n) => n.deletedAt === null);+ const body = (await res.json()) as Partial<NotesData>;+ return {+ notes: (body.notes ?? []).filter((n) => n.deletedAt === null),+ folders: body.folders ?? [],+ };}/** Write one note. The server answers with the winning version — this write,@@ -52,12 +78,12 @@ export async function saveNote(note: {title: string;body: string;colorIndex: number;+ folderId: string | null;}): Promise<CutNote> {- const res = await notesFetch(`/api/cut/notes/${encodeURIComponent(note.id)}`, {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...note, updatedAt: Date.now() }),- });+ const res = await notesFetch(+ `/api/cut/notes/${encodeURIComponent(note.id)}`,+ json({ ...note, updatedAt: Date.now() }),+ );if (!res.ok) throw new Error("Could not save the note.");return (await res.json()) as CutNote;}@@ -68,3 +94,22 @@ 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> {+ const res = await notesFetch(+ `/api/cut/notes/folders/${encodeURIComponent(id)}`,+ json({ name }),+ );+ 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. */+export async function deleteNoteFolder(id: string): Promise<void> {+ const res = await notesFetch(`/api/cut/notes/folders/${encodeURIComponent(id)}`, {+ method: "DELETE",+ });+ if (!res.ok) throw new Error("Could not delete the folder.");+}diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.tsindex c40b20a1..64d5e040 100644--- a/site/src/cut/lib/queries.ts+++ b/site/src/cut/lib/queries.ts@@ -24,7 +24,7 @@ import { cutMode } from "./backend";import { useCutMode } from "./backend/hooks";import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";import { fetchLibrary, type LibraryData } from "./library";-import { fetchNotes, type CutNote } from "./notes";+import { fetchNotes, type NotesData } from "./notes";import {availableResidencies,backendFor,@@ -215,18 +215,21 @@ export function usePhoneLink() {}export const notesKey = ["cut", "notes"] as const;-const NOTES_SNAPSHOT = "cut-notes";+// The snapshot carries the notes and their folders together; the key moved+// with that shape so a page holding the old array never paints from it.+const NOTES_SNAPSHOT = "cut-notes-v2";-/** The account's synced notes, phone and desktop edits merged server-side. */+/** The account's synced notes and their folders, phone and desktop edits+ * merged server-side. */export function useNotes() {const client = useQueryClient();- useEffect(() => seedFromSnapshot<CutNote[]>(client, notesKey, NOTES_SNAPSHOT), [client]);- return useQuery<CutNote[]>({+ useEffect(() => seedFromSnapshot<NotesData>(client, notesKey, NOTES_SNAPSHOT), [client]);+ return useQuery<NotesData>({queryKey: notesKey,queryFn: async () => {- const notes = await fetchNotes();- writeSnapshot(NOTES_SNAPSHOT, notes);- return notes;+ const data = await fetchNotes();+ writeSnapshot(NOTES_SNAPSHOT, data);+ return data;},staleTime: 0,refetchOnMount: "always",@@ -234,8 +237,8 @@ export function useNotes() {});}-/** Optimistic edit of the cached notes list, snapshot moving with it. */-export function patchNotes(client: QueryClient, fn: (prev: CutNote[]) => CutNote[]) {- const next = client.setQueryData<CutNote[]>(notesKey, (prev) => (prev ? fn(prev) : prev));+/** Optimistic edit of the cached notes, snapshot moving with it. */+export function patchNotes(client: QueryClient, fn: (prev: NotesData) => NotesData) {+ const next = client.setQueryData<NotesData>(notesKey, (prev) => (prev ? fn(prev) : prev));if (next) writeSnapshot(NOTES_SNAPSHOT, next);}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 5b7319ed..0c218e99 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -348,7 +348,7 @@ Project media (\`media\` in editor_state) is every file in the open project. TheThe Library is shared across every project: folders, reusable assets, and templates — a template is a saved arrangement (clips, overlays, titles, captions, by reference) that comes back editable.- 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.-- notes_list reads the user's synced notes (written on their phone or the Notes tab) — the place to look when they point at "my note" for a script, caption, or voiceover text.+- notes_list reads the user's synced notes (written on their phone or the Notes tab) and the folders they are filed in — the place to look when they point at "my note" or name a folder for a script, caption, or voiceover text.- library_organize handles folders (create/rename/delete), 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. 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/notes.ts b/site/src/cut/server/cloud/notes.tsindex aa75cf06..04e2a0bf 100644--- a/site/src/cut/server/cloud/notes.ts+++ b/site/src/cut/server/cloud/notes.ts@@ -2,6 +2,11 @@// desktop Notes tab. Both sides merge by last-writer-wins on the client's// `updatedAt` stamp, and deletes keep tombstone rows so a removal made// offline on one device still lands on the other.+//+// 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.import { prisma } from "@/lib/prisma";import { caught, err } from "./util";@@ -10,16 +15,25 @@ export interface NoteView {title: string;body: string;colorIndex: number;+ folderId: string | null;updatedAt: number;deletedAt: number | null;createdAt: number;}+export interface NoteFolderView {+ id: string;+ name: string;+ updatedAt: number;+ createdAt: number;+}+const view = (row: {id: string;title: string;body: string;colorIndex: number;+ folderId: string | null;updatedAt: Date;deletedAt: Date | null;createdAt: Date;@@ -28,23 +42,53 @@ const view = (row: {title: row.title,body: row.body,colorIndex: row.colorIndex,+ folderId: row.folderId,updatedAt: row.updatedAt.getTime(),deletedAt: row.deletedAt?.getTime() ?? null,createdAt: row.createdAt.getTime(),});+const folderView = (row: {+ id: string;+ name: string;+ updatedAt: Date;+ createdAt: Date;+}): NoteFolderView => ({+ id: row.id,+ name: row.name,+ updatedAt: row.updatedAt.getTime(),+ createdAt: row.createdAt.getTime(),+});+const NOTE_ID = /^[\w-]{1,64}$/;const TEXT_MAX = 20_000;+/** The folder a note may be filed in: one of this account's note folders, or+ * the top level. An id naming nothing files the note at the top level rather+ * than failing the write — the folder may have been deleted on the other+ * device while this one was offline. */+async function resolveFolder(userId: string, folderId: unknown): Promise<string | null> {+ if (typeof folderId !== "string" || !folderId) return null;+ const row = await prisma.cutFolder.findFirst({+ where: { id: folderId, userId, scope: "note" },+ select: { id: true },+ });+ return row?.id ?? null;+}+export const notesCloud = {- /** Every note including tombstones, newest first. Notes are small and the- * set is one person's, so the merge reads the whole list. */+ /** Every note including tombstones, newest first, and the folders they file+ * into. Notes are small and the set is one person's, so the merge reads the+ * whole list. */async list(userId: string) {- const rows = await prisma.cutNote.findMany({- where: { userId },- orderBy: { updatedAt: "desc" },- });- return Response.json({ notes: rows.map(view) });+ const [rows, folders] = await Promise.all([+ prisma.cutNote.findMany({ where: { userId }, orderBy: { updatedAt: "desc" } }),+ prisma.cutFolder.findMany({+ where: { userId, scope: "note" },+ orderBy: { createdAt: "asc" },+ }),+ ]);+ return Response.json({ notes: rows.map(view), folders: folders.map(folderView) });},/** Upsert one note. The write applies only when its stamp is not older than@@ -57,6 +101,7 @@ export const notesCloud = {title?: string;body?: string;colorIndex?: number;+ folderId?: string | null;updatedAt?: number;};if (typeof body.updatedAt !== "number" || !Number.isFinite(body.updatedAt)) {@@ -67,6 +112,7 @@ export const notesCloud = {title: String(body.title ?? "").slice(0, 200),body: String(body.body ?? "").slice(0, TEXT_MAX),colorIndex: Number.isInteger(body.colorIndex) ? (body.colorIndex as number) : 0,+ folderId: await resolveFolder(userId, body.folderId),updatedAt: stamp,deletedAt: null,};@@ -100,4 +146,45 @@ export const notesCloud = {return caught(e, "Could not delete the note.");}},++ // --- 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. */+ 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 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 },+ });+ if (!existing) {+ const row = await prisma.cutFolder.create({ data: { id, userId, name, scope: "note" } });+ return Response.json(folderView(row));+ }+ const row = await prisma.cutFolder.update({ where: { id }, data: { name } });+ 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. */+ 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 } });+ });+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete the folder.");+ }+ },};diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 528ac10e..09c7fd3a 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -99,6 +99,8 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "POST", path: "/api/cut-cloud/turns/:jobId/cancel", handler: (_r, u, p) => turnsCloud.cancel(u, p.jobId) },{ method: "GET", path: "/api/cut-cloud/notes", handler: (_r, u) => notesCloud.list(u) },+ { method: "PUT", path: "/api/cut-cloud/notes/folders/:id", handler: (r, u, p) => notesCloud.putFolder(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/notes/folders/:id", handler: (_r, u, p) => notesCloud.removeFolder(u, p.id) },{ method: "PUT", path: "/api/cut-cloud/notes/:id", handler: (r, u, p) => notesCloud.put(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/notes/:id", handler: (_r, u, p) => notesCloud.remove(u, p.id) },{ method: "GET", path: "/api/cut-cloud/phone", handler: (_r, u) => phoneApi.get(u) },