Repository Public
1// SP Notes iOS2// File: Tests/EditorNodesExportTests.swift3// Description: Exports of the 3.0 nodes: Markdown and plain text are the Core's bytes on the Core's fixtures, HTML is the Core's4// markup (renders embedded when they are on the device), RTF and PDF carry the text or the cards, and the ZIP5// archive takes the files the new blocks reference.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import PDFKit10import Testing11import UIKit12import SPNotesCore13@testable import SPNotes1415@MainActor16@Suite("Nœuds 3.0 — exports") struct EditorNodesExportTests {17 @Test(arguments: nextNodesFixtureNames)18 func markdownAndPlainTextAreTheCoreBytesOfTheFixtures(name: String) throws {19 let document = try NoteDocument(json: try nextNodesFixture(name, "json"))20 let markdown = try NoteExporter.data(document: document, title: "T", format: .markdown) { _ in nil }21 let text = try NoteExporter.data(document: document, title: "T", format: .plainText) { _ in nil }22 #expect(markdown == (try nextNodesFixture(name, "md")), "Markdown of \(name)")23 #expect(text == (try nextNodesFixture(name, "txt")), "plain text of \(name)")24 // …and they are unchanged after a pass through the editor25 let harness = try EditorHarness()26 harness.editor.load(document)27 let edited = harness.editor.document()28 #expect(Data(edited.markdown().utf8) == markdown && Data(edited.plainText().utf8) == text)29 // HTML: the Core's body, inside the standalone page30 let html = String(decoding: try NoteExporter.data(document: document, title: "T", format: .html) { _ in nil }, as: UTF8.self)31 let body = String(decoding: try nextNodesFixture(name, "html"), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)32 #expect(html.contains(body), "HTML body of \(name)")33 }3435 @Test func htmlEmbedsTheRendersThatAreOnTheDevice() throws {36 let preview = "11111111-1111-4111-8111-111111111111"37 var mermaid = MermaidBlock(code: "graph TD\n A-->B")38 mermaid.setPreview(attachmentId: preview)39 let document = NoteDocument(lines: [Line(blockAtom: mermaid.node())])40 let picture = UIGraphicsImageRenderer(size: CGSize(width: 40, height: 30)).image { _ in UIColor.red.setFill(); UIRectFill(CGRect(x: 0, y: 0, width: 40, height: 30)) }41 let html = NoteExporter.html(document: document, title: "T") { $0 == "/api/files/" + preview ? picture : nil }42 #expect(html.contains("<figure class=\"nx nx-mermaid\"><img src=\"data:image/") && !html.contains("<img src=\"/api/files/"))43 let offline = NoteExporter.html(document: document, title: "T") { _ in nil }44 #expect(offline.contains("<img src=\"/api/files/\(preview)\""), "a render that is not here keeps its link")45 }4647 @Test func rtfAndPDFCarryTheNewBlocks() throws {48 let document = try NoteDocument(json: try nextNodesFixture("all-nodes", "json"))49 // RTF: the text of every block (transcript, annotations, code, output…), the chart as a picture50 let rtf = try NoteExporter.rtf(document: document) { _ in nil }51 let parsed = try NSAttributedString(data: rtf, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil).string52 for needle in ["graph TD", "Tâches ouvertes", "[Bollerslev 1986, p. 12]", "Références", "article.pdf", "Volatility clustering is pervasive.", "console.log", "Bonjour à tous.", "Canvas"] {53 #expect(parsed.contains(needle), "RTF contains « \(needle) »")54 }55 #expect(String(decoding: rtf, as: UTF8.self).contains("\\pict"), "the chart is embedded as a picture")56 #expect(NoteExporter.fallbackText(for: BlockRefBlock(pageId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", blockId: "par0000009").node(), isBlock: true) == "[[aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa#par0000009]]")57 #expect(NoteExporter.fallbackText(for: PMNode(type: "holoBlock", attrs: ["a": 1]), isBlock: true) == "[holoBlock]")58 // PDF: one valid document, the text around the blocks selectable, the cards drawn with resolved data and no "waiting" wording59 let store = BlockCardStore()60 store.blockTargets[BlockCardStore.targetKey(pageId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", blockId: "par0000009")] = BlockCardStore.BlockTarget(pageTitle: "Source", text: "Texte référencé")61 NoteExporter.cardSource = store62 defer { NoteExporter.cardSource = nil }63 let pdf = try #require(PDFDocument(data: NoteExporter.pdf(document: document, title: "Blocs", imageProvider: { _ in nil })))64 #expect(pdf.pageCount >= 2)65 #expect((pdf.string ?? "").contains("la variance conditionnelle est persistante"))66 let final = BlockCardStore()67 final.isFinal = true68 var asked = 069 final.onNeed = { _ in asked += 1 }70 for node in document.lines.compactMap(\.atomNode) {71 guard let typed = node.typed, let card = BlockCardBuilder.card(for: typed, width: 400, traits: NoteExporter.light, store: final) else { continue }72 for case .notice(let text, _, _) in card.items { #expect(!text.contains("…"), "\(node.type): « \(text) » is not a waiting message") }73 }74 #expect(asked == 0, "an export never asks for outside data")75 }7677 @Test func theArchiveTakesTheFilesOfTheNewBlocks() async throws {78 let app = try makeApp()79 let id = try await app.createNote(title: "Dossier", document: NoteDocument(markdown: "x"))80 func attach(_ data: Data, _ name: String, _ mime: String) async throws -> String {81 let node = try await app.attach(data: data, filename: name, mime: mime, to: id)82 return try #require(node.stringAttr("attachmentId") ?? AttachmentFiles.attachmentID(fromSource: node.stringAttr("src") ?? ""))83 }84 let png = try #require(UIGraphicsImageRenderer(size: CGSize(width: 20, height: 20)).image { _ in UIColor.blue.setFill(); UIRectFill(CGRect(x: 0, y: 0, width: 20, height: 20)) }.pngData())85 let pdfId = try await attach(samplePDFData(), "rapport.pdf", "application/pdf")86 let audioId = try await attach(SampleData.sampleWAV(seconds: 1), "memo.wav", "audio/wav")87 let inkId = try await attach(try SampleData.sampleInk().jsonData(), "dessin.ink.json", "application/json")88 let previewId = try await attach(png, "dessin.png", "image/png")89 let renderId = try await attach(png, "diagramme.png", "image/png")90 var drawing = DrawingBlock(width: 600, height: 260)91 drawing.setInk(attachmentId: inkId, preview: previewId, width: 600, height: 260)92 var mermaid = MermaidBlock(code: "graph TD")93 mermaid.setPreview(attachmentId: renderId)94 let missing = "99999999-9999-4999-8999-999999999999"95 let document = NoteDocument(lines: [Line(blockAtom: PDFBlock(attachmentId: pdfId, name: "rapport.pdf").node()), Line(blockAtom: AudioBlock(attachmentId: audioId, duration: 1, title: "Mémo").node()),96 Line(blockAtom: drawing.node()), Line(blockAtom: mermaid.node()), Line(blockAtom: PDFBlock(attachmentId: missing, name: "absent.pdf").node())])97 #expect(Set(document.attachmentReferences()) == [pdfId, audioId, inkId, previewId, renderId, missing])98 let (note, absent) = await NoteArchive.note(title: "Dossier", document: document, app: app)99 #expect(note.attachments.count == 5 && absent == 1)100 let url = try NoteArchive.exportArchive(notes: [note], format: .markdown)101 defer { try? FileManager.default.removeItem(at: url) }102 let reader = try ZipReader(url: url)103 let names = Set(reader.entries.map(\.name))104 #expect(names == ["Dossier.md", "attachments/rapport.pdf", "attachments/memo.wav", "attachments/dessin.ink.json", "attachments/dessin.png", "attachments/diagramme.png", "metadata.json"])105 let markdown = String(decoding: try reader.contents(of: try #require(reader.entries.first { $0.name == "Dossier.md" })), as: UTF8.self)106 #expect(markdown.contains("[PDF: rapport.pdf](attachments/rapport.pdf)") && markdown.contains("[Audio: Mémo](attachments/memo.wav)") && markdown.contains(""))107 #expect(markdown.contains("[PDF: absent.pdf](/api/files/\(missing))"), "a file that is not on the device keeps its server link")108 }109}110