SPB Git

Repository Public

BlockRefModel.swift 12.8 KB 280 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Blocks/BlockRefModel.swift3// Description: Resolution and read-only rendering model of a cross-reference (`blockRef` node, SPEC §2): the source page4//              is read from the local store, the block is found by its id anywhere in the document, and it is flattened5//              into a small list of displayable items (paragraphs, headings, list items, code, quotes, callouts; any6//              other node becomes a neutral card). No web view, no conversion of the source: the reference only reads.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPNotesDocument13import SPNotesStore14import SPNotesSync1516/// One displayable piece of a referenced block.17public struct BlockRefItem: Identifiable, Equatable, Sendable {18    public enum Kind: Equatable, Sendable {19        case paragraph20        case heading(level: Int)21        case bullet22        case ordered(number: Int)23        case task(checked: Bool)24        case code(language: String)25        /// A node the reference does not draw (table, image, diagram…): a neutral card with its name.26        case atom(type: String)27        case divider28    }2930    public var id: Int31    public var kind: Kind32    public var text: AttributedString33    /// Nesting inside lists.34    public var depth: Int35    /// Inside a block quote.36    public var quoted: Bool37    /// The emoji of the callout this item is in, on its first item only.38    public var calloutIcon: String?39    /// Inside a callout.40    public var inCallout: Bool4142    public var plainText: String { String(text.characters) }43}4445public enum BlockRefRenderer {46    /// The node with this block id, searched in the whole document (lists, quotes, callouts, details included).47    public static func find(blockId: String, in node: PMNode) -> PMNode? {48        if node.attrs?["id"]?.stringValue == blockId { return node }49        for child in node.content ?? [] {50            if let found = find(blockId: blockId, in: child) { return found }51        }52        return nil53    }5455    /// The displayable items of a block (or of several top-level blocks).56    public static func items(_ nodes: [PMNode], limit: Int = 200) -> [BlockRefItem] {57        var out: [BlockRefItem] = []58        var context = Context()59        for node in nodes { append(node, &out, &context, limit: limit) }60        return out61    }6263    struct Context {64        var depth = 065        var quoted = false66        var inCallout = false67        var pendingCalloutIcon: String?68        var marker: BlockRefItem.Kind?69    }7071    private static func push(_ kind: BlockRefItem.Kind, _ text: AttributedString, _ out: inout [BlockRefItem], _ context: inout Context) {72        out.append(BlockRefItem(id: out.count, kind: kind, text: text, depth: context.depth, quoted: context.quoted, calloutIcon: context.pendingCalloutIcon, inCallout: context.inCallout))73        context.pendingCalloutIcon = nil74    }7576    private static func append(_ node: PMNode, _ out: inout [BlockRefItem], _ context: inout Context, limit: Int) {77        guard out.count < limit else { return }78        switch node.type {79        case NodeType.paragraph, NodeType.detailsSummary, NodeType.footnote:80            let text = inline(node.content ?? [])81            // The first paragraph of a list item carries the item's marker.82            if let marker = context.marker {83                push(marker, text, &out, &context)84                context.marker = nil85            } else if !text.characters.isEmpty {86                push(.paragraph, text, &out, &context)87            }88        case NodeType.heading:89            let level = min(6, max(1, node.attrs?["level"]?.intValue ?? 1))90            push(.heading(level: level), inline(node.content ?? []), &out, &context)91        case NodeType.codeBlock:92            let language = node.attrs?["language"]?.stringValue ?? ""93            push(.code(language: language == "plaintext" ? "" : language), AttributedString((node.content ?? []).compactMap(\.text).joined()), &out, &context)94        case NodeType.horizontalRule:95            push(.divider, AttributedString(), &out, &context)96        case NodeType.bulletList, NodeType.orderedList, NodeType.taskList:97            var number = node.attrs?["start"]?.intValue ?? 198            for item in node.content ?? [] {99                let kind: BlockRefItem.Kind100                switch node.type {101                case NodeType.orderedList: kind = .ordered(number: number); number += 1102                case NodeType.taskList: kind = .task(checked: item.attrs?["checked"]?.boolValue ?? false)103                default: kind = .bullet104                }105                appendItem(item, kind, &out, &context, limit: limit)106            }107        case NodeType.listItem:108            appendItem(node, .bullet, &out, &context, limit: limit)109        case NodeType.taskItem:110            appendItem(node, .task(checked: node.attrs?["checked"]?.boolValue ?? false), &out, &context, limit: limit)111        case NodeType.blockquote:112            let was = context.quoted113            context.quoted = true114            for child in node.content ?? [] { append(child, &out, &context, limit: limit) }115            context.quoted = was116        case NodeType.callout, NodeType.aiBlock:117            let was = (context.inCallout, context.pendingCalloutIcon)118            context.inCallout = true119            context.pendingCalloutIcon = node.type == NodeType.aiBlock ? "✦" : (node.attrs?["icon"]?.stringValue ?? "💡")120            for child in node.content ?? [] { append(child, &out, &context, limit: limit) }121            context.inCallout = was.0122            context.pendingCalloutIcon = was.1123        case NodeType.details, NodeType.detailsContent, NodeType.doc:124            for child in node.content ?? [] { append(child, &out, &context, limit: limit) }125        default:126            push(.atom(type: node.type), AttributedString(atomLabel(node)), &out, &context)127        }128    }129130    private static func appendItem(_ item: PMNode, _ kind: BlockRefItem.Kind, _ out: inout [BlockRefItem], _ context: inout Context, limit: Int) {131        let children = item.content ?? []132        context.marker = kind133        if children.first?.type != NodeType.paragraph {134            push(kind, AttributedString(), &out, &context)135            context.marker = nil136        }137        for (index, child) in children.enumerated() {138            if index == 0, child.type == NodeType.paragraph {139                append(child, &out, &context, limit: limit)140            } else {141                context.marker = nil142                context.depth += 1143                append(child, &out, &context, limit: limit)144                context.depth -= 1145            }146        }147        context.marker = nil148    }149150    /// Inline content with its marks (bold, italic, code, strike, underline, link).151    public static func inline(_ nodes: [PMNode]) -> AttributedString {152        var out = AttributedString()153        for node in nodes {154            switch node.type {155            case NodeType.text:156                var piece = AttributedString(node.text ?? "")157                var intent: InlinePresentationIntent = []158                for mark in node.marks ?? [] {159                    switch mark.type {160                    case "bold": intent.insert(.stronglyEmphasized)161                    case "italic": intent.insert(.emphasized)162                    case "code": intent.insert(.code)163                    case "strike": intent.insert(.strikethrough)164                    case "underline": piece.underlineStyle = .single165                    case "link":166                        if let href = mark.attrs?["href"]?.stringValue, let url = URL(string: href) { piece.link = url }167                    default: break168                    }169                }170                if !intent.isEmpty { piece.inlinePresentationIntent = intent }171                out.append(piece)172            case NodeType.hardBreak:173                out.append(AttributedString("\n"))174            case NodeType.mention:175                out.append(AttributedString("@" + (node.attrs?["label"]?.stringValue ?? "")))176            case NodeType.inlineMath:177                var piece = AttributedString(node.attrs?["latex"]?.stringValue ?? "")178                piece.inlinePresentationIntent = .code179                out.append(piece)180            case NodeType.citation:181                let label = node.attrs?["label"]?.stringValue ?? ""182                let locator = node.attrs?["locator"]?.stringValue ?? ""183                out.append(AttributedString("[" + [label, locator].filter { !$0.isEmpty }.joined(separator: ", ") + "]"))184            case NodeType.footnoteRef:185                out.append(AttributedString("*"))186            default:187                if let text = node.text { out.append(AttributedString(text)) }188            }189        }190        return out191    }192193    /// What a node the reference does not draw is called.194    public static func atomLabel(_ node: PMNode) -> String {195        switch node.type {196        case NodeType.table: return L("Tableau")197        case NodeType.image: return L("Image")198        case NodeType.fileBlock: return LF("Fichier : %@", node.attrs?["name"]?.stringValue ?? "")199        case NodeType.blockMath: return node.attrs?["latex"]?.stringValue ?? L("Formule")200        case NodeType.youtube: return L("Vidéo")201        case NodeType.mermaid: return L("Diagramme Mermaid")202        case NodeType.drawing: return L("Dessin")203        case NodeType.chart:204            let title = node.attrs?["title"]?.stringValue ?? ""205            return title.isEmpty ? L("Graphique") : LF("Graphique : %@", title)206        case NodeType.queryView:207            let title = node.attrs?["title"]?.stringValue ?? ""208            return title.isEmpty ? L("Vue dynamique") : LF("Vue : %@", title)209        case NodeType.bibliography: return node.attrs?["title"]?.stringValue ?? L("Références")210        case NodeType.pdf: return LF("PDF : %@", node.attrs?["name"]?.stringValue ?? "")211        case NodeType.blockRef: return L("Référence à un autre bloc")212        case NodeType.runCode: return L("Code exécutable")213        case NodeType.audio:214            let title = node.attrs?["title"]?.stringValue ?? ""215            return title.isEmpty ? L("Note vocale") : LF("Note vocale : %@", title)216        case NodeType.canvasLink: return L("Canevas")217        default: return L("Bloc non affiché ici")218        }219    }220}221222@Observable @MainActor223public final class BlockRefModel {224    public enum Resolution: Equatable, Sendable {225        case loading226        /// The page or the block does not exist (any more) on this device: « Référence introuvable ».227        case missing228        case found(Target)229    }230231    public struct Target: Equatable, Sendable {232        public var pageId: String233        public var blockId: String?234        public var pageTitle: String235        public var pageIcon: String?236        public var items: [BlockRefItem]237        /// A whole-page reference shows the beginning of the page only.238        public var truncated: Bool239    }240241    public let block: BlockRefBlock242    public private(set) var resolution: Resolution = .loading243    private let store: NotesStore244    private weak var router: (any FeatureRouter)?245246    /// How many top-level blocks a whole-page embed shows.247    public static let pagePreviewBlocks = 6248249    public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, block: BlockRefBlock) {250        store = repositories.context.store251        self.router = router252        self.block = block253    }254255    public var isLink: Bool { block.mode == .link }256    public var phase: LoadPhase { resolution == .loading ? .loading : .loaded }257258    public func load() async {259        guard let pageId = block.pageId else { resolution = .missing; return }260        let record: PageRecord?261        do { record = try await store.page(id: pageId) } catch { record = nil }262        guard let record, record.deletedAt == nil, let root = try? PMNode(data: record.content) else { resolution = .missing; return }263        let title = record.title.isEmpty ? L("Sans titre") : record.title264        if let blockId = block.blockId {265            guard let node = BlockRefRenderer.find(blockId: blockId, in: root) else { resolution = .missing; return }266            resolution = .found(Target(pageId: pageId, blockId: blockId, pageTitle: title, pageIcon: record.icon, items: BlockRefRenderer.items([node]), truncated: false))267        } else {268            let blocks = root.content ?? []269            let shown = Array(blocks.prefix(Self.pagePreviewBlocks))270            resolution = .found(Target(pageId: pageId, blockId: nil, pageTitle: title, pageIcon: record.icon, items: BlockRefRenderer.items(shown), truncated: blocks.count > shown.count))271        }272    }273274    /// Opens the source at the referenced block (nothing when the target is missing).275    public func open() {276        guard case .found(let target) = resolution else { return }277        router?.openPage(id: target.pageId, blockId: target.blockId)278    }279}280
Files main
Menu

Theme