Open source CapCut alternative.
TypeScript
feat(ios): notes file into folders, and a saved link brings its media down
David Le665e03e0d0bc
diff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swiftindex 5c39d7fc..38a66e08 100644--- a/apps/ios/Donkey/Controllers/CutCloudClient.swift+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift@@ -212,14 +212,69 @@ extension CutCloudClient: CloudSyncServicing {_ = try await send(try request("DELETE", "/api/cut-cloud/library/\(id)"))}- func importInspirationLink(_ url: URL) async throws {- _ = try await send(+ func importInspirationLink(_ url: URL) async throws -> String {+ struct QueuedJob: Decodable { var jobId: String }+ let data = try await send(try request("POST","/api/cut-cloud/library/import-url",body: ["url": url.absoluteString, "origin": "inspiration"]))+ return try decode(QueuedJob.self, from: data).jobId+ }++ func importedLink(jobId: String) async throws -> JobOutcome<ImportedLink> {+ struct JobStatus: Decodable {+ struct Result: Decodable {+ struct Asset: Decodable {+ var id: String+ var fileName: String+ var type: String+ }+ var assets: [Asset]?+ }+ var state: String+ var result: Result?+ }+ let data = try await send(try request("GET", "/api/cut-cloud/jobs/\(jobId)"))+ let status = try decode(JobStatus.self, from: data)+ switch status.state {+ case "queued", "running":+ return .running+ case "done":+ // A source that was only words brings back no media; the card+ // stays the link it was saved as.+ guard let asset = status.result?.assets?.first else { return .failed }+ return .done(+ ImportedLink(+ assetId: asset.id,+ fileName: asset.fileName,+ isVideo: asset.type == "video"+ )+ )+ default:+ return .failed+ }+ }++ func downloadLibraryMedia(fileName: String, to destination: URL) async throws {+ let path = "/api/cut-cloud/library/media/" + (fileName.addingPercentEncoding(+ withAllowedCharacters: .urlPathAllowed+ ) ?? fileName)+ let url = try await resolveRedirect(path)+ let temporary: URL+ do {+ (temporary, _) = try await URLSession.shared.download(from: url)+ } catch {+ throw CloudSyncError.transport+ }+ try? FileManager.default.removeItem(at: destination)+ do {+ try FileManager.default.moveItem(at: temporary, to: destination)+ } catch {+ throw CloudSyncError.transport+ }}func fetchUsage() async throws -> StorageUsage {@@ -239,56 +294,91 @@ extension CutCloudClient: CloudSyncServicing {var title: Stringvar body: Stringvar colorIndex: Int+ var folderId: String?var updatedAt: Doublevar deletedAt: Double?var createdAt: Double}- func fetchNotes() async throws -> [RemoteNote] {- struct NotesResponse: Decodable { var notes: [NoteDTO] }- let data = try await send(try request("GET", "/api/cut-cloud/notes"))- return try decode(NotesResponse.self, from: data).notes.compactMap { dto in- guard let id = UUID(uuidString: dto.id) else { return nil }- return RemoteNote(- id: id,- title: dto.title,- body: dto.body,- colorIndex: dto.colorIndex,- updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),- deletedAt: dto.deletedAt.map { Date(timeIntervalSince1970: $0 / 1000) },- createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000)- )- }+ private struct NoteFolderDTO: Decodable {+ var id: String+ var name: String+ var updatedAt: Double+ var createdAt: Double}- func putNote(_ note: RemoteNote) async throws -> RemoteNote {- let data = try await send(- try request(- "PUT",- "/api/cut-cloud/notes/\(note.id.uuidString.lowercased())",- body: [- "title": note.title,- "body": note.body,- "colorIndex": note.colorIndex,- "updatedAt": Int(note.updatedAt.timeIntervalSince1970 * 1000),- ]- )- )- let dto = try decode(NoteDTO.self, from: data)- return RemoteNote(- id: note.id,+ private func remoteNote(_ dto: NoteDTO, id: UUID) -> RemoteNote {+ RemoteNote(+ id: id,title: dto.title,body: dto.body,colorIndex: dto.colorIndex,+ folderId: dto.folderId.flatMap(UUID.init(uuidString:)),updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),deletedAt: dto.deletedAt.map { Date(timeIntervalSince1970: $0 / 1000) },createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000))}+ func fetchNotes() async throws -> RemoteNotes {+ struct NotesResponse: Decodable {+ var notes: [NoteDTO]+ var folders: [NoteFolderDTO]?+ }+ let data = try await send(try request("GET", "/api/cut-cloud/notes"))+ let response = try decode(NotesResponse.self, from: data)+ return RemoteNotes(+ notes: response.notes.compactMap { dto in+ guard let id = UUID(uuidString: dto.id) else { return nil }+ return remoteNote(dto, id: id)+ },+ // Folders are keyed by the id whichever client made them chose,+ // and both clients mint UUIDs; anything else is not this phone's.+ folders: (response.folders ?? []).compactMap { dto in+ guard let id = UUID(uuidString: dto.id) else { return nil }+ return RemoteNoteFolder(+ id: id,+ name: dto.name,+ updatedAt: Date(timeIntervalSince1970: dto.updatedAt / 1000),+ createdAt: Date(timeIntervalSince1970: dto.createdAt / 1000)+ )+ }+ )+ }++ func putNote(_ note: RemoteNote) async throws -> RemoteNote {+ var body: [String: Any] = [+ "title": note.title,+ "body": note.body,+ "colorIndex": note.colorIndex,+ "updatedAt": Int(note.updatedAt.timeIntervalSince1970 * 1000),+ ]+ body["folderId"] = note.folderId.map { $0.uuidString.lowercased() } ?? NSNull()+ let data = try await send(+ try request("PUT", "/api/cut-cloud/notes/\(note.id.uuidString.lowercased())", body: body)+ )+ return remoteNote(try decode(NoteDTO.self, from: data), id: note.id)+ }+func deleteNote(id: UUID) async throws {_ = try await send(try request("DELETE", "/api/cut-cloud/notes/\(id.uuidString.lowercased())"))}++ func putNoteFolder(_ folder: RemoteNoteFolder) async throws {+ _ = try await send(+ try request(+ "PUT",+ "/api/cut-cloud/notes/folders/\(folder.id.uuidString.lowercased())",+ body: ["name": folder.name]+ )+ )+ }++ func deleteNoteFolder(id: UUID) async throws {+ _ = try await send(+ try request("DELETE", "/api/cut-cloud/notes/folders/\(id.uuidString.lowercased())")+ )+ }}// MARK: - Projects down-syncdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swiftindex 167d9532..35c2cea0 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/CloudSync.swift@@ -84,6 +84,7 @@ nonisolated public struct RemoteNote: Equatable, Sendable {public var title: Stringpublic var body: Stringpublic var colorIndex: Int+ public var folderId: UUID?public var updatedAt: Datepublic var deletedAt: Date?public var createdAt: Date@@ -93,6 +94,7 @@ nonisolated public struct RemoteNote: Equatable, Sendable {title: String,body: String,colorIndex: Int,+ folderId: UUID? = nil,updatedAt: Date,deletedAt: Date? = nil,createdAt: Date = .now@@ -101,12 +103,64 @@ nonisolated public struct RemoteNote: Equatable, Sendable {self.title = titleself.body = bodyself.colorIndex = colorIndex+ self.folderId = folderIdself.updatedAt = updatedAtself.deletedAt = deletedAtself.createdAt = createdAt}}+/// A note folder as the cloud stores it. Folders carry no tombstone: a+/// folder missing from the listing was deleted.+nonisolated public struct RemoteNoteFolder: Equatable, Sendable {+ public var id: UUID+ public var name: String+ public var updatedAt: Date+ public var createdAt: Date++ public init(id: UUID, name: String, updatedAt: Date, createdAt: Date) {+ self.id = id+ self.name = name+ self.updatedAt = updatedAt+ self.createdAt = createdAt+ }+}++/// One listing of the account's notes: the notes themselves, tombstones+/// included, and every folder they file into.+nonisolated public struct RemoteNotes: Equatable, Sendable {+ public var notes: [RemoteNote]+ public var folders: [RemoteNoteFolder]++ public init(notes: [RemoteNote], folders: [RemoteNoteFolder]) {+ self.notes = notes+ self.folders = folders+ }+}++/// What the cloud brought back for a saved link, once its import job is done.+nonisolated public struct ImportedLink: Equatable, Sendable {+ /// The library asset the worker registered, so a delete here takes the+ /// cloud copy with it.+ public var assetId: String+ /// The media's name on the cloud shelf, for the download.+ public var fileName: String+ public var isVideo: Bool++ public init(assetId: String, fileName: String, isVideo: Bool) {+ self.assetId = assetId+ self.fileName = fileName+ self.isVideo = isVideo+ }+}++/// Where a queued cloud job stands.+nonisolated public enum JobOutcome<Value: Sendable>: Sendable {+ case running+ case done(Value)+ case failed+}+nonisolated public enum CloudSyncError: Error, Equatable {/// The account is out of cloud storage: uploads pause, the Library shows/// its banner, and nothing retries until space frees up.@@ -127,13 +181,22 @@ public protocol CloudSyncServicing: AnyObject {) async throws -> RemoteAssetfunc deleteLibraryAsset(id: String) async throws/// Queue a cloud-side import of an inspiration link (the render worker- /// fetches the media into the Inspiration folder).- func importInspirationLink(_ url: URL) async throws+ /// fetches the media into the Inspiration folder). Returns the job id the+ /// phone follows to bring the media down.+ func importInspirationLink(_ url: URL) async throws -> String+ /// Where an import job stands. `done` carries the first piece of media+ /// the source yielded; a source that was only words comes back `failed`.+ func importedLink(jobId: String) async throws -> JobOutcome<ImportedLink>+ /// Download one library media file to a local URL.+ func downloadLibraryMedia(fileName: String, to destination: URL) async throwsfunc fetchUsage() async throws -> StorageUsage- func fetchNotes() async throws -> [RemoteNote]+ func fetchNotes() async throws -> RemoteNotes/// Returns the winning version — this write, or a newer one already there.func putNote(_ note: RemoteNote) async throws -> RemoteNotefunc deleteNote(id: UUID) async throws+ /// Create or rename one folder under the id the phone gave it.+ func putNoteFolder(_ folder: RemoteNoteFolder) async throws+ func deleteNoteFolder(id: UUID) async throws}// MARK: - Projects (down-sync)diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swiftindex 30b71c86..9c22d368 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/DonkeyStore.swift@@ -13,6 +13,8 @@ final class NoteRecord {var title: Stringvar body: Stringvar colorIndex: Int+ /// The folder this note is filed in; nil is the top level.+ var folderId: UUID?var createdAt: Date/// Last edit, the sync's last-writer-wins clock. Older rows carry nil and/// read as their creation time.@@ -26,6 +28,7 @@ final class NoteRecord {title = note.titlebody = note.bodycolorIndex = note.color.rawValue+ folderId = note.folderIdcreatedAt = note.createdAtupdatedAt = note.updatedAtself.dirty = dirty@@ -37,12 +40,36 @@ final class NoteRecord {title: title,body: body,color: NoteColor(rawValue: colorIndex) ?? .butter,+ folderId: folderId,createdAt: createdAt,updatedAt: updatedAt ?? createdAt)}}+/// A folder notes are filed in. Folders are few and small, so the whole set+/// pushes and pulls each pass; `dirty` marks one this phone changed.+@Model+final class NoteFolderRecord {+ @Attribute(.unique) var id: UUID+ var name: String+ var createdAt: Date+ var updatedAt: Date+ var dirty: Bool++ init(_ folder: NoteFolder, dirty: Bool) {+ id = folder.id+ name = folder.name+ createdAt = folder.createdAt+ updatedAt = folder.updatedAt+ self.dirty = dirty+ }++ var folder: NoteFolder {+ NoteFolder(id: id, name: name, createdAt: createdAt, updatedAt: updatedAt)+ }+}+@Modelfinal class InspirationRecord {@Attribute(.unique) var id: UUID@@ -54,6 +81,14 @@ final class InspirationRecord {var remoteAssetId: String?/// When a link's cloud-side import was queued.var linkSyncedAt: Date?+ /// The import job the worker is running for this link, while it runs.+ var importJobId: String?+ /// The media the cloud brought back for this link, downloaded here.+ var fetchedFileName: String?+ var fetchedIsVideo: Bool?+ /// The source had no media to bring back, or the fetch failed. The card+ /// stays a link and nothing retries.+ var importFailed: Bool?init(id: UUID, linkURL: String?, mediaFileName: String?, isVideo: Bool, createdAt: Date) {self.id = id@@ -65,7 +100,17 @@ final class InspirationRecord {var item: InspirationItem? {if let linkURL, let url = URL(string: linkURL) {- return InspirationItem(id: id, kind: .link(url), createdAt: createdAt)+ return InspirationItem(+ id: id,+ kind: .link(url),+ createdAt: createdAt,+ fetched: fetchedFileName.map {+ InspirationMedia(fileName: $0, isVideo: fetchedIsVideo ?? false)+ },+ importState: importFailed == true+ ? .failed+ : (linkSyncedAt == nil ? .waiting : .fetching)+ )}if let mediaFileName {return InspirationItem(id: id, kind: .media(fileName: mediaFileName, isVideo: isVideo), createdAt: createdAt)@@ -141,7 +186,13 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStorifor directory in [mediaDirectory, recordingsDirectory] {try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)}- let schema = Schema([NoteRecord.self, InspirationRecord.self, RecordingRecord.self, TombstoneRecord.self])+ let schema = Schema([+ NoteRecord.self,+ NoteFolderRecord.self,+ InspirationRecord.self,+ RecordingRecord.self,+ TombstoneRecord.self,+ ])let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: inMemory)container = try ModelContainer(for: schema, configurations: [configuration])context = ModelContext(container)@@ -161,6 +212,7 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoriexisting.title = note.titleexisting.body = note.bodyexisting.colorIndex = note.color.rawValue+ existing.folderId = note.folderIdexisting.updatedAt = note.updatedAtexisting.dirty = true} else {@@ -175,6 +227,38 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoritry context.save()}+ public func loadNoteFolders() throws -> [NoteFolder] {+ let descriptor = FetchDescriptor<NoteFolderRecord>(sortBy: [SortDescriptor(\.createdAt)])+ return try context.fetch(descriptor).map(\.folder)+ }++ public func upsert(_ folder: NoteFolder) throws {+ let id = folder.id+ let descriptor = FetchDescriptor<NoteFolderRecord>(predicate: #Predicate { $0.id == id })+ if let existing = try context.fetch(descriptor).first {+ existing.name = folder.name+ existing.updatedAt = folder.updatedAt+ existing.dirty = true+ } else {+ context.insert(NoteFolderRecord(folder, dirty: true))+ }+ try context.save()+ }++ public func deleteNoteFolder(id: UUID) throws {+ try context.delete(model: NoteFolderRecord.self, where: #Predicate { $0.id == id })+ // The notes stay; they come back to the top level, and each one is a+ // write of its own so the cloud files them there too.+ let descriptor = FetchDescriptor<NoteRecord>(predicate: #Predicate { $0.folderId == id })+ for record in try context.fetch(descriptor) {+ record.folderId = nil+ record.updatedAt = .now+ record.dirty = true+ }+ context.insert(TombstoneRecord(kind: SyncTombstone.Kind.noteFolder.rawValue, remoteId: id.uuidString, stamp: .now))+ try context.save()+ }+public func loadInspiration() throws -> [InspirationItem] {let descriptor = FetchDescriptor<InspirationRecord>(sortBy: [SortDescriptor(\.createdAt, order: .reverse)])return try context.fetch(descriptor).compactMap(\.item)@@ -200,7 +284,7 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoripublic func deleteInspiration(id: UUID) throws {let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })if let record = try context.fetch(descriptor).first {- if let fileName = record.mediaFileName {+ for fileName in [record.mediaFileName, record.fetchedFileName].compactMap({ $0 }) {try? FileManager.default.removeItem(at: mediaDirectory.appending(path: fileName))}if let remote = record.remoteAssetId {@@ -277,6 +361,7 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoriexisting.title = note.titleexisting.body = note.bodyexisting.colorIndex = note.color.rawValue+ existing.folderId = note.folderIdexisting.updatedAt = note.updatedAtexisting.dirty = false} else {@@ -298,6 +383,48 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoritry context.save()}+ public func dirtyNoteFolders() throws -> [NoteFolder] {+ let descriptor = FetchDescriptor<NoteFolderRecord>(sortBy: [SortDescriptor(\.createdAt)])+ return try context.fetch(descriptor).filter(\.dirty).map(\.folder)+ }++ public func applyRemoteNoteFolder(_ folder: NoteFolder) throws {+ let id = folder.id+ let descriptor = FetchDescriptor<NoteFolderRecord>(predicate: #Predicate { $0.id == id })+ if let existing = try context.fetch(descriptor).first {+ guard !existing.dirty else { return }+ existing.name = folder.name+ existing.updatedAt = folder.updatedAt+ } else {+ context.insert(NoteFolderRecord(folder, dirty: false))+ }+ try context.save()+ }++ public func clearNoteFolderDirty(id: UUID, ifUpdatedAt stamp: Date) throws {+ let descriptor = FetchDescriptor<NoteFolderRecord>(predicate: #Predicate { $0.id == id })+ guard let record = try context.fetch(descriptor).first, record.updatedAt == stamp else { return }+ record.dirty = false+ try context.save()+ }++ /// Folder ids this phone holds that the cloud no longer lists, so they+ /// were deleted elsewhere. A folder still waiting to be pushed is not one+ /// of them.+ public func cleanNoteFolderIds() throws -> [UUID] {+ let descriptor = FetchDescriptor<NoteFolderRecord>()+ return try context.fetch(descriptor).filter { !$0.dirty }.map(\.id)+ }++ public func removeNoteFolderFromCloudDelete(id: UUID) throws {+ try context.delete(model: NoteFolderRecord.self, where: #Predicate { $0.id == id })+ let descriptor = FetchDescriptor<NoteRecord>(predicate: #Predicate { $0.folderId == id })+ for record in try context.fetch(descriptor) where record.dirty != true {+ record.folderId = nil+ }+ try context.save()+ }+public func recordingRemote(_ id: UUID) throws -> (assetId: String?, claimedFileName: String?) {let descriptor = FetchDescriptor<RecordingRecord>(predicate: #Predicate { $0.id == id })let record = try context.fetch(descriptor).first@@ -340,10 +467,48 @@ public final class DonkeyStore: IdeasStoring, RecordingStoring, SyncJournalStoritry context.save()}- public func markInspirationLinkSynced(_ id: UUID) throws {+ public func markInspirationLinkSynced(_ id: UUID, jobId: String) throws {let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })guard let record = try context.fetch(descriptor).first else { return }record.linkSyncedAt = .now+ record.importJobId = jobId+ try context.save()+ }++ public func inspirationImportJobId(_ id: UUID) throws -> String? {+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })+ return try context.fetch(descriptor).first?.importJobId+ }++ /// Where a link's fetched media is written. The name is the item's, so a+ /// repeated fetch overwrites rather than piling up files.+ public func fetchedMediaDestination(_ id: UUID, isVideo: Bool) -> URL {+ mediaDirectory.appending(path: id.uuidString + "-source" + (isVideo ? ".mp4" : ".jpg"))+ }++ public func markInspirationFetched(+ _ id: UUID,+ fileName: String,+ isVideo: Bool,+ remoteAssetId: String+ ) throws {+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })+ guard let record = try context.fetch(descriptor).first else { return }+ record.fetchedFileName = fileName+ record.fetchedIsVideo = isVideo+ record.remoteAssetId = remoteAssetId+ record.importJobId = nil+ record.importFailed = nil+ try context.save()+ }++ /// The cloud brought nothing back. The card stays a link and the job is+ /// not asked about again.+ public func markInspirationImportFailed(_ id: UUID) throws {+ let descriptor = FetchDescriptor<InspirationRecord>(predicate: #Predicate { $0.id == id })+ guard let record = try context.fetch(descriptor).first else { return }+ record.importJobId = nil+ record.importFailed = truetry context.save()}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swiftindex 95a3c558..936bbf3d 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Ideas.swift@@ -30,11 +30,30 @@ nonisolated public enum NoteColor: Int, CaseIterable, Codable, Sendable {}}+/// A folder notes are filed in. Ids are minted by whichever client makes the+/// folder — the phone here, the desktop in its Notes tab — and the cloud+/// stores the folder under that id, so a folder made offline pushes as itself.+nonisolated public struct NoteFolder: Identifiable, Equatable, Hashable, Sendable {+ public var id: UUID+ public var name: String+ public var createdAt: Date+ public var updatedAt: Date++ public init(id: UUID = UUID(), name: String, createdAt: Date = .now, updatedAt: Date = .now) {+ self.id = id+ self.name = name+ self.createdAt = createdAt+ self.updatedAt = updatedAt+ }+}+nonisolated public struct Note: Identifiable, Equatable, Sendable {public var id: UUIDpublic var title: Stringpublic var body: Stringpublic var color: NoteColor+ /// The folder this note is filed in; nil is the top level.+ public var folderId: UUID?public var createdAt: Date/// Last edit, wherever it happened. The sync's last-writer-wins clock:/// the newer stamp survives when the phone and the desktop both wrote.@@ -45,6 +64,7 @@ nonisolated public struct Note: Identifiable, Equatable, Sendable {title: String,body: String,color: NoteColor,+ folderId: UUID? = nil,createdAt: Date = .now,updatedAt: Date = .now) {@@ -52,6 +72,7 @@ nonisolated public struct Note: Identifiable, Equatable, Sendable {self.title = titleself.body = bodyself.color = color+ self.folderId = folderIdself.createdAt = createdAtself.updatedAt = updatedAt}@@ -70,15 +91,68 @@ nonisolated public enum InspirationKind: Equatable, Sendable {case media(fileName: String, isVideo: Bool)}+/// Media stored on this phone: the file name under the repository's+/// Inspiration directory, and whether it plays.+nonisolated public struct InspirationMedia: Equatable, Sendable {+ public var fileName: String+ public var isVideo: Bool++ public init(fileName: String, isVideo: Bool) {+ self.fileName = fileName+ self.isVideo = isVideo+ }+}++/// Where a saved link stands with the cloud fetch that turns it into media.+nonisolated public enum InspirationImport: Equatable, Sendable {+ /// Nothing has been asked of the cloud yet — the item was just saved, or+ /// the phone is offline.+ case waiting+ /// The worker is fetching the source.+ case fetching+ /// The source had no media to bring back, or the fetch failed. The card+ /// stays a link.+ case failed+}+nonisolated public struct InspirationItem: Identifiable, Equatable, Sendable {public var id: UUIDpublic var kind: InspirationKindpublic var createdAt: Date+ /// A saved link whose media the cloud fetched and this phone downloaded.+ /// The card plays it in place, the way a photo-library import plays.+ public var fetched: InspirationMedia?+ /// Where the fetch of a link stands. Media saved from the photo library+ /// has nothing to fetch and reads as `.waiting`.+ public var importState: InspirationImport- public init(id: UUID = UUID(), kind: InspirationKind, createdAt: Date = .now) {+ public init(+ id: UUID = UUID(),+ kind: InspirationKind,+ createdAt: Date = .now,+ fetched: InspirationMedia? = nil,+ importState: InspirationImport = .waiting+ ) {self.id = idself.kind = kindself.createdAt = createdAt+ self.fetched = fetched+ self.importState = importState+ }++ /// The media this card shows: what the phone imported, or what the cloud+ /// brought back for a link.+ public var media: InspirationMedia? {+ if case .media(let fileName, let isVideo) = kind {+ return InspirationMedia(fileName: fileName, isVideo: isVideo)+ }+ return fetched+ }++ /// The source link, for a saved link.+ public var link: URL? {+ if case .link(let url) = kind { return url }+ return nil}}@@ -97,6 +171,11 @@ public protocol IdeasStoring: AnyObject {func loadNotes() throws -> [Note]func upsert(_ note: Note) throwsfunc deleteNote(id: UUID) throws+ func loadNoteFolders() throws -> [NoteFolder]+ func upsert(_ folder: NoteFolder) throws+ /// Delete a folder. Its notes come back to the top level rather than+ /// going with it — the same line the cloud draws.+ func deleteNoteFolder(id: UUID) throwsfunc loadInspiration() throws -> [InspirationItem]func addLink(_ url: URL) throws -> InspirationItemfunc addMedia(data: Data, isVideo: Bool) throws -> InspirationItem@@ -112,6 +191,7 @@ nonisolated public enum IdeasFilter: String, CaseIterable, Sendable {@Observablepublic final class IdeasModel {public private(set) var notes: [Note] = []+ public private(set) var folders: [NoteFolder] = []public private(set) var inspiration: [InspirationItem] = []public var filter: IdeasFilter = .all@@ -126,21 +206,75 @@ public final class IdeasModel {public init(store: any IdeasStoring) {self.store = store- notes = (try? store.loadNotes()) ?? []- inspiration = (try? store.loadInspiration()) ?? []+ reloadFromStore()}/// Re-read what the store holds — how a cloud merge lands on screen.public func reloadFromStore() {notes = (try? store.loadNotes()) ?? []+ folders = (try? store.loadNoteFolders()) ?? []inspiration = (try? store.loadInspiration()) ?? []}+ /// The notes filed in one folder, or at the top level when `folderId` is+ /// nil.+ public func notes(in folderId: UUID?) -> [Note] {+ notes.filter { $0.folderId == folderId }+ }++ public func folder(_ id: UUID?) -> NoteFolder? {+ guard let id else { return nil }+ return folders.first { $0.id == id }+ }++ // MARK: Folders++ @discardableResult+ public func addFolder(named name: String) -> NoteFolder? {+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty else { return nil }+ let folder = NoteFolder(name: trimmed)+ try? store.upsert(folder)+ folders.append(folder)+ onLocalChange?()+ return folder+ }++ public func renameFolder(id: UUID, to name: String) {+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty, var folder = folders.first(where: { $0.id == id }) else { return }+ folder.name = trimmed+ folder.updatedAt = .now+ try? store.upsert(folder)+ if let index = folders.firstIndex(where: { $0.id == id }) { folders[index] = folder }+ onLocalChange?()+ }++ /// Delete a folder. Its notes come back to the top level.+ public func deleteFolder(id: UUID) {+ try? store.deleteNoteFolder(id: id)+ reloadFromStore()+ onLocalChange?()+ }++ /// File a note in a folder, or at the top level.+ public func move(noteId: UUID, to folderId: UUID?) {+ guard var note = notes.first(where: { $0.id == noteId }), note.folderId != folderId else { return }+ note.folderId = folderId+ note.updatedAt = .now+ try? store.upsert(note)+ if let index = notes.firstIndex(where: { $0.id == noteId }) { notes[index] = note }+ onLocalChange?()+ }+nonisolated public struct NoteDraft: Identifiable, Equatable {public var id: UUIDpublic var title: Stringpublic var body: Stringpublic var color: NoteColor+ /// The folder the note is filed in — the one it was opened from for a+ /// new note.+ public var folderId: UUID?public var isNew: Boolpublic var hasContent: Bool {@@ -149,11 +283,18 @@ public final class IdeasModel {}}- public func openEditor(for note: Note? = nil) {+ public func openEditor(for note: Note? = nil, in folderId: UUID? = nil) {if let note {- draft = NoteDraft(id: note.id, title: note.title, body: note.body, color: note.color, isNew: false)+ draft = NoteDraft(+ id: note.id,+ title: note.title,+ body: note.body,+ color: note.color,+ folderId: note.folderId,+ isNew: false+ )} else {- draft = NoteDraft(id: UUID(), title: "", body: "", color: .butter, isNew: true)+ draft = NoteDraft(id: UUID(), title: "", body: "", color: .butter, folderId: folderId, isNew: true)}}@@ -177,6 +318,7 @@ public final class IdeasModel {title: title,body: body,color: draft.color,+ folderId: draft.folderId,createdAt: existing?.createdAt ?? .now,updatedAt: .now)diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swiftindex b017e679..19de83ac 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/SyncEngine.swift@@ -11,6 +11,9 @@ nonisolated public struct SyncTombstone: Equatable, Sendable, Identifiable {nonisolated public enum Kind: String, Sendable {/// A synced note deleted here; the cloud keeps a tombstone row.case note+ /// A note folder deleted here. The cloud row goes; the notes in it+ /// come back to the top level on both sides.+ case noteFolder/// A synced recording or inspiration item deleted here; the cloud/// asset goes with it.case libraryAsset@@ -45,6 +48,15 @@ public protocol SyncJournalStoring: AnyObject {/// Remove a note the cloud deleted. No tombstone: the delete came down.func removeNoteFromCloudDelete(id: UUID) throws+ // Folders: the same push-then-pull, with no tombstone rows in the cloud —+ // a folder this phone holds clean and the cloud no longer lists was+ // deleted on the other side.+ func dirtyNoteFolders() throws -> [NoteFolder]+ func applyRemoteNoteFolder(_ folder: NoteFolder) throws+ func clearNoteFolderDirty(id: UUID, ifUpdatedAt: Date) throws+ func cleanNoteFolderIds() throws -> [UUID]+ func removeNoteFolderFromCloudDelete(id: UUID) throws+// Recordingsfunc recordingRemote(_ id: UUID) throws -> (assetId: String?, claimedFileName: String?)/// Journal a recording's cloud copy. Returns false when the row is gone —@@ -58,7 +70,19 @@ public protocol SyncJournalStoring: AnyObject {func inspirationRemoteAssetId(_ id: UUID) throws -> String?func isInspirationLinkSynced(_ id: UUID) throws -> Boolfunc markInspirationMediaSynced(_ id: UUID, remoteAssetId: String) throws- func markInspirationLinkSynced(_ id: UUID) throws+ /// A link handed to the cloud worker: the job that is fetching it.+ func markInspirationLinkSynced(_ id: UUID, jobId: String) throws+ /// The job still fetching this link, if one is.+ func inspirationImportJobId(_ id: UUID) throws -> String?+ /// Where the fetched media is written on this phone.+ func fetchedMediaDestination(_ id: UUID, isVideo: Bool) -> URL+ func markInspirationFetched(+ _ id: UUID,+ fileName: String,+ isVideo: Bool,+ remoteAssetId: String+ ) throws+ func markInspirationImportFailed(_ id: UUID) throws// Tombstonesfunc tombstones() throws -> [SyncTombstone]@@ -134,6 +158,35 @@ public final class SyncEngine {return .synced}+ /// How often the phone looks at the cloud on its own. Notes are written+ /// at the desk as well as here, so the list a person is looking at goes+ /// stale without anyone touching the phone; a pass on this clock brings+ /// those edits in. Pull to refresh runs the same pass at once.+ public static let heartbeat: Duration = .seconds(45)++ /// The periodic pull, for as long as the caller keeps the task alive. The+ /// app entry runs it while the app is in the foreground.+ public func beat() async {+ while !Task.isCancelled {+ try? await Task.sleep(for: Self.heartbeat)+ guard !Task.isCancelled else { return }+ kick()+ }+ }++ /// A pass the caller waits on — pull to refresh. A pass already running+ /// is joined by booking one more, so the gesture never starts a second+ /// runner over the same queues.+ public func refreshNow() async {+ guard signedIn(), network != .offline else { return }+ if running {+ runAgain = true+ return+ }+ running = true+ await run()+ }+/// Something changed — a new recording, a note edit, the network, a/// sign-in. One runner drains every queue; a kick during a run schedules/// one more pass so nothing lands between checks.@@ -164,7 +217,7 @@ public final class SyncEngine {await replayTombstones()await syncNotes()// Link imports are small payloads, so they queue ahead of the media.- await uploadPendingInspirationLinks()+ await syncInspirationLinks()guard online else { return }await refreshStorage()guard !storageFull else { return }@@ -195,18 +248,27 @@ public final class SyncEngine {/// Anything the journal still owes the cloud after a pass.private var pendingWork: Bool {if !(((try? journal.tombstones()) ?? []).isEmpty) { return true }- if !(((try? journal.dirtyNotes()) ?? []).isEmpty) { return true }+ if notesPending { return true }if (media?.recordings ?? []).contains(where: {!unreadable.contains($0.id) && ((try? journal.recordingRemote($0.id))?.assetId) == nil}) { return true }return (ideas?.inspiration ?? []).contains { item inswitch item.kind {- case .link: ((try? journal.isInspirationLinkSynced(item.id)) ?? true) == false- case .media: ((try? journal.inspirationRemoteAssetId(item.id)) ?? nil) == nil+ case .link:+ ((try? journal.isInspirationLinkSynced(item.id)) ?? true) == false+ || ((try? journal.inspirationImportJobId(item.id)) ?? nil) != nil+ case .media:+ ((try? journal.inspirationRemoteAssetId(item.id)) ?? nil) == nil}}}+ /// Folders and notes the phone still owes the cloud.+ private var notesPending: Bool {+ !(((try? journal.dirtyNotes()) ?? []).isEmpty)+ || !(((try? journal.dirtyNoteFolders()) ?? []).isEmpty)+ }+// MARK: Deletesprivate func replayTombstones() async {@@ -216,6 +278,9 @@ public final class SyncEngine {case .note:guard let id = UUID(uuidString: tombstone.remoteId) else { break }try await service.deleteNote(id: id)+ case .noteFolder:+ guard let id = UUID(uuidString: tombstone.remoteId) else { break }+ try await service.deleteNoteFolder(id: id)case .libraryAsset:try await service.deleteLibraryAsset(id: tombstone.remoteId)}@@ -234,6 +299,25 @@ public final class SyncEngine {private func syncNotes() async {guard online else { return }+ // Folders go up before the notes that name them, so a note filed in a+ // folder made offline never reaches a cloud that has no such folder.+ for folder in (try? journal.dirtyNoteFolders()) ?? [] {+ do {+ try await service.putNoteFolder(+ RemoteNoteFolder(+ id: folder.id,+ name: folder.name,+ updatedAt: folder.updatedAt,+ createdAt: folder.createdAt+ )+ )+ try? journal.clearNoteFolderDirty(id: folder.id, ifUpdatedAt: folder.updatedAt)+ } catch CloudSyncError.unauthorized {+ return+ } catch {+ // Transient; stays dirty.+ }+ }// Push local edits first so the pull that follows can't overwrite them.for note in (try? journal.dirtyNotes()) ?? [] {do {@@ -243,6 +327,7 @@ public final class SyncEngine {title: note.title,body: note.body,colorIndex: note.color.rawValue,+ folderId: note.folderId,updatedAt: note.updatedAt,createdAt: note.createdAt)@@ -259,13 +344,41 @@ public final class SyncEngine {}do {let remote = try await service.fetchNotes()- try mergeRemoteNotes(remote)+ try mergeRemoteFolders(remote.folders)+ try mergeRemoteNotes(remote.notes)ideas?.reloadFromStore()} catch {// The next kick pulls again.}}+ /// Folders carry no tombstone in the cloud, so the listing is the truth:+ /// what it holds is applied, and a folder this phone has clean that the+ /// listing does not name was deleted on the other side.+ private func mergeRemoteFolders(_ remote: [RemoteNoteFolder]) throws {+ let pendingDeletes = Set(+ ((try? journal.tombstones()) ?? [])+ .filter { $0.kind == .noteFolder }+ .compactMap { UUID(uuidString: $0.remoteId) }+ )+ var live: Set<UUID> = []+ for folder in remote {+ if pendingDeletes.contains(folder.id) { continue }+ live.insert(folder.id)+ try journal.applyRemoteNoteFolder(+ NoteFolder(+ id: folder.id,+ name: folder.name,+ createdAt: folder.createdAt,+ updatedAt: folder.updatedAt+ )+ )+ }+ for id in try journal.cleanNoteFolderIds() where !live.contains(id) {+ try journal.removeNoteFolderFromCloudDelete(id: id)+ }+ }+private func mergeRemoteNotes(_ remote: [RemoteNote]) throws {let localById = Dictionary(uniqueKeysWithValues: (ideas?.notes ?? []).map { ($0.id, $0) }@@ -297,6 +410,7 @@ public final class SyncEngine {title: remote.title,body: remote.body,color: NoteColor(rawValue: remote.colorIndex) ?? .butter,+ folderId: remote.folderId,createdAt: remote.createdAt,updatedAt: remote.updatedAt)@@ -369,20 +483,56 @@ public final class SyncEngine {// MARK: Inspiration- private func uploadPendingInspirationLinks() async {+ /// Saved links, both halves of the round trip: a link the cloud has not+ /// been told about is queued, and a link it is fetching is followed until+ /// the media can come down onto this phone. A card shows the spinner from+ /// the moment the link is saved and the video itself the moment it lands.+ private func syncInspirationLinks() async {+ var landed = falsefor item in ideas?.inspiration ?? [] {guard case .link(let url) = item.kind else { continue }guard online else { continue }- guard ((try? journal.isInspirationLinkSynced(item.id)) ?? true) == false else { continue }+ if ((try? journal.isInspirationLinkSynced(item.id)) ?? true) == false {+ do {+ let jobId = try await service.importInspirationLink(url)+ try? journal.markInspirationLinkSynced(item.id, jobId: jobId)+ landed = true+ } catch CloudSyncError.unauthorized {+ return+ } catch {+ // Transient or capped for the day; the next kick retries.+ }+ continue+ }+ guard let job = (try? journal.inspirationImportJobId(item.id)) ?? nil else { continue }do {- try await service.importInspirationLink(url)- try? journal.markInspirationLinkSynced(item.id)+ switch try await service.importedLink(jobId: job) {+ case .running:+ continue+ case .failed:+ try? journal.markInspirationImportFailed(item.id)+ landed = true+ case .done(let imported):+ let destination = journal.fetchedMediaDestination(item.id, isVideo: imported.isVideo)+ try await service.downloadLibraryMedia(+ fileName: imported.fileName,+ to: destination+ )+ try? journal.markInspirationFetched(+ item.id,+ fileName: destination.lastPathComponent,+ isVideo: imported.isVideo,+ remoteAssetId: imported.assetId+ )+ landed = true+ }} catch CloudSyncError.unauthorized {return} catch {- // Transient or capped for the day; the next kick retries.+ // Transient; the next pass asks after the job again.}}+ if landed { ideas?.reloadFromStore() }}private func uploadPendingInspirationMedia() async {diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swiftindex 3316b4c7..35dd75fb 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/IdeasScreen.swift@@ -7,26 +7,41 @@ import DonkeyKitModelsstruct IdeasScreen: View {@Bindable var app: AppModel@Bindable var ideas: IdeasModel+ var media: MediaModelvar auth: AuthModellet onRecordNote: (Note) -> Void@State private var showsLinkSheet = false@State private var showsPhotoPicker = false@State private var pickerItems: [PhotosPickerItem] = []-- private let columns = [GridItem(.adaptive(minimum: 160, maximum: 260), spacing: 14)]+ @State private var folderPrompt: FolderPrompt?+ @State private var moving: Note?+ @State private var path: [NoteFolder] = []var body: some View {- VStack(spacing: 0) {- ScreenHeader(title: "Ideas", app: app, auth: auth)- ScrollView {- VStack(alignment: .leading, spacing: 18) {- filterChips- content+ NavigationStack(path: $path) {+ VStack(spacing: 0) {+ ScreenHeader(title: "Ideas", app: app, auth: auth)+ ScrollView {+ VStack(alignment: .leading, spacing: 18) {+ filterChips+ content+ }+ .padding(.horizontal, 20)+ .padding(.top, 14)+ .padding(.bottom, 24)}- .padding(.horizontal, 20)- .padding(.top, 14)- .padding(.bottom, 24)+ // The phone pulls on its own clock; this is the same pass on+ // the reader's word.+ .refreshable { await media.sync?.refreshNow() }+ }+ .navigationDestination(for: NoteFolder.self) { folder in+ NoteFolderScreen(+ ideas: ideas,+ media: media,+ folder: folder,+ onMove: { moving = $0 }+ )}}.overlay(alignment: .bottomTrailing) { addMenu }@@ -37,6 +52,10 @@ struct IdeasScreen: View {LinkSheet(app: app, ideas: ideas).presentationDetents([.medium])}+ .sheet(item: $moving) { note in+ MoveToFolderSheet(ideas: ideas, note: note)+ }+ .folderPrompt($folderPrompt, ideas: ideas).photosPicker(isPresented: $showsPhotoPicker,selection: $pickerItems,@@ -54,13 +73,19 @@ struct IdeasScreen: View {app.show(toast: "Saved to Inspiration")}}+ // A folder opened here and then deleted on the desktop takes the+ // screen standing on it with it.+ .onChange(of: ideas.folders) { _, folders in+ path.removeAll { folder in !folders.contains { $0.id == folder.id } }+ }}private var addMenu: some View {Menu {Button("Paste link", systemImage: "link") { showsLinkSheet = true }Button("Camera roll", systemImage: "photo") { showsPhotoPicker = true }- Button("New note", systemImage: "pencil") { ideas.openEditor() }+ Button("New note", systemImage: "note.text") { ideas.openEditor() }+ Button("New folder", systemImage: "folder.badge.plus") { folderPrompt = .create }} label: {Image(systemName: "plus").font(.title2.weight(.bold))@@ -81,18 +106,21 @@ struct IdeasScreen: View {.pickerStyle(.segmented)}+ /// The notes at the top level; the ones inside folders are shown there.+ private var loose: [Note] { ideas.notes(in: nil) }+@ViewBuilder private var content: some View {switch ideas.filter {case .all:- if ideas.notes.isEmpty && ideas.inspiration.isEmpty {+ if ideas.notes.isEmpty && ideas.folders.isEmpty && ideas.inspiration.isEmpty {EmptyState(title: "Nothing here yet",message: "Add a note or save some inspiration to get started.")} else {- if !ideas.notes.isEmpty {+ if !ideas.notes.isEmpty || !ideas.folders.isEmpty {sectionLabel("Notes")- notesGrid+ notesSection}if !ideas.inspiration.isEmpty {sectionLabel("Inspiration")@@ -100,10 +128,10 @@ struct IdeasScreen: View {}}case .notes:- if ideas.notes.isEmpty {+ if ideas.notes.isEmpty && ideas.folders.isEmpty {EmptyState(title: "No notes yet", message: "Tap the note button to capture an idea.")} else {- notesGrid+ notesSection}case .inspiration:if ideas.inspiration.isEmpty {@@ -117,15 +145,132 @@ struct IdeasScreen: View {}}+ @ViewBuilder private var notesSection: some View {+ FolderList(+ folders: ideas.folders,+ count: { ideas.notes(in: $0).count },+ onRename: { folderPrompt = .rename($0) },+ onDelete: { ideas.deleteFolder(id: $0.id) }+ )+ NotesGrid(notes: loose, ideas: ideas, onMove: { moving = $0 })+ }+private func sectionLabel(_ text: String) -> some View {Text(text).font(.footnote.weight(.bold)).foregroundStyle(.secondary)}- private var notesGrid: some View {- LazyVGrid(columns: columns, spacing: 14) {- ForEach(ideas.notes) { note in+ private var inspirationGrid: some View {+ LazyVGrid(columns: ideaColumns, spacing: 14) {+ ForEach(ideas.inspiration) { item in+ InspirationCard(item: item, ideas: ideas)+ .contextMenu {+ Button("Delete", systemImage: "trash", role: .destructive) {+ ideas.deleteInspiration(id: item.id)+ }+ .tint(.red)+ }+ }+ }+ }+}++let ideaColumns = [GridItem(.adaptive(minimum: 160, maximum: 260), spacing: 14)]++/// One folder's notes, pushed from the Ideas screen.+struct NoteFolderScreen: View {+ @Bindable var ideas: IdeasModel+ var media: MediaModel+ let folder: NoteFolder+ let onMove: (Note) -> Void++ private var notes: [Note] { ideas.notes(in: folder.id) }++ var body: some View {+ ScrollView {+ if notes.isEmpty {+ EmptyState(+ title: "This folder is empty",+ message: "Notes you move here — or write here — show up in this folder."+ )+ .padding(.top, 40)+ } else {+ NotesGrid(notes: notes, ideas: ideas, onMove: onMove)+ .padding(.horizontal, 20)+ .padding(.top, 14)+ .padding(.bottom, 24)+ }+ }+ .refreshable { await media.sync?.refreshNow() }+ .navigationTitle(ideas.folder(folder.id)?.name ?? folder.name)+ .navigationBarTitleDisplayMode(.large)+ .toolbar {+ ToolbarItem(placement: .primaryAction) {+ Button("New note", systemImage: "square.and.pencil") {+ ideas.openEditor(in: folder.id)+ }+ }+ }+ }+}++/// The Apple-standard folder list: a row per folder with its count, opened by+/// a tap, renamed or deleted by a swipe or a long press.+struct FolderList: View {+ let folders: [NoteFolder]+ let count: (UUID) -> Int+ let onRename: (NoteFolder) -> Void+ let onDelete: (NoteFolder) -> Void++ var body: some View {+ if !folders.isEmpty {+ VStack(spacing: 0) {+ ForEach(folders) { folder in+ NavigationLink(value: folder) {+ HStack(spacing: 12) {+ Image(systemName: "folder.fill")+ .font(.title3)+ .foregroundStyle(.tint)+ Text(folder.name)+ .foregroundStyle(.primary)+ Spacer(minLength: 8)+ Text("\(count(folder.id))")+ .foregroundStyle(.secondary)+ .monospacedDigit()+ Image(systemName: "chevron.right")+ .font(.footnote.weight(.semibold))+ .foregroundStyle(.tertiary)+ }+ .padding(.vertical, 12)+ .contentShape(.rect)+ }+ .buttonStyle(.plain)+ .contextMenu {+ Button("Rename", systemImage: "pencil") { onRename(folder) }+ Button("Delete", systemImage: "trash", role: .destructive) {+ onDelete(folder)+ }+ }+ if folder.id != folders.last?.id {+ Divider()+ }+ }+ }+ .padding(.horizontal, 14)+ .background(.fill.quaternary, in: RoundedRectangle(cornerRadius: 16))+ }+ }+}++struct NotesGrid: View {+ let notes: [Note]+ var ideas: IdeasModel+ let onMove: (Note) -> Void++ var body: some View {+ LazyVGrid(columns: ideaColumns, spacing: 14) {+ ForEach(notes) { note inButton {ideas.openEditor(for: note)} label: {@@ -133,6 +278,7 @@ struct IdeasScreen: View {}.buttonStyle(.plain).contextMenu {+ Button("Move to Folder…", systemImage: "folder") { onMove(note) }Button("Delete", systemImage: "trash", role: .destructive) {ideas.deleteNote(id: note.id)}@@ -141,21 +287,134 @@ struct IdeasScreen: View {}}}+}- private var inspirationGrid: some View {- LazyVGrid(columns: columns, spacing: 14) {- ForEach(ideas.inspiration) { item in- InspirationCard(item: item, ideas: ideas)- .contextMenu {- Button("Delete", systemImage: "trash", role: .destructive) {- ideas.deleteInspiration(id: item.id)- }- .tint(.red)+/// Where a note is filed, chosen from the folders that exist — or a new one+/// named on the spot.+struct MoveToFolderSheet: View {+ var ideas: IdeasModel+ let note: Note++ @State private var prompt: FolderPrompt?+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ NavigationStack {+ List {+ Section {+ row(name: "Notes", systemImage: "note.text", folderId: nil)+ ForEach(ideas.folders) { folder in+ row(name: folder.name, systemImage: "folder", folderId: folder.id)}+ }+ Section {+ Button("New Folder…", systemImage: "folder.badge.plus") { prompt = .create }+ }+ }+ .navigationTitle("Move Note")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Cancel") { dismiss() }+ }+ }+ // A folder made here takes the note with it.+ .folderPrompt($prompt, ideas: ideas) { folder in+ ideas.move(noteId: note.id, to: folder.id)+ dismiss()+ }+ }+ .presentationDetents([.medium, .large])+ }++ private func row(name: String, systemImage: String, folderId: UUID?) -> some View {+ Button {+ ideas.move(noteId: note.id, to: folderId)+ dismiss()+ } label: {+ HStack {+ Label(name, systemImage: systemImage)+ Spacer()+ if note.folderId == folderId {+ Image(systemName: "checkmark")+ .foregroundStyle(.tint)+ }}}+ .foregroundStyle(.primary)+ }+}++/// Naming a folder: the standard alert with a text field, for a new folder or+/// a rename.+enum FolderPrompt: Identifiable {+ case create+ case rename(NoteFolder)++ var id: String {+ switch self {+ case .create: "create"+ case .rename(let folder): folder.id.uuidString+ }}+ var title: String {+ switch self {+ case .create: "New Folder"+ case .rename: "Rename Folder"+ }+ }++ var initialName: String {+ switch self {+ case .create: ""+ case .rename(let folder): folder.name+ }+ }+}++extension View {+ func folderPrompt(+ _ prompt: Binding<FolderPrompt?>,+ ideas: IdeasModel,+ onCreate: @escaping (NoteFolder) -> Void = { _ in }+ ) -> some View {+ modifier(FolderPromptModifier(prompt: prompt, ideas: ideas, onCreate: onCreate))+ }+}++private struct FolderPromptModifier: ViewModifier {+ @Binding var prompt: FolderPrompt?+ var ideas: IdeasModel+ let onCreate: (NoteFolder) -> Void++ @State private var name = ""++ func body(content: Content) -> some View {+ content+ .alert(prompt?.title ?? "", isPresented: showing, presenting: prompt) { prompt in+ TextField("Name", text: $name)+ .textInputAutocapitalization(.words)+ Button("Cancel", role: .cancel) {}+ Button("Save") {+ switch prompt {+ case .create:+ if let folder = ideas.addFolder(named: name) { onCreate(folder) }+ case .rename(let folder):+ ideas.renameFolder(id: folder.id, to: name)+ }+ }+ } message: { _ in+ Text("Enter a name for this folder.")+ }+ .onChange(of: prompt?.id) { _, _ in+ name = prompt?.initialName ?? ""+ }+ }++ private var showing: Binding<Bool> {+ Binding(get: { prompt != nil }, set: { if !$0 { prompt = nil } })+ }}struct NoteCard: View {@@ -202,30 +461,13 @@ struct InspirationCard: View {var ideas: IdeasModelvar body: some View {- switch item.kind {- case .link(let url):- Link(destination: url) {- VStack(alignment: .leading, spacing: 8) {- Label(url.host()?.replacingOccurrences(of: "www.", with: "") ?? "link", systemImage: "link")- .font(.footnote.weight(.bold))- .lineLimit(1)- Text(url.absoluteString)- .font(.caption)- .foregroundStyle(.secondary)- .lineLimit(4)- .multilineTextAlignment(.leading)- Spacer(minLength: 0)- }- .padding(14)- .frame(maxWidth: .infinity, minHeight: 120, alignment: .topLeading)- .background(.fill.tertiary)- .clipShape(RoundedRectangle(cornerRadius: 16))- }- .buttonStyle(.plain)- case .media(let fileName, let isVideo):- let url = ideas.mediaURL(fileName: fileName)+ // A saved link becomes its media: the cloud fetches the source and the+ // phone brings the video or photo down, so the card plays what the+ // link pointed at. Until it lands the card holds the source's name.+ if let media = item.media {+ let url = ideas.mediaURL(fileName: media.fileName)MediaTile(ratio: 3 / 4) {- if isVideo {+ if media.isVideo {VideoPlayer(player: AVPlayer(url: url))} else if let image = UIImage(contentsOfFile: url.localPath) {Image(uiImage: image)@@ -233,7 +475,46 @@ struct InspirationCard: View {.scaledToFill()}}+ } else if let link = item.link {+ LinkCard(url: link, state: item.importState)+ }+ }+}++/// A saved link with no media yet: fetching, or a source that had none.+struct LinkCard: View {+ let url: URL+ let state: InspirationImport++ var body: some View {+ let host = url.host()?.replacingOccurrences(of: "www.", with: "") ?? "link"+ Link(destination: url) {+ VStack(alignment: .leading, spacing: 8) {+ Label(host, systemImage: "link")+ .font(.footnote.weight(.bold))+ .lineLimit(1)+ if state == .failed {+ Text(url.absoluteString)+ .font(.caption)+ .foregroundStyle(.secondary)+ .lineLimit(4)+ .multilineTextAlignment(.leading)+ } else {+ HStack(spacing: 8) {+ ProgressView()+ Text("Fetching…")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ }+ Spacer(minLength: 0)+ }+ .padding(14)+ .frame(maxWidth: .infinity, minHeight: 120, alignment: .topLeading)+ .background(.fill.tertiary)+ .clipShape(RoundedRectangle(cornerRadius: 16))}+ .buttonStyle(.plain)}}@@ -273,7 +554,7 @@ struct LinkSheet: View {private func saveURL() {guard ideas.addInspiration(urlText: urlText) else { return }dismiss()- app.show(toast: "Saved to Inspiration")+ app.show(toast: "Fetching the link…")}}#endifdiff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swiftindex 981e42c2..248cbb07 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/MediaScreen.swift@@ -47,6 +47,7 @@ struct MediaScreen: View {.padding(.top, 14).padding(.bottom, 24)}+ .refreshable { await media.sync?.refreshNow() }}}}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swiftindex 59156963..338a0d1a 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/NoteEditorView.swift@@ -13,24 +13,49 @@ struct NoteEditorView: View {var body: some View {let color = ideas.draft?.color ?? .butter+ let hasContent = ideas.draft?.hasContent ?? falseVStack(spacing: 0) {- HStack {+ // Close on the left, and on the right the two things a finished+ // note is for: reading it to camera, and putting it away.+ HStack(spacing: 18) {Button {ideas.closeEditor()} label: {Image(systemName: "xmark").font(.title3.weight(.bold))}+ .accessibilityLabel("Close")+Spacer()+Button {- ideas.cycleDraftColor()+ guard let note = ideas.saveDraft() else { return }+ onRecordNote(note)} label: {- Circle()- .fill(color.accentColor)- .strokeBorder(Color.notePaperInk.opacity(0.75), lineWidth: 3)- .frame(width: 28, height: 28)+ Image(systemName: "play.circle.fill")+ .font(.title2.weight(.bold))}- .accessibilityLabel("Note color")+ .disabled(!hasContent)+ .accessibilityLabel("Read on camera")++ Button {+ // The keyboard goes first when it is up, so Done reads the+ // note before it closes it — the way Notes behaves.+ if focused != nil {+ focused = nil+ return+ }+ let wasNew = ideas.draft?.isNew ?? true+ guard ideas.saveDraft() != nil else {+ ideas.closeEditor()+ return+ }+ app.show(toast: wasNew ? "Note saved" : "Note updated")+ } label: {+ Image(systemName: "checkmark")+ .font(.title3.weight(.bold))+ }+ .accessibilityLabel("Done")}.padding(.horizontal, 20).padding(.top, 16)@@ -40,10 +65,13 @@ struct NoteEditorView: View {.padding(.horizontal, 22).padding(.top, 12).focused($focused, equals: .title)+ .submitLabel(.next)+ .onSubmit { focused = .body }TextEditor(text: bodyBinding).font(.system(size: 20, weight: .medium)).scrollContentBackground(.hidden)+ .scrollDismissesKeyboard(.interactively).padding(.horizontal, 18).focused($focused, equals: .body).overlay(alignment: .topLeading) {@@ -59,36 +87,15 @@ struct NoteEditorView: View {HStack {Button {- guard let note = ideas.saveDraft() else { return }- onRecordNote(note)+ ideas.cycleDraftColor()} label: {- Label("Record", systemImage: "record.circle")- .font(.body.weight(.bold))- .padding(.horizontal, 8)- .padding(.vertical, 6)+ Circle()+ .fill(color.accentColor)+ .strokeBorder(Color.notePaperInk.opacity(0.75), lineWidth: 3)+ .frame(width: 32, height: 32)}- .buttonStyle(.bordered)- .buttonBorderShape(.roundedRectangle(radius: 14))- .disabled(!(ideas.draft?.hasContent ?? false))-+ .accessibilityLabel("Note color")Spacer()-- Button {- let wasNew = ideas.draft?.isNew ?? true- guard ideas.saveDraft() != nil else { return }- app.show(toast: wasNew ? "Note saved" : "Note updated")- } label: {- Text("Save")- .font(.body.weight(.bold))- // The editor paints everything in the note's ink, which- // would hide the label on the ink-tinted prominent pill.- .foregroundStyle(.white)- .padding(.horizontal, 14)- .padding(.vertical, 6)- }- .buttonStyle(.borderedProminent)- .buttonBorderShape(.roundedRectangle(radius: 14))- .disabled(!(ideas.draft?.hasContent ?? false))}.padding(.horizontal, 20).padding(.vertical, 14)diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swiftindex 74d2871d..8e10ce5b 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/RootView.swift@@ -41,7 +41,7 @@ public struct RootView<CameraPreview: View>: View {ZStack {TabView(selection: $app.selectedTab) {Tab("Ideas", systemImage: "lightbulb", value: .ideas) {- IdeasScreen(app: app, ideas: ideas, auth: auth, onRecordNote: recordNote)+ IdeasScreen(app: app, ideas: ideas, media: media, auth: auth, onRecordNote: recordNote)}Tab("Library", systemImage: "books.vertical", value: .media) {MediaScreen(app: app, media: media, auth: auth)@@ -71,6 +71,13 @@ public struct RootView<CameraPreview: View>: View {.preferredColorScheme(app.appearance.colorScheme)}.task { await auth.restore() }+ // Notes and folders are written at the desk as well as here, so the+ // phone looks at the cloud on its own clock for as long as it is on+ // screen. Pull to refresh asks for the same pass at once.+ .task(id: scenePhase) {+ guard scenePhase == .active else { return }+ await media.sync?.beat()+ }.onChange(of: scenePhase) { _, phase inif phase == .active, auth.isSignedIn {media.sync?.kick()diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swiftindex c1451236..52353f09 100644--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift@@ -133,6 +133,14 @@ import Testingvar deletedAssets: [String] = []var deletedNotes: [UUID] = []var links: [URL] = []+ var polled: [String] = []+ var downloads: [String] = []+ var folders: [UUID: RemoteNoteFolder] = [:]+ var deletedFolders: [UUID] = []+ /// What an import job answers with once it is asked about.+ var imported: JobOutcome<ImportedLink> = .done(+ ImportedLink(assetId: "asset-link", fileName: "source.mp4", isVideo: true)+ )var usage = StorageUsage(bytes: 0, quotaBytes: 1_000_000)var uploadResult: Result<RemoteAsset, CloudSyncError> =.success(RemoteAsset(id: "asset-1", fileName: "clip.mov"))@@ -149,9 +157,27 @@ import Testing}func deleteLibraryAsset(id: String) async throws { deletedAssets.append(id) }- func importInspirationLink(_ url: URL) async throws { links.append(url) }++ func importInspirationLink(_ url: URL) async throws -> String {+ links.append(url)+ return "job-\(links.count)"+ }++ func importedLink(jobId: String) async throws -> JobOutcome<ImportedLink> {+ polled.append(jobId)+ return imported+ }++ func downloadLibraryMedia(fileName: String, to destination: URL) async throws {+ downloads.append(fileName)+ try Data("media".utf8).write(to: destination)+ }+func fetchUsage() async throws -> StorageUsage { usage }- func fetchNotes() async throws -> [RemoteNote] { Array(notes.values) }++ func fetchNotes() async throws -> RemoteNotes {+ RemoteNotes(notes: Array(notes.values), folders: Array(folders.values))+ }func putNote(_ note: RemoteNote) async throws -> RemoteNote {if let existing = notes[note.id], existing.updatedAt > note.updatedAt { return existing }@@ -163,6 +189,19 @@ import TestingdeletedNotes.append(id)notes[id] = nil}++ func putNoteFolder(_ folder: RemoteNoteFolder) async throws {+ folders[folder.id] = folder+ }++ func deleteNoteFolder(id: UUID) async throws {+ deletedFolders.append(id)+ folders[id] = nil+ for (noteId, note) in notes where note.folderId == id {+ notes[noteId]?.folderId = nil+ _ = noteId+ }+ }}struct Rig {@@ -319,13 +358,71 @@ import Testing#expect(rig.ideas.notes.isEmpty)}- @Test func inspirationLinkImportsOnce() async throws {+ @Test func inspirationLinkImportsOnceAndLandsItsMedia() async throws {let rig = try makeRig()#expect(rig.ideas.addInspiration(urlText: "youtube.com/watch?v=9"))await rig.engine.run()#expect(rig.cloud.links.map(\.host) == ["youtube.com"])+ // The queue pass only hands the link over; the next pass follows the+ // job and brings the media down.await rig.engine.run()#expect(rig.cloud.links.count == 1)+ #expect(rig.cloud.downloads == ["source.mp4"])+ let item = try #require(rig.ideas.inspiration.first)+ #expect(item.media?.isVideo == true)+ // Nothing is asked of the job again once its media is here.+ await rig.engine.run()+ #expect(rig.cloud.downloads.count == 1)+ }++ @Test func inspirationLinkWithNoMediaStaysALink() async throws {+ let rig = try makeRig()+ rig.cloud.imported = .failed+ #expect(rig.ideas.addInspiration(urlText: "example.com/article"))+ await rig.engine.run()+ await rig.engine.run()+ let item = try #require(rig.ideas.inspiration.first)+ #expect(item.media == nil)+ #expect(item.importState == .failed)+ #expect(rig.cloud.downloads.isEmpty)+ }++ @Test func folderPushesAheadOfTheNoteFiledInIt() 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()+ #expect(rig.cloud.folders[folder.id]?.name == "Scripts")+ #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 folderDeletedHereReachesTheCloud() async throws {+ let rig = try makeRig()+ let folder = try #require(rig.ideas.addFolder(named: "Scripts"))+ await rig.engine.run()+ rig.ideas.deleteFolder(id: folder.id)+ await rig.engine.run()+ #expect(rig.cloud.deletedFolders == [folder.id])+ #expect(try rig.store.tombstones().isEmpty)}@Test func cellularMovesEverything() async throws {diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.mdindex 7a29a951..5be573dd 100644--- a/docs/guides/ios-app.md+++ b/docs/guides/ios-app.md@@ -23,11 +23,21 @@ Every byte moves at most once. Uploads go straight to storage on presignedURLs; an interrupted upload re-presigns under the name it already claimed, anda retried completion lands on the asset it already made. Recordings arrive inthe desktop library marked as camera clips (the Camera Roll tab), inspiration-media lands in the Inspiration folder, and inspiration links queue a-cloud-side import that fetches the media there. Notes merge both ways by-last-writer-wins on the edit stamp, with tombstones so a delete made offline-on either side still lands on the other. Deleting a synced recording on the-phone deletes the cloud copy too.+media lands in the Inspiration folder, and a saved inspiration link queues a+cloud-side import: the worker fetches the source, the phone follows the job,+and the media comes back down onto the phone, so the card that was a link+plays the video the link pointed at. A source that turns out to be only words+stays a link. Notes merge both ways by last-writer-wins on the edit stamp,+with tombstones so a delete made offline on either side still lands on the+other. The folders notes file into travel with them, under ids whichever+device made them chose; a folder carries no tombstone, so a folder the cloud+listing no longer names was deleted elsewhere and its notes come back to the+top level. Deleting a synced recording on the phone deletes the cloud copy+too.++Notes are written at the desk as well as here, so the phone pulls on a clock+of its own while it is on screen, and pull to refresh runs the same pass at+once.A pass that ends with work still queued — a request that timed out, a 5xx —books its own next try and backs off, up to five minutes between attempts, so