Repository Public
1// SP Notes iOS2// File: Features/Editor/NoteEditorSupport.swift3// Description: Logic of the note screen kept out of the views so it can be tested: save/sync wording, statistics, the export menu,4// and the note operations the screen adds to the application model (versions, reminders, attachments).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SPNotesCore10import UIKit1112// MARK: - Save and sync state shown in the navigation bar1314/// What the navigation bar says about the note: where the text is (on the device) and whether the server has it.15struct NoteSyncBadge: Equatable {16 enum Tone: Equatable { case neutral, attention, problem }17 var text: String18 var symbol: String19 var tone: Tone20 /// A longer sentence for VoiceOver and the statistics sheet.21 var detail: String2223 static func make(save: NoteEditorModel.SaveState, sync: SyncState?, session: SessionState, isOnline: Bool) -> NoteSyncBadge {24 switch save {25 case .editing:26 return NoteSyncBadge(text: String(localized: "Enregistrement…"), symbol: "pencil.line", tone: .neutral,27 detail: String(localized: "Modifications en cours d’enregistrement sur l’appareil."))28 case .failed(let message):29 return NoteSyncBadge(text: String(localized: "Non enregistré"), symbol: "exclamationmark.triangle", tone: .problem,30 detail: String(localized: "L’enregistrement sur l’appareil a échoué : \(message)"))31 case .saved:32 break33 }34 switch sync {35 case .conflict?:36 return NoteSyncBadge(text: String(localized: "Conflit"), symbol: "exclamationmark.icloud", tone: .problem,37 detail: String(localized: "Enregistré sur l’appareil. Une autre version existe sur le serveur : choisis laquelle garder."))38 case .error?:39 return NoteSyncBadge(text: String(localized: "Erreur de synchronisation"), symbol: "xmark.icloud", tone: .problem,40 detail: String(localized: "Enregistré sur l’appareil. Le dernier envoi au serveur a échoué ; un nouvel essai sera fait."))41 case .pending?:42 if session != .signedIn {43 return NoteSyncBadge(text: String(localized: "Sur l’appareil"), symbol: "icloud.slash", tone: .attention,44 detail: String(localized: "Enregistré sur l’appareil seulement. Connecte-toi pour synchroniser."))45 }46 if !isOnline {47 return NoteSyncBadge(text: String(localized: "Hors ligne"), symbol: "icloud.slash", tone: .attention,48 detail: String(localized: "Enregistré sur l’appareil. La synchronisation reprendra au retour du réseau."))49 }50 return NoteSyncBadge(text: String(localized: "Enregistré"), symbol: "arrow.triangle.2.circlepath.icloud", tone: .neutral,51 detail: String(localized: "Enregistré sur l’appareil, en attente de synchronisation."))52 case .synced?, nil:53 return NoteSyncBadge(text: String(localized: "Enregistré"), symbol: "checkmark.icloud", tone: .neutral,54 detail: String(localized: "Enregistré sur l’appareil et synchronisé."))55 }56 }57}5859// MARK: - Statistics6061struct NoteStatistics: Equatable {62 var words: Int63 var characters: Int64 var charactersWithoutSpaces: Int65 var paragraphs: Int66 /// Minutes at 230 words per minute, at least 1 when there is text.67 var readingMinutes: Int6869 init(document: NoteDocument) {70 let text = document.plainText()71 words = document.wordCount72 characters = text.count73 charactersWithoutSpaces = text.reduce(0) { $0 + ($1.isWhitespace ? 0 : 1) }74 paragraphs = text.split(whereSeparator: \.isNewline).filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }.count75 readingMinutes = words == 0 ? 0 : max(1, Int((Double(words) / 230).rounded()))76 }77}7879// MARK: - Export menu8081/// The entries of "Exporter…" in the order of the menu, and the export itself.82@MainActor83enum NoteExportMenu {84 static let formats: [ExportFormat] = [.markdown, .plainText, .pdf, .rtf, .html]8586 static func identifier(_ format: ExportFormat) -> String { "export-\(format.rawValue)" }8788 /// Writes the export of the open note to a temporary file (the caller shares it).89 static func export(model: NoteEditorModel, format: ExportFormat) throws -> URL {90 // 2.0: the block cards of a PDF are drawn with what the open note already resolved91 NoteExporter.cardSource = model.controller.atoms.cards92 defer { NoteExporter.cardSource = nil }93 return try export(document: model.controller.document(), title: model.title, format: format, app: model.app)94 }9596 static func export(document: NoteDocument, title: String, format: ExportFormat, app: AppModel) throws -> URL {97 try NoteExporter.export(document: document, title: AppModel.displayTitle(title.trimmingCharacters(in: .whitespacesAndNewlines)), format: format) { src in app.image(forSource: src) }98 }99}100101// MARK: - Editor model helpers (owned by the screen; the engine files are not touched)102103extension NoteEditorModel {104 /// Saves the text being edited and waits until it is in the local database (before reading the note from the store:105 /// duplicate, history, conflict resolution). `flush()` alone does not wait.106 func saveNow() async {107 flush()108 guard isLoaded, !isMissing else { return }109 _ = try? await app.save(noteId: noteId, title: title, document: controller.document())110 }111112 /// Ranges of the atoms (image or file) that show the attachment `id`, last first.113 func atomRanges(forAttachment id: String) -> [NSRange] {114 var ranges: [NSRange] = []115 let storage = controller.storage116 storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, _ in117 guard let atom = value as? AtomAttachment else { return }118 let node = atom.node119 let source = AttachmentFiles.attachmentID(fromSource: node.stringAttr("src") ?? "")120 if node.stringAttr("attachmentId") == id || source == id { ranges.append(range) }121 }122 return ranges.reversed()123 }124125 /// Removes the blocks that show an attachment (after the file was deleted). Returns how many were removed.126 @discardableResult127 func removeAtoms(forAttachment id: String) -> Int {128 let ranges = atomRanges(forAttachment: id)129 for range in ranges { controller.deleteAtom(at: range) }130 return ranges.count131 }132133 /// Inserts recognised text (scan, picture, handwriting) as plain paragraphs below the caret's paragraph.134 func insertRecognizedText(_ text: String) {135 let lines = text.replacingOccurrences(of: "\r\n", with: "\n").split(separator: "\n", omittingEmptySubsequences: true)136 .map { Line.paragraph(text: String($0)) }137 controller.insertLines(lines)138 }139140 /// The title field lives inside the text view (it is created by `NoteEditorView`).141 var titleTextView: UITextView? {142 controller.textView.subviews.compactMap { $0 as? UITextView }.first { $0.accessibilityIdentifier == "note-title" }143 }144145 /// Read-only (a note in the trash): neither the body nor the title accepts input.146 func setReadOnly(_ readOnly: Bool) {147 let textView = controller.textView148 if textView.isEditable == readOnly {149 if readOnly { textView.resignFirstResponder() }150 textView.isEditable = !readOnly151 }152 if let title = titleTextView, title.isEditable == readOnly {153 if readOnly { title.resignFirstResponder() }154 title.isEditable = !readOnly155 }156 }157158 /// The system find bar over the note's text.159 func presentFind() {160 let textView = controller.textView161 textView.isFindInteractionEnabled = true162 textView.becomeFirstResponder()163 textView.findInteraction?.presentFindNavigator(showingReplace: false)164 }165}166167// MARK: - Note operations added to the application model168169extension AppModel {170 /// Restores a version kept on this device. The store first snapshots the current state, then applies the version as an171 /// ordinary local edit; the change is then synchronised like any other.172 @discardableResult173 func restoreLocalVersion(_ versionId: String) async throws -> PageRecord {174 let page = try await store.restoreVersion(id: versionId)175 syncNow()176 return page177 }178179 /// Applies a server snapshot as a normal local save (a local restore point is taken first), so it goes through the usual180 /// synchronisation instead of rewriting the server history from here.181 @discardableResult182 func applyServerVersion(noteId: String, title: String, content: Data) async throws -> Bool {183 let document = try NoteDocument(json: content)184 _ = try await store.snapshot(pageId: noteId, reason: "before-restore")185 return try await save(noteId: noteId, title: title, document: document)186 }187188 /// Creates a reminder for a note. The reminder is saved (and syncs as a task) whether or not notifications are allowed;189 /// the permission is asked here, at the first reminder. Returns the reminder and whether a notification could be scheduled.190 func addReminder(noteId: String, noteTitle: String, label: String, dueAt: Date,191 permission: (@MainActor () async -> Bool)? = nil) async throws -> (reminder: ReminderRecord, notifies: Bool) {192 let record = try await store.createReminder(pageId: noteId, title: ReminderLogic.cleanLabel(label), dueAt: dueAt)193 let allowed = await (permission ?? { [reminders] in await reminders.ensurePermission() })()194 if allowed { await reminders.schedule(record, noteTitle: noteTitle) }195 syncNow()196 return (record, allowed)197 }198199 @discardableResult200 func setReminderDone(_ id: String, done: Bool, noteTitle: String, notifies: Bool = true) async throws -> ReminderRecord {201 let record = try await store.updateReminder(id: id, done: done)202 if done { reminders.cancel(reminderId: id) } else if notifies { await reminders.schedule(record, noteTitle: noteTitle) }203 syncNow()204 return record205 }206207 func removeReminder(_ id: String) async throws {208 try await store.deleteReminder(id: id)209 reminders.cancel(reminderId: id)210 syncNow()211 }212213 func setKeepOffline(attachment id: String, _ keep: Bool) async throws {214 try await store.setAttachmentKeepOffline(id: id, keep)215 syncNow()216 }217218 /// Where the web application shows a page (databases are opened there).219 func webURL(forPage id: String) -> URL? {220 URL(string: "/p/\(id)", relativeTo: configuration.api.baseURL)?.absoluteURL221 }222}223224// MARK: - Sharing text225226enum TextShare {227 /// The system share sheet for plain text, anchored on the screen centre on iPad.228 @MainActor229 static func present(_ text: String) {230 let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }231 let window = scenes.first { $0.activationState == .foregroundActive }?.keyWindow ?? scenes.first?.keyWindow232 var top = window?.rootViewController233 while let presented = top?.presentedViewController, !presented.isBeingDismissed { top = presented }234 guard let presenter = top else { return }235 let controller = UIActivityViewController(activityItems: [text], applicationActivities: nil)236 if let popover = controller.popoverPresentationController {237 popover.sourceView = presenter.view238 popover.sourceRect = CGRect(x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 0, height: 0)239 popover.permittedArrowDirections = []240 }241 presenter.present(controller, animated: true)242 }243}244