Repository Public
1// SP Notes iOS2// File: Features/Notes/NoteActions.swift3// Description: The operations the lists offer on notes and folders (pin, favourite, archive, trash with undo, restore, purge,4// duplicate, share, drag and drop), written once and used by swipes, context menus, bulk actions and drops.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import CoreTransferable9import SPNotesCore10import SwiftUI11import UniformTypeIdentifiers1213extension AppModel {14 /// Runs a local operation and reports a failure in the banner instead of losing it. Returns true on success.15 @discardableResult16 func attempt(_ work: @MainActor () async throws -> Void) async -> Bool {17 do { try await work(); return true } catch {18 banner = Self.describe(error)19 return false20 }21 }2223 static func describe(_ error: Error) -> String {24 if let store = error as? StoreError {25 switch store {26 case .cycle: return String(localized: "Un dossier ne peut pas être déplacé dans lui-même.")27 case .notFound: return String(localized: "Cet élément n’existe plus.")28 default: return String(localized: "L’opération n’a pas pu être enregistrée sur cet appareil.")29 }30 }31 if let localized = error as? LocalizedError, let text = localized.errorDescription { return text }32 return String(localized: "L’opération n’a pas pu être enregistrée sur cet appareil.")33 }3435 /// Creates a note where the window is: in the folder or section shown, with the tag shown, as a favourite in Favoris.36 func createNote(in source: NoteSource?, title: String = "", markdown: String? = nil) async throws -> String {37 let document = markdown.map { NoteDocument(markdown: $0) }38 switch source {39 case .folder(let id)?: return try await createNote(title: title, parentId: id, document: document)40 case .section(let section)? where NoteSection.editable.contains(section): return try await createNote(title: title, section: section, document: document)41 case .tag(let tag)?: return try await createNote(title: title, document: document, tags: [tag])42 case .smart(.favorites)?:43 let id = try await createNote(title: title, document: document)44 try await setFavorite(id, true)45 return id46 default: return try await createNote(title: title, document: document)47 }48 }4950 @discardableResult51 func createFolder(title: String, parentId: String?, section: String) async throws -> String {52 try await createNote(title: title, parentId: parentId, section: parentId == nil ? section : nil, isFolder: true)53 }5455 /// Number of pages (notes and folders) below a page, the trash excluded.56 func descendantCount(of id: String) async -> Int {57 var count = 058 var queue = [id]59 while let next = queue.popLast() {60 let children = (try? await store.children(of: next, includeArchived: true)) ?? []61 count += children.count62 queue.append(contentsOf: children.filter(\.hasChildren).map(\.id))63 }64 return count65 }6667 /// Permanently removes everything in the trash from this device (the server part waits for the passkey confirmation).68 func emptyTrash() async {69 while true {70 guard let batch = try? await store.summaries(list: .trash, limit: 200), !batch.isEmpty else { return }71 var removed = 072 for page in batch where (try? await store.summary(id: page.id)) != nil {73 if (try? await purge(page.id)) != nil { removed += 1 }74 }75 if removed == 0 { return }76 }77 }7879 /// Title and text of a note, for sharing.80 func plainText(of id: String) async -> String {81 guard let page = try? await store.page(id: id) else { return "" }82 let title = Self.displayTitle(page.title)83 return page.plainText.isEmpty ? title : title + "\n\n" + page.plainText84 }85}8687/// The note operations bound to a window (so they can show the undo toast and close what disappears).88@MainActor89struct NoteCommands {90 let app: AppModel91 let shell: ShellState9293 func togglePin(_ note: PageSummary) async { await app.attempt { try await app.setPinned(note.id, !note.pinned) } }94 func toggleFavorite(_ note: PageSummary) async { await app.attempt { try await app.setFavorite(note.id, !note.favorite) } }9596 func setArchived(_ ids: [String], _ value: Bool) async {97 guard await app.attempt({ for id in ids { try await app.setArchived(id, value) } }) else { return }98 if value { ids.forEach(shell.close(note:)) }99 let message = value100 ? (ids.count == 1 ? String(localized: "Note archivée") : String(localized: "\(ids.count) notes archivées"))101 : (ids.count == 1 ? String(localized: "Note désarchivée") : String(localized: "\(ids.count) notes désarchivées"))102 shell.show(message, actionTitle: String(localized: "Annuler")) {103 Task { await app.attempt { for id in ids { try await app.setArchived(id, !value) } } }104 }105 }106107 /// Moves to the trash and offers to undo.108 func trash(_ ids: [String]) async {109 guard !ids.isEmpty else { return }110 guard await app.attempt({ for id in ids { try await app.trash(id) } }) else { return }111 ids.forEach(shell.close(note:))112 Haptics.tap()113 shell.show(ids.count == 1 ? String(localized: "Déplacée dans la corbeille") : String(localized: "\(ids.count) éléments déplacés dans la corbeille"),114 actionTitle: String(localized: "Annuler")) {115 Task { await app.attempt { for id in ids { try await app.restore(id) } } }116 }117 }118119 func restore(_ ids: [String]) async {120 guard await app.attempt({ for id in ids { try await app.restore(id) } }) else { return }121 shell.show(ids.count == 1 ? String(localized: "Note restaurée") : String(localized: "\(ids.count) éléments restaurés"))122 }123124 func purge(_ ids: [String]) async {125 // A page may already be gone with its parent folder: that is not a failure.126 for id in ids where (try? await app.store.summary(id: id)) != nil { await app.attempt { try await app.purge(id) } }127 ids.forEach(shell.close(note:))128 }129130 func duplicate(_ note: PageSummary) async {131 await app.attempt {132 _ = try await app.duplicate(note.id)133 shell.show(String(localized: "Copie créée"))134 }135 }136137 func file(_ note: PageSummary, section: String = "notes") async {138 await app.attempt {139 try await app.fileInboxItem(note.id, section: section)140 shell.show(String(localized: "Classée dans \(NoteSection.title(section))"))141 }142 }143144 /// Creates a note in the given source and opens it for typing.145 func newNote(in source: NoteSource?) async {146 await app.attempt {147 let id = try await app.createNote(in: source)148 Haptics.tap()149 shell.open(note: id, isNew: true)150 }151 }152153 /// Applies a drop of notes on a list of the sidebar or on a folder.154 func drop(_ ids: [String], on source: NoteSource) async {155 guard !ids.isEmpty else { return }156 switch source {157 case .smart(.favorites): await app.attempt { for id in ids { try await app.setFavorite(id, true) } }158 case .smart(.archived): await setArchived(ids, true)159 case .smart(.trash): await trash(ids)160 case .folder(let folder):161 await app.attempt { for id in ids where id != folder { try await app.move(id, toParent: folder) } }162 case .section(let section) where NoteSection.editable.contains(section):163 await app.attempt { for id in ids { try await app.move(id, toParent: nil, section: section) } }164 default: break165 }166 }167168 static func accepts(dropOn source: NoteSource) -> Bool {169 switch source {170 case .smart(.favorites), .smart(.archived), .smart(.trash), .folder: return true171 case .section(let section): return NoteSection.editable.contains(section)172 default: return false173 }174 }175}176177// MARK: - Drag and drop, sharing178179extension UTType {180 /// A reference to notes of this app, dragged between its own lists.181 static let spNoteReference = UTType(exportedAs: "ai.spboucher.spnotes.note-reference")182}183184/// What a dragged note row carries: ids only (the drop target looks the notes up). Other apps receive the web address of185/// the note(s) — as a URL and as plain text — so a note can be dropped into Mail, Messages, Reminders, a browser…186struct NoteTransfer: Codable, Transferable, Equatable {187 var ids: [String]188189 /// The web addresses of the notes (`https://note.spboucher.ai/p/<id>`).190 var webURLs: [URL] { ids.filter(DeepLink.isValidNoteID).map { DeepLink.webURL(noteId: $0) } }191 /// One address per line.192 var plainText: String { webURLs.map(\.absoluteString).joined(separator: "\n") }193194 /// True when a dropped text is nothing but addresses of notes of this app (a note dragged from one of our own lists).195 static func isOwnReference(_ text: String) -> Bool {196 let lines = text.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }197 return !lines.isEmpty && lines.allSatisfy { URL(string: $0).flatMap(DeepLink.web) != nil }198 }199200 static var transferRepresentation: some TransferRepresentation {201 CodableRepresentation(contentType: .spNoteReference)202 ProxyRepresentation(exporting: { (transfer: NoteTransfer) in transfer.webURLs.first ?? DeepLink.webURL(noteId: "") })203 .exportingCondition { $0.webURLs.count == 1 }204 ProxyRepresentation(exporting: \.plainText)205 }206}207208/// The text of a note, produced only when the share sheet asks for it (lists never load contents).209struct NoteTextShare: Transferable {210 let id: String211 let app: AppModel212 static var transferRepresentation: some TransferRepresentation {213 DataRepresentation(exportedContentType: .utf8PlainText) { item in Data(await item.app.plainText(of: item.id).utf8) }214 }215}216217/// The note a dedicated window shows (iPad multi-window, Stage Manager): the value of `WindowGroup(for:)`, so the system218/// restores the window with its note after a relaunch. Its scene is created by SwiftUI — it does NOT use `NoteActivity.type`219/// (1.0 reused that type for "new window", so one activation could be handled twice).220struct NoteWindowTarget: Codable, Hashable, Sendable {221 var noteId: String222 var blockId: String?223224 init(noteId: String, blockId: String? = nil) {225 self.noteId = noteId226 self.blockId = blockId227 }228}229