SPB Git

Repository Public

BlockCardBuilder.swift 23.6 KB 426 lines swift

1// SP Notes iOS2// File: Editor/BlockCardBuilder.swift3// Description: What each 3.0 block shows in its card (SPEC §2), built from the Core's typed views — never from raw JSON — and4//              from what was resolved outside the document (`BlockCardStore`: attachment pictures, PDF thumbnails, query rows,5//              referenced blocks, cited references, page titles). Nothing is invented: what is not known is said to be unknown.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import UIKit1112/// What a card needs from outside the document. Asked once; the owner resolves it and invalidates the cards.13enum BlockCardNeed: Hashable {14    case image(attachmentId: String)15    case pdf(attachmentId: String)16    case ink(attachmentId: String)17    case query(BlockCardStore.QueryKey)18    case blockRef(pageId: String, blockId: String?)19    case page(id: String)20    case references([String])21}2223/// Resolved facts the cards draw from. Filled asynchronously by `BlockCardResolver`; read synchronously while drawing.24@MainActor25final class BlockCardStore {26    struct QueryKey: Hashable {27        var source: String28        var databaseId: String?29        var viewId: String?30        var filter: QueryFilter31        var limit: Int32    }33    struct QueryRows: Hashable {34        var columns: [String]35        var rows: [[String]]36        var total: Int37        var fetchedAt: Date38        var fromCache: Bool39    }40    enum QueryState: Hashable { case rows(QueryRows), unavailable(String) }41    struct BlockTarget: Hashable {42        var pageTitle: String?43        /// Nil when the page exists and the block does not (or the page is missing: then `pageTitle` is nil too).44        var text: String?45    }46    struct PDFInfo: Hashable {47        var thumbnail: UIImage?48        var pageCount: Int49    }50    struct Reference: Hashable {51        var label: String52        var entry: String53    }5455    var queries: [QueryKey: QueryState] = [:]56    var blockTargets: [String: BlockTarget] = [:]57    /// Page id → title; an entry with nil = the page does not exist on this device.58    var pageTitles: [String: String?] = [:]59    var pdfs: [String: PDFInfo] = [:]60    var inks: [String: UIImage] = [:]61    var references: [String: Reference] = [:]62    /// Attachment ids whose download was tried and failed (offline, deleted).63    var unavailableAttachments = Set<String>()64    /// Reference ids asked for and not found in the local copy.65    var unknownReferences = Set<String>()6667    /// The local picture of an attachment (`/api/files/<id>`), nil when it is not on the device.68    var imageProvider: (String) -> UIImage? = { _ in nil }69    /// The references cited in the document being shown, in order (for `bibliography`).70    var citedReferences: () -> [String] = { [] }71    var onNeed: (BlockCardNeed) -> Void = { _ in }72    private var requested = Set<BlockCardNeed>()7374    /// True for a one-shot rendering (an export): nothing is asked for, and what is not known is said as a fact, not as a wait.75    var isFinal = false7677    /// Takes what another store already resolved (the open note's, for its export).78    func adopt(_ other: BlockCardStore) {79        queries = other.queries; blockTargets = other.blockTargets; pageTitles = other.pageTitles; pdfs = other.pdfs; inks = other.inks80        references = other.references; unavailableAttachments = other.unavailableAttachments; unknownReferences = other.unknownReferences81        citedReferences = other.citedReferences82    }8384    func need(_ need: BlockCardNeed) {85        guard !isFinal, !requested.contains(need) else { return }86        requested.insert(need)87        onNeed(need)88    }8990    /// Forgets what was asked (another note is loaded, or the files changed) so it is asked again.91    func forgetRequests() { requested.removeAll(); unavailableAttachments.removeAll(); unknownReferences.removeAll() }9293    static func targetKey(pageId: String, blockId: String?) -> String { pageId + "#" + (blockId ?? "") }94    func picture(attachmentId: String) -> UIImage? { imageProvider("/api/files/" + attachmentId) }95}9697extension QueryViewBlock {98    var cardKey: BlockCardStore.QueryKey {99        BlockCardStore.QueryKey(source: source.rawValue, databaseId: databaseId, viewId: viewId, filter: filter, limit: limit)100    }101}102103/// French labels of the typed values shown in cards and sheets.104enum BlockLabels {105    static func chartKind(_ kind: ChartKind) -> String {106        switch kind {107        case .bar: String(localized: "Barres")108        case .line: String(localized: "Courbe")109        case .area: String(localized: "Aires")110        case .pie: String(localized: "Secteurs")111        case .scatter: String(localized: "Nuage de points")112        default: kind.rawValue113        }114    }115    static func querySource(_ source: QuerySource) -> String {116        switch source {117        case .tasks: String(localized: "Tâches")118        case .pages: String(localized: "Pages")119        case .database: String(localized: "Base de données")120        case .references: String(localized: "Références")121        case .backlinks: String(localized: "Rétroliens")122        default: source.rawValue123        }124    }125    static func queryLayout(_ layout: QueryLayout) -> String {126        switch layout {127        case .list: String(localized: "Liste")128        case .table: String(localized: "Tableau")129        case .board: String(localized: "Colonnes")130        default: layout.rawValue131        }132    }133    static func transcriptStatus(_ status: TranscriptStatus) -> String {134        switch status {135        case .none: String(localized: "Sans transcription")136        case .pending: String(localized: "Transcription en cours")137        case .done: String(localized: "Transcrit")138        case .failed: String(localized: "Transcription échouée")139        default: status.rawValue140        }141    }142    static func filterSummary(_ filter: QueryFilter) -> [String] {143        var out: [String] = []144        if let tag = filter.tag { out.append("#" + tag) }145        if let section = filter.section { out.append(section) }146        if let status = filter.status { out.append(String(localized: "état : \(status)")) }147        if let text = filter.text { out.append("« \(text) »") }148        if let after = filter.dueAfter { out.append(String(localized: "dès le \(String(after.prefix(10)))")) }149        if let before = filter.dueBefore { out.append(String(localized: "avant le \(String(before.prefix(10)))")) }150        if filter.parentId != nil { out.append(String(localized: "sous une page")) }151        return out152    }153    /// mm:ss, minutes not capped at 59 (like the transcript time codes).154    static func duration(_ seconds: Double) -> String {155        let total = Int(max(0, seconds).rounded())156        return String(format: "%02d:%02d", total / 60, total % 60)157    }158    static func date(_ iso: String?) -> String? {159        guard let iso, let date = TaskItemDetail.date(from: iso) else { return nil }160        return date.formatted(date: .abbreviated, time: .shortened)161    }162    static func pages(_ count: Int) -> String { count == 1 ? String(localized: "1 page") : String(localized: "\(count) pages") }163    static func annotations(_ count: Int) -> String { count == 1 ? String(localized: "1 annotation") : String(localized: "\(count) annotations") }164    static func firstLines(_ text: String, _ count: Int) -> String {165        text.split(separator: "\n", omittingEmptySubsequences: false).prefix(count).joined(separator: "\n")166    }167}168169@MainActor170enum BlockCardBuilder {171    static func card(for block: TypedBlock, width: CGFloat, traits: UITraitCollection, store: BlockCardStore) -> BlockCard? {172        switch block {173        case .mermaid(let b): return mermaid(b, store)174        case .drawing(let b): return drawing(b, store)175        case .chart(let b): return chart(b, width: width, traits: traits)176        case .queryView(let b): return queryView(b, store)177        case .bibliography(let b): return bibliography(b, store)178        case .pdf(let b): return pdf(b, store)179        case .blockRef(let b): return blockRef(b, store)180        case .runCode(let b): return runCode(b)181        case .audio(let b): return audio(b)182        case .canvasLink(let b): return canvasLink(b, store)183        case .citation: return nil184        }185    }186187    /// The picture of an attachment when it is on the device; otherwise asks for it and says why nothing is shown.188    private static func picture(_ id: String, _ store: BlockCardStore) -> (UIImage?, BlockCard.Item?) {189        if let image = store.picture(attachmentId: id) { return (image, nil) }190        if store.unavailableAttachments.contains(id) || store.isFinal {191            return (nil, .notice(String(localized: "Fichier non disponible sur cet appareil pour l’instant"), symbol: "icloud.slash", tone: .neutral))192        }193        store.need(.image(attachmentId: id))194        return (nil, .notice(String(localized: "Téléchargement en cours…"), symbol: "arrow.down.circle", tone: .neutral))195    }196197    static func mermaid(_ block: MermaidBlock, _ store: BlockCardStore) -> BlockCard {198        var card = BlockCard(symbol: "point.3.connected.trianglepath.dotted", kicker: "Mermaid", title: String(localized: "Diagramme"))199        let code = block.code.trimmingCharacters(in: .whitespacesAndNewlines)200        if code.isEmpty {201            card.items.append(.notice(String(localized: "Diagramme vide — touche pour écrire le code"), symbol: "pencil", tone: .neutral))202            return card203        }204        if block.isPreviewCurrent, let preview = block.preview {205            let (image, notice) = picture(preview, store)206            if let image {207                card.items.append(.picture(image, maxHeight: 360, framed: true))208                return card209            }210            card.items.append(.text(BlockLabels.firstLines(code, 8), style: .mono, maxLines: 8))211            if let notice { card.items.append(notice) }212            return card213        }214        card.items.append(.text(BlockLabels.firstLines(code, 8), style: .mono, maxLines: 8))215        card.items.append(.notice(String(localized: "Rendu à mettre à jour depuis le Web"), symbol: "arrow.triangle.2.circlepath", tone: .warning))216        return card217    }218219    static func drawing(_ block: DrawingBlock, _ store: BlockCardStore) -> BlockCard {220        var card = BlockCard(symbol: "pencil.and.scribble", kicker: String(localized: "Dessin"), title: String(localized: "Dessin à main levée"))221        if block.width > 0, block.height > 0 { card.meta.append("\(Int(block.width)) × \(Int(block.height))") }222        if let preview = block.preview, let image = store.picture(attachmentId: preview) {223            card.items.append(.picture(image, maxHeight: 360, framed: true))224            return card225        }226        if let ink = block.ink {227            if let image = store.inks[ink] {228                card.items.append(.picture(image, maxHeight: 360, framed: true))229                return card230            }231            if !store.unavailableAttachments.contains(ink) { store.need(.ink(attachmentId: ink)) }232        }233        if let preview = block.preview, !store.unavailableAttachments.contains(preview) { store.need(.image(attachmentId: preview)) }234        if block.ink == nil && block.preview == nil {235            card.items.append(.notice(String(localized: "Dessin vide"), symbol: "scribble", tone: .neutral))236        } else {237            card.items.append(.notice(String(localized: "Aperçu non disponible sur cet appareil pour l’instant"), symbol: "icloud.slash", tone: .neutral))238        }239        return card240    }241242    static func chart(_ block: ChartBlock, width: CGFloat, traits: UITraitCollection) -> BlockCard {243        let title = block.title.trimmingCharacters(in: .whitespacesAndNewlines)244        var card = BlockCard(symbol: block.kind == .pie ? "chart.pie.fill" : (block.kind == .line || block.kind == .area ? "chart.xyaxis.line" : "chart.bar.fill"),245                             kicker: String(localized: "Graphique") + " · " + BlockLabels.chartKind(block.kind),246                             title: title.isEmpty ? String(localized: "Graphique") : title)247        if let image = ChartSnapshot.image(block, width: max(120, width - 28), traits: traits) {248            card.items.append(.picture(image, maxHeight: 260, framed: false))249        } else {250            card.items.append(.notice(String(localized: "Aucune donnée à tracer"), symbol: "chart.bar.xaxis", tone: .neutral))251        }252        if block.source != nil {253            card.meta.append(String(localized: "Instantané"))254            card.meta.append(String(localized: "source : base de données"))255        }256        let rows = block.rows.count257        if rows > 0 { card.meta.append(rows == 1 ? String(localized: "1 ligne") : String(localized: "\(rows) lignes")) }258        return card259    }260261    static func queryView(_ block: QueryViewBlock, _ store: BlockCardStore) -> BlockCard {262        let title = block.title.trimmingCharacters(in: .whitespacesAndNewlines)263        var card = BlockCard(symbol: "list.bullet.rectangle.portrait", kicker: String(localized: "Vue dynamique"),264                             title: title.isEmpty ? BlockLabels.querySource(block.source) : title)265        card.items.append(.chips([BlockLabels.querySource(block.source), BlockLabels.queryLayout(block.layout)] + BlockLabels.filterSummary(block.filter)))266        switch store.queries[block.cardKey] {267        case .rows(let result)?:268            if result.rows.isEmpty {269                card.items.append(.notice(String(localized: "Aucun résultat"), symbol: "tray", tone: .neutral))270            } else if block.layout == .table, result.columns.count > 1 {271                let columns = Array(result.columns.prefix(3))272                card.items.append(.grid(columns: columns, rows: result.rows.prefix(5).map { Array($0.prefix(3)) }))273            } else {274                card.items.append(.rows(result.rows.prefix(5).map { row in275                    BlockCard.Row(leading: nil, text: row.first ?? "", trailing: row.count > 1 ? row[1] : nil)276                }))277            }278            if result.total > min(5, result.rows.count) { card.meta.append(String(localized: "\(result.total) résultats")) }279            if result.fromCache { card.meta.append(String(localized: "mis à jour \(result.fetchedAt.formatted(.relative(presentation: .named)))")) }280        case .unavailable(let reason)?:281            card.items.append(.notice(reason, symbol: "icloud.slash", tone: .neutral))282        case nil:283            store.need(.query(block.cardKey))284            card.items.append(store.isFinal ? .notice(String(localized: "Les résultats de cette vue se lisent dans l’app ou sur le Web"), symbol: "list.bullet.rectangle", tone: .neutral)285                                            : .notice(String(localized: "Résultats en cours de lecture…"), symbol: "arrow.down.circle", tone: .neutral))286        }287        return card288    }289290    static func bibliography(_ block: BibliographyBlock, _ store: BlockCardStore) -> BlockCard {291        let title = block.title.trimmingCharacters(in: .whitespacesAndNewlines)292        var card = BlockCard(symbol: "books.vertical.fill", kicker: String(localized: "Bibliographie"), title: title.isEmpty ? String(localized: "Références") : title)293        card.meta.append(String(localized: "style \(block.style.uppercased())"))294        let cited = store.citedReferences()295        guard !cited.isEmpty else {296            card.items.append(.notice(String(localized: "Aucune référence citée dans cette page"), symbol: "text.quote", tone: .neutral))297            return card298        }299        let missing = cited.filter { store.references[$0] == nil && !store.unknownReferences.contains($0) }300        if !missing.isEmpty { store.need(.references(missing.sorted())) }301        let known = cited.compactMap { store.references[$0] }302        if !known.isEmpty {303            // whole entries (up to three lines each), not one-line excerpts304            for reference in known.prefix(6) { card.items.append(.text(reference.entry, style: .body, maxLines: 3)) }305            if known.count > 6 { card.meta.append(String(localized: "\(known.count - 6) de plus")) }306        }307        let unknown = cited.count - known.count308        if unknown > 0 {309            card.items.append(.notice(unknown == 1 ? String(localized: "1 référence citée n’est pas sur cet appareil") : String(localized: "\(unknown) références citées ne sont pas sur cet appareil"), symbol: "icloud.slash", tone: .neutral))310        }311        card.meta.insert(cited.count == 1 ? String(localized: "1 référence citée") : String(localized: "\(cited.count) références citées"), at: 0)312        return card313    }314315    static func pdf(_ block: PDFBlock, _ store: BlockCardStore) -> BlockCard {316        let name = block.name.trimmingCharacters(in: .whitespacesAndNewlines)317        var card = BlockCard(symbol: "doc.richtext.fill", kicker: "PDF", title: name.isEmpty ? String(localized: "Document PDF") : name)318        if let id = block.attachmentId {319            if let info = store.pdfs[id] {320                if let thumbnail = info.thumbnail { card.items.append(.picture(thumbnail, maxHeight: 230, framed: true)) }321                else { card.items.append(.notice(String(localized: "Fichier non téléchargé sur cet appareil"), symbol: "icloud.slash", tone: .neutral)) }322                if info.pageCount > 0 { card.meta.append(BlockLabels.pages(info.pageCount)) }323            } else {324                store.need(.pdf(attachmentId: id))325                if !store.isFinal { card.items.append(.notice(String(localized: "Aperçu en préparation…"), symbol: "arrow.down.circle", tone: .neutral)) }326            }327        } else {328            card.items.append(.notice(String(localized: "Aucun fichier associé"), symbol: "questionmark.folder", tone: .neutral))329        }330        if block.page > 1 { card.meta.append(String(localized: "page \(block.page)")) }331        let annotations = block.annotations332        if !annotations.isEmpty {333            card.meta.append(BlockLabels.annotations(annotations.count))334            card.items.append(.rows(annotations.prefix(2).map { BlockCard.Row(leading: "p.\($0.page)", text: [$0.text, $0.note].filter { !$0.isEmpty }.joined(separator: " — "), trailing: nil) }.filter { !$0.text.isEmpty }))335            if case .rows(let rows)? = card.items.last, rows.isEmpty { card.items.removeLast() }336        }337        return card338    }339340    static func blockRef(_ block: BlockRefBlock, _ store: BlockCardStore) -> BlockCard {341        let isLink = block.mode == .link342        var card = BlockCard(symbol: isLink ? "link" : "arrow.turn.down.right", kicker: isLink ? String(localized: "Lien vers un bloc") : String(localized: "Bloc référencé"),343                             title: String(localized: "Référence"))344        guard let pageId = block.pageId else {345            card.title = String(localized: "Référence introuvable")346            card.tone = .neutral347            return card348        }349        guard let target = store.blockTargets[BlockCardStore.targetKey(pageId: pageId, blockId: block.blockId)] else {350            store.need(.blockRef(pageId: pageId, blockId: block.blockId))351            if !store.isFinal { card.items.append(.notice(String(localized: "Lecture de la référence…"), symbol: "arrow.down.circle", tone: .neutral)) }352            return card353        }354        guard let pageTitle = target.pageTitle, let text = target.text else {355            card.title = target.pageTitle ?? String(localized: "Référence introuvable")356            card.items.append(.notice(String(localized: "Référence introuvable"), symbol: "exclamationmark.triangle", tone: .warning))357            return card358        }359        card.title = pageTitle360        if !isLink, !text.isEmpty { card.items.append(.text(text, style: .body, maxLines: 6)) }361        card.items.append(.action(String(localized: "Ouvrir la note")))362        return card363    }364365    static func runCode(_ block: RunCodeBlock) -> BlockCard {366        var card = BlockCard(symbol: "terminal.fill", kicker: String(localized: "Code exécutable"), title: block.language.isEmpty ? String(localized: "Code") : block.language)367        let code = block.code.trimmingCharacters(in: .newlines)368        if code.isEmpty { card.items.append(.notice(String(localized: "Aucun code — touche pour écrire"), symbol: "pencil", tone: .neutral)) }369        else { card.items.append(.text(BlockLabels.firstLines(code, 8), style: .mono, maxLines: 8)) }370        if let output = block.output {371            let text = output.text.trimmingCharacters(in: .newlines)372            if !text.isEmpty { card.items.append(.text(BlockLabels.firstLines(text, 5), style: output.isError ? .monoDanger : .mono, maxLines: 5)) }373            card.meta.append(output.isError ? String(localized: "Dernière sortie : erreur") : String(localized: "Dernière sortie"))374            if let ms = output.milliseconds { card.meta.append("\(Int(ms.rounded())) ms") }375            if let date = BlockLabels.date(output.at) { card.meta.append(date) }376        }377        card.items.append(.notice(String(localized: "Exécutable sur le Web uniquement"), symbol: "globe", tone: .neutral))378        return card379    }380381    static func audio(_ block: AudioBlock) -> BlockCard {382        let title = block.title.trimmingCharacters(in: .whitespacesAndNewlines)383        var card = BlockCard(symbol: "waveform", kicker: String(localized: "Note vocale"), title: title.isEmpty ? String(localized: "Enregistrement") : title)384        if block.duration > 0 { card.meta.append(BlockLabels.duration(block.duration)) }385        if let date = BlockLabels.date(block.recordedAt) { card.meta.append(date) }386        var status = BlockLabels.transcriptStatus(block.transcriptStatus)387        if let engine = block.transcriptEngine, !engine.isEmpty { status += " (\(engine))" }388        card.meta.append(status)389        let segments = block.transcript.filter { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }390        if !segments.isEmpty {391            card.items.append(.rows(segments.prefix(2).map { BlockCard.Row(leading: $0.timecode, text: $0.text, trailing: nil) }))392            if segments.count > 2 { card.meta.append(String(localized: "\(segments.count) segments")) }393        }394        if block.summary != nil {395            // an AI summary exists: marked as AI, never shown as plain content396            card.items.append(.notice(String(localized: "Résumé généré par IA disponible"), symbol: "sparkles", tone: .ai))397        }398        if block.attachmentId == nil { card.items.append(.notice(String(localized: "Aucun fichier audio associé"), symbol: "questionmark.folder", tone: .neutral)) }399        return card400    }401402    static func canvasLink(_ block: CanvasLinkBlock, _ store: BlockCardStore) -> BlockCard {403        var card = BlockCard(symbol: "rectangle.3.group.fill", kicker: "Canvas", title: String(localized: "Tableau blanc"))404        guard let pageId = block.pageId else {405            card.items.append(.notice(String(localized: "Aucun canvas associé"), symbol: "questionmark.folder", tone: .neutral))406            return card407        }408        if let known = store.pageTitles[pageId] {409            if let title = known, !title.isEmpty { card.title = title }410            else { card.items.append(.notice(String(localized: "Canvas introuvable sur cet appareil"), symbol: "exclamationmark.triangle", tone: .warning)); return card }411        } else {412            store.need(.page(id: pageId))413        }414        card.items.append(.action(String(localized: "Ouvrir le canvas")))415        return card416    }417}418419extension BlockCardBuilder {420    /// The neutral, read-only card of a block this app does not know: it is kept verbatim in the document.421    static func unknown(_ node: PMNode) -> BlockCard {422        BlockCard(symbol: "square.dashed", kicker: String(localized: "Bloc non pris en charge"), title: String(localized: "Bloc « \(node.type) »"), tone: .neutral,423                  items: [.notice(String(localized: "Conservé tel quel — modifiable sur le web"), symbol: "lock", tone: .neutral)])424    }425}426
Files main
Menu

Theme