SPB Git

Repository Public

NativeDocumentView.swift 5.6 KB 117 lines swift

1// SP Notes iOS2// File: Features/Editor/NativeDocumentView.swift3// Description: A read-only, native rendering of a note document (the editor's own TextKit 2 stack, not editable): used to show4//              assistant answers, history versions and the two sides of a conflict exactly as the editor would draw them.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI10import UIKit1112struct NativeDocumentView: UIViewRepresentable {13    var document: NoteDocument14    /// true: the view scrolls its content (fills the space it is given). false: it takes the height of its content (chat bubbles).15    var scrolls = true16    /// Keeps the end of the text visible when the content grows (a streamed answer), unless the reader scrolled up.17    var followsEnd = false18    var identifier = "document-reader"19    @Environment(AppModel.self) private var app2021    init(document: NoteDocument, scrolls: Bool = true, followsEnd: Bool = false, identifier: String = "document-reader") {22        self.document = document23        self.scrolls = scrolls24        self.followsEnd = followsEnd25        self.identifier = identifier26    }2728    /// Markdown (what the assistant returns) shown as formatted text.29    init(markdown: String, scrolls: Bool = true, followsEnd: Bool = false, identifier: String = "document-reader") {30        self.init(document: NoteDocument(markdown: markdown), scrolls: scrolls, followsEnd: followsEnd, identifier: identifier)31    }3233    /// A stored document (JSON of a version or of a server copy); an unreadable one shows as empty.34    init(content: Data, scrolls: Bool = true, identifier: String = "document-reader") {35        self.init(document: (try? NoteDocument(json: content)) ?? NoteDocument(), scrolls: scrolls, identifier: identifier)36    }3738    func makeCoordinator() -> Coordinator { Coordinator() }3940    func makeUIView(context: Context) -> NoteTextView {41        let controller = context.coordinator.controller42        let textView = controller.textView43        textView.isEditable = false44        textView.isSelectable = true45        textView.inputAccessoryView = nil46        textView.isScrollEnabled = scrolls47        textView.accessibilityIdentifier = identifier48        textView.accessibilityLabel = nil49        // Reading only: the editor's own tap handling (checkboxes, atoms) is switched off so nothing can be changed here.50        for recognizer in textView.gestureRecognizers ?? [] where recognizer is UITapGestureRecognizer && recognizer.delegate === textView {51            recognizer.isEnabled = false52        }53        if !scrolls {54            textView.textContainerInset = UIEdgeInsets(top: 2, left: 0, bottom: 2, right: 0)55            textView.alwaysBounceVertical = false56            textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)57        }58        controller.atoms.imageProvider = { [weak app] src in app?.image(forSource: src) }59        controller.atoms.onMissingImage = { [weak app, weak controller] src in60            Task { @MainActor in61                guard let app, await app.resolveImage(source: src) else { return }62                controller?.invalidateImages(src: src)63            }64        }65        // 2.0: the cards of the 3.0 blocks read their outside data here too (pictures, referenced blocks, query rows…)66        let resolver = BlockCardResolver(app: app, noteId: "", store: controller.atoms.cards)67        resolver.invalidate = { [weak controller] types in controller?.invalidateAtoms { types.isEmpty || types.contains($0.type) } }68        context.coordinator.resolver = resolver69        return textView70    }7172    func updateUIView(_ textView: NoteTextView, context: Context) {73        let coordinator = context.coordinator74        guard coordinator.shown != document else { return }75        let wasAtEnd = textView.contentOffset.y >= textView.contentSize.height - textView.bounds.height - 6076        coordinator.shown = document77        coordinator.controller.load(document)78        if !scrolls { textView.invalidateIntrinsicContentSize() }79        if scrolls, followsEnd, wasAtEnd {80            textView.layoutIfNeeded()81            let bottom = max(-textView.adjustedContentInset.top, textView.contentSize.height - textView.bounds.height + textView.adjustedContentInset.bottom)82            textView.setContentOffset(CGPoint(x: 0, y: bottom), animated: false)83        }84    }8586    func sizeThatFits(_ proposal: ProposedViewSize, uiView textView: NoteTextView, context: Context) -> CGSize? {87        guard !scrolls, let width = proposal.width, width.isFinite, width > 0 else { return nil }88        // Block atoms (tables, pictures) are drawn for a given width: give the text view its width before measuring.89        if abs(textView.bounds.width - width) > 0.5 {90            textView.bounds.size.width = width91            textView.layoutIfNeeded()92        }93        let fitted = textView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude))94        return CGSize(width: width, height: ceil(fitted.height))95    }9697    @MainActor98    final class Coordinator {99        let controller = EditorController()100        var shown: NoteDocument?101        var resolver: BlockCardResolver?102    }103}104105/// Small facts shown next to a rendered version (history, conflicts).106enum DocumentFacts {107    static func words(_ count: Int) -> String {108        count == 1 ? String(localized: "1 mot") : String(localized: "\(count) mots")109    }110111    static func characters(_ count: Int) -> String {112        count == 1 ? String(localized: "1 caractère") : String(localized: "\(count) caractères")113    }114115    static func dateTime(_ date: Date) -> String { date.formatted(date: .abbreviated, time: .shortened) }116}117
Files main
Menu

Theme