SPB Git

Repository Public

NoteEditorModel.swift 17.1 KB 354 lines swift

1// SP Notes iOS2// File: Features/Editor/NoteEditorModel.swift3// Description: One open note: loads it into the native editor, saves every change to the local database after a short pause in4//              typing (and at once when the app leaves the foreground), and applies versions arriving from other devices without5//              taking the focus or the caret away. Saving never waits for the network.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesCore12import UIKit1314@MainActor15@Observable16final class NoteEditorModel: EditorControllerDelegate {17    enum SaveState: Equatable { case saved, editing, failed(String) }18    /// What the screen must present in answer to an editor event or a toolbar action.19    enum Request: Equatable {20        case link(current: String?)21        case table(node: PMNode, range: NSRange)22        case math(latex: String, inline: Bool, range: NSRange?)23        case drawing(attachmentId: String?, range: NSRange?)24        case preview(attachmentId: String, name: String)25        case atomMenu(node: PMNode, range: NSRange)26        case photoLibrary, camera, scanner, filePicker, noteLink, assistant27        /// 2.0: a block of SPEC §2 (or any block with a registered detail screen) was tapped → `BlockDetails`.28        case blockDetail(node: PMNode, range: NSRange)29        /// 2.0: choices needed before a block can be inserted, and the due date of the caret's task item.30        case blockRefPicker, canvasPicker, citationPicker, pdfPicker, audioPicker31        case taskDue(current: String?)32    }3334    /// 2.0: asks the editor to scroll to the block with this id and flash it (deep links, citations, backlinks, search hits).35    /// Kept until the note is loaded. Returns false when the note is loaded and has no such block.36    @discardableResult37    func reveal(blockId: String) -> Bool {38        guard isLoaded else { pendingRevealBlockId = blockId; return true }39        pendingRevealBlockId = nil40        return controller.revealBlock(id: blockId)41    }42    @ObservationIgnored var pendingRevealBlockId: String?43    /// 2.0: resolves what the block cards show from outside the document (Features/Editor/Blocks/BlockCardResolver.swift).44    @ObservationIgnored lazy var cardResolver = BlockCardResolver(app: app, noteId: noteId, store: controller.atoms.cards)45    @ObservationIgnored nonisolated(unsafe) var revealObserver: NSObjectProtocol?4647    let noteId: String48    let app: AppModel49    @ObservationIgnored let controller = EditorController()50    @ObservationIgnored let toolbar = EditorToolbar()5152    var title = ""53    private(set) var page: PageRecord?54    private(set) var isLoaded = false55    private(set) var isMissing = false56    private(set) var saveState: SaveState = .saved57    private(set) var context = EditorController.Context()58    private(set) var hasConflict = false59    private(set) var wordCount = 060    var request: Request?6162    @ObservationIgnored private var saveTask: Task<Void, Never>?63    @ObservationIgnored private var lastSavedContent = Data()64    @ObservationIgnored private var lastSavedTitle = ""65    @ObservationIgnored private var dirty = false66    @ObservationIgnored private var lastSnapshot = Date.distantPast67    @ObservationIgnored private nonisolated(unsafe) var backgroundObserver: NSObjectProtocol?6869    init(noteId: String, app: AppModel) {70        self.noteId = noteId71        self.app = app72        controller.delegate = self73        controller.textView.inputAccessoryView = toolbar74        controller.textView.onRequestLink = { [weak self] in self?.perform(.link) }75        controller.textView.onPasteImages = { [weak self] images in Task { await self?.insertImages(images) } }76        controller.atoms.imageProvider = { [weak app] src in app?.image(forSource: src) }77        controller.atoms.onMissingImage = { [weak self] src in78            Task { [weak self] in79                guard let self, await self.app.resolveImage(source: src) else { return }80                self.controller.invalidateImages(src: src)81            }82        }83        toolbar.onAction = { [weak self] action in self?.perform(action) }84        installBlocks()85        backgroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { [weak self] _ in86            MainActor.assumeIsolated { self?.flush() }87        }88    }8990    deinit {91        if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver) }92        if let revealObserver { NotificationCenter.default.removeObserver(revealObserver) }93    }9495    // MARK: loading9697    func load() async {98        guard !isLoaded else { return }99        await app.prepareAttachments(forNote: noteId)100        guard let page = try? await app.store.page(id: noteId) else { isMissing = true; isLoaded = true; return }101        apply(page, replacingContent: true)102        isLoaded = true103        revealPendingBlock()104        await app.markOpened(noteId)105        // a restore point of the note as it was when opened (the store skips it when nothing changed since the last one)106        _ = try? await app.store.snapshot(pageId: noteId, reason: "open")107        lastSnapshot = Date()108    }109110    private func apply(_ page: PageRecord, replacingContent: Bool) {111        self.page = page112        hasConflict = page.syncState == .conflict113        wordCount = page.wordCount114        if replacingContent {115            let document = (try? NoteDocument(json: page.content)) ?? NoteDocument()116            controller.atoms.forgetRequests()117            controller.load(document)118            title = page.title == AppModel.untitled ? "" : page.title119            lastSavedContent = page.content120            lastSavedTitle = title121            context = controller.context()122            toolbar.update(context)123        }124    }125126    /// The local database changed (sync, another scene, an extension): refresh what is shown, without disturbing typing.127    func storeChanged() async {128        guard isLoaded, !isMissing else { return }129        guard let fresh = try? await app.store.page(id: noteId) else { isMissing = true; return }130        await app.prepareAttachments(forNote: noteId)131        refreshCards()   // 2.0: files may have arrived for the block cards132        // The content changed underneath (a version from another device was applied, or a conflict was settled) and nothing is133        // waiting to be saved here: show it. With unsaved typing, the local text is saved first and the store keeps it.134        let contentChanged = fresh.content != lastSavedContent || (fresh.title == AppModel.untitled ? "" : fresh.title) != lastSavedTitle135        if contentChanged && !dirty {136            apply(fresh, replacingContent: true)137        } else {138            apply(fresh, replacingContent: false)139        }140    }141142    // MARK: saving143144    func titleChanged() { markDirty() }145146    private func markDirty() {147        dirty = true148        saveState = .editing149        saveTask?.cancel()150        saveTask = Task { [weak self] in151            try? await Task.sleep(for: .milliseconds(600))152            guard !Task.isCancelled else { return }153            await self?.save()154        }155    }156157    /// Saves now (leaving the screen, the app going to the background).158    func flush() {159        saveTask?.cancel()160        guard dirty else { return }161        // The document is read synchronously here, so the save holds the text even if the process is suspended right after.162        let document = controller.document(), title = title163        let background = UIApplication.shared.beginBackgroundTask(withName: "save-note")164        Task {165            await save(document: document, title: title)166            UIApplication.shared.endBackgroundTask(background)167        }168    }169170    private func save() async { await save(document: controller.document(), title: title) }171172    /// Saves pending edits and returns when they are in the local database (before an action that reads the stored note:173    /// duplicate, history, export, conflict resolution, trash).174    func flushAndWait() async {175        saveTask?.cancel()176        guard dirty else { return }177        await save()178    }179180    /// Read-only presentation (a note in the trash, a page type this app does not edit): no editing, no formatting bar.181    var isReadOnly = false {182        didSet {183            controller.textView.isEditable = !isReadOnly184            controller.textView.inputAccessoryView = isReadOnly ? nil : toolbar185            controller.textView.reloadInputViews()186        }187    }188189    private func save(document: NoteDocument, title: String) async {190        guard isLoaded, !isMissing else { return }191        dirty = false192        do {193            let data = try { var d = document; d.ensureBlockIds(); return try d.jsonData() }()194            let knownTitle = lastSavedTitle.trimmingCharacters(in: .whitespacesAndNewlines)195            try await app.save(noteId: noteId, title: title, document: document, fromEditor: true, knownTitle: knownTitle.isEmpty ? AppModel.untitled : knownTitle)196            lastSavedContent = data197            lastSavedTitle = title198            wordCount = document.wordCount199            // the scoped feed does not report the editor's own save back to it: read the row once here (sync state, dates)200            if let fresh = try? await app.store.page(id: noteId) { apply(fresh, replacingContent: false) }201            if !dirty { saveState = .saved }202            if Date().timeIntervalSince(lastSnapshot) > 600 {203                _ = try? await app.store.snapshot(pageId: noteId, reason: "autosave")204                lastSnapshot = Date()205            }206        } catch {207            dirty = true208            saveState = .failed(error.localizedDescription)209        }210    }211212    // MARK: EditorControllerDelegate213214    func editorDidChange(_ controller: EditorController) { markDirty() }215216    func editorDidChangeSelection(_ controller: EditorController) {217        let next = controller.context()218        toolbar.update(next)219        context = next220    }221222    func editor(_ controller: EditorController, didTapAtom node: PMNode, at range: NSRange) {223        switch node.type {224        case "table": request = .table(node: node, range: range)225        case "blockMath": request = .math(latex: node.stringAttr("latex") ?? "", inline: false, range: range)226        case "inlineMath": request = .math(latex: node.stringAttr("latex") ?? "", inline: true, range: range)227        case "image":228            request = .atomMenu(node: node, range: range)229        case "fileBlock":230            if let id = node.stringAttr("attachmentId") ?? AttachmentFiles.attachmentID(fromSource: node.stringAttr("src") ?? "") {231                request = .preview(attachmentId: id, name: node.stringAttr("name") ?? "")232            }233        case "mention":234            if let id = node.stringAttr("id") { app.pendingRoute = .note(id) }235        // 2.0: the blocks of SPEC §2 open their detail screen through `BlockDetails` (the atom menu when no provider takes them)236        case _ where node.typed != nil:237            request = .blockDetail(node: node, range: range)238        default:239            request = .atomMenu(node: node, range: range)240        }241    }242243    func editor(_ controller: EditorController, didTapLink href: String) { open(link: href) }244245    /// Internal links (`/p/<id>`) open the note; anything else goes to the system (default browser, mail, phone…).246    func open(link href: String) {247        if let range = href.range(of: "^/p/[0-9a-fA-F-]{36}", options: .regularExpression) {248            app.pendingRoute = .note(String(href[range].dropFirst(3)).lowercased())249            return250        }251        guard let url = URL(string: href, relativeTo: app.configuration.api.baseURL)?.absoluteURL else { return }252        UIApplication.shared.open(url)253    }254255    // MARK: toolbar actions256257    func perform(_ action: EditorAction) {258        switch action {259        case .mark(let type): controller.toggleMark(type)260        case .heading(let level): controller.setBlockType("heading", level: level)261        case .body: controller.setBlockType("paragraph")262        case .codeBlock: controller.setBlockType("codeBlock")263        case .list(let kind): controller.toggleList(kind)264        case .indent: controller.indent()265        case .outdent: controller.outdent()266        case .quote: controller.toggleBlockquote()267        case .callout: controller.toggleCallout()268        case .link: request = .link(current: controller.linkAtSelection()?.href)269        case .openLink: if let href = controller.linkAtSelection()?.href { open(link: href) }270        case .insertPhoto: request = .photoLibrary271        case .insertCamera: request = .camera272        case .insertScan: request = .scanner273        case .insertFile: request = .filePicker274        case .insertDrawing: request = .drawing(attachmentId: nil, range: nil)275        case .insertTable: controller.insertBlockAtom(PMNode.table(rows: 3, cols: 3, withHeaderRow: true))276        case .insertRule: controller.insertBlockAtom(PMNode.horizontalRule())277        case .insertMath: request = .math(latex: "", inline: false, range: nil)278        case .insertInlineMath: request = .math(latex: "", inline: true, range: nil)279        case .insertNoteLink: request = .noteLink280        case .assistant: request = .assistant281        case .undo: controller.textView.undoManager?.undo(); editorDidChange(controller)282        case .redo: controller.textView.undoManager?.redo(); editorDidChange(controller)283        case .dismissKeyboard: controller.textView.resignFirstResponder()284        default: performNext(action) // 2.0 actions: NoteEditorModel+Blocks.swift285        }286    }287288    // MARK: insertions289290    func insertFiles(_ urls: [URL]) async {291        for url in urls {292            do { controller.insertBlockAtom(try await app.attach(fileAt: url, to: noteId)) } catch { app.banner = error.localizedDescription }293        }294        await app.prepareAttachments(forNote: noteId)295    }296297    func insertImages(_ images: [UIImage]) async {298        for image in images {299            guard let data = image.jpegData(compressionQuality: 0.88) else { continue }300            let name = "image-\(Int(Date().timeIntervalSince1970))-\(Int.random(in: 100...999)).jpg"301            do { controller.insertBlockAtom(try await app.attach(data: data, filename: name, mime: "image/jpeg", to: noteId)) } catch { app.banner = error.localizedDescription }302        }303    }304305    /// Stores a drawing as two attachments — the PNG shown everywhere and the editable PencilKit source — and inserts or replaces306    /// the image atom. The source is never flattened away.307    func insertDrawing(png: Data, source: Data, replacing range: NSRange?) async {308        let stem = "drawing-\(UUID().uuidString.lowercased())"309        do {310            _ = try await app.attach(data: source, filename: stem + ".pkdrawing", mime: "application/octet-stream", to: noteId)311            let node = try await app.attach(data: png, filename: stem + ".png", mime: "image/png", to: noteId)312            if let range { controller.updateAtom(at: range, node: node) } else { controller.insertBlockAtom(node) }313        } catch { app.banner = error.localizedDescription }314    }315316    /// The editable source of a drawing image, found by its companion file name on the same note.317    func drawingSource(forImage node: PMNode) async -> Data? {318        guard let name = node.stringAttr("alt") ?? node.stringAttr("title"), name.hasPrefix("drawing-"), name.hasSuffix(".png") else { return nil }319        let companion = String(name.dropLast(4)) + ".pkdrawing"320        guard let record = (try? await app.store.attachments(pageId: noteId))?.first(where: { $0.filename == companion }),321              let url = try? await app.localFile(forAttachment: record.id) else { return nil }322        return try? Data(contentsOf: url)323    }324325    static func isDrawing(_ node: PMNode) -> Bool {326        guard node.type == "image", let name = node.stringAttr("alt") ?? node.stringAttr("title") else { return false }327        return name.hasPrefix("drawing-") && name.hasSuffix(".png")328    }329330    func insertMath(_ latex: String, inline: Bool, replacing range: NSRange?) {331        let node = inline ? PMNode.inlineMath(latex: latex) : PMNode.blockMath(latex: latex)332        if let range { controller.updateAtom(at: range, node: node) } else if inline { controller.insertInlineAtom(node) } else { controller.insertBlockAtom(node) }333    }334335    func insertMention(noteId target: String, title: String) {336        controller.insertInlineAtom(PMNode.mention(id: target, label: title))337    }338339    /// Inserts Markdown (an assistant answer) as document blocks after the caret's paragraph, or in place of the selection's paragraphs.340    func insertMarkdown(_ markdown: String, replacingSelection: Bool) {341        let lines = NoteDocument(markdown: markdown).lines342        let selection = controller.textView.selectedRange343        if replacingSelection && selection.length > 0 {344            controller.insertLines(lines, replacing: selection)345        } else {346            // below the END of the selection (not below its first paragraph)347            if selection.length > 0 { controller.textView.selectedRange = NSRange(location: NSMaxRange(selection), length: 0) }348            controller.insertLines(lines)349        }350    }351352    func focusBody() { controller.textView.becomeFirstResponder() }353}354
Files main
Menu

Theme