Repository Public
1// SP Notes iOS2// File: Features/Capture/QuickCaptureModel.swift3// Description: Quick Capture without its view: the modes, what each one saves (kind, title, text, link, files, recording), the4// draft kept when the sheet is closed by accident, and the choice of the signature motion (scale-in and Lumen5// pulse, or a plain fade under Reduce Motion).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesCore12import SPNotesDesign13import SwiftUI1415/// The modes of the capture sheet. The raw value is the name used by routes (`spnotes://capture?kind=…`, Quick Actions, `SPNOTES_OPEN=capture:…`).16enum CaptureMode: String, CaseIterable, Identifiable, Sendable, Codable {17 case text, idea, link, photo, scan, audio, dictation, file1819 var id: String { rawValue }2021 /// Lenient parsing of a route value (French and server names accepted); nil for anything unknown.22 init?(route value: String?) {23 guard let value = value?.lowercased().trimmingCharacters(in: .whitespaces), !value.isEmpty else { return nil }24 switch value {25 case "text", "texte", "note": self = .text26 case "idea", "idee", "idée": self = .idea27 case "link", "lien", "url": self = .link28 case "photo", "image": self = .photo29 case "scan", "document", "numerisation": self = .scan30 case "audio", "voice", "vocal": self = .audio31 case "dictation", "dictee", "dictée": self = .dictation32 case "file", "fichier": self = .file33 default: return nil34 }35 }3637 var title: String {38 switch self {39 case .text: return String(localized: "Texte")40 case .idea: return String(localized: "Idée")41 case .link: return String(localized: "Lien")42 case .photo: return String(localized: "Photo")43 case .scan: return String(localized: "Numériser")44 case .audio: return String(localized: "Audio")45 case .dictation: return String(localized: "Dictée")46 case .file: return String(localized: "Fichier")47 }48 }4950 var symbol: String {51 switch self {52 case .text: return "text.alignleft"53 case .idea: return "lightbulb"54 case .link: return "link"55 case .photo: return "photo"56 case .scan: return "doc.viewfinder"57 case .audio: return "mic"58 case .dictation: return "waveform.badge.mic"59 case .file: return "paperclip"60 }61 }6263 /// True when the keyboard should be up as soon as the sheet opens.64 var startsTyping: Bool { self == .text || self == .idea || self == .link }65}6667/// Signature motion #6, as decisions (the views apply them; the tests read them).68enum CaptureMotion {69 enum Appearance: Equatable { case scaleIn, fade }7071 static func appearance(reduceMotion: Bool) -> Appearance { reduceMotion ? .fade : .scaleIn }72 /// Sub-200 ms in motion; at most the reduced cross-fade otherwise.73 static func appearDuration(reduceMotion: Bool) -> Double { reduceMotion ? min(NVMotion.Token.fast.duration, NVMotion.reducedMaxDuration) : NVMotion.Token.fast.duration }74 static func appearAnimation(reduceMotion: Bool) -> Animation { NVMotion.animation(.fast, reduceMotion: reduceMotion) }75 static func transition(reduceMotion: Bool) -> AnyTransition { NVTransition.captureScaleIn(reduceMotion: reduceMotion) }76 /// The Lumen ring expands on save unless motion is reduced (it then only fades).77 static func pulseExpands(reduceMotion: Bool) -> Bool { !reduceMotion }78 /// How long the confirmation stays before the sheet closes by itself.79 static let confirmationDelay: Duration = .milliseconds(1400)80}8182/// The text of a capture in progress, kept across an accidental dismissal (and a relaunch). Files and recordings are not kept83/// here: the sheet refuses to be swiped away while it holds one.84struct CaptureDraftStore {85 struct Draft: Codable, Equatable {86 var mode: CaptureMode = .text87 var title = ""88 var text = ""89 var link = ""90 var isEmpty: Bool { [title, text, link].allSatisfy { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } }91 }9293 var defaults: UserDefaults = .standard94 var key = "capture.draft.v1"9596 func load() -> Draft? {97 guard let data = defaults.data(forKey: key), let draft = try? JSONDecoder().decode(Draft.self, from: data), !draft.isEmpty else { return nil }98 return draft99 }100101 func save(_ draft: Draft) {102 if draft.isEmpty { clear() } else if let data = try? JSONEncoder().encode(draft) { defaults.set(data, forKey: key) }103 }104105 func clear() { defaults.removeObject(forKey: key) }106}107108@MainActor109@Observable110final class QuickCaptureModel {111 var mode: CaptureMode112 var title = ""113 var text = ""114 var link = ""115 private(set) var files: [CaptureFile] = []116 private(set) var isSaving = false117 private(set) var savedPageId: String?118 /// Changes at each successful save: the trigger of the Lumen pulse.119 private(set) var saveCount = 0120 var error: String?121 /// True when the sheet opened on a draft found from an earlier, unfinished capture.122 private(set) var restoredDraft = false123124 let recorder: VoiceRecorderModel125 let dictation: DictationModel126 @ObservationIgnored private let drafts: CaptureDraftStore127128 init(mode: CaptureMode = .text, recorder: VoiceRecorderModel? = nil, dictation: DictationModel? = nil, drafts: CaptureDraftStore = CaptureDraftStore(), restoresDraft: Bool = true) {129 self.mode = mode130 self.recorder = recorder ?? VoiceDebug.recorder() ?? VoiceRecorderModel.system()131 self.dictation = dictation ?? DictationModel(engine: SystemDictation())132 self.drafts = drafts133 if restoresDraft, let draft = drafts.load() {134 title = draft.title; text = draft.text; link = draft.link135 // the caller's mode wins when it asked for a specific one (« Dictée » from a Quick Action); the text is kept either way136 if mode == .text { self.mode = draft.mode }137 restoredDraft = true138 }139 self.dictation.onUpdate = { [weak self] in self?.text = $0 }140 }141142 // MARK: what would be saved143144 var hasRecording: Bool { recorder.isActive || recorder.result != nil }145 /// Things a swipe would lose (they are not part of the stored draft).146 var holdsUnsavedMedia: Bool { !files.isEmpty || hasRecording || dictation.keptAudio != nil || dictation.isListening }147 var hasContent: Bool { !currentDraft.isEmpty || holdsUnsavedMedia }148 private var currentDraft: CaptureDraftStore.Draft { CaptureDraftStore.Draft(mode: mode, title: title, text: text, link: link) }149150 var canSave: Bool {151 guard !isSaving else { return false }152 let hasText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, hasTitle = !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty153 switch mode {154 case .text, .idea: return hasText || hasTitle155 case .dictation: return hasText || hasTitle || dictation.keptAudio != nil156 case .link: return CaptureKinds.httpURL(link) != nil || CaptureKinds.firstLink(in: link) != nil157 case .photo, .scan, .file: return !files.isEmpty158 case .audio: return hasRecording159 }160 }161162 /// The capture kind (server vocabulary) the current content is saved as.163 var kind: String {164 switch mode {165 case .text, .idea:166 // a text that is only an address is a link167 return CaptureKinds.httpURL(text) != nil && files.isEmpty ? CaptureKindName.link : CaptureKindName.note168 case .dictation: return text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && dictation.keptAudio != nil ? CaptureKindName.audio : CaptureKindName.note169 case .link: return CaptureKindName.link170 case .photo: return CaptureKindName.photo171 case .scan: return CaptureKindName.document172 case .audio: return CaptureKindName.audio173 case .file: return CaptureKinds.kind(forFiles: files) == CaptureKindName.photo ? CaptureKindName.photo : CaptureKindName.file174 }175 }176177 var draft: CaptureDraft {178 if mode == .link { return CaptureDraft(kind: kind, text: text, url: CaptureKinds.httpURL(link) ?? CaptureKinds.firstLink(in: link)) }179 if kind == CaptureKindName.link { return CaptureDraft(kind: kind, text: nil, url: CaptureKinds.httpURL(text)) }180 return CaptureDraft(kind: kind, text: text)181 }182183 var icon: String? { mode == .idea ? CaptureKinds.ideaIcon : nil }184185 // MARK: editing186187 func select(_ next: CaptureMode) {188 guard next != mode else { return }189 if dictation.isListening { dictation.stop() }190 mode = next191 }192193 func add(files urls: [URL]) {194 for url in urls where !files.contains(where: { $0.url == url }) { files.append(CaptureFile(url: url, filename: url.lastPathComponent)) }195 }196197 func remove(file: CaptureFile) {198 files.removeAll { $0 == file }199 MediaTemp.discard(file.url)200 }201202 func appendRecognized(_ recognized: String) {203 let clean = recognized.trimmingCharacters(in: .whitespacesAndNewlines)204 guard !clean.isEmpty else { return }205 text = text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? clean : text + "\n\n" + clean206 }207208 /// Paste detection of the link mode: a pasted sentence that contains an address keeps the address in the field and the rest as the note.209 func linkFieldChanged() {210 guard CaptureKinds.httpURL(link) == nil, let found = CaptureKinds.firstLink(in: link), link.contains(where: \.isWhitespace) else { return }211 let rest = link.replacingOccurrences(of: found, with: "").trimmingCharacters(in: .whitespacesAndNewlines)212 link = found213 if !rest.isEmpty { appendRecognized(rest) }214 }215216 func toggleDictation() async {217 if dictation.isListening { dictation.stop() } else { await dictation.start(appendingTo: text) }218 }219220 // MARK: drafts221222 /// The sheet is going away without a save: the text is kept for the next time.223 func keepDraft() { if savedPageId == nil || !currentDraft.isEmpty { drafts.save(currentDraft) } }224225 /// The user chose to throw the capture away.226 func discardAll() {227 if dictation.isListening { dictation.stop() }228 dictation.releaseAudio(discard: true)229 recorder.discard()230 files.forEach { MediaTemp.discard($0.url) }231 files = []232 title = ""; text = ""; link = ""233 drafts.clear()234 restoredDraft = false235 }236237 // MARK: saving238239 /// Saves into the inbox. Returns the page id, nil when it failed (`error` says why; nothing is lost: the sheet keeps its content).240 @discardableResult241 func save(app: AppModel) async -> String? {242 guard canSave else { return nil }243 isSaving = true244 defer { isSaving = false }245 if dictation.isListening { dictation.stop() }246 var voice: VoiceCapture?247 if mode == .audio, let audio = recorder.result ?? recorder.stop() {248 voice = VoiceCapture(fileURL: audio.fileURL, duration: audio.duration, recordedAt: audio.startedAt, title: title.trimmingCharacters(in: .whitespacesAndNewlines))249 } else if mode == .dictation, let audio = dictation.keptAudio {250 // the dictated text is the transcript of the kept audio, made on the device251 let said = dictation.spoken.trimmingCharacters(in: .whitespacesAndNewlines)252 voice = VoiceCapture(fileURL: audio.fileURL, duration: audio.duration, recordedAt: audio.startedAt, title: title.trimmingCharacters(in: .whitespacesAndNewlines),253 transcript: said.isEmpty ? [] : [TranscriptSegment(t: 0, text: said)], transcriptEngine: said.isEmpty ? nil : TranscriptEngines.onDevice)254 }255 do {256 let attached = [.photo, .scan, .file].contains(mode) ? files : []257 let outcome = try await app.capture(draft, title: title, icon: icon, files: attached, voice: voice)258 if outcome.failedFiles > 0 { app.banner = String(localized: "Un fichier n’a pas pu être joint à la capture.") }259 // everything is in the note now: the temporary copies and the draft go260 attached.forEach { MediaTemp.discard($0.url) }261 if let voice { MediaTemp.discard(voice.fileURL) }262 files = []263 recorder.reset()264 dictation.releaseAudio(discard: false)265 dictation.reset()266 title = ""; text = ""; link = ""267 drafts.clear()268 restoredDraft = false269 error = nil270 savedPageId = outcome.pageId271 saveCount += 1272 return outcome.pageId273 } catch {274 self.error = error.localizedDescription275 return nil276 }277 }278279 /// Ready for another capture in the same sheet.280 func startAnother() { savedPageId = nil }281}282