Repository Public
1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/BlocksNodesTests.swift3// Description: The block detail models that need no audio: Mermaid (render shown only when its hash matches the source),4// runnable code (edit, output kept and flagged, never executed), living blocks (request built from the5// node, rows / board / overdue rules, happy path, offline copy, server error, empty, unknown source) and6// cross-references (search by block id, read-only rendering, missing target, router).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesAPI12import SPNotesDocument13import SPNotesSync14import Testing15@testable import SPNotesFeatures16@testable import SPNotesFeaturesCatalog1718@Suite("Blocks · Mermaid and runnable code")19@MainActor20struct MermaidRunCodeTests {21 @Test("mermaid: the render is fetched and shown only while previewHash = sha256(code); an edit invalidates it honestly and typing the source back restores it")22 func mermaid() async {23 var changes: [MermaidBlock] = []24 let model = MermaidBlockModel(block: BlockSamples.mermaidWithPreview, imageLoader: BlockSamples.imageLoader) { changes.append($0) }25 #expect(model.preview == .loading)26 await model.load()27 guard case .current(let data) = model.preview else { Issue.record("expected the current render, got \(model.preview)"); return }28 #expect(data.count > 1000)2930 model.setCode(BlockSamples.mermaidCode + "\n Graphe --> Idée")31 #expect(model.preview == .outdated)32 #expect(changes.count == 1)33 // The stored render and hash are untouched: only the web replaces them.34 #expect(changes[0].preview == BlockSamples.mermaidPreviewId)35 #expect(changes[0].previewHash == MermaidBlock.hash(of: BlockSamples.mermaidCode))36 #expect(!changes[0].isPreviewCurrent)37 await model.load()38 #expect(model.preview == .outdated) // nothing is fetched for a stale render3940 model.setCode(BlockSamples.mermaidCode)41 #expect(model.preview == .current(data))42 model.setCode(BlockSamples.mermaidCode)43 #expect(changes.count == 2) // an identical text is not an edit44 }4546 @Test("mermaid: no render, no loader, offline loader, unreadable image")47 func mermaidStates() async {48 let none = MermaidBlockModel(block: MermaidBlock(code: "graph TD; A-->B"))49 await none.load()50 #expect(none.preview == .none)5152 let noLoader = MermaidBlockModel(block: BlockSamples.mermaidWithPreview)53 await noLoader.load()54 if case .unavailable = noLoader.preview {} else { Issue.record("expected unavailable") }5556 let offline = MermaidBlockModel(block: BlockSamples.mermaidWithPreview, imageLoader: { _ in throw RepositoryError.offline })57 await offline.load()58 if case .unavailable(let failure) = offline.preview { #expect(failure.isOffline) } else { Issue.record("expected unavailable offline") }5960 let garbage = MermaidBlockModel(block: BlockSamples.mermaidWithPreview, imageLoader: { _ in Data("not an image".utf8) })61 await garbage.load()62 if case .unavailable(let failure) = garbage.preview { #expect(!failure.isOffline) } else { Issue.record("expected unavailable") }6364 #expect(BlockImage.image(from: BlockSamples.mermaidPreviewPNG(), scale: 2)?.size == CGSize(width: 620, height: 120))65 }6667 @Test("runCode: the code is editable, the output is kept and flagged as older, nothing is executed")68 func runCode() {69 var changes: [RunCodeBlock] = []70 let model = RunCodeBlockModel(block: BlockSamples.runCode) { changes.append($0) }71 #expect(model.output?.text == "Volatilité réalisée : 0.0279")72 #expect(model.output?.isError == false)73 #expect(!model.editedSinceOutput)74 let utc = TimeZone(identifier: "UTC")!75 #expect(model.outputCaption(timeZone: utc)?.hasPrefix("3 ms · ") == true)76 let original = model.code77 model.setCode(original + "\n// note")78 #expect(model.editedSinceOutput)79 #expect(changes.count == 1)80 #expect(changes[0].output?.text == "Volatilité réalisée : 0.0279") // only a run on the web replaces the output81 #expect(changes[0].code.hasSuffix("// note"))82 model.setCode(original)83 #expect(!model.editedSinceOutput)8485 let failed = RunCodeBlockModel(block: BlockSamples.runCodeFailed)86 #expect(failed.output?.isError == true)87 #expect(failed.outputCaption(timeZone: utc)?.hasPrefix("1,4 ms") == true)88 let fresh = RunCodeBlockModel(block: RunCodeBlock(language: "python", code: "print(1)"))89 #expect(fresh.output == nil)90 #expect(fresh.outputCaption() == nil)91 fresh.setCode("print(2)")92 #expect(!fresh.editedSinceOutput)93 #expect(RunCodeBlockModel.languageLabel("javascript") == "JavaScript")94 #expect(RunCodeBlockModel.languageLabel("rust") == "rust")95 }96}9798@Suite("Blocks · living block (queryView)")99@MainActor100struct QueryViewTests {101 @Test("the request is built from the node: source, limit, cleaned filter, database and page requirements, unknown source")102 func request() throws {103 var block = QueryViewBlock(source: .tasks, title: "T", filter: QueryFilter(tag: " wp46 ", status: "", text: "garch"), limit: 40)104 var query = try QueryViewLogic.liveQuery(for: block, hostPageId: nil).get()105 #expect(query.source == "tasks")106 #expect(query.limit == 40)107 #expect(query.filter == LiveQueryFilter(tag: "wp46", text: "garch"))108 #expect(query.pageId == nil)109110 block.filter = QueryFilter(fields: [:])111 query = try QueryViewLogic.liveQuery(for: block, hostPageId: nil).get()112 #expect(query.filter == nil)113114 block.source = .database115 #expect(QueryViewLogic.liveQuery(for: block, hostPageId: nil) == .failure(.needsDatabase))116 block.databaseId = "5aa3a103-d4d7-4d6e-8f78-8b122393dc1f"117 let withDatabase = try QueryViewLogic.liveQuery(for: block, hostPageId: nil).get()118 #expect(withDatabase.databaseId == "5aa3a103-d4d7-4d6e-8f78-8b122393dc1f")119120 block.source = .backlinks121 #expect(QueryViewLogic.liveQuery(for: block, hostPageId: nil) == .failure(.needsPage))122 let withPage = try QueryViewLogic.liveQuery(for: block, hostPageId: BlockSamples.sourcePageId).get()123 #expect(withPage.pageId == BlockSamples.sourcePageId)124125 block.source = QuerySource(rawValue: "galaxies")126 #expect(QueryViewLogic.liveQuery(for: block, hostPageId: nil) == .failure(.unknownSource("galaxies")))127 }128129 @Test("overdue = past the end of the due day (UTC day of the stored instant), never when done; board groups in order of first appearance")130 func rules() {131 let due = APIDate.parse("2026-11-17T12:00:00.000Z")!132 #expect(!QueryViewLogic.isOverdue(due: due, done: false, now: APIDate.parse("2026-11-17T23:59:00.000Z")!))133 #expect(QueryViewLogic.isOverdue(due: due, done: false, now: APIDate.parse("2026-11-18T00:00:00.000Z")!))134 #expect(!QueryViewLogic.isOverdue(due: due, done: true, now: APIDate.parse("2026-12-01T00:00:00.000Z")!))135 #expect(!QueryViewLogic.isOverdue(due: nil, done: false, now: Date()))136137 func row(_ id: String, _ status: String?) -> QueryRowDisplay {138 QueryRowDisplay(id: id, title: id, subtitle: "", icon: nil, status: status, done: status == "done", due: nil, overdue: false, pageId: nil, blockId: nil)139 }140 let groups = QueryViewLogic.groups([row("a", "doing"), row("b", nil), row("c", "todo"), row("d", "doing"), row("e", nil)])141 #expect(groups.map(\.status) == ["doing", nil, "todo"])142 #expect(groups.map { $0.rows.map(\.id) } == [["a", "d"], ["b", "e"], ["c"]])143 #expect(QueryViewLogic.statusLabel(nil) == "Sans état")144 #expect(QueryViewLogic.statusLabel("doing") == "En cours")145 #expect(QueryViewLogic.statusLabel("À valider") == "À valider")146 #expect(QueryViewLogic.cellText(.text("2026-11-25T12:00:00.000Z"), type: LiveQueryColumnType.date).contains("25"))147 #expect(QueryViewLogic.cellText(.bool(true), type: LiveQueryColumnType.checkbox) == "Oui")148 #expect(QueryViewLogic.cellText(.number(1982), type: LiveQueryColumnType.number) == "1982")149 #expect(QueryViewLogic.cellText(.null, type: LiveQueryColumnType.text) == "")150 #expect(QueryViewLogic.cellText(.text("todo"), type: LiveQueryColumnType.select) == "À faire")151 #expect(QueryViewLogic.cellText(.text("high"), type: LiveQueryColumnType.select) == "Haute")152 #expect(QueryViewLogic.cellText(.text("projects"), type: LiveQueryColumnType.select) == "Projets")153 #expect(QueryViewLogic.cellText(.text("Lu"), type: LiveQueryColumnType.select) == "Lu")154 }155156 @Test("happy path: tasks resolved, rows typed, overdue computed from the injected clock, rows open the page at the block, layout edits the node")157 func happy() async throws {158 let world = try await FeatureWorld()159 let router = FeatureRouterRecorder()160 var changes: [QueryViewBlock] = []161 let model = QueryViewBlockModel(repositories: world.repositories, router: router, block: BlockSamples.queryView(.tasks), now: { FeatureSamples.now }) { changes.append($0) }162 await model.load()163 #expect(model.phase == .loaded)164 #expect(model.rows.count == 7)165 #expect(model.total == 9)166 #expect(model.hiddenCount == 2)167 #expect(model.freshness?.fromCache == false)168 let first = try #require(model.rows.first)169 #expect(first.title == "Relire la section 2")170 #expect(first.overdue) // due 17 Nov., now 19 Nov.171 #expect(first.subtitle == "Volatilité conditionnelle · WP 46")172 #expect(model.rows.filter(\.done).count == 2)173 #expect(model.rows.filter(\.overdue).count == 1) // done rows are never overdue174 #expect(model.groups.map(\.status) == ["todo", "doing", "done"])175 model.open(first)176 #expect(router.calls == [.page(id: BlockSamples.sourcePageId, blockId: "ref-t1")])177178 model.setLayout(.board)179 #expect(changes.last?.layout == .board)180 model.setLayout(.board)181 #expect(changes.count == 1)182183 // The request the server received is the node's.184 #expect(world.fake.count("POST", "^/api/query") == 1)185 }186187 @Test("the other sources decode the recorded answers: pages, database (opens the database), references (rows open nothing), backlinks")188 func sources() async throws {189 let world = try await FeatureWorld()190 let router = FeatureRouterRecorder()191 let pages = QueryViewBlockModel(repositories: world.repositories, router: router, block: BlockSamples.queryView(.pages, title: ""))192 await pages.load()193 #expect(pages.title == "Pages")194 #expect(pages.rows.count == 2)195 #expect(pages.rows.first?.subtitle == "Projets")196 #expect(pages.rows.first?.pageId != nil)197198 let database = QueryViewBlockModel(repositories: world.repositories, router: router, block: BlockSamples.queryView(.database))199 await database.load()200 #expect(database.rows.first?.title == "Fixture · Engle (1982)")201 #expect(database.result?.name == "Fixture · savoir · lectures")202 database.openDatabase()203 #expect(router.calls.last == .database(id: "5aa3a103-d4d7-4d6e-8f78-8b122393dc1f"))204205 let references = QueryViewBlockModel(repositories: world.repositories, router: router, block: BlockSamples.queryView(.references))206 await references.load()207 let reference = try #require(references.rows.first)208 #expect(reference.subtitle == "Greene, William H. · 2018")209 #expect(reference.pageId == nil)210 let before = router.calls.count211 references.open(reference)212 #expect(router.calls.count == before)213214 let backlinks = QueryViewBlockModel(repositories: world.repositories, router: router, block: BlockSamples.queryView(.backlinks), hostPageId: BlockSamples.sourcePageId)215 await backlinks.load()216 #expect(backlinks.rows.count == 1)217 let orphan = QueryViewBlockModel(repositories: world.repositories, block: BlockSamples.queryView(.backlinks))218 await orphan.load()219 #expect(orphan.problem == .needsPage)220 #expect(orphan.phase == .loaded)221 }222223 @Test("offline: the last answer is shown with its date; never fetched = calm failure; server error; empty; settings edit the node and ask again")224 func offlineErrorEmpty() async throws {225 let world = try await FeatureWorld()226 let model = QueryViewBlockModel(repositories: world.repositories, block: BlockSamples.queryView(.tasks), now: { FeatureSamples.now })227 await model.load()228 world.setOffline(true)229 await model.load()230 #expect(model.phase == .loaded)231 #expect(model.rows.count == 7)232 #expect(model.freshness?.fromCache == true)233234 let never = QueryViewBlockModel(repositories: world.repositories, block: BlockSamples.queryView(.references))235 await never.load()236 #expect(never.phase.failure?.isOffline == true)237 #expect(never.rows.isEmpty)238 world.setOffline(false)239240 world.fake.inject(.status(500), method: "POST", path: "^/api/query")241 let failing = QueryViewBlockModel(repositories: world.repositories, block: BlockSamples.queryView(.pages))242 await failing.load()243 #expect(failing.phase.failure?.kind == .server)244245 var changes: [QueryViewBlock] = []246 let editable = QueryViewBlockModel(repositories: world.repositories, block: BlockSamples.queryView(.tasks), onChange: { changes.append($0) })247 await editable.load()248 var settings = editable.settings249 settings.text = "introuvable"250 settings.limit = 10251 settings.title = "Recherche vide"252 await editable.apply(settings)253 #expect(changes.last?.filter.text == "introuvable")254 #expect(changes.last?.limit == 10)255 #expect(editable.title == "Recherche vide")256 #expect(editable.phase == .loaded)257 #expect(editable.rows.isEmpty)258 #expect(editable.total == 0)259 await editable.apply(settings)260 #expect(changes.count == 1) // unchanged settings are not an edit261262 let unknown = QueryViewBlockModel(repositories: world.repositories, block: QueryViewBlock(source: QuerySource(rawValue: "galaxies")))263 await unknown.load()264 #expect(unknown.problem == .unknownSource("galaxies"))265 #expect(QueryViewSettings.statusChoices(for: .tasks).contains("doing"))266 #expect(QueryViewSettings.statusChoices(for: .references).isEmpty)267 }268}269270@Suite("Blocks · cross-reference (blockRef)")271@MainActor272struct BlockRefTests {273 private var root: PMNode { try! PMNode(data: BlockSamples.sourceDocument) }274275 @Test("a block is found by id at any depth; rendering keeps marks, list structure, task state, code, callout and quote; other nodes are neutral cards")276 func renderer() throws {277 #expect(BlockRefRenderer.find(blockId: "ref-li2", in: root)?.type == NodeType.listItem)278 #expect(BlockRefRenderer.find(blockId: "absent", in: root) == nil)279280 let paragraph = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-p1", in: root))])281 #expect(paragraph.count == 1)282 #expect(paragraph[0].kind == .paragraph)283 #expect(paragraph[0].plainText == "La volatilité réalisée à une minute précède la détérioration comptable de deux trimestres.")284 #expect(paragraph[0].text.runs.contains { $0.inlinePresentationIntent == .stronglyEmphasized })285 #expect(paragraph[0].text.runs.contains { $0.inlinePresentationIntent == .emphasized })286287 let list = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-list", in: root))])288 #expect(list.map(\.kind) == [.bullet, .bullet, .bullet])289 #expect(list.map(\.depth) == [0, 0, 1])290 #expect(list[2].plainText == "Le quotidien sert de témoin")291292 let tasks = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-tasks", in: root))])293 #expect(tasks.map(\.kind) == [.task(checked: true), .task(checked: false)])294 let oneTask = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-t2", in: root))])295 #expect(oneTask.map(\.kind) == [.task(checked: false)])296297 let callout = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-callout", in: root))])298 #expect(callout.map(\.calloutIcon) == ["⚖️", nil])299 #expect(callout.filter { !$0.inCallout }.isEmpty)300301 let code = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-code", in: root))])302 #expect(code[0].kind == .code(language: "python"))303 #expect(code[0].plainText.contains("rolling(60)"))304305 let quote = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-quote", in: root))])306 #expect(quote[0].quoted)307308 let table = BlockRefRenderer.items([try #require(BlockRefRenderer.find(blockId: "ref-table", in: root))])309 #expect(table[0].kind == .atom(type: NodeType.table))310 #expect(table[0].plainText == "Tableau")311312 let ordered = PMNode(type: NodeType.orderedList, attrs: ["start": 3], content: [313 PMNode(type: NodeType.listItem, content: [PMNode(type: NodeType.paragraph, content: [PMNode(type: NodeType.text, text: "trois")])]),314 PMNode(type: NodeType.listItem, content: [PMNode(type: NodeType.paragraph, content: [PMNode(type: NodeType.text, text: "quatre")])]),315 ])316 #expect(BlockRefRenderer.items([ordered]).map(\.kind) == [.ordered(number: 3), .ordered(number: 4)])317 let unknown = PMNode(type: "hologram", attrs: ["z": 1])318 #expect(BlockRefRenderer.items([unknown]).first?.kind == .atom(type: "hologram"))319 #expect(BlockRefRenderer.items([root], limit: 3).count == 3)320 let inline = BlockRefRenderer.inline([PMNode(type: NodeType.text, text: "Voir "), PMNode(type: NodeType.citation, attrs: ["label": "Engle 1982", "locator": "p. 4"]),321 PMNode(type: NodeType.hardBreak), PMNode(type: NodeType.mention, attrs: ["label": "Marie"])])322 #expect(String(inline.characters) == "Voir [Engle 1982, p. 4]\n@Marie")323 }324325 @Test("model: embed of a block, whole-page reference, link mode, missing block, missing page, trashed page; opening goes through the router; works offline")326 func model() async throws {327 let world = try await FeatureWorld()328 world.setOffline(true) // the source is read from the local store329 let router = FeatureRouterRecorder()330331 let embed = BlockRefModel(repositories: world.repositories, router: router, block: BlockSamples.blockRef("ref-callout"))332 #expect(embed.resolution == .loading)333 await embed.load()334 guard case .found(let target) = embed.resolution else { Issue.record("expected a target, got \(embed.resolution)"); return }335 #expect(target.pageTitle == "Plan de l'étude")336 #expect(target.items.count == 2)337 #expect(!target.truncated)338 #expect(!embed.isLink)339 embed.open()340 #expect(router.calls == [.page(id: BlockSamples.sourcePageId, blockId: "ref-callout")])341342 let page = BlockRefModel(repositories: world.repositories, router: router, block: BlockSamples.blockRef(nil))343 await page.load()344 guard case .found(let whole) = page.resolution else { Issue.record("expected the page"); return }345 #expect(whole.blockId == nil)346 #expect(whole.truncated) // 8 top-level blocks, 6 shown347 page.open()348 #expect(router.calls.last == .page(id: BlockSamples.sourcePageId, blockId: nil))349350 let link = BlockRefModel(repositories: world.repositories, router: router, block: BlockSamples.blockRef("ref-p1", mode: .link))351 await link.load()352 #expect(link.isLink)353354 let missingBlock = BlockRefModel(repositories: world.repositories, router: router, block: BlockSamples.blockRef("absent"))355 await missingBlock.load()356 #expect(missingBlock.resolution == .missing)357 let calls = router.calls.count358 missingBlock.open()359 #expect(router.calls.count == calls) // a missing target opens nothing360361 let missingPage = BlockRefModel(repositories: world.repositories, block: BlockSamples.blockRef("x", pageId: BlockSamples.missingPageId))362 await missingPage.load()363 #expect(missingPage.resolution == .missing)364 let noPage = BlockRefModel(repositories: world.repositories, block: BlockRefBlock(storage: PMNode(type: NodeType.blockRef, attrs: ["pageId": .null])))365 await noPage.load()366 #expect(noPage.resolution == .missing)367 #expect(BlockRefBlock.missingTargetText == "Référence introuvable")368369 world.setOffline(false)370 world.fake.webTrash(BlockSamples.sourcePageId)371 await world.sync()372 let trashed = BlockRefModel(repositories: world.repositories, block: BlockSamples.blockRef("ref-p1"))373 await trashed.load()374 #expect(trashed.resolution == .missing)375 }376}377