SPB Git

Repository Public

EditorController.swift 9.0 KB 142 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Components/EditorController.swift3// Description: Owns one native note editor (text view + scroll view) and bridges it to SwiftUI: observable selection state, change notifications, atom activation, file drops, completions, and the local resources the block cards draw from (files, referenced blocks, page titles, citations).4import SwiftUI5import SPNotesDocument6import SPNotesEditor78@Observable final class EditorController: NoteTextViewDelegate, AtomResources {9    @ObservationIgnored let scrollView: NSScrollView10    @ObservationIgnored let textView: NoteTextView11    private(set) var selection = SelectionState()12    private(set) var wordCount = 013    /// Atom whose native editor (table grid, equation field, chart, PDF…) is requested.14    var activeAtom: ActiveAtom?15    /// A picker or popover of the note pane asked by a command.16    var sheet: EditorSheet?17    /// Menu commands that need a sheet of the note pane (link editor, file picker).18    var requestLink = 019    var requestFile: (imagesOnly: Bool, id: UUID)?20    @ObservationIgnored var onChange: (() -> Void)?21    @ObservationIgnored var onOpenLink: ((String) -> Void)?22    @ObservationIgnored var onOpenRoute: ((Route) -> Void)?23    @ObservationIgnored var onReceiveFiles: (([URL], [NSImage]) -> Void)?24    @ObservationIgnored var completions: ((Character, String) -> [CompletionItem])?25    @ObservationIgnored var imageProvider: ((String) -> NSImage?)?26    /// Looks things up in the local store for the cards; answers arrive later and the atoms are drawn again.27    @ObservationIgnored var lookup: EditorLookup?28    @ObservationIgnored private var citedCount: Int?2930    struct ActiveAtom: Identifiable, Equatable { let id = UUID(); let node: PMNode; let range: NSRange; let isBlock: Bool; let anchor: CGRect }31    /// Pickers and popovers opened from commands of the editor.32    enum EditorSheet: Identifiable, Equatable {33        case blockRef, citation, canvasLink, audioRecording34        case task(location: Int, anchor: CGRect)35        var id: String { switch self { case .blockRef: "blockRef"; case .citation: "citation"; case .canvasLink: "canvas"; case .audioRecording: "audio"; case .task(let l, _): "task-\(l)" } }36    }3738    init() {39        let made = NoteTextView.makeScrollable()40        scrollView = made.scroll; textView = made.view41        textView.noteDelegate = self; textView.resources = self42    }4344    func load(_ doc: NoteDocument) { textView.load(doc); wordCount = doc.wordCount; selection = textView.selectionState; citedCount = doc.citedReferences().count }45    func document() -> NoteDocument { textView.document() }46    func focus() { textView.window?.makeFirstResponder(textView) }47    var isFirstResponder: Bool { textView.window?.firstResponder === textView }4849    // MARK: NoteTextViewDelegate5051    func noteTextViewDidChange(_ view: NoteTextView) { citedCount = nil; onChange?() }52    func noteTextViewSelectionDidChange(_ view: NoteTextView) { let s = view.selectionState; if s != selection { selection = s } }53    func noteTextView(_ view: NoteTextView, open link: String) { onOpenLink?(link) }54    func noteTextView(_ view: NoteTextView, activate atom: AtomAttachment, at range: NSRange) {55        var actual = NSRange()56        let screen = view.firstRect(forCharacterRange: range, actualRange: &actual)57        let inWindow = view.window?.convertFromScreen(screen) ?? .zero58        activeAtom = ActiveAtom(node: atom.node, range: range, isBlock: atom.isBlock, anchor: view.convert(inWindow, from: nil))59    }60    func noteTextView(_ view: NoteTextView, receive files: [URL], images: [NSImage], at location: Int) { onReceiveFiles?(files, images) }61    func noteTextView(_ view: NoteTextView, completionsFor trigger: Character, query: String) -> [CompletionItem] { completions?(trigger, query) ?? [] }62    func noteTextView(_ view: NoteTextView, editTaskAt location: Int, anchor: CGRect) { sheet = .task(location: location, anchor: anchor) }63    func noteTextView(_ view: NoteTextView, openPage pageId: String, blockId: String?) { onOpenRoute?(Route(pageId: pageId, blockId: blockId)) }6465    // MARK: AtomResources6667    func image(for src: String) -> NSImage? { imageProvider?(src) }68    func attachmentURL(id: String) -> URL? { lookup?.fileURL(attachmentId: id) }69    func blockReference(pageId: String, blockId: String?) -> BlockReference? { lookup?.blockReference(pageId: pageId, blockId: blockId) }70    func pageTitle(id: String) -> String? { lookup?.pageTitle(id: id) }71    func citedReferenceCount() -> Int? { citedCount }72    func citationLabel(refId: String) -> String? { lookup?.citationLabel(refId: refId) }73    /// The count shown by a bibliography card follows the citations of the document (recomputed after edits, off the drawing path).74    func refreshCitedCount() { let n = textView.document().citedReferences().count; if n != citedCount { citedCount = n; textView.refreshAtoms() } }75}7677/// The editor inside SwiftUI. The AppKit views belong to the controller: SwiftUI only hosts them, so re-rendering the78/// surrounding interface never rebuilds the text view, never moves the caret and never takes the focus away.79struct NoteEditorView: NSViewRepresentable {80    let controller: EditorController81    func makeNSView(context: Context) -> NSScrollView { controller.scrollView }82    func updateNSView(_ nsView: NSScrollView, context: Context) {}83}8485/// Answers the editor's questions about the local store without blocking the drawing: a miss starts an asynchronous86/// read, and `onResolved` asks the editor to draw its cards again.87@MainActor final class EditorLookup {88    private weak var env: AppEnvironment?89    var onResolved: (() -> Void)?90    private var files: [String: URL] = [:], refs: [String: BlockReference] = [:], titles: [String: String?] = [:], labels: [String: String?] = [:]91    private var asked = Set<String>()92    init(env: AppEnvironment) { self.env = env }9394    private func once(_ key: String, _ work: @escaping @MainActor (AppEnvironment) async -> Bool) {95        guard asked.insert(key).inserted, let env else { return }96        Task { @MainActor in if await work(env) { self.onResolved?() } }97    }98    /// Forgets what was not found (a file may have been downloaded, a page synchronised since).99    func invalidate() { asked.removeAll(); refs = refs.filter { $0.value != .missing }; titles = titles.filter { $0.value != nil } }100101    func fileURL(attachmentId id: String) -> URL? {102        if let u = files[id] { return u }103        once("file:" + id) { env in104            if let rec = try? await env.store.attachment(id: id), let rel = rec.localPath, FileManager.default.fileExists(atPath: env.files.url(relativePath: rel).path) { self.files[id] = env.files.url(relativePath: rel); return true }105            if env.account.isSignedIn, env.connectivity.reachable, let url = try? await env.syncMonitor.download(attachmentId: id) { self.files[id] = url; return true }106            return false107        }108        return nil109    }110    func blockReference(pageId: String, blockId: String?) -> BlockReference? {111        let key = pageId + "#" + (blockId ?? "")112        if let r = refs[key] { return r }113        once("ref:" + key) { env in self.refs[key] = await Self.resolve(pageId: pageId, blockId: blockId, env: env); return true }114        return nil115    }116    /// Text of a block of another page, read from the local store (the open editor when the page is being edited).117    static func resolve(pageId: String, blockId: String?, env: AppEnvironment) async -> BlockReference {118        let doc: NoteDocument; let title: String119        if let s = env.existingSession(pageId) { doc = s.editor.document(); title = s.title }120        else if let page = try? await env.store.page(id: pageId), page.deletedAt == nil, let d = try? NoteDocument(json: page.content) { doc = d; title = page.title == "Untitled" ? "" : page.title }121        else { return .missing }122        guard let blockId, !blockId.isEmpty else { return .resolved(pageTitle: title, text: doc.preview(maxLength: 400)) }123        // the block itself, or every line of the container (list, callout, quote) that carries the id124        let lines = doc.lines.filter { $0.attrs["id"] == .string(blockId) || $0.path.contains { $0.attrs["id"] == .string(blockId) } }125        guard !lines.isEmpty else { return .missing }126        return .resolved(pageTitle: title, text: NoteDocument(lines: lines.map { var l = $0; l.path = []; return l }).plainText().trimmingCharacters(in: .whitespacesAndNewlines))127    }128    func pageTitle(id: String) -> String? {129        if let t = titles[id] { return t }130        once("title:" + id) { env in if let p = try? await env.store.summary(id: id), p.deletedAt == nil { self.titles[id] = p.title == "Untitled" ? "" : p.title; return true }; return false }131        return nil132    }133    func citationLabel(refId: String) -> String? {134        if let l = labels[refId] { return l }135        once("cite:" + refId) { env in136            guard let ref = try? await env.repositories.research.resolveLocally(ids: [refId])[refId] else { return false }137            self.labels[refId] = CitationFormat.label(ref); return true138        }139        return nil140    }141}142
Files main
Menu

Theme