Repository Public
1// SP Notes iOS2// File: Features/Editor/Blocks/BlockCardResolver.swift3// Description: Resolves what the block cards need from outside the document — attachment pictures, PDF thumbnails (PDFKit), ink4// renders (Core `InkRenderer`), rows of living views (`repositories.knowledge.query`, cache first), referenced5// blocks and page titles (local store), cited references (local copy) — then asks the editor to redraw the cards.6// Never blocks typing: everything is asynchronous and each need is asked once.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import PDFKit11import SPNotesCore12import UIKit1314extension NoteDocument {15 /// Plain text of the block whose `id` is `blockId`: a text block or atom line, or every line of a container (list item,16 /// quote, callout…). Nil when the document has no such block.17 func blockText(id blockId: String) -> String? {18 let wanted = JSONValue.string(blockId)19 if let line = lines.first(where: { $0.attrs["id"] == wanted }) { return NoteDocument(lines: [line]).plainText().trimmingCharacters(in: .whitespacesAndNewlines) }20 for line in lines {21 guard let frame = line.path.first(where: { $0.attrs["id"] == wanted }) else { continue }22 let members = lines.filter { $0.path.contains { $0.key == frame.key } }23 return NoteDocument(lines: members).plainText().trimmingCharacters(in: .whitespacesAndNewlines)24 }25 return nil26 }2728 /// The blocks a reference can point to: id, kind and a one-line excerpt (text blocks and atoms that have an id).29 func referencableBlocks() -> [(id: String, type: String, text: String)] {30 lines.compactMap { line in31 guard let id = line.attrs["id"]?.stringValue, !id.isEmpty else { return nil }32 let text = NoteDocument(lines: [line]).plainText().split(whereSeparator: \.isNewline).joined(separator: " ").trimmingCharacters(in: .whitespaces)33 return (id, line.type, text)34 }35 }36}3738extension AppModel {39 /// The local file of an attachment only when it is already on the device (never downloads).40 func fileOnDevice(forAttachment id: String) async -> URL? {41 guard let record = try? await store.attachment(id: id), let path = record.localPath, files.exists(relativePath: path) else { return nil }42 return files.url(relativePath: path)43 }44}4546enum ReferenceFormat {47 /// « Author Year », as cached in a citation's `label`.48 static func label(_ reference: ResearchReference) -> String {49 if let label = reference.label, !label.isEmpty { return label }50 let surnames = (reference.authors ?? []).compactMap { $0.split(separator: " ").last.map(String.init) }51 let who: String52 switch surnames.count {53 case 0: who = reference.citeKey54 case 1: who = surnames[0]55 case 2: who = surnames[0] + " & " + surnames[1]56 default: who = surnames[0] + " et al."57 }58 return reference.year.map { "\(who) \($0)" } ?? who59 }6061 /// One readable line: authors (year). Title. Journal. — a neutral author–year form built from the stored fields; the62 /// style-exact entry (APA, Chicago…) is formatted by the server's exports.63 static func entry(_ reference: ResearchReference) -> String {64 var parts: [String] = []65 let authors = (reference.authors ?? []).joined(separator: ", ")66 if !authors.isEmpty { parts.append(authors + (reference.year.map { " (\($0))" } ?? "")) }67 else if let year = reference.year { parts.append("(\(year))") }68 if !reference.title.isEmpty { parts.append(reference.title) }69 if let journal = reference.journal, !journal.isEmpty { parts.append(journal) }70 return parts.isEmpty ? reference.citeKey : parts.joined(separator: ". ") + "."71 }72}7374@MainActor75final class BlockCardResolver {76 let app: AppModel77 let noteId: String78 let store: BlockCardStore79 /// Redraws the cards of these node types (empty = every card).80 var invalidate: (Set<String>) -> Void = { _ in }81 private var tasks: [BlockCardNeed: Task<Void, Never>] = [:]8283 init(app: AppModel, noteId: String, store: BlockCardStore) {84 self.app = app85 self.noteId = noteId86 self.store = store87 store.onNeed = { [weak self] need in self?.resolve(need) }88 }8990 func resolve(_ need: BlockCardNeed) {91 guard tasks[need] == nil else { return }92 tasks[need] = Task { [weak self] in93 guard let self else { return }94 let types = await self.fetch(need)95 self.tasks[need] = nil96 if !Task.isCancelled { self.invalidate(types) }97 }98 }99100 /// Waits for everything in flight (tests).101 func settle() async {102 while let task = tasks.values.first { await task.value }103 }104105 /// Fetches one need into the store; returns the node types whose cards must be redrawn.106 func fetch(_ need: BlockCardNeed) async -> Set<String> {107 switch need {108 case .image(let id):109 if await app.resolveImage(source: "/api/files/" + id) == false { store.unavailableAttachments.insert(id) }110 return [NodeType.mermaid, NodeType.drawing]111 case .pdf(let id):112 // only a file that is already here: a PDF can be large, it is downloaded when the user opens it113 if let url = await app.fileOnDevice(forAttachment: id), let document = PDFDocument(url: url), !document.isLocked {114 store.pdfs[id] = BlockCardStore.PDFInfo(thumbnail: PDFThumbnail.image(for: url, size: CGSize(width: 480, height: 620)), pageCount: document.pageCount)115 } else {116 store.pdfs[id] = BlockCardStore.PDFInfo(thumbnail: nil, pageCount: 0)117 }118 return [NodeType.pdf]119 case .ink(let id):120 if let url = try? await app.localFile(forAttachment: id), let data = try? Data(contentsOf: url), let ink = try? InkDocument(data: data),121 let image = InkRenderer.image(ink, scale: 2, background: .none, crop: .canvas) {122 store.inks[id] = UIImage(cgImage: image, scale: 2, orientation: .up)123 } else {124 store.unavailableAttachments.insert(id)125 }126 return [NodeType.drawing]127 case .query(let key):128 store.queries[key] = await rows(for: key)129 return [NodeType.queryView]130 case .blockRef(let pageId, let blockId):131 store.blockTargets[BlockCardStore.targetKey(pageId: pageId, blockId: blockId)] = await target(pageId: pageId, blockId: blockId)132 return [NodeType.blockRef]133 case .page(let id):134 if let page = try? await app.store.page(id: id), page.deletedAt == nil { store.pageTitles[id] = .some(AppModel.displayTitle(page.title)) }135 else { store.pageTitles[id] = .some(nil) }136 return [NodeType.canvasLink]137 case .references(let ids):138 let found = (try? await app.repositories.research.resolveLocally(ids: ids)) ?? [:]139 for id in ids {140 if let reference = found[id] { store.references[id] = BlockCardStore.Reference(label: ReferenceFormat.label(reference), entry: ReferenceFormat.entry(reference)) }141 else { store.unknownReferences.insert(id) }142 }143 return [NodeType.bibliography]144 }145 }146147 func target(pageId: String, blockId: String?) async -> BlockCardStore.BlockTarget {148 guard let page = try? await app.store.page(id: pageId), page.deletedAt == nil else { return BlockCardStore.BlockTarget(pageTitle: nil, text: nil) }149 let title = AppModel.displayTitle(page.title)150 guard let document = try? NoteDocument(json: page.content) else { return BlockCardStore.BlockTarget(pageTitle: title, text: nil) }151 if let blockId { return BlockCardStore.BlockTarget(pageTitle: title, text: document.blockText(id: blockId)) }152 return BlockCardStore.BlockTarget(pageTitle: title, text: document.preview(maxLength: 280))153 }154155 func liveQuery(for key: BlockCardStore.QueryKey) -> LiveQuery {156 let f = key.filter157 let filter = f.isEmpty ? nil : LiveQueryFilter(tag: f.tag, section: f.section, status: f.status, parentId: f.parentId, text: f.text, dueBefore: f.dueBefore, dueAfter: f.dueAfter)158 return LiveQuery(source: key.source, databaseId: key.databaseId, viewId: key.viewId, pageId: key.source == QuerySource.backlinks.rawValue ? noteId : nil, limit: key.limit, filter: filter)159 }160161 /// The rows of a living view: the cached answer when it is recent, the server otherwise, the cache again when offline.162 /// Nothing is computed on the device: without an answer the card says so.163 func rows(for key: BlockCardStore.QueryKey, policy: CachePolicy = .cacheFirst(maxAge: Staleness.query)) async -> BlockCardStore.QueryState {164 do {165 let cached = try await app.repositories.knowledge.query(liveQuery(for: key), policy: policy)166 let table = cached.value.table167 let rows = table.rows.map { row in row.map { $0.text ?? "" } }168 return .rows(BlockCardStore.QueryRows(columns: table.columns, rows: rows, total: cached.value.total, fetchedAt: cached.fetchedAt, fromCache: cached.source == .cache))169 } catch let error as RepositoryError {170 switch error {171 case .notCached, .offline: return .unavailable(String(localized: "Résultats non disponibles hors ligne — ils s’afficheront à la prochaine connexion"))172 case .signedOut: return .unavailable(String(localized: "Connecte-toi pour lire cette vue"))173 case .unsupported: return .unavailable(String(localized: "Le serveur ne propose pas encore les vues dynamiques"))174 default: return .unavailable(String(localized: "La vue n’a pas pu être lue"))175 }176 } catch {177 return .unavailable(String(localized: "La vue n’a pas pu être lue"))178 }179 }180}181