Repository Public
1// SP Notes iOS2// File: Tests/EditorNodesTests.swift3// Description: The 3.0 nodes in the native editor: lossless round trip of the Core's fixtures and of unknown content, insertion4// through the toolbar actions, the designed cards (light, dark, accessibility sizes, live data), taps and the5// detail-screen seam, commits from the sheets, and what the cards read from outside the document.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import PDFKit10import SwiftUI11import Testing12import UIKit13import SPNotesCore14@testable import SPNotes1516private final class NodesBundleMarker {}1718/// A fixture of the Core (`SPNotesCore/Tests/SPNotesDocumentTests/Fixtures/next-nodes`, copied in `Tests/Fixtures/next-nodes`).19func nextNodesFixture(_ name: String, _ ext: String) throws -> Data {20 let url = try #require(Bundle(for: NodesBundleMarker.self).url(forResource: name, withExtension: ext), "fixture \(name).\(ext)")21 return try Data(contentsOf: url)22}2324let nextNodesFixtureNames = ["all-nodes", "defaults", "edge-cases", "mixed-document"]2526@MainActor27func traits(_ style: UIUserInterfaceStyle, _ category: UIContentSizeCategory = .large) -> UITraitCollection {28 UITraitCollection { mutable in29 mutable.userInterfaceStyle = style30 mutable.preferredContentSizeCategory = category31 mutable.displayScale = 232 }33}3435/// Share of the pixels of an image that are not fully transparent, and the mean colour of those.36func inkStatistics(_ image: UIImage) -> (coverage: Double, mean: (r: Double, g: Double, b: Double)) {37 guard let cg = image.cgImage else { return (0, (0, 0, 0)) }38 let width = cg.width, height = cg.height39 var pixels = [UInt8](repeating: 0, count: width * height * 4)40 guard let context = CGContext(data: &pixels, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(),41 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return (0, (0, 0, 0)) }42 context.draw(cg, in: CGRect(x: 0, y: 0, width: width, height: height))43 var count = 0.0, r = 0.0, g = 0.0, b = 0.044 for i in stride(from: 0, to: pixels.count, by: 4) where pixels[i + 3] > 8 {45 count += 1; r += Double(pixels[i]); g += Double(pixels[i + 1]); b += Double(pixels[i + 2])46 }47 guard count > 0 else { return (0, (0, 0, 0)) }48 return (count / Double(width * height), (r / count, g / count, b / count))49}5051@MainActor52func samplePDFData(pages: Int = 2) -> Data {53 UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 300, height: 400)).pdfData { context in54 for page in 0..<pages {55 context.beginPage()56 ("Page \(page + 1)" as NSString).draw(at: CGPoint(x: 40, y: 60), withAttributes: [.font: UIFont.boldSystemFont(ofSize: 28)])57 }58 }59}6061@MainActor62@Suite("Nœuds 3.0 — codec sans perte") struct EditorNodesCodecTests {63 @Test(arguments: nextNodesFixtureNames)64 func theCoreFixturesRoundTripByteForByteThroughTheEditor(name: String) throws {65 var reference = try NoteDocument(json: try nextNodesFixture(name, "json"))66 reference.ensureBlockIds()67 let expected = try reference.jsonData()68 let harness = try EditorHarness()69 harness.editor.load(reference)70 #expect(try harness.editor.document().jsonData() == expected)71 // every new block is an atom of the storage, a citation an inline atom: nothing became text72 let blocks = reference.lines.filter { if case .blockAtom = $0.content { return true } else { return false } }.count73 var blockAtoms = 074 harness.editor.storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: harness.editor.storage.length)) { value, range, _ in75 if let atom = value as? AtomAttachment, atom.isBlock { blockAtoms += range.length }76 }77 #expect(blockAtoms == blocks)78 }7980 static let unknownContent = #"""81 {"type":"doc","content":[82 {"type":"paragraph","attrs":{"textAlign":null,"id":"p1aaaaaaaa"},"content":[{"type":"text","text":"Avant "},{"type":"citation","attrs":{"refId":"cccccccc-cccc-4ccc-8ccc-cccccccccccc","locator":"p. 3","label":"Fama 1970","futur":{"poids":2}}},{"type":"text","text":" après"}]},83 {"type":"holoBlock","attrs":{"id":"hb00000001","depth":3,"frames":[1,2,{"k":null}]},"extraKey":"gardé"},84 {"type":"mermaid","attrs":{"id":"mmd0000001","code":"graph TD\n A-->B","preview":null,"previewHash":null,"theme":"forest","zoom":1.5}},85 {"type":"chart","attrs":{"id":"cht0000001","kind":"radar","title":"T","columns":["a","b"],"rows":[["x",1],["y","2"]],"x":null,"y":[],"source":{"databaseId":"dddddddd-dddd-4ddd-8ddd-dddddddddddd","futureKey":true},"palette":["#fff"]}},86 {"type":"audio","attrs":{"id":"aud0000001","attachmentId":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee","duration":12.5,"title":"T","recordedAt":null,"transcript":[{"t":0,"text":"un","speaker":"A"}],"transcriptStatus":"queued-v2","transcriptEngine":null,"summary":null,"waveform":[0.1,0.5]}},87 {"type":"pdf","attrs":{"id":"pdf0000001","attachmentId":"ffffffff-ffff-4fff-8fff-ffffffffffff","name":"a.pdf","page":2,"annotations":[{"id":"a1","page":1,"kind":"stamp","color":"#ff0000","rects":[[0,0,1,1]],"text":"t","note":"","createdAt":"2026-01-01T00:00:00.000Z","layer":7}],"zoom":"fit"}},88 {"type":"paragraph","attrs":{"textAlign":null,"id":"p2aaaaaaaa"}}89 ]}90 """#9192 @Test func unknownBlocksAndUnknownAttributesOfKnownNodesSurviveTheEditorByteForByte() throws {93 let original = try NoteDocument(json: Data(Self.unknownContent.utf8))94 let expected = try original.jsonData()95 let harness = try EditorHarness(Self.unknownContent)96 #expect(try harness.document.jsonData() == expected)97 // typing around the blocks changes only the text98 harness.caret(after: " après")99 harness.type(" coup")100 let edited = harness.document101 #expect(edited.lines.dropFirst().map(\.node) == original.lines.dropFirst().map(\.node))102 // the unknown block is a neutral read-only card: its tap opens the atom menu, never a sheet103 let app = try makeApp()104 let model = NoteEditorModel(noteId: "x", app: app)105 let unknown = try #require(original.lines.first { $0.type == "holoBlock" }?.atomNode)106 model.editor(model.controller, didTapAtom: unknown, at: NSRange(location: 0, length: 1))107 #expect(model.request == .atomMenu(node: unknown, range: NSRange(location: 0, length: 1)))108 }109110 @Test func aCommitFromASheetChangesOneAttributeAndKeepsTheUnknownOnes() throws {111 let app = try makeApp()112 let model = NoteEditorModel(noteId: "x", app: app)113 model.controller.textView.frame = CGRect(x: 0, y: 0, width: 390, height: 800)114 model.controller.load(try NoteDocument(json: Data(Self.unknownContent.utf8)))115 // mermaid: the code changes, `theme` and `zoom` (unknown) stay116 let mermaid = try #require(model.controller.firstAtom(ofType: NodeType.mermaid))117 var block = try #require(MermaidBlock(node: mermaid.node))118 block.code = "graph LR\n A-->C"119 model.blockDetailContext(range: mermaid.range, dismiss: {}).commit(block.node())120 let saved = try #require(model.controller.firstAtom(ofType: NodeType.mermaid)?.node)121 #expect(saved.attrs?["code"] == .string("graph LR\n A-->C"))122 #expect(saved.attrs?["theme"] == .string("forest") && saved.attrs?["zoom"] == .double(1.5) && saved.attrs?["id"] == .string("mmd0000001"))123 // chart: the title changes; the unknown kind, the unknown key of `source` and `palette` stay124 let chart = try #require(model.controller.firstAtom(ofType: NodeType.chart))125 var grid = ChartGrid(block: try #require(ChartBlock(node: chart.node)))126 grid.block.title = "Nouveau"127 grid.setText("x", row: 0, column: 0) // same text: the cell is not rewritten128 grid.setText("2", row: 1, column: 1) // same text as the stored string "2": stays a string129 model.blockDetailContext(range: chart.range, dismiss: {}).commit(grid.block.node())130 let chartNode = try #require(model.controller.firstAtom(ofType: NodeType.chart)?.node)131 #expect(chartNode.attrs?["title"] == .string("Nouveau") && chartNode.attrs?["kind"] == .string("radar"))132 #expect(chartNode.attrs?["palette"] == .array([.string("#fff")]))133 #expect(chartNode.attrs?["source"] == chart.node.attrs?["source"])134 #expect(chartNode.attrs?["rows"] == chart.node.attrs?["rows"])135 // audio: the title changes; unknown status, `waveform` and the unknown key of a segment stay136 let audio = try #require(model.controller.firstAtom(ofType: NodeType.audio))137 var voice = try #require(AudioBlock(node: audio.node))138 voice.title = "Réunion"139 model.blockDetailContext(range: audio.range, dismiss: {}).commit(voice.node())140 let audioNode = try #require(model.controller.firstAtom(ofType: NodeType.audio)?.node)141 #expect(audioNode.attrs?["title"] == .string("Réunion") && audioNode.attrs?["transcriptStatus"] == .string("queued-v2"))142 #expect(audioNode.attrs?["waveform"] == audio.node.attrs?["waveform"] && audioNode.attrs?["transcript"] == audio.node.attrs?["transcript"])143 // citation (inline): the locator changes, `futur` stays144 let citation = try #require(model.controller.firstAtom(ofType: NodeType.citation))145 var cite = try #require(CitationInline(node: citation.node))146 cite.locator = "p. 9"147 model.blockDetailContext(range: citation.range, dismiss: {}).commit(cite.node())148 let citeNode = try #require(model.controller.firstAtom(ofType: NodeType.citation)?.node)149 #expect(citeNode.attrs?["locator"] == .string("p. 9") && citeNode.attrs?["futur"] == citation.node.attrs?["futur"])150 // the rest of the document did not move, and one undo brings the citation back151 let after = model.controller.document()152 #expect(after.lines.first { $0.type == "holoBlock" }?.node == (try NoteDocument(json: Data(Self.unknownContent.utf8))).lines.first { $0.type == "holoBlock" }?.node)153 // deleting from a sheet removes the block154 let pdf = try #require(model.controller.firstAtom(ofType: NodeType.pdf))155 model.blockDetailContext(range: pdf.range, dismiss: {}).commit(nil)156 #expect(model.controller.firstAtom(ofType: NodeType.pdf) == nil)157 }158}159160@MainActor161@Suite("Nœuds 3.0 — insertion et toucher") struct EditorNodesActionTests {162 private func model() throws -> NoteEditorModel {163 let model = NoteEditorModel(noteId: "0b7f6c0e-3f0a-4d5e-9b0a-aaaaaaaaaaaa", app: try makeApp())164 model.controller.textView.frame = CGRect(x: 0, y: 0, width: 390, height: 800)165 model.controller.load(NoteDocument(markdown: "Texte"))166 return model167 }168169 @Test(arguments: [(EditorAction.insertMermaid, "mermaid", true), (.insertChart, "chart", true), (.insertQueryView, "queryView", true),170 (.insertRunCode, "runCode", true), (.insertBibliography, "bibliography", false)])171 func aToolbarActionInsertsTheBlockWithItsSchemaDefaults(action: EditorAction, type: String, opensSheet: Bool) throws {172 let model = try model()173 model.perform(action)174 let document = model.controller.document()175 let line = try #require(document.lines.first { $0.type == type })176 #expect(document.schemaViolations(strict: true).isEmpty, "\(document.schemaViolations(strict: true))")177 let node = try #require(line.atomNode)178 #expect(node.typed != nil && node.stringAttr("id")?.isEmpty == false)179 if opensSheet {180 guard case .blockDetail(let opened, let range)? = model.request else { Issue.record("no sheet for \(type)"); return }181 #expect(opened == node)182 #expect((model.controller.storage.attribute(.attachment, at: range.location, effectiveRange: nil) as? AtomAttachment)?.node == node)183 } else {184 #expect(model.request == nil)185 }186 // one undo removes it187 model.controller.textView.undoManager?.undo()188 #expect(model.controller.document().lines.contains { $0.type == type } == false)189 }190191 @Test func theChoicesAskedBeforeInsertingProduceTheRightRequestsAndNodes() async throws {192 let model = try model()193 for (action, request) in [(EditorAction.insertBlockRef, NoteEditorModel.Request.blockRefPicker), (.insertCanvasLink, .canvasPicker), (.insertCitation, .citationPicker),194 (.insertPDF, .pdfPicker), (.insertAudio, .audioPicker)] {195 model.request = nil196 model.perform(action)197 #expect(model.request == request)198 }199 let page = "0b7f6c0e-3f0a-4d5e-9b0a-111111111111", reference = "0b7f6c0e-3f0a-4d5e-9b0a-222222222222"200 model.insertBlockRef(pageId: page, blockId: "blk0000001")201 model.insertCanvasLink(pageId: page)202 model.controller.textView.selectedRange = NSRange(location: 5, length: 0)203 model.insertCitation(refId: reference, label: "Fama 1970", locator: "p. 3")204 let document = model.controller.document()205 #expect(document.schemaViolations(strict: true).isEmpty, "\(document.schemaViolations(strict: true))")206 #expect(document.pageReferences().contains(page))207 #expect(document.citedReferences() == [reference])208 #expect(document.markdown().contains("[[\(page)#blk0000001]]") && document.markdown().contains("[@Fama 1970]") && document.markdown().contains("[Canvas](/p/\(page))"))209 }210211 @Test func aPickedPDFBecomesAPDFBlockAndAnAudioFileAnAudioBlockWithItsRealDuration() async throws {212 let app = try makeApp()213 let id = try await app.createNote(title: "Fichiers", document: NoteDocument(markdown: "Texte"))214 let model = NoteEditorModel(noteId: id, app: app)215 await model.load()216 let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)217 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)218 let pdfURL = directory.appendingPathComponent("Rapport.pdf"), wavURL = directory.appendingPathComponent("Mémo vocal.wav")219 try samplePDFData().write(to: pdfURL)220 try SampleData.sampleWAV(seconds: 3).write(to: wavURL)221 await model.insertPDFs([pdfURL])222 await model.insertAudioFiles([wavURL])223 let document = model.controller.document()224 guard case .pdf(let pdf)? = document.lines.compactMap({ $0.atomNode?.typed }).first(where: { if case .pdf = $0 { return true } else { return false } }) else { Issue.record("no pdf block"); return }225 #expect(pdf.name == "Rapport.pdf" && pdf.attachmentId != nil && pdf.page == 1 && pdf.annotations.isEmpty)226 guard case .audio(let audio)? = document.lines.compactMap({ $0.atomNode?.typed }).first(where: { if case .audio = $0 { return true } else { return false } }) else { Issue.record("no audio block"); return }227 #expect(audio.title == "Mémo vocal" && audio.attachmentId != nil)228 #expect(abs(audio.duration - 3) < 0.05, "duration read from the file: \(audio.duration)")229 #expect(audio.transcript.isEmpty && audio.transcriptStatus == .none)230 #expect(Set(document.attachmentReferences()) == Set([pdf.attachmentId, audio.attachmentId].compactMap { $0 }))231 #expect(document.schemaViolations(strict: true).isEmpty)232 }233234 @Test func aTapOnANewBlockAsksForItsDetailScreenAndTheProviderDecidesTheStyle() throws {235 let model = try model()236 let document = try NoteDocument(json: try nextNodesFixture("all-nodes", "json"))237 var seen = Set<String>()238 for line in document.lines {239 var nodes: [PMNode] = []240 switch line.content {241 case .blockAtom(let node): nodes = [node]242 case .inline(let runs): nodes = runs.compactMap { if case .atom(let node) = $0, node.type == NodeType.citation { return node } else { return nil } }243 }244 for node in nodes where node.typed != nil {245 seen.insert(node.type)246 model.request = nil247 model.editor(model.controller, didTapAtom: node, at: NSRange(location: 3, length: 1))248 #expect(model.request == .blockDetail(node: node, range: NSRange(location: 3, length: 1)), "\(node.type)")249 let provider = try #require(BlockDetails.provider(for: node), "\(node.type)")250 #expect(provider.style(for: node) == ((node.type == NodeType.pdf || node.type == NodeType.drawing) ? .fullScreen : .sheet))251 _ = provider.view(for: node, context: model.blockDetailContext(range: NSRange(location: 3, length: 1), dismiss: {}))252 }253 }254 #expect(seen == Set(NodeType.nextBlocks + [NodeType.citation]))255 // nodes that existed before keep their own path256 model.editor(model.controller, didTapAtom: PMNode.horizontalRule(), at: NSRange(location: 0, length: 1))257 #expect(model.request == .atomMenu(node: PMNode.horizontalRule(), range: NSRange(location: 0, length: 1)))258 }259260 @Test func aProviderWithAHigherPriorityReplacesTheInAppScreen() throws {261 struct Shared: BlockDetailProviding {262 func canPresent(_ node: PMNode) -> Bool { node.type == NodeType.mermaid }263 func style(for node: PMNode) -> BlockDetailStyle { .fullScreen }264 func view(for node: PMNode, context: BlockDetailContext) -> AnyView { AnyView(Text("features")) }265 }266 BlockDetails.resetForTests()267 defer { BlockDetails.resetForTests() }268 let drawing = DrawingBlock().node(), pdf = PDFBlock(attachmentId: "ffffffff-ffff-4fff-8fff-ffffffffffff", name: "a.pdf").node(), mermaid = MermaidBlock(code: "a").node(), chart = ChartBlock().node()269 // by default: the Pencil screens own the drawing and the PDF, SPNotesFeatures the data blocks, the in-app sheets the rest270 #expect(BlockDetails.provider(for: drawing) is PencilBlockDetails && BlockDetails.provider(for: pdf) is PencilBlockDetails)271 #expect(BlockDetails.provider(for: mermaid) is InAppBlockDetails && BlockDetails.provider(for: chart) is FeaturesBlockDetails)272 #expect(FeaturesBlockDetails.types == [NodeType.chart, NodeType.queryView, NodeType.blockRef, NodeType.bibliography, NodeType.runCode])273 // the in-app provider still knows how to show them (read-only fallback viewers) when no platform screen is registered274 #expect(InAppBlockDetails().canPresent(drawing) && InAppBlockDetails().style(for: pdf) == .fullScreen)275 // a provider registered above `.inApp` (the shared SPNotesFeatures screens) takes over its blocks, and only those276 BlockDetails.register(Shared(), priority: .features)277 #expect(BlockDetails.provider(for: mermaid) is Shared)278 #expect(BlockDetails.provider(for: drawing) is PencilBlockDetails)279 }280}281282@MainActor283@Suite("Nœuds 3.0 — cartes") struct EditorNodesCardTests {284 private func allNodes() throws -> [PMNode] {285 try NoteDocument(json: try nextNodesFixture("all-nodes", "json")).lines.compactMap { $0.atomNode }.filter { $0.typed != nil }286 }287288 @Test func everyNewBlockHasACardThatDrawsInLightDarkAndAtAnAccessibilitySize() throws {289 let nodes = try allNodes()290 #expect(Set(nodes.map(\.type)) == Set(NodeType.nextBlocks))291 let store = BlockCardStore()292 for node in nodes {293 let typed = try #require(node.typed)294 var sizes: [CGSize] = []295 var means: [Double] = []296 for (style, category) in [(UIUserInterfaceStyle.light, UIContentSizeCategory.large), (.dark, .large), (.light, .accessibilityExtraExtraLarge)] {297 let t = traits(style, category)298 let card = try #require(BlockCardBuilder.card(for: typed, width: 357, traits: t, store: store), "\(node.type)")299 #expect(!card.title.isEmpty && !card.kicker.isEmpty, "\(node.type)")300 let image = BlockCardPainter.image(card, width: 357, traits: t)301 #expect(image.size.width == 357 && image.size.height > 60, "\(node.type) \(image.size)")302 let ink = inkStatistics(image)303 #expect(ink.coverage > 0.5, "\(node.type): the card surface is drawn (\(ink.coverage))")304 sizes.append(image.size)305 means.append((ink.mean.r + ink.mean.g + ink.mean.b) / 3)306 }307 #expect(means[0] > 200 && means[1] < 90, "\(node.type): light is light, dark is dark (\(means))")308 #expect(sizes[2].height > sizes[0].height, "\(node.type): the card grows with Dynamic Type (\(sizes))")309 }310 }311312 @Test func aCardIsPaintedOnceForTheSameContentWidthAndAppearance() throws {313 BlockCardCache.removeAll()314 let renderer = AtomRenderer()315 renderer.traits = traits(.light)316 let node = RunCodeBlock(language: "python", code: "print(1)").node()317 let before = BlockCardCache.paintCount318 let first = try #require(renderer.renderCard(node, width: 340))319 let second = try #require(renderer.renderCard(node, width: 340))320 #expect(first === second && BlockCardCache.paintCount == before + 1)321 renderer.traits = traits(.dark)322 _ = renderer.renderCard(node, width: 340)323 _ = renderer.renderCard(node, width: 300)324 #expect(BlockCardCache.paintCount == before + 3)325 }326327 @Test func typingNeverRepaintsACardAndReopeningANoteTakesItsCardsFromTheCache() throws {328 BlockCardCache.removeAll()329 ChartSnapshot.removeAll()330 var lines: [Line] = [Line.paragraph(text: "Texte")]331 for index in 0..<4 {332 lines.append(Line(blockAtom: RunCodeBlock(language: "python", code: "print(\(index))").node()))333 lines.append(Line(blockAtom: ChartBlock(kind: index % 2 == 0 ? .bar : .line, title: "G\(index)", columns: ["x", "y"], rows: [["a", .number(Double(index))], ["b", 2]]).node()))334 }335 let document = NoteDocument(lines: lines)336 let harness = try EditorHarness()337 let start = Date()338 harness.editor.load(document)339 let firstLoad = Date().timeIntervalSince(start)340 let painted = BlockCardCache.paintCount341 #expect(painted >= 8)342 harness.caret(after: "Texte")343 let typing = Date()344 harness.type(" et encore du texte tapé au clavier, sans rien redessiner")345 let perKey = Date().timeIntervalSince(typing) / 55346 #expect(BlockCardCache.paintCount == painted, "typing does not repaint any card")347 #expect(perKey < 0.02, "typing stays fast beside 8 cards (\(perKey * 1000) ms per key)")348 // the same note opened again (same width and appearance): every card comes from the cache349 let again = try EditorHarness()350 let reload = Date()351 again.editor.load(document)352 let secondLoad = Date().timeIntervalSince(reload)353 #expect(BlockCardCache.paintCount == painted, "cache holds \(BlockCardCache.cachedBytes >> 20) MiB of \(BlockCardCache.byteBudget >> 20)")354 #expect(secondLoad < firstLoad, "cached load \(secondLoad) s vs first \(firstLoad) s")355 // the cache is bounded by memory: older bitmaps leave when the budget is passed356 #expect(BlockCardCache.cachedBytes > 0 && BlockCardCache.cachedBytes <= BlockCardCache.byteBudget)357 for index in 0..<40 { _ = BlockCardCache.image(for: BlockCard(symbol: "terminal", kicker: "K", title: "T\(index)", items: [.text(String(repeating: "ligne\n", count: 40), style: .mono, maxLines: 40)]), width: 390, traits: traits(.light)) }358 #expect(BlockCardCache.cachedBytes <= BlockCardCache.byteBudget)359 }360361 @Test func mermaidShowsItsRenderOnlyWhileTheHashMatchesTheCode() throws {362 let preview = "11111111-1111-4111-8111-111111111111"363 let picture = UIGraphicsImageRenderer(size: CGSize(width: 200, height: 120)).image { _ in UIColor.systemTeal.setFill(); UIRectFill(CGRect(x: 0, y: 0, width: 200, height: 120)) }364 let store = BlockCardStore()365 store.imageProvider = { $0 == "/api/files/" + preview ? picture : nil }366 var block = MermaidBlock(code: "graph TD\n A-->B")367 block.setPreview(attachmentId: preview)368 #expect(block.isPreviewCurrent && block.previewHash == MermaidBlock.hash(of: "graph TD\n A-->B"))369 var card = BlockCardBuilder.mermaid(block, store)370 #expect(card.items == [.picture(picture, maxHeight: 360, framed: true)])371 // the code changes: the stored render no longer matches → the source and the notice372 block.code = "graph TD\n A-->C"373 #expect(!block.isPreviewCurrent)374 card = BlockCardBuilder.mermaid(block, store)375 #expect(card.items.count == 2)376 guard case .text(let source, .mono, _) = card.items[0], case .notice(let notice, _, _) = card.items[1] else { Issue.record("unexpected items \(card.items)"); return }377 #expect(source.contains("A-->C") && notice == "Rendu à mettre à jour depuis le Web")378 // a matching hash whose picture is not on the device asks for it once and shows the source meanwhile379 var asked: [BlockCardNeed] = []380 let empty = BlockCardStore()381 empty.onNeed = { asked.append($0) }382 block.setPreview(attachmentId: preview)383 _ = BlockCardBuilder.mermaid(block, empty)384 _ = BlockCardBuilder.mermaid(block, empty)385 #expect(asked == [.image(attachmentId: preview)])386 }387388 @Test(arguments: ["bar", "line", "area", "pie", "scatter"])389 func aChartOfEachKindIsDrawnWithSwiftCharts(kind: String) throws {390 let chart = ChartBlock(kind: ChartKind(rawValue: kind), title: "Ventes", columns: ["Mois", "Ventes", "Coûts"], rows: [["jan", 10, 4], ["fév", 14, 6], ["mar", 9, "7,5"], ["avr", nil, 3]], x: "Mois", y: ["Ventes", "Coûts"])391 let plot = ChartPlot(chart)392 #expect(plot.seriesNames == ["Ventes", "Coûts"] && plot.data.count == 7, "a cell without a value is not plotted; a number written with a comma is")393 for style in [UIUserInterfaceStyle.light, .dark] {394 let image = try #require(ChartSnapshot.image(chart, width: 330, traits: traits(style)), "\(kind)")395 #expect(image.size.width == 330 && image.size.height >= 150)396 #expect(inkStatistics(image).coverage > 0.02, "\(kind): marks are drawn")397 }398 let card = BlockCardBuilder.chart(chart, width: 358, traits: traits(.light))399 #expect(card.title == "Ventes" && card.kicker.contains(BlockLabels.chartKind(ChartKind(rawValue: kind))))400 guard case .picture? = card.items.first else { Issue.record("no chart picture"); return }401 }402403 @Test func aChartWithoutDataSaysSoAndASnapshotNamesItsSource() throws {404 let empty = BlockCardBuilder.chart(ChartBlock(kind: .bar, title: ""), width: 358, traits: traits(.light))405 #expect(empty.items == [.notice("Aucune donnée à tracer", symbol: "chart.bar.xaxis", tone: .neutral)] && empty.title == "Graphique")406 #expect(ChartSnapshot.image(ChartBlock(kind: .line, title: "x", columns: ["a", "b"], rows: [["u", "texte"]]), width: 300, traits: traits(.light)) == nil)407 var live = ChartBlock(kind: .line, title: "Suivi", columns: ["x", "y"], rows: [[1, 2], [2, 4]])408 live.source = ChartSource(databaseId: "dddddddd-dddd-4ddd-8ddd-dddddddddddd")409 let card = BlockCardBuilder.chart(live, width: 358, traits: traits(.light))410 #expect(card.meta.contains("Instantané") && card.meta.contains("source : base de données"))411 #expect(ChartPlot(live).numericX, "numbers on X read as a numeric axis for a line")412 }413414 @Test func theOtherCardsSayWhatTheNodeHoldsAndNothingElse() throws {415 let store = BlockCardStore()416 // runCode: language, code, last output with its facts, and the limit of the natives417 var run = RunCodeBlock(language: "javascript", code: "console.log(1)")418 run[attr: "output"] = .object(["text": .string("boom"), "error": .bool(true), "ms": .int(12), "at": .string("2026-11-19T14:02:11.000Z")])419 let runCard = BlockCardBuilder.runCode(run)420 #expect(runCard.title == "javascript" && runCard.items.contains(.text("boom", style: .monoDanger, maxLines: 5)))421 #expect(runCard.items.last == .notice("Exécutable sur le Web uniquement", symbol: "globe", tone: .neutral))422 #expect(runCard.meta.contains("Dernière sortie : erreur") && runCard.meta.contains("12 ms"))423 // audio: duration mm:ss, status + engine, first segments, the AI summary marked as AI424 var audio = AudioBlock(attachmentId: "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", duration: 754, title: "Réunion", recordedAt: nil)425 audio[attr: "transcript"] = .array([.object(["t": .int(0), "text": .string("Bonjour")]), .object(["t": .int(75), "text": .string("Budget")]), .object(["t": .int(90), "text": .string("Fin")])])426 audio[attr: "transcriptStatus"] = .string("done")427 audio[attr: "transcriptEngine"] = .string("whisper-1")428 audio[attr: "summary"] = .object(["text": .string("Résumé"), "decisions": .array([]), "tasks": .array([]), "model": .string("m"), "at": .string("2026-11-19T14:02:11.000Z")])429 let audioCard = BlockCardBuilder.audio(audio)430 #expect(audioCard.meta.contains("12:34") && audioCard.meta.contains("Transcrit (whisper-1)") && audioCard.meta.contains("3 segments"))431 #expect(audioCard.items.first == .rows([BlockCard.Row(leading: "00:00", text: "Bonjour", trailing: nil), BlockCard.Row(leading: "01:15", text: "Budget", trailing: nil)]))432 #expect(audioCard.items.contains(.notice("Résumé généré par IA disponible", symbol: "sparkles", tone: .ai)))433 // queryView: neutral while unknown, rows when resolved, the date when they come from the cache434 let query = QueryViewBlock(source: .tasks, title: "Ouvertes", filter: QueryFilter(tag: "thèse", status: "open"))435 var needs: [BlockCardNeed] = []436 store.onNeed = { needs.append($0) }437 var card = BlockCardBuilder.queryView(query, store)438 #expect(needs == [.query(query.cardKey)])439 #expect(card.items.first == .chips(["Tâches", "Liste", "#thèse", "état : open"]))440 store.queries[query.cardKey] = .unavailable("Résultats non disponibles hors ligne")441 card = BlockCardBuilder.queryView(query, store)442 #expect(card.items.last == .notice("Résultats non disponibles hors ligne", symbol: "icloud.slash", tone: .neutral))443 store.queries[query.cardKey] = .rows(BlockCardStore.QueryRows(columns: ["Titre", "Échéance"], rows: [["Relire", "2026-11-21"], ["Écrire", ""]], total: 9, fetchedAt: Date().addingTimeInterval(-7200), fromCache: true))444 card = BlockCardBuilder.queryView(query, store)445 #expect(card.items.contains(.rows([BlockCard.Row(leading: nil, text: "Relire", trailing: "2026-11-21"), BlockCard.Row(leading: nil, text: "Écrire", trailing: "")])))446 #expect(card.meta.first == "9 résultats" && card.meta.last?.hasPrefix("mis à jour") == true)447 // blockRef: resolved text; « Référence introuvable » when the block is missing448 let page = "0b7f6c0e-3f0a-4d5e-9b0a-111111111111"449 let ref = BlockRefBlock(pageId: page, blockId: "blk0000001")450 store.blockTargets[BlockCardStore.targetKey(pageId: page, blockId: "blk0000001")] = BlockCardStore.BlockTarget(pageTitle: "Source", text: "Le texte du bloc")451 var refCard = BlockCardBuilder.blockRef(ref, store)452 #expect(refCard.title == "Source" && refCard.items.first == .text("Le texte du bloc", style: .body, maxLines: 6))453 store.blockTargets[BlockCardStore.targetKey(pageId: page, blockId: "blk0000001")] = BlockCardStore.BlockTarget(pageTitle: "Source", text: nil)454 refCard = BlockCardBuilder.blockRef(ref, store)455 #expect(refCard.items == [.notice("Référence introuvable", symbol: "exclamationmark.triangle", tone: .warning)])456 // bibliography: the cited references that are known, the count of those that are not457 store.citedReferences = { ["r1", "r2"] }458 store.references["r1"] = BlockCardStore.Reference(label: "Fama 1970", entry: "Eugene F. Fama (1970). Efficient Capital Markets.")459 store.unknownReferences = ["r2"]460 let bibliography = BlockCardBuilder.bibliography(BibliographyBlock(), store)461 #expect(bibliography.items.first == .text("Eugene F. Fama (1970). Efficient Capital Markets.", style: .body, maxLines: 3))462 #expect(bibliography.items.last == .notice("1 référence citée n’est pas sur cet appareil", symbol: "icloud.slash", tone: .neutral))463 #expect(bibliography.meta == ["2 références citées", "style APA"])464 // canvasLink and drawing: neutral when the target / the files are not here465 store.pageTitles[page] = .some("Tableau blanc")466 #expect(BlockCardBuilder.canvasLink(CanvasLinkBlock(pageId: page), store).items == [.action("Ouvrir le canvas")])467 #expect(BlockCardBuilder.canvasLink(CanvasLinkBlock(pageId: page), store).title == "Tableau blanc")468 #expect(BlockCardBuilder.drawing(DrawingBlock(), store).items == [.notice("Dessin vide", symbol: "scribble", tone: .neutral)])469 }470471 @Test func theCitationChipShowsLabelAndLocator() throws {472 let renderer = AtomRenderer()473 renderer.traits = traits(.light)474 let short = renderer.citationChip(CitationInline(refId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc", label: "Fama 1970").node(), font: .preferredFont(forTextStyle: .body))475 let long = renderer.citationChip(CitationInline(refId: "cccccccc-cccc-4ccc-8ccc-cccccccccccc", label: "Fama 1970", locator: "p. 383–417").node(), font: .preferredFont(forTextStyle: .body))476 #expect(short.0.size.width > 40 && long.0.size.width > short.0.size.width + 30)477 #expect(inkStatistics(long.0).coverage > 0.5)478 }479}480481@MainActor482@Suite("Nœuds 3.0 — données hors du document") struct EditorNodesResolverTests {483 @Test func aReferencedBlockIsReadFromTheLocalStoreAndAMissingOneIsSaidMissing() async throws {484 let app = try makeApp()485 var source = NoteDocument(markdown: "Premier paragraphe\n\n- un\n- deux")486 source.ensureBlockIds()487 let sourceId = try await app.createNote(title: "Source", document: source)488 let stored = try NoteDocument(json: try #require(try await app.store.page(id: sourceId)).content)489 let paragraphId = try #require(stored.lines[0].attrs["id"]?.stringValue)490 let itemId = try #require(stored.lines[1].path.last?.attrs["id"]?.stringValue)491 let listId = try #require(stored.lines[1].path.first?.attrs["id"]?.stringValue)492 let resolver = BlockCardResolver(app: app, noteId: "x", store: BlockCardStore())493 #expect(await resolver.target(pageId: sourceId, blockId: paragraphId) == BlockCardStore.BlockTarget(pageTitle: "Source", text: "Premier paragraphe"))494 #expect(await resolver.target(pageId: sourceId, blockId: itemId).text == "un")495 #expect(await resolver.target(pageId: sourceId, blockId: listId).text?.contains("deux") == true)496 #expect(await resolver.target(pageId: sourceId, blockId: "nope000000") == BlockCardStore.BlockTarget(pageTitle: "Source", text: nil))497 #expect(await resolver.target(pageId: "0b7f6c0e-3f0a-4d5e-9b0a-999999999999", blockId: paragraphId) == BlockCardStore.BlockTarget(pageTitle: nil, text: nil))498499 // in an open note: the card asks, the resolver answers, the card is redrawn with the text500 let noteId = try await app.createNote(title: "Cible", document: NoteDocument(lines: [Line(blockAtom: BlockRefBlock(pageId: sourceId, blockId: paragraphId).node())]))501 let model = NoteEditorModel(noteId: noteId, app: app)502 model.controller.textView.frame = CGRect(x: 0, y: 0, width: 390, height: 800)503 await model.load()504 await model.cardResolver.settle()505 let atom = try #require(model.controller.firstAtom(ofType: NodeType.blockRef))506 let card = try #require(model.controller.atoms.card(for: atom.node))507 #expect(card.title == "Source" && card.items.first == .text("Premier paragraphe", style: .body, maxLines: 6))508 #expect((model.controller.storage.attribute(.attachment, at: atom.range.location, effectiveRange: nil) as? AtomAttachment)?.image != nil)509 #expect(model.saveState == .saved, "resolving card data never dirties the note")510 }511512 @Test func aPDFOnTheDeviceGetsItsFirstPageAndItsPageCountAndAnInkItsRender() async throws {513 let app = try makeApp()514 let id = try await app.createNote(title: "Médias", document: NoteDocument(markdown: "x"))515 let file = try await app.attach(data: samplePDFData(pages: 3), filename: "trois.pdf", mime: "application/pdf", to: id)516 let pdfId = try #require(file.stringAttr("attachmentId"))517 let ink = SampleData.sampleInk()518 let inkId = try #require((try await app.attach(data: try ink.jsonData(), filename: "d.ink.json", mime: "application/json", to: id)).stringAttr("attachmentId"))519 let store = BlockCardStore()520 let resolver = BlockCardResolver(app: app, noteId: id, store: store)521 #expect(await resolver.fetch(.pdf(attachmentId: pdfId)) == [NodeType.pdf])522 #expect(store.pdfs[pdfId]?.pageCount == 3 && store.pdfs[pdfId]?.thumbnail != nil)523 var block = PDFBlock(attachmentId: pdfId, name: "trois.pdf", page: 2)524 block.add(PDFAnnotation(page: 1, kind: .highlight, text: "Surligné", note: "important"))525 let card = BlockCardBuilder.pdf(block, store)526 #expect(card.title == "trois.pdf" && card.meta == ["3 pages", "page 2", "1 annotation"])527 guard case .picture? = card.items.first else { Issue.record("no thumbnail"); return }528 #expect(card.items.last == .rows([BlockCard.Row(leading: "p.1", text: "Surligné — important", trailing: nil)]))529 // a file that is not here is never downloaded for a card: the card says so530 #expect(await resolver.fetch(.pdf(attachmentId: "99999999-9999-4999-8999-999999999999")) == [NodeType.pdf])531 #expect(BlockCardBuilder.pdf(PDFBlock(attachmentId: "99999999-9999-4999-8999-999999999999", name: "x.pdf"), store).items.first == .notice("Fichier non téléchargé sur cet appareil", symbol: "icloud.slash", tone: .neutral))532 // ink → Core renderer533 _ = await resolver.fetch(.ink(attachmentId: inkId))534 let rendered = try #require(store.inks[inkId])535 #expect(rendered.size == CGSize(width: 600, height: 260) && inkStatistics(rendered).coverage > 0.01)536 var drawing = DrawingBlock(width: 600, height: 260)537 drawing[attr: "ink"] = .string(inkId)538 #expect(BlockCardBuilder.drawing(drawing, store).items == [.picture(rendered, maxHeight: 360, framed: true)])539 }540541 @Test func aLivingViewWithoutServerOrCacheIsNeutralAndNeverInvented() async throws {542 let app = try makeApp()543 let resolver = BlockCardResolver(app: app, noteId: "x", store: BlockCardStore())544 let key = QueryViewBlock(source: .tasks, title: "t").cardKey545 guard case .unavailable(let reason) = await resolver.rows(for: key, policy: .cacheOnly) else { Issue.record("rows without a server"); return }546 #expect(!reason.isEmpty)547 // backlinks are asked for the open note548 let backlinks = BlockCardResolver(app: app, noteId: "0b7f6c0e-3f0a-4d5e-9b0a-111111111111", store: BlockCardStore()).liveQuery(for: QueryViewBlock(source: .backlinks).cardKey)549 #expect(backlinks.pageId == "0b7f6c0e-3f0a-4d5e-9b0a-111111111111" && backlinks.source == "backlinks" && backlinks.filter == nil && backlinks.limit == 25)550 let filtered = resolver.liveQuery(for: QueryViewBlock(source: .pages, filter: QueryFilter(tag: "a", text: "b"), limit: 7).cardKey)551 #expect(filtered.filter == LiveQueryFilter(tag: "a", text: "b") && filtered.limit == 7 && filtered.pageId == nil)552 }553554 @Test func citedReferencesComeFromTheLocalResearchCopy() async throws {555 let app = try makeApp()556 await SampleData.seedSampleReferences(into: app)557 let known = SampleData.sampleReferenceIDs[0], unknown = "0b7f6c0e-3f0a-4d5e-9b0a-333333333333"558 let document = NoteDocument(lines: [Line.paragraph([.text("Voir ", marks: []), .atom(CitationInline(refId: known, label: "Fama 1970").node()), .atom(CitationInline(refId: unknown, label: "Inconnu").node()),559 .atom(CitationInline(refId: known, label: "Fama 1970", locator: "p. 2").node())]), Line(blockAtom: BibliographyBlock().node())])560 let id = try await app.createNote(title: "Papier", document: document)561 let model = NoteEditorModel(noteId: id, app: app)562 model.controller.textView.frame = CGRect(x: 0, y: 0, width: 390, height: 800)563 await model.load()564 #expect(model.controller.citedReferenceIds() == [known, unknown])565 await model.cardResolver.settle()566 let atom = try #require(model.controller.firstAtom(ofType: NodeType.bibliography))567 let card = try #require(model.controller.atoms.card(for: atom.node))568 #expect(card.items.first == .text("Eugene F. Fama (1970). Efficient Capital Markets: A Review of Theory and Empirical Work. The Journal of Finance.", style: .body, maxLines: 3))569 #expect(card.items.last == .notice("1 référence citée n’est pas sur cet appareil", symbol: "icloud.slash", tone: .neutral))570 // removing the citation of the unknown reference updates the list571 let range = try #require(model.controller.firstAtom(ofType: NodeType.citation)).range572 model.controller.deleteAtom(at: NSRange(location: range.location + 1, length: 1))573 let updated = try #require(model.controller.atoms.card(for: atom.node))574 #expect(updated.items.count == 1 && updated.meta.first == "1 référence citée")575 }576}577