Open source CapCut alternative.
TypeScript
feat: deleting a folder deletes the notes inside it
David Le999e461820cd
diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swiftindex c5cc739a..5fafb2b4 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift@@ -321,33 +321,36 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoritry context.save()}+ /// Delete a folder and everything under it: the folders filed inside,+ /// however deep, and every note they hold. The cloud deletes the same+ /// tree off the folder's own tombstone; each note leaves one too, so a+ /// note that moved there offline still goes.public func deleteNoteFolder(id: UUID) throws {- let parentId = try noteFolderParent(id)- try context.delete(model: NoteFolderRecord.self, where: #Predicate { $0.id == id })- // What the folder held stays and comes up one level. Each note is a- // write of its own so the cloud files it there too, and so is each- // folder.- let notes = FetchDescriptor<NoteRecord>(predicate: #Predicate { $0.folderId == id })- for record in try context.fetch(notes) {- record.folderId = parentId- record.updatedAt = .now- record.dirty = true+ let tree = try noteFolderTree(id)+ for record in try context.fetch(FetchDescriptor<NoteFolderRecord>()) where tree.contains(record.id) {+ context.delete(record)}- let folders = FetchDescriptor<NoteFolderRecord>(predicate: #Predicate { $0.parentId == id })- for record in try context.fetch(folders) {- record.parentId = parentId- record.updatedAt = .now- record.dirty = true+ for record in try context.fetch(FetchDescriptor<NoteRecord>()) {+ guard let folderId = record.folderId, tree.contains(folderId) else { continue }+ context.insert(TombstoneRecord(kind: SyncTombstone.Kind.note.rawValue, remoteId: record.id.uuidString, stamp: .now))+ context.delete(record)}context.insert(TombstoneRecord(kind: SyncTombstone.Kind.noteFolder.rawValue, remoteId: id.uuidString, stamp: .now))try context.save()}- /// Where a folder is filed, read before it goes so what it held can- /// follow.- private func noteFolderParent(_ id: UUID) throws -> UUID? {- let descriptor = FetchDescriptor<NoteFolderRecord>(predicate: #Predicate { $0.id == id })- return try context.fetch(descriptor).first?.parentId+ /// A folder and every folder filed under it, however deep.+ private func noteFolderTree(_ id: UUID) throws -> Set<UUID> {+ let folders = try context.fetch(FetchDescriptor<NoteFolderRecord>())+ var tree: Set<UUID> = [id]+ var frontier = [id]+ while let next = frontier.popLast() {+ for folder in folders where folder.parentId == next && !tree.contains(folder.id) {+ tree.insert(folder.id)+ frontier.append(folder.id)+ }+ }+ return tree}public func loadNoteLabels() throws -> [NoteLabel] {@@ -540,18 +543,11 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStori}public func removeNoteFolderFromCloudDelete(id: UUID) throws {- // The cloud filed what the folder held one level up; the listing- // already carried the folders, and the notes follow here.- let parentId = try noteFolderParent(id)+ // The cloud deleted everything under the folder too: the folders+ // inside leave the listing the same way, and the notes come down as+ // tombstones. A note edited here since keeps its edit, at the top+ // level.try context.delete(model: NoteFolderRecord.self, where: #Predicate { $0.id == id })- let notes = FetchDescriptor<NoteRecord>(predicate: #Predicate { $0.folderId == id })- for record in try context.fetch(notes) where record.dirty != true {- record.folderId = parentId- }- let folders = FetchDescriptor<NoteFolderRecord>(predicate: #Predicate { $0.parentId == id })- for record in try context.fetch(folders) {- record.parentId = parentId- }try context.save()}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swiftindex 14a87308..b123469b 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift@@ -449,7 +449,7 @@ public final class IdeasModel {onLocalChange?()}- /// Delete a folder. What it held comes up one level.+ /// Delete a folder and everything under it: its folders and their notes.public func deleteFolder(id: UUID) {try? store.deleteNoteFolder(id: id)reloadFromStore()diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swiftindex 53cb2bdb..63ca3020 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift@@ -357,6 +357,9 @@ struct FolderList: View {/// The row a drag is held over.@State private var targeted: UUID?+ /// A folder holding anything asks before it goes, since everything under+ /// it goes with it.+ @State private var deleting: NoteFolder?var body: some View {if !folders.isEmpty {@@ -393,7 +396,11 @@ struct FolderList: View {onMove(NotesDragItem(kind: .folder, id: folder.id))}Button("Delete", systemImage: "trash", role: .destructive) {- onDelete(folder)+ if ideas.notes(in: folder.id).isEmpty && ideas.folders(in: folder.id).isEmpty {+ onDelete(folder)+ } else {+ deleting = folder+ }}}if folder.id != folders.last?.id {@@ -403,6 +410,16 @@ struct FolderList: View {}.padding(.horizontal, 14).background(.fill.quaternary, in: RoundedRectangle(cornerRadius: 16))+ .alert(+ "Delete “\(deleting?.name ?? "")”?",+ isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }),+ presenting: deleting+ ) { folder in+ Button("Delete", role: .destructive) { onDelete(folder) }+ Button("Cancel", role: .cancel) {}+ } message: { _ in+ Text("Everything inside the folder goes with it, here and in Donkey Cut.")+ }}}}diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swiftindex 8bbd12f8..a1b02c5a 100644--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift@@ -388,16 +388,24 @@ import Testingfolders[folder.id] = stored}- /// What the folder held comes up one level, the way the site files it.+ /// The folder goes with everything under it, the way the site deletes it.func deleteNoteFolder(id: UUID) async throws {deletedFolders.append(id)- let parent = folders[id]?.parentId- folders[id] = nil- for (noteId, note) in notes where note.folderId == id {- notes[noteId]?.folderId = parent+ var tree: Set<UUID> = [id]+ var grew = true+ while grew {+ grew = false+ for (folderId, folder) in folders where !tree.contains(folderId) {+ if let parent = folder.parentId, tree.contains(parent) {+ tree.insert(folderId)+ grew = true+ }+ }}- for (folderId, folder) in folders where folder.parentId == id {- folders[folderId]?.parentId = parent+ for folderId in tree { folders[folderId] = nil }+ for (noteId, note) in notes where note.folderId.map(tree.contains) == true {+ notes[noteId]?.deletedAt = .now+ notes[noteId]?.updatedAt = .now}}@@ -717,23 +725,6 @@ import Testing#expect(rig.cloud.notes[note.id]?.folderId == folder.id)}- @Test func folderDeletedInTheCloudReleasesItsNotes() async throws {- let rig = try makeRig()- let folder = try #require(rig.ideas.addFolder(named: "Scripts"))- rig.ideas.openEditor(in: folder.id)- rig.ideas.draft?.body = "filed"- let note = try #require(rig.ideas.saveDraft())- await rig.engine.run()- // Gone from the desktop: the listing no longer names it, which is the- // only signal a folder delete has.- rig.cloud.folders[folder.id] = nil- rig.cloud.notes[note.id]?.folderId = nil- rig.cloud.notes[note.id]?.updatedAt = note.updatedAt.addingTimeInterval(30)- await rig.engine.run()- #expect(rig.ideas.folders.isEmpty)- #expect(rig.ideas.notes(in: nil).count == 1)- }-@Test func aListingWithoutFoldersKeepsTheOnesHere() async throws {let rig = try makeRig()let folder = try #require(rig.ideas.addFolder(named: "Scripts"))@@ -785,7 +776,7 @@ import Testing#expect(rig.ideas.folderTree(excluding: parent.id).isEmpty)}- @Test func deletingAFolderLiftsWhatItHeld() async throws {+ @Test func deletingAFolderTakesWhatItHeld() async throws {let rig = try makeRig()let parent = try #require(rig.ideas.addFolder(named: "Scripts"))let child = try #require(rig.ideas.addFolder(named: "Drafts", in: parent.id))@@ -795,15 +786,19 @@ import Testinglet note = try #require(rig.ideas.saveDraft())await rig.engine.run()rig.ideas.deleteFolder(id: child.id)- #expect(rig.ideas.folder(grandchild.id)?.parentId == parent.id)- #expect(rig.ideas.notes(in: parent.id).map(\.id) == [note.id])+ #expect(rig.ideas.folder(child.id) == nil)+ #expect(rig.ideas.folder(grandchild.id) == nil)+ #expect(rig.ideas.folder(parent.id) != nil)+ #expect(rig.ideas.notes.isEmpty)await rig.engine.run()#expect(rig.cloud.deletedFolders == [child.id])- #expect(rig.cloud.folders[grandchild.id]?.parentId == parent.id)- #expect(rig.cloud.notes[note.id]?.folderId == parent.id)+ #expect(rig.cloud.deletedNotes == [note.id])+ #expect(rig.cloud.folders[grandchild.id] == nil)+ #expect(rig.ideas.notes.isEmpty)+ #expect(try rig.store.tombstones().isEmpty)}- @Test func folderDeletedInTheCloudLiftsWhatItHeldHere() async throws {+ @Test func folderDeletedInTheCloudTakesWhatItHeldHere() async throws {let rig = try makeRig()let parent = try #require(rig.ideas.addFolder(named: "Scripts"))let child = try #require(rig.ideas.addFolder(named: "Drafts", in: parent.id))@@ -812,13 +807,14 @@ import Testingrig.ideas.draft?.body = "filed"let note = try #require(rig.ideas.saveDraft())await rig.engine.run()- // Deleted at the desk: the listing no longer names it, and what it- // held is filed a level up there. The notes keep their stamps.+ // Deleted at the desk: the listing no longer names it or the folders+ // inside, and its notes come down as tombstones.try await rig.cloud.deleteNoteFolder(id: child.id)await rig.engine.run()#expect(rig.ideas.folder(child.id) == nil)- #expect(rig.ideas.folder(grandchild.id)?.parentId == parent.id)- #expect(rig.ideas.notes(in: parent.id).map(\.id) == [note.id])+ #expect(rig.ideas.folder(grandchild.id) == nil)+ #expect(rig.ideas.folder(parent.id) != nil)+ #expect(!rig.ideas.notes.contains { $0.id == note.id })}@Test func labelPushesAheadOfTheNoteWearingIt() async throws {diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.mdindex 4d8dc516..0e03a4ee 100644--- a/docs/guides/ios-app.md+++ b/docs/guides/ios-app.md@@ -49,7 +49,7 @@ as it lands — so a reel stands tall beside a landscape clip, and the griddeals cards into whichever of its two columns is shorter. A card always says where its link stands: waiting to be handed over,fetching, or failed with the reason and a way to try again. Every attempt thatfails writes that reason on the item, so a card can never spin on a request-nothing is making any more. Notes merge by edit stamp; tombstones carry offline deletions. Folder ids come from the creating device, parents sync first, and deleting a folder moves its contents up one level. Labels travel with each note; deleted labels disappear everywhere, and writes above twenty labels fail.+nothing is making any more. Notes merge by edit stamp; tombstones carry offline deletions. Folder ids come from the creating device, parents sync first, and deleting a folder deletes everything in it. Labels travel with each note; deleted labels disappear everywhere, and writes above twenty labels fail.The desktop Library creates notes through its context menu and existing note editor; notes stay cloud-synced, with Library placement stored independently of phone folders and preserved when a phone edits their text.diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex 8014d381..26eb1e25 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -87,7 +87,7 @@ export const LIBRARY_TOOLS = [{name: "library_organize",description:- "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 deletes one with everything in it — its folders and every item they hold — permanently; a camera clip filed there stays in Camera Roll, and an inspiration item in it leaves the phone too. 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 deletes one with everything in it — its folders and every item and note they hold — permanently; a camera clip filed there stays in Camera Roll, and an inspiration item in it leaves the phone too. 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",diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 56dd3d53..732828cf 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -370,10 +370,18 @@ export function LibraryView() {return () => window.removeEventListener("paste", onPaste);}, []);+ // The notes filed in a set of Library folders, which a delete of those+ // folders takes with it.+ const notesIn = (tree: Set<string>) =>+ (notes.data?.notes ?? []).filter((n) => {+ const at = n.libraryLocation;+ return !!at?.folderId && tree.has(at.folderId) &&+ folders.find((f) => f.id === at.folderId)?.residency === at.residency;+ });// Delete a set. A folder takes everything under it — the folders filed- // there, however deep, and every item they hold — the way the shelf deletes- // it; an item filed in one of those needs no delete of its own. A camera- // clip filed there stays in Camera Roll, unfiled.+ // there, however deep, and every item and note they hold — the way the+ // shelf deletes it; an item filed in one of those needs no delete of its+ // own. A camera clip filed there stays in Camera Roll, unfiled.const remove = async (set: DeleteSet) => {setDeleting(null);// A shelf that isn't answering keeps its items.@@ -392,6 +400,9 @@ export function LibraryView() {.map((a) => (inTree(a) ? { ...a, folderId: null } : a)),templates: d.templates.filter((t) => !gone.has(t.id)),}));+ const goneNotes = new Set(notesIn(takes.tree).map((n) => n.id));+ if (goneNotes.size)+ patchNotes(client, (d) => ({ ...d, notes: d.notes.filter((n) => !goneNotes.has(n.id)) }));setSelected(new Set());try {await Promise.all([@@ -400,16 +411,18 @@ export function LibraryView() {),...goneFolders.map((f) => deleteLibraryFolder(f.residency, f.id)),]);- if (goneFolders.length) void client.invalidateQueries({ queryKey: notesKey });} catch {void reload();+ } finally {+ // Notes the delete took, or the ones a failed delete left in place.+ if (goneFolders.length) void client.invalidateQueries({ queryKey: notesKey });}};// How many items the folders hold between them, however deep — what the// confirm counts beside them.const heldBy = (fs: LibraryFolder[]) => {const takes = folderDeleteTakes(listing, fs);- return takes.assets.length + takes.templates.length;+ return takes.assets.length + takes.templates.length + notesIn(takes.tree).length;};// How many of the items a delete takes were synced from the phone, which// takes them off the phone too.@@ -982,7 +995,7 @@ export function LibraryView() {title={deleting ? `Delete ${pickLabel(deleting.folders, deleting.items, ["item", "items"], deletingHeld)}?` : ""}- description={`${deleting?.folders.length ? "Notes return to the Library root. " : ""}${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}Projects that already use ${deletingTotal === 1 ? "it" : "them"} keep their own copy.`}+ description={`${foldersGoNote(deleting?.folders.length ?? 0, deletingHeld)}${phoneGoNote(deleting ? phoneSynced(deleting) : 0, deletingTotal)}Projects that already use ${deletingTotal === 1 ? "it" : "them"} keep their own copy.`}action="Remove"onClose={() => setDeleting(null)}onConfirm={() => deleting && void remove(deleting)}diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsxindex 058cd560..bc283230 100644--- a/site/src/cut/components/NotesView.tsx+++ b/site/src/cut/components/NotesView.tsx@@ -18,6 +18,7 @@ import {saveNote,saveNoteFolder,saveNoteLabel,+ subtreeOf,type CutNote,type CutNoteFolder,} from "@/cut/lib/notes";@@ -27,6 +28,7 @@ import { cn } from "@/lib/utils";import { setObjectDragImage } from "@/cut/lib/assetDrag";import { PICKED_RING } from "@/cut/lib/assetPick";import { FolderCrumb, FolderShelf, Marquee } from "./desktopFolders";+import { DeleteConfirm, foldersGoNote } from "./selectionMenu";import { LIBRARY_SQUARE } from "./LibraryCard";import { NoteComposer, noteChanged, type NoteDraft } from "./NoteComposer";@@ -147,11 +149,29 @@ export function NotesView({ library, ref }: Props = {}) {};const [selected, setSelected] = useState<Set<string>>(new Set());const [folderCreating, setFolderCreating] = useState(false);+ const [deletingFolder, setDeletingFolder] = useState<string | null>(null);const list = notes.data?.notes ?? [];const folders = notes.data?.folders ?? [];const labels = notes.data?.labels ?? [];const labelName = new Map(labels.map((l) => [l.id, l.name]));+ // What deleting a folder takes: the folders under it, however deep, and+ // every note they hold, the way the server deletes it.+ const folderTakes = (id: string) => {+ const tree = new Set(subtreeOf(folders, id));+ const notes = list.filter((n) => !!n.folderId && tree.has(n.folderId));+ return { tree, notes, held: tree.size - 1 + notes.length };+ };+ const removeFolder = async (id: string) => {+ const { tree } = folderTakes(id);+ patchNotes(client, (prev) => ({+ ...prev,+ folders: prev.folders.filter((f) => !tree.has(f.id)),+ notes: prev.notes.filter((n) => !n.folderId || !tree.has(n.folderId)),+ }));+ await settleFolder(id);+ await deleteNoteFolder(id).catch(() => reload());+ };// The open folder and the open note both live in the URL (?folder=…¬e=…),// so the browser's back button — the mouse's too — steps out of the note and// then out of the folder, and the location survives a reload.@@ -560,21 +580,11 @@ export function NotesView({ library, ref }: Props = {}) {}}}onRename={renameFolder}- 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)- .map((f) => (f.parentId === id ? { ...f, parentId } : f)),- notes: prev.notes.map((n) =>- n.folderId === id ? { ...n, folderId: parentId } : n,- ),- }));- await settleFolder(id);- await deleteNoteFolder(id).catch(() => reload());+ // An empty folder goes at once; one holding anything asks first,+ // since everything under it goes with it.+ onDelete={(id) => {+ if (folderTakes(id).held > 0) setDeletingFolder(id);+ else void removeFolder(id);}}onDropIds={(ids, folderId) => void moveNotes(ids, folderId)}onDropFolders={(ids, folderId) => void moveFolders(ids, folderId)}@@ -654,6 +664,17 @@ export function NotesView({ library, ref }: Props = {}) {})}</Marquee>)}+ <DeleteConfirm+ open={deletingFolder !== null}+ title={`Delete “${folders.find((f) => f.id === deletingFolder)?.name ?? "folder"}”?`}+ description={`${foldersGoNote(1, deletingFolder ? folderTakes(deletingFolder).held : 0)}It is removed from your phone too.`}+ onClose={() => setDeletingFolder(null)}+ onConfirm={() => {+ const id = deletingFolder;+ setDeletingFolder(null);+ if (id) void removeFolder(id);+ }}+ /></div>);}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 38acc0c4..b7366e7e 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -125,6 +125,7 @@ import {} from "./library";import { forgetLinkedCopies } from "./linkedLibrary";import { fetchNotes } from "./notes";+import { noteInLibraryFolder } from "./noteReference";import {captureFreezeFrame,beatlessFor,@@ -3979,14 +3980,18 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {const r = folderShelf(id);if (!r) throw new ToolError(`No library folder with id ${id}.`);const takes = folderDeleteTakes(lib, [{ id }]);+ const notes = (await fetchNotes()).notes.filter((n) =>+ [...takes.tree].some((f) => noteInLibraryFolder(n, f, r)),+ ).length;forgetLinkedCopies(takes.assets);await deleteLibraryFolder(r, id);const phone = takes.assets.filter((a) => !!a.origin).length;return {deleted: true,items: takes.assets.length + takes.templates.length,+ ...(notes > 0 ? { notes } : {}),...(phone > 0 ? { removedFromPhone: phone } : {}),- note: "Everything in it — folders and items — was deleted too. A camera clip filed there stays in Camera Roll.",+ note: "Everything in it — folders, items and notes — was deleted too. A camera clip filed there stays in Camera Roll.",};}case "move_asset": {diff --git a/site/src/cut/lib/folderTree.ts b/site/src/cut/lib/folderTree.tsindex 378f4d55..cac000d0 100644--- a/site/src/cut/lib/folderTree.ts+++ b/site/src/cut/lib/folderTree.ts@@ -3,9 +3,7 @@* 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, a deleted folder takes everything under it with it, and- * a parent nothing answers for reads as the top level. Note folders are the- * exception on deletes: what they held comes up one level, the way the phone- * files it.+ * a parent nothing answers for reads as the top level.*/export interface TreeFolder {diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 558d0df4..a8133a69 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -512,17 +512,18 @@ export function folderDeleteTakes(};}-/** Delete a folder and everything in it, folders and items alike. */+/** Delete a folder and everything in it: folders, items and the notes filed+ * there. The cloud shelf takes its notes itself; on the others the notes go+ * once the folder has, so a delete that fails leaves them in place. */export async function deleteLibraryFolder(residency: Residency,id: string,): Promise<void> {+ let tree: string[] = [];if (residency !== "cloud") {const listing = await backendFor(residency).fetch("/api/cut/library");if (!listing.ok) throw new Error("Could not read the folder.");- const data = await listing.json() as LibraryData;- const { unfileLibraryNotes } = await import("@/cut/lib/notes");- await unfileLibraryNotes(residency, subtreeOf(data.folders, id));+ tree = subtreeOf((await listing.json() as LibraryData).folders, id);}const res = await backendFor(residency).fetch(`/api/cut/library/folders/${id}`,@@ -531,6 +532,10 @@ export async function deleteLibraryFolder(},);if (!res.ok) throw new Error("Could not delete folder.");+ if (residency !== "cloud") {+ const { deleteLibraryFolderNotes } = await import("@/cut/lib/notes");+ await deleteLibraryFolderNotes(residency, tree);+ }}/** File a library item — an asset or a template — into a folder on its owndiff --git a/site/src/cut/lib/noteReference.ts b/site/src/cut/lib/noteReference.tsindex 33b6fe15..9c1bd359 100644--- a/site/src/cut/lib/noteReference.ts+++ b/site/src/cut/lib/noteReference.ts@@ -15,7 +15,7 @@ export function noteInLibraryFolder(note: Pick<CutNote, "libraryLocation">, foldconst location = note.libraryLocation;return !!location && location.folderId === folderId && (!residency || location.residency === residency);}-export const noteUnfileSchema = z.object({ residency: z.enum(["browser", "local", "cloud"]), folderIds: z.array(z.string().min(1).max(128)).max(10000) });+export const noteLibraryFoldersSchema = z.object({ residency: z.enum(["browser", "local", "cloud"]), folderIds: z.array(z.string().min(1).max(128)).max(10000) });export const noteReadSchema = z.object({ id: noteIdSchema.optional(), link: z.string().optional() });export const noteSaveSchema = z.object({id: noteIdSchema.optional().describe("Existing note id; omit to create a note"),diff --git a/site/src/cut/lib/notes.ts b/site/src/cut/lib/notes.tsindex fe80db1c..84d7b767 100644--- a/site/src/cut/lib/notes.ts+++ b/site/src/cut/lib/notes.ts@@ -16,7 +16,7 @@ import { noteReadSchema, noteSaveSchema, parseNoteLink, type NoteLocation } fromimport { settleParents } from "./folderTree";import { backendFor } from "./residency";-export { folderTrail, folderWithin } from "./folderTree";+export { folderTrail, folderWithin, subtreeOf } from "./folderTree";export interface CutNote {libraryLocation?: NoteLocation | null;@@ -153,12 +153,17 @@ export async function saveNoteFolder(return (await res.json()) as CutNoteFolder;}-export async function unfileLibraryNotes(residency: "browser" | "local", folderIds: string[]): Promise<void> {- const res = await notesFetch("/api/cut/notes/library-location", json({ residency, folderIds }));- if (!res.ok) throw new Error("Could not move the folder’s notes to the Library root.");+/** Delete the notes filed in Library folders on a shelf that keeps no notes+ * of its own — what deleting those folders takes. */+export async function deleteLibraryFolderNotes(residency: "browser" | "local", folderIds: string[]): Promise<void> {+ const res = await notesFetch("/api/cut/notes/library-folders/delete", {+ ...json({ residency, folderIds }),+ method: "POST",+ });+ if (!res.ok) throw new Error("Could not delete the folder’s notes.");}-/** Delete a folder. What it held comes up one level. */+/** Delete a folder and everything under it: its folders and their notes. */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/library.ts b/site/src/cut/server/cloud/library.tsindex 543ed471..e70fe9fe 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -833,7 +833,7 @@ export const libraryCloud = {const folderId = (t.doc as unknown as TemplateDoc).folderId;if (folderId && tree.includes(folderId)) await deleteTemplateCascade(userId, t);}- await notesCloud.unfileLibraryFolders(userId, "cloud", tree);+ await notesCloud.deleteLibraryFolderNotes(userId, "cloud", tree);await prisma.cutFolder.deleteMany({where: { userId, scope: "library", id: { in: tree } },});diff --git a/site/src/cut/server/cloud/notes.test.ts b/site/src/cut/server/cloud/notes.test.tsindex 2568ecaf..17d6c37b 100644--- a/site/src/cut/server/cloud/notes.test.ts+++ b/site/src/cut/server/cloud/notes.test.ts@@ -11,10 +11,15 @@ function harness() {update: mock(async (args: unknown) => { void args; return row; }), create: mock(async (args: unknown) => { void args; return row; }),updateMany: mock(async (args: unknown) => { void args; return { count: 1 }; }),},- cutFolder: { findFirst: mock(async (args: unknown) => { void args; return null as { id: string } | null; }) },+ cutFolder: {+ findFirst: mock(async (args: unknown) => { void args; return null as { id: string } | null; }),+ findMany: mock(async (args: unknown) => { void args; return [] as { id: string; parentId: string | null }[]; }),+ deleteMany: mock(async (args: unknown) => { void args; return { count: 0 }; }),+ },cutNoteLabel: { findMany: mock(async (args: unknown) => { void args; return []; }) },};- return { db, api: createNotesCloud(db as unknown as typeof prisma) };+ const withTx = { ...db, $transaction: async (fn: (tx: typeof db) => Promise<unknown>) => fn(db) };+ return { db, api: createNotesCloud(withTx as unknown as typeof prisma) };}const request = (body: unknown) => new Request("https://donkeycut.com/api/cut-cloud/notes/n1", { method: "PUT", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } });describe("synced Library notes", () => {@@ -73,12 +78,35 @@ describe("synced Library notes", () => {expect(await res.json()).toMatchObject({ title: "Script", libraryLocation: location });expect(db.cutNote.update.mock.calls.length).toBe(0);});- test("folder deletion unfiles only matching owner, shelf, and folders", async () => {+ test("deleting Library folders deletes only the matching owner's notes on that shelf", async () => {const { api, db } = harness();- await api.unfileLibraryFolders("owner", "local", ["brand", "child"]);- expect(db.cutNote.updateMany.mock.calls[0][0]).toEqual({ where: { userId: "owner", AND: [+ await api.deleteLibraryFolderNotes("owner", "local", ["brand", "child"]);+ const call = db.cutNote.updateMany.mock.calls[0][0] as { where: unknown; data: { deletedAt: Date; updatedAt: Date } };+ expect(call.where).toEqual({ userId: "owner", deletedAt: null, AND: [{ libraryLocation: { path: ["residency"], equals: "local" } },{ OR: ["brand", "child"].map((id) => ({ libraryLocation: { path: ["folderId"], equals: id } })) },- ] }, data: { libraryLocation: { residency: "local", folderId: null } } });+ ] });+ expect(call.data.deletedAt instanceof Date).toBe(true);+ expect(call.data.updatedAt).toEqual(call.data.deletedAt);+ });+ test("deleting a note folder takes the folders under it and every note they hold", async () => {+ const { api, db } = harness();+ db.cutFolder.findMany.mockResolvedValue([+ { id: "scripts", parentId: null },+ { id: "drafts", parentId: "scripts" },+ { id: "old", parentId: "drafts" },+ { id: "other", parentId: null },+ ]);+ expect((await api.removeFolder("owner", "scripts")).status).toBe(200);+ const notes = db.cutNote.updateMany.mock.calls[0][0] as { where: unknown; data: { deletedAt: Date } };+ expect(notes.where).toEqual({ userId: "owner", folderId: { in: ["scripts", "drafts", "old"] }, deletedAt: null });+ expect(notes.data.deletedAt instanceof Date).toBe(true);+ expect(db.cutFolder.deleteMany.mock.calls[0][0]).toEqual({ where: { userId: "owner", scope: "note", id: { in: ["scripts", "drafts", "old"] } } });+ });+ test("deleting a folder someone else owns changes nothing", async () => {+ const { api, db } = harness();+ expect((await api.removeFolder("owner", "scripts")).status).toBe(200);+ expect(db.cutNote.updateMany.mock.calls.length).toBe(0);+ expect(db.cutFolder.deleteMany.mock.calls.length).toBe(0);});});diff --git a/site/src/cut/server/cloud/notes.ts b/site/src/cut/server/cloud/notes.tsindex fd34c75f..d15ec3f0 100644--- a/site/src/cut/server/cloud/notes.ts+++ b/site/src/cut/server/cloud/notes.ts@@ -8,9 +8,9 @@// 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 { noteLocationSchema, noteUnfileSchema } from "@/cut/lib/noteReference";+import { noteLibraryFoldersSchema, noteLocationSchema } from "@/cut/lib/noteReference";import { Prisma } from "@/generated/prisma/client";-import { resolveParent } from "@/cut/lib/folderTree";+import { resolveParent, subtreeOf } from "@/cut/lib/folderTree";import { NOTE_LABELS_MAX } from "@/cut/lib/types";import { prisma } from "@/lib/prisma";import { caught, err } from "./util";@@ -138,22 +138,25 @@ async function resolveLabels(db: typeof prisma, userId: string, labelIds: unknow}export function createNotesCloud(db: typeof prisma = prisma) {- async function unfileLibraryFolders(userId: string, residency: string, folderIds: string[]) {+ /** A deleted Library folder takes the notes filed in it, the way it takes+ * its files: each stays as a tombstone so the phone drops it too. */+ async function deleteLibraryFolderNotes(userId: string, residency: string, folderIds: string[]) {if (!folderIds.length) return;+ const now = new Date();await db.cutNote.updateMany({- where: { userId, AND: [+ where: { userId, deletedAt: null, AND: [{ libraryLocation: { path: ["residency"], equals: residency } },{ OR: folderIds.map((id) => ({ libraryLocation: { path: ["folderId"], equals: id } })) },] },- data: { libraryLocation: { residency, folderId: null } },+ data: { updatedAt: now, deletedAt: now },});}return {- unfileLibraryFolders,- async unfileLibrary(userId: string, req: Request) {- const parsed = noteUnfileSchema.safeParse(await req.json());+ deleteLibraryFolderNotes,+ async deleteInLibraryFolders(userId: string, req: Request) {+ const parsed = noteLibraryFoldersSchema.safeParse(await req.json());if (!parsed.success) return err("Invalid Library folders.", 400);- await unfileLibraryFolders(userId, parsed.data.residency, parsed.data.folderIds);+ await deleteLibraryFolderNotes(userId, parsed.data.residency, parsed.data.folderIds);return Response.json({ ok: true });},async get(userId: string, id: string) {@@ -292,25 +295,24 @@ export function createNotesCloud(db: typeof prisma = prisma) {}},- /** Delete one folder. What it held — its notes and the folders inside it —- * comes up one level, filed where the folder was. */+ /** Delete one folder and everything under it: the folders filed inside,+ * however deep, and every note they hold, which stay as tombstones so the+ * phone drops its copies on the next merge. */async removeFolder(userId: string, id: string) {try {await db.$transaction(async (tx) => {- const gone = await tx.cutFolder.findFirst({- where: { id, userId, scope: "note" },- select: { parentId: true },+ const folders = await tx.cutFolder.findMany({+ where: { userId, scope: "note" },+ select: { id: true, parentId: true },});- if (!gone) return;- await tx.cutFolder.delete({ where: { id } });+ if (!folders.some((f) => f.id === id)) return;+ const tree = subtreeOf(folders, id);+ const now = new Date();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 },+ where: { userId, folderId: { in: tree }, deletedAt: null },+ data: { updatedAt: now, deletedAt: now },});+ await tx.cutFolder.deleteMany({ where: { userId, scope: "note", id: { in: tree } } });});return Response.json({ ok: true });} catch (e) {diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 20cd1828..43f48a11 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -122,7 +122,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "POST", path: "/api/cut-cloud/projects/:id/scene-lease", handler: (r, u, p) => cloudSceneLease(u, p.id, r) },{ method: "POST", path: "/api/cut-cloud/turns/:jobId/cancel", handler: (_r, u, p) => turnsCloud.cancel(u, p.jobId) },- { method: "PUT", path: "/api/cut-cloud/notes/library-location", handler: (r, u) => notesCloud.unfileLibrary(u, r) },+ { method: "POST", path: "/api/cut-cloud/notes/library-folders/delete", handler: (r, u) => notesCloud.deleteInLibraryFolders(u, r) },{ 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) },