SPB Git

Repository Public

NoteEditorModel+Blocks.swift 9.3 KB 178 lines swift

1// SP Notes iOS2// File: Features/Editor/NoteEditorModel+Blocks.swift3// Description: 2.0 behaviour of an open note around the blocks of SPEC §2: the toolbar / slash-menu actions that insert them4//              (typed builders of the Core, sensible defaults), task due date and priority, callout kinds, the context handed to5//              a block's detail screen, the card resolver, and the hand-off that reveals a block when a note is opened at it.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AVFoundation10import Foundation11import SPNotesCore12import UIKit1314/// « Open this note at this block »: posted before the route is set, consumed by the editor of that note when it loads, or at15/// once when the note is already open. (`AppRoute.note(_, blockId:)` carries the same information; the shell posts it here.)16@MainActor17enum BlockRevealRequests {18    static let notification = Notification.Name("ai.spboucher.spnotes.revealBlock")19    private static var pending: [String: String] = [:]2021    static func post(noteId: String, blockId: String) {22        pending[noteId] = blockId23        NotificationCenter.default.post(name: notification, object: nil, userInfo: ["noteId": noteId, "blockId": blockId])24    }2526    static func consume(noteId: String) -> String? { pending.removeValue(forKey: noteId) }27}2829extension NoteEditorModel {30    // MARK: installation3132    /// Wires the 2.0 engine hooks; called once from `init`.33    func installBlocks() {34        controller.onCommand = { [weak self] action in self?.perform(action) }35        controller.onTapTaskBadge = { [weak self] location in36            guard let self else { return }37            self.controller.textView.selectedRange = self.controller.clampSelection(NSRange(location: location, length: 0))38            self.request = .taskDue(current: self.controller.context().taskDue)39        }40        cardResolver.invalidate = { [weak self] types in41            self?.controller.invalidateAtoms { types.isEmpty || types.contains($0.type) }42        }43        revealObserver = NotificationCenter.default.addObserver(forName: BlockRevealRequests.notification, object: nil, queue: .main) { [weak self] note in44            let noteId = note.userInfo?["noteId"] as? String, blockId = note.userInfo?["blockId"] as? String45            MainActor.assumeIsolated {46                guard let self, let blockId, noteId == self.noteId, self.isLoaded, BlockRevealRequests.consume(noteId: self.noteId) != nil else { return }47                self.reveal(blockId: blockId)48            }49        }50    }5152    /// Scrolls to the pending block once the text view has a width (the screen may still be appearing).53    func revealPendingBlock(attempt: Int = 0) {54        guard let id = pendingRevealBlockId ?? BlockRevealRequests.consume(noteId: noteId) else { return }55        pendingRevealBlockId = id56        if controller.textView.bounds.width < 10, controller.textView.window == nil, attempt < 20 {57            DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in self?.revealPendingBlock(attempt: attempt + 1) }58            return59        }60        pendingRevealBlockId = nil61        controller.revealBlock(id: id)62    }6364    /// The store changed outside the editor (a file arrived, a page was edited elsewhere): what the cards could not show is65    /// asked again. Cards whose content did not change come back from the cache.66    func refreshCards() {67        let store = controller.atoms.cards68        store.forgetRequests()69        store.pdfs = store.pdfs.filter { $0.value.thumbnail != nil }70        store.blockTargets.removeAll()71        store.pageTitles.removeAll()72        controller.invalidateAtoms { $0.typed != nil }73    }7475    // MARK: detail screens76    // `blockDetailContext(range:isEditable:dismiss:)` — what a block detail screen can do with this note — is in77    // Features/Drawing/DrawingEntryPoints.swift (one implementation for every provider). A route to a block78    // (`.note(id, blockId:)`) set on `app.pendingRoute` is revealed through `BlockRevealRequests` by the shell.7980    // MARK: actions8182    /// The 2.0 toolbar and slash-menu actions.83    func performNext(_ action: EditorAction) {84        switch action {85        case .insertMermaid: insertAndOpen(MermaidBlock(code: "graph TD\n  A[Début] --> B[Fin]").node())86        case .insertChart:87            insertAndOpen(ChartBlock(kind: .bar, title: "", columns: [String(localized: "Catégorie"), String(localized: "Valeur")],88                                     rows: [["A", 1], ["B", 2], ["C", 3]], x: nil, y: []).node())89        case .insertQueryView: insertAndOpen(QueryViewBlock(source: .tasks, title: "").node())90        case .insertRunCode: insertAndOpen(RunCodeBlock(language: "javascript", code: "").node())91        case .insertBibliography: controller.insertBlockAtom(BibliographyBlock().node())92        case .insertBlockRef: request = .blockRefPicker93        case .insertCanvasLink: request = .canvasPicker94        case .insertCitation: request = .citationPicker95        case .insertPDF: request = .pdfPicker96        case .insertAudio: request = .audioPicker97        case .insertDetails:98            if !controller.insertDetails() { app.banner = String(localized: "Un bloc dépliable se crée à partir d’un paragraphe, hors d’une liste.") }99        case .insertFootnote:100            if !controller.insertFootnote() { app.banner = String(localized: "Une note de bas de page s’ajoute depuis un texte.") }101        case .calloutKind(let kind): controller.setCallout(kind)102        case .removeCallout: controller.removeCallout()103        case .codeLanguage(let language): controller.setCodeLanguage(language)104        case .taskDue(let due): controller.setTaskDue(due)105        case .taskDuePicker: request = .taskDue(current: controller.context().taskDue)106        case .taskPriority(let priority): controller.setTaskPriority(priority)107        case .atomOpen:108            if let atom = controller.selectedBlockAtom() { editor(controller, didTapAtom: atom.node, at: atom.range) }109        case .atomCopy:110            if let atom = controller.selectedBlockAtom() {111                UIPasteboard.general.string = NoteExporter.fallbackText(for: atom.node, isBlock: true)112                Haptics.success()113            }114        case .atomDelete:115            if let atom = controller.selectedBlockAtom() { controller.deleteAtom(at: atom.range) }116        default: break117        }118    }119120    /// Inserts a block with its defaults and opens its detail screen at once (there is something to fill in).121    private func insertAndOpen(_ node: PMNode) {122        let range = controller.insertBlockAtom(node)123        request = .blockDetail(node: node, range: range)124    }125126    // MARK: insertions that need a choice first127128    /// A PDF picked from Files becomes a `pdf` block (annotations live in the node; the file is an attachment).129    func insertPDFs(_ urls: [URL]) async {130        for url in urls {131            do {132                let file = try await app.attach(fileAt: url, to: noteId, mime: "application/pdf")133                guard let id = file.stringAttr("attachmentId") else { controller.insertBlockAtom(file); continue }134                controller.insertBlockAtom(PDFBlock(attachmentId: id, name: file.stringAttr("name") ?? url.lastPathComponent).node())135            } catch { app.banner = error.localizedDescription }136        }137        await app.prepareAttachments(forNote: noteId)138    }139140    /// An audio file picked from Files becomes an `audio` block: its real duration is read from the file, nothing is transcribed.141    func insertAudioFiles(_ urls: [URL]) async {142        for url in urls {143            do {144                let duration = (try? await AVURLAsset(url: url).load(.duration)).map { CMTimeGetSeconds($0) } ?? 0145                let file = try await app.attach(fileAt: url, to: noteId)146                guard let id = file.stringAttr("attachmentId") else { controller.insertBlockAtom(file); continue }147                let title = (file.stringAttr("name") ?? url.lastPathComponent).split(separator: ".").dropLast().joined(separator: ".")148                controller.insertBlockAtom(AudioBlock(attachmentId: id, duration: duration.isFinite ? max(0, duration) : 0, title: title, recordedAt: nil).node())149            } catch { app.banner = error.localizedDescription }150        }151        await app.prepareAttachments(forNote: noteId)152    }153154    func insertBlockRef(pageId: String, blockId: String?, mode: BlockRefMode = .embed) {155        controller.insertBlockAtom(BlockRefBlock(pageId: pageId, blockId: blockId, mode: mode).node())156    }157158    func insertCanvasLink(pageId: String) {159        controller.insertBlockAtom(CanvasLinkBlock(pageId: pageId).node())160    }161162    func insertCitation(refId: String, label: String, locator: String) {163        controller.insertInlineAtom(CitationInline(refId: refId, label: label, locator: locator).node())164    }165}166167#if DEBUG168extension AppModel {169    /// Debug launches only: `SPNOTES_OPEN=note/<id>` or `note/<id>#<blockId>` opens that note once the sample data is in.170    func openDebugRoute(_ value: String? = ProcessInfo.processInfo.environment["SPNOTES_OPEN"]) {171        guard let value, value.hasPrefix("note/") else { return }172        let parts = value.dropFirst(5).split(separator: "#", maxSplits: 1).map(String.init)173        guard let id = parts.first, !id.isEmpty else { return }174        pendingRoute = .note(id, blockId: parts.count > 1 ? parts[1] : nil)175    }176}177#endif178
Files main
Menu

Theme