Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/EditorTests/NextNodeTests.swift3// Description: Headless tests of the 3.0 document format in the native editor: byte-identical round trip of every new node, card render models, insertion, attribute edits through the typed models, unknown nodes, callout kinds, task due / priority, AI sources, toggles, footnotes, navigation to a block, the opening animation plan (and its Reduce Motion path).4import AppKit5import Testing6import SPNotesDocument7import SPNotesDesign8@testable import SPNotesEditor910let pageA = "6a006b40-d91b-4eb4-93cb-0e644363feeb", pageB = "0b0e2a52-3f0c-4a60-9c5e-1b1a9f3b7c11", fileA = "11111111-2222-4333-8444-555555555555", fileB = "22222222-3333-4444-8555-666666666666", refA = "33333333-4444-4555-8666-777777777777"11let mermaidCode = "flowchart TD\n A --> B"12let mermaidHash = MermaidBlock.hash(of: mermaidCode)1314/// One document with every 3.0 node (attributes filled, plus keys a newer editor could add) and a node type nobody knows.15let next = doc(#"""16{"type":"paragraph","attrs":{"id":"p000000001"},"content":[{"type":"text","text":"Voir "},{"type":"citation","attrs":{"refId":"\#(refA)","locator":"p. 3","label":"Engle 1982","futureKey":true}},{"type":"text","text":" pour le détail."}]},17{"type":"mermaid","attrs":{"id":"mmd0000001","code":"flowchart TD\n A --> B","preview":"\#(fileA)","previewHash":"\#(mermaidHash)","theme":"future"}},18{"type":"mermaid","attrs":{"id":"mmd0000002","code":"sequenceDiagram\n A->>B: salut","preview":"\#(fileA)","previewHash":"deadbeef"}},19{"type":"drawing","attrs":{"id":"drw0000001","ink":"\#(fileB)","preview":null,"pk":null,"width":640,"height":400,"background":"grid"}},20{"type":"chart","attrs":{"id":"cht0000001","kind":"bar","title":"Ventes","columns":["Mois","2025","2026"],"rows":[["jan",10,12.5],["fév",14,null],["mars",9,18]],"x":"Mois","y":["2025","2026"],"source":null}},21{"type":"queryView","attrs":{"id":"qry0000001","source":"tasks","databaseId":null,"viewId":null,"filter":{"tag":"thèse","status":"open","futureFilter":[1,2]},"layout":"list","limit":25,"title":"Tâches de la thèse"}},22{"type":"bibliography","attrs":{"id":"bib0000001","style":"apa","title":"Références"}},23{"type":"pdf","attrs":{"id":"pdf0000001","attachmentId":"\#(fileA)","name":"article.pdf","page":2,"annotations":[{"id":"a1","page":2,"kind":"highlight","color":"#ffd54a","rects":[[0.1,0.2,0.5,0.03]],"text":"passage","note":"à relire","createdAt":"2026-11-19T10:00:00.000Z","zzz":1}]}},24{"type":"blockRef","attrs":{"id":"ref0000001","pageId":"\#(pageA)","blockId":"ppppppppp1","mode":"embed"}},25{"type":"blockRef","attrs":{"id":"ref0000002","pageId":"\#(pageB)","blockId":"absent0000","mode":"embed"}},26{"type":"runCode","attrs":{"id":"run0000001","language":"javascript","code":"const a = 1;\nconsole.log(a + 41);","output":{"text":"un\n42","error":false,"ms":3,"at":"2026-11-19T10:00:00.000Z"}}},27{"type":"audio","attrs":{"id":"aud0000001","attachmentId":"\#(fileB)","duration":125.4,"title":"Réunion du lundi","recordedAt":"2026-11-18T14:00:00.000Z","transcript":[{"t":0,"text":"Bonjour à tous."},{"t":62.5,"text":"On décide de livrer vendredi."}],"transcriptStatus":"done","transcriptEngine":"whisper","summary":null}},28{"type":"canvasLink","attrs":{"id":"cvs0000001","pageId":"\#(pageA)"}},29{"type":"taskList","attrs":{"id":"tsk0000001"},"content":[{"type":"taskItem","attrs":{"checked":false,"id":"itm0000001","due":"2026-11-21","priority":"high","taskId":null},"content":[{"type":"paragraph","attrs":{"id":"p000000002"},"content":[{"type":"text","text":"Rendre le chapitre"}]}]}]},30{"type":"callout","attrs":{"id":"cal0000001","kind":"decision","icon":"⚖️"},"content":[{"type":"paragraph","attrs":{"id":"p000000003"},"content":[{"type":"text","text":"On garde SQLite."}]}]},31{"type":"aiBlock","attrs":{"id":"aib0000001","model":"claude-haiku","prompt":null,"at":null,"sources":[{"pageId":"\#(pageA)","blockId":"ppppppppp1","title":"Autre note"}],"action":"synthesis"},"content":[{"type":"paragraph","attrs":{"id":"p000000004"},"content":[{"type":"text","text":"Synthèse proposée."}]}]},32{"type":"hologram","attrs":{"id":"hol0000001","depth":3,"layers":[{"z":1},{"z":null}]}},33{"type":"futureWrap","attrs":{"mode":"x"},"content":[{"type":"paragraph","attrs":{"id":"p000000005"},"content":[{"type":"text","text":"dans un conteneur inconnu"}]},{"type":"futureLeaf","attrs":{"k":"v"}}]},34{"type":"paragraph","attrs":{"id":"p000000009"}}35"""#)3637@MainActor final class FakeResources: AtomResources {38 var images: [String: NSImage] = [:], files: [String: URL] = [:], refs: [String: BlockReference] = [:], titles: [String: String] = [:], cited: Int? = 139 func image(for src: String) -> NSImage? { images[src] }40 func attachmentURL(id: String) -> URL? { files[id] }41 func blockReference(pageId: String, blockId: String?) -> BlockReference? { refs[pageId + "#" + (blockId ?? "")] }42 func pageTitle(id: String) -> String? { titles[id] }43 func citedReferenceCount() -> Int? { cited }44 func citationLabel(refId: String) -> String? { nil }45 /// The editor holds its resources weakly: the fixtures live as long as the test process.46 static var alive: [FakeResources] = []47 static func standard() -> FakeResources {48 let r = FakeResources(); alive.append(r)49 let img = NSImage(size: NSSize(width: 320, height: 160)); img.lockFocus(); NSColor.systemTeal.setFill(); NSRect(x: 0, y: 0, width: 320, height: 160).fill(); NSColor.white.setFill(); NSRect(x: 40, y: 50, width: 90, height: 60).fill(); NSRect(x: 190, y: 50, width: 90, height: 60).fill(); img.unlockFocus()50 r.images["/api/files/\(fileA)"] = img51 r.refs[pageA + "#ppppppppp1"] = .resolved(pageTitle: "Autre note", text: "Le texte du bloc d'origine, lu dans la base locale.")52 r.refs[pageB + "#absent0000"] = .missing53 r.titles[pageA] = "Plan de la thèse"54 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spn-next-\(UUID().uuidString)"); try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)55 // a real one-page PDF and a real ink document56 let pdf = dir.appendingPathComponent("a.pdf"); var box = CGRect(x: 0, y: 0, width: 300, height: 400)57 if let ctx = CGContext(pdf as CFURL, mediaBox: &box, nil) { ctx.beginPDFPage(nil); ctx.setFillColor(CGColor(gray: 0.2, alpha: 1)); ctx.fill(CGRect(x: 30, y: 300, width: 240, height: 12)); ctx.fill(CGRect(x: 30, y: 270, width: 180, height: 8)); ctx.endPDFPage(); ctx.beginPDFPage(nil); ctx.fill(CGRect(x: 30, y: 200, width: 200, height: 20)); ctx.endPDFPage(); ctx.closePDF() }58 r.files[fileA] = pdf59 let ink = InkDocument(width: 640, height: 400, strokes: [InkStroke(tool: .pen, color: .black, width: 3, points: [InkPoint(x: 40, y: 60), InkPoint(x: 200, y: 180), InkPoint(x: 420, y: 90), InkPoint(x: 600, y: 340)])])60 let inkURL = dir.appendingPathComponent("b.json"); try? ink.jsonValue.canonicalData().write(to: inkURL); r.files[fileB] = inkURL61 return r62 }63}6465@MainActor func makeNextEditor(_ resources: FakeResources? = nil) -> NoteTextView {66 let (_, v) = NoteTextView.makeScrollable(); v.resources = resources67 v.load(try! NoteDocument(json: Data(next.utf8)))68 return v69}70@MainActor func atom(_ v: NoteTextView, _ type: String, _ nth: Int = 0) -> (node: PMNode, range: NSRange) {71 var found: [(PMNode, NSRange)] = []72 v.storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: v.storage.length)) { a, r, _ in if let a = a as? AtomAttachment, a.node.type == type { found.append((a.node, r)) } }73 return found[nth]74}75@MainActor func card(_ v: NoteTextView, _ type: String, _ nth: Int = 0) -> AtomCardModel { AtomCardModel.make(atom(v, type, nth).node, resources: v.resources) }7677@MainActor @Suite struct NextNodeTests {78 @Test func everyNewNodeSurvivesARoundTripByteForByte() throws {79 let v = makeNextEditor(FakeResources.standard())80 let original = try PMNode(data: Data(next.utf8)).jsonData()81 #expect(try v.document().jsonData() == original, "unknown attributes inside known nodes and the unknown node are untouched")82 // and after an edit elsewhere and its undo, and after the whole document was laid out and drawn83 v.textLayoutManager?.ensureLayout(for: v.textLayoutManager!.documentRange)84 step(); caret(v, 2); type(v, "Z"); step(); v.undoManager?.undo()85 #expect(try v.document().jsonData() == original)86 #expect(try NoteDocument(json: original).schemaViolations().filter { !$0.description.contains("hologram") && !$0.description.contains("future") }.isEmpty)87 }8889 @Test func eachNewBlockHasItsCardModel() {90 let v = makeNextEditor(FakeResources.standard())91 let current = card(v, "mermaid", 0)92 #expect(current.body == .image(src: "/api/files/\(fileA)")); #expect(current.notice == nil); #expect(current.title == "Organigramme")93 let stale = card(v, "mermaid", 1)94 #expect(stale.body == .code("sequenceDiagram\n A->>B: salut"), "the render is shown only when previewHash is the sha256 of the code")95 #expect(stale.notice == AtomCardModel.mermaidStaleNotice); #expect(stale.title == "Diagramme de séquence")96 #expect(card(v, "drawing").body == .ink(attachmentId: fileB)); #expect(card(v, "drawing").summary.contains("640 × 400"))97 let chart = card(v, "chart"); #expect(chart.title == "Ventes"); #expect(chart.body == .chart); #expect(chart.summary == "Barres · 2 séries · 3 lignes")98 let q = card(v, "queryView"); #expect(q.title == "Tâches de la thèse"); #expect(q.summary.contains("Source : Tâches")); #expect(q.summary.contains("#thèse"))99 #expect(card(v, "bibliography").summary == "1 référence citée · style APA")100 let pdf = card(v, "pdf"); #expect(pdf.title == "article.pdf"); #expect(pdf.body == .pdfPage(attachmentId: fileA, page: 2)); #expect(pdf.summary == "page 2 · 1 annotation")101 let ref = card(v, "blockRef", 0); #expect(ref.title == "Autre note"); #expect(ref.body == .text("Le texte du bloc d'origine, lu dans la base locale."))102 let gone = card(v, "blockRef", 1); #expect(gone.title == "Référence introuvable"); #expect(gone.tone == .warning)103 let run = card(v, "runCode"); #expect(run.title == "javascript"); #expect(run.summary == "Dernière sortie : 42"); #expect(!run.summaryIsError)104 let audio = card(v, "audio"); #expect(audio.title == "Réunion du lundi"); #expect(audio.summary == "2:05 · 2 segments transcrits")105 #expect(audio.body == .lines(["[00:00] Bonjour à tous.", "[01:02] On décide de livrer vendredi."]))106 #expect(card(v, "canvasLink").title == "Plan de la thèse")107 // without resources nothing crashes and nothing is invented108 let bare = makeNextEditor(nil)109 #expect(card(bare, "blockRef", 0).title == "…"); #expect(card(bare, "canvasLink").summary == "Canvas introuvable sur ce Mac"); #expect(card(bare, "bibliography").summary.hasPrefix("Références citées"))110 }111112 @Test func aNodeTypeNobodyKnowsIsANeutralCardAndIsKeptVerbatim() throws {113 let v = makeNextEditor()114 let unknown = card(v, "hologram")115 #expect(unknown.isUnsupported); #expect(unknown.title == "Bloc non pris en charge"); #expect(unknown.eyebrow == "« hologram »"); #expect(unknown.tone == .neutral)116 let node = atom(v, "hologram").node117 #expect(node.attrs?["layers"] == .array([.object(["z": .int(1)]), .object(["z": .null])]))118 // an unknown container shows its content inside a labelled frame; an unknown leaf inside it is a card too119 let inner = (v.storage.string as NSString).range(of: "dans un conteneur inconnu").location120 let deco = v.storage.attribute(.spDecoration, at: inner, effectiveRange: nil) as? ParaDecoration121 #expect(deco?.panel == .unknown(type: "futureWrap")); #expect(deco?.panelHeader == "Bloc non pris en charge · « futureWrap » — conservé tel quel")122 #expect(card(v, "futureLeaf").isUnsupported)123 // typing next to it, moving it and undoing never alter it124 let r = atom(v, "hologram").range; caret(v, r.location + 1); type(v, "après"); step()125 #expect(atom(v, "hologram").node == node)126 v.setSelectedRange(NSRange(location: atom(v, "hologram").range.location, length: 0)); v.moveBlock(up: true)127 #expect(atom(v, "hologram").node == node)128 #expect(v.document().lines.contains { $0.type == "hologram" })129 let wrap = v.document().pmNode().content?.first { $0.type == "futureWrap" }130 #expect(wrap?.attrs == ["mode": .string("x")]); #expect(wrap?.content?.map(\.type) == ["paragraph", "futureLeaf"])131 }132133 @Test func everyCardIsDrawnInBothAppearancesAndPlaceholdersAreNotCached() {134 let res = FakeResources.standard()135 for dark in [false, true] {136 NSAppearance(named: dark ? .darkAqua : .aqua)!.performAsCurrentDrawingAppearance {137 let renderer = AtomRenderer(theme: EditorTheme(), resources: res)138 let v = makeNextEditor(res)139 for type in NodeType.nextBlocks + ["hologram"] {140 let img = renderer.image(for: atom(v, type).node, isBlock: true, width: 700)141 #expect(img.size.width >= 220 && img.size.width <= 680, "\(type)"); #expect(img.size.height >= 60, "\(type) \(img.size)")142 }143 #expect(!renderer.pending.value, "every resource was available")144 let chip = renderer.image(for: atom(v, "citation").node, isBlock: false, width: 700); #expect(chip.size.width > 60); #expect(chip.size.height < 26)145 }146 }147 // a preview that is not on this Mac yet draws a placeholder and asks to be drawn again148 let missing = AtomRenderer(theme: EditorTheme(), resources: FakeResources())149 _ = missing.image(for: atom(makeNextEditor(), "pdf").node, isBlock: true, width: 700); #expect(missing.pending.value)150 // a chart with data is taller than the same chart without151 let v = makeNextEditor(res); let r = AtomRenderer(theme: EditorTheme(), resources: res)152 var empty = ChartBlock(node: atom(v, "chart").node)!; empty.rows = []153 #expect(r.image(for: atom(v, "chart").node, isBlock: true, width: 700).size.height > r.image(for: empty.node(), isBlock: true, width: 700).size.height + 150)154 }155156 @Test func newBlocksAreInsertedWithSchemaDefaultsAndAnId() throws {157 let v = makeEditor(doc(p("début", id: "aaaaaaaaa1")))158 caret(v, 5)159 v.insertMermaid("graph LR\n A-->B"); v.insertChart(); v.insertRunCode(language: "python", code: "print(1)"); v.insertQueryView(source: .pages, title: "Récentes"); v.insertBibliography()160 v.insertPDF(attachmentId: fileA, name: "a.pdf"); v.insertAudio(attachmentId: fileB, duration: 12, title: "Mémo"); v.insertDrawing(); v.insertBlockRef(pageId: pageA, blockId: "ppppppppp1"); v.insertCanvasLink(pageId: pageA)161 let d = v.document()162 #expect(Set(d.lines.map(\.type)).isSuperset(of: Set(NodeType.nextBlocks)))163 #expect(d.schemaViolations().isEmpty, "\(d.schemaViolations())")164 let ids = d.lines.compactMap { $0.attrs["id"]?.string }; #expect(Set(ids).count == ids.count); #expect(ids.count == d.lines.count)165 #expect(d.typedBlock(at: d.lines.firstIndex { $0.type == "runCode" }!) == .runCode(RunCodeBlock(node: d.lines.first { $0.type == "runCode" }!.atomNode!)!))166 // inline citation in the text167 step(); caret(v, 5); v.insertCitation(refId: refA, label: "Bollerslev 1986", locator: "p. 12")168 #expect(v.document().citedReferences() == [refA]); #expect(v.document().markdown().contains("[@Bollerslev 1986]"))169 // the slash menu offers every new block170 let menu = Set(NoteTextView.builtinSlashItems().map(\.id))171 #expect(menu.isSuperset(of: ["mermaid", "chart", "runcode", "query", "bibliography", "drawing", "toggle", "footnote", "decision", "question", "hypothesis"]))172 // each insertion is one undo step173 let count = v.document().lines.count; step(); v.undoManager?.undo(); #expect(v.document().citedReferences().isEmpty); #expect(v.document().lines.count == count)174 }175176 @Test func attributesAreEditedThroughTheTypedModelsAndUnknownKeysSurvive() throws {177 let v = makeNextEditor(FakeResources.standard())178 // mermaid: new code → the stored render no longer matches, the card falls back to the source with the notice179 var m = MermaidBlock(node: atom(v, "mermaid").node)!; m.code = "flowchart LR\n X --> Y"180 v.replaceAtom(at: atom(v, "mermaid").range, with: m.node())181 #expect(card(v, "mermaid").notice == AtomCardModel.mermaidStaleNotice); #expect(atom(v, "mermaid").node.attrs?["theme"] == .string("future"), "a key of a newer editor is kept")182 #expect(atom(v, "mermaid").node.attrs?["id"] == .string("mmd0000001"))183 step(); v.undoManager?.undo(); #expect(card(v, "mermaid").notice == nil)184 // chart: data grid185 var c = ChartBlock(node: atom(v, "chart").node)!; c.rows.append(["avr", 20, 21]); c.kind = .line; c.title = "Ventes 2026"186 v.replaceAtom(at: atom(v, "chart").range, with: c.node())187 #expect(card(v, "chart").summary == "Courbes · 2 séries · 4 lignes"); #expect(card(v, "chart").title == "Ventes 2026")188 // runCode: code changes, output stays (natives never execute)189 var r = RunCodeBlock(node: atom(v, "runCode").node)!; r.code = "console.log(7)"190 v.replaceAtom(at: atom(v, "runCode").range, with: r.node()); #expect(RunCodeBlock(node: atom(v, "runCode").node)?.output?.text == "un\n42")191 // queryView config, blockRef target, pdf page, audio title, citation locator192 var q = QueryViewBlock(node: atom(v, "queryView").node)!; q.layout = .board; q.limit = 10193 v.replaceAtom(at: atom(v, "queryView").range, with: q.node())194 #expect(card(v, "queryView").summary.contains("tableau kanban")); #expect(atom(v, "queryView").node.attrs?["filter"]?["futureFilter"] == .array([.int(1), .int(2)]))195 var b = BlockRefBlock(node: atom(v, "blockRef", 1).node)!; b.pageId = pageA; b.blockId = "ppppppppp1"196 v.replaceAtom(at: atom(v, "blockRef", 1).range, with: b.node()); #expect(card(v, "blockRef", 1).title == "Autre note")197 var pdf = PDFBlock(node: atom(v, "pdf").node)!; pdf.page = 1198 v.replaceAtom(at: atom(v, "pdf").range, with: pdf.node()); #expect(PDFBlock(node: atom(v, "pdf").node)?.annotations.first?.fields["zzz"] == .int(1))199 var a = AudioBlock(node: atom(v, "audio").node)!; a.title = "Point d'équipe"200 v.replaceAtom(at: atom(v, "audio").range, with: a.node()); #expect(card(v, "audio").title == "Point d'équipe")201 var cit = CitationInline(node: atom(v, "citation").node)!; cit.locator = "p. 9"202 v.replaceAtom(at: atom(v, "citation").range, with: cit.node()); #expect(atom(v, "citation").node.attrs?["futureKey"] == .bool(true))203 #expect(v.document().markdown().contains("[@Engle 1982]"))204 let d = v.document(); #expect(d.schemaViolations().filter { !$0.description.contains("holo") && !$0.description.contains("future") }.isEmpty, "\(d.schemaViolations())")205 }206207 @Test func returnOnASelectedBlockOpensItsEditor() {208 final class Spy: NoteTextViewDelegate {209 var activated: [String] = [], tasks: [Int] = [], opened: [(String, String?)] = []210 func noteTextViewDidChange(_ view: NoteTextView) {}211 func noteTextViewSelectionDidChange(_ view: NoteTextView) {}212 func noteTextView(_ view: NoteTextView, open link: String) {}213 func noteTextView(_ view: NoteTextView, activate atom: AtomAttachment, at range: NSRange) { activated.append(atom.node.type) }214 func noteTextView(_ view: NoteTextView, receive files: [URL], images: [NSImage], at location: Int) {}215 func noteTextView(_ view: NoteTextView, completionsFor trigger: Character, query: String) -> [CompletionItem] { [] }216 func noteTextView(_ view: NoteTextView, editTaskAt location: Int, anchor: CGRect) { tasks.append(location) }217 func noteTextView(_ view: NoteTextView, openPage pageId: String, blockId: String?) { opened.append((pageId, blockId)) }218 }219 let v = makeNextEditor(); let spy = Spy(); v.noteDelegate = spy220 let r = atom(v, "chart").range; let before = v.document().lines.count221 v.setSelectedRange(r); v.insertNewline(nil)222 #expect(spy.activated == ["chart"]); #expect(v.document().lines.count == before, "Return on a selected block opens it instead of adding a paragraph")223 #expect(v.selectionState.context == .atom("chart"))224 // beside the block, Return still opens a paragraph225 caret(v, r.location + 1); v.insertNewline(nil); #expect(v.document().lines.count == before + 1)226 // the task command asks for the popover of the item under the caret227 caret(v, (v.storage.string as NSString).range(of: "Rendre").location + 2); v.requestTaskDetails(); #expect(spy.tasks.count == 1)228 #expect(v.selectionState.context == .task)229 }230}231232@MainActor @Suite struct NextStructureTests {233 @Test func calloutKindsAreSetChangedAndKeepACustomIcon() throws {234 let v = makeEditor(doc(p("une décision", id: "aaaaaaaaa1")))235 caret(v, 3); v.setCallout(.decision)236 var c = v.currentCallout; #expect(c?.kind == .decision); #expect(c?.container.attrs["icon"] == .string("⚖️")); #expect(v.selectionState.calloutKind == "decision")237 step(); v.setCallout(.question); c = v.currentCallout; #expect(c?.kind == .question); #expect(c?.container.attrs["icon"] == .string("❓"))238 step(); v.setCallout(.hypothesis); #expect(v.currentCallout?.container.attrs["icon"] == .string("🧪"))239 #expect(v.document().schemaViolations().isEmpty); #expect(v.document().lines.count == 1, "changing the kind never splits the callout")240 step(); v.undoManager?.undo(); #expect(v.currentCallout?.kind == .question)241 // an icon the owner chose is kept when the kind changes242 let custom = makeNextEditor(); caret(custom, (custom.storage.string as NSString).range(of: "On garde").location + 1)243 custom.restyleParagraphs(in: custom.paragraphRange(at: custom.selectedRange().location)) { s, _ in s.with(path: s.path.map { var c = $0; if c.type == "callout" { c.attrs["icon"] = .string("🦊") }; return c }) }244 custom.setCallout(.warning); #expect(custom.currentCallout?.kind == .warning); #expect(custom.currentCallout?.container.attrs["icon"] == .string("🦊"))245 for k in CalloutKind.known { #expect(EditorTheme.calloutTone(k.rawValue) != .ai, "violet is reserved for AI content") }246 }247248 @Test func taskItemsCarryDueAndPriorityAndShowThemAsChips() throws {249 let v = makeNextEditor()250 let loc = (v.storage.string as NSString).range(of: "Rendre le chapitre").location251 #expect(v.taskItem(at: loc) == NoteTextView.TaskItemState(due: "2026-11-21", priority: .high, checked: false, taskId: nil))252 let deco = v.storage.attribute(.spDecoration, at: loc, effectiveRange: nil) as? ParaDecoration253 #expect(deco?.taskChips.map(\.symbol) == ["calendar", "flag"]); #expect(deco?.taskChips.last?.text == "Haute"); #expect(deco?.taskChips.last?.tone == .danger)254 // the chips of an open task whose date is past are red; done or future ones are neutral255 let day = Styler.localDay("2026-11-21")!256 #expect(Styler.taskChips(["due": "2026-11-21", "checked": false], today: day.addingTimeInterval(3 * 86_400)).first?.tone == .danger)257 #expect(Styler.taskChips(["due": "2026-11-21", "checked": true], today: day.addingTimeInterval(3 * 86_400)).first?.tone == .neutral)258 #expect(Styler.taskChips(["due": "2026-11-21", "checked": false], today: day).first?.text == "Aujourd'hui")259 #expect(Styler.taskChips(["due": "2026-11-21"], today: day.addingTimeInterval(-86_400)).first?.text == "Demain")260 #expect(Styler.taskChips(["checked": false]).isEmpty)261 // edit through the command (what the popover calls): one undo step, a valid document, the item id is kept262 v.setTaskAttributes(at: loc, due: "2026-12-01", priority: .low)263 #expect(v.taskItem(at: loc)?.due == "2026-12-01"); #expect(v.taskItem(at: loc)?.priority == .low)264 let details = v.document().taskItemDetails(); #expect(details.count == 1); #expect(details[0].due == "2026-12-01"); #expect(details[0].priority == .low); #expect(details[0].blockId == "itm0000001")265 step(); v.setTaskAttributes(at: loc, due: nil, priority: nil); #expect((v.storage.attribute(.spDecoration, at: loc, effectiveRange: nil) as? ParaDecoration)?.taskChips.isEmpty == true)266 #expect(v.document().schemaViolations().filter { !$0.description.contains("holo") && !$0.description.contains("future") }.isEmpty)267 step(); v.undoManager?.undo(); #expect(v.taskItem(at: loc)?.priority == .low)268 }269270 @Test func anAIBlockIsMarkedAndShowsItsSources() {271 let v = makeNextEditor()272 let loc = (v.storage.string as NSString).range(of: "Synthèse proposée").location273 let deco = v.storage.attribute(.spDecoration, at: loc, effectiveRange: nil) as? ParaDecoration274 #expect(deco?.panel == .ai); #expect(deco?.panelHeader == "Généré par IA · claude-haiku · synthesis", "AI content is always visibly marked")275 #expect(deco?.aiSources.count == 1); #expect(deco?.aiSources.first?.pageId == pageA); #expect(deco?.aiSources.first?.blockId == "ppppppppp1"); #expect(deco?.aiSources.first?.text.contains("Autre note") == true)276 #expect(v.selectionState.context == .text); caret(v, loc + 2); #expect(v.selectionState.context == .ai)277 }278279 @Test func togglesAndFootnotesCanBeCreated() throws {280 let v = makeEditor(doc(p("Méthode", id: "aaaaaaaaa1") + "," + p("suite", id: "aaaaaaaaa2")))281 caret(v, 3); v.insertDetails(); type(v, "contenu replié")282 #expect(types(v) == ["details>detailsSummary", "details>detailsContent>paragraph", "paragraph"]); #expect(texts(v).prefix(2) == ["Méthode", "contenu replié"])283 #expect(v.document().schemaViolations().isEmpty, "\(v.document().schemaViolations())")284 step(); v.undoManager?.undo(); v.undoManager?.undo(); 285 let f = makeEditor(doc(p("Un fait", id: "aaaaaaaaa1") + "," + p("autre", id: "aaaaaaaaa2")))286 caret(f, 7); f.insertFootnote(); caret(f, 0); caret(f, (f.storage.string as NSString).range(of: "autre").location + 5); f.insertFootnote()287 let d = f.document()288 #expect(d.lines.map(\.type) == ["paragraph", "paragraph", "footnote", "footnote"]); #expect(d.lines.suffix(2).map { $0.attrs["id"] } == [.string("1"), .string("2")])289 #expect(d.markdown().contains("[^1]")); #expect(d.markdown().contains("[^2]")); #expect(d.schemaViolations().isEmpty, "\(d.schemaViolations())")290 }291292 @Test func aBlockIsFoundByItsIdAndFlashed() {293 let v = makeNextEditor()294 let s = v.storage.string as NSString295 #expect(v.rangeOfBlock(id: "p000000003")?.location == s.range(of: "On garde SQLite.").location, "text block")296 #expect(v.rangeOfBlock(id: "cal0000001")?.location == s.range(of: "On garde SQLite.").location, "container: its first paragraph")297 #expect(v.rangeOfBlock(id: "itm0000001")?.location == s.range(of: "Rendre le chapitre").location, "a list item (3.0 ids)")298 #expect(v.rangeOfBlock(id: "cht0000001") == v.paragraphRange(at: atom(v, "chart").range.location), "block atom")299 #expect(v.rangeOfBlock(id: "nope") == nil); #expect(!v.scrollToBlock(id: "nope"))300 #expect(v.scrollToBlock(id: "run0000001", reduceMotion: false)); #expect(v.selectedRange().location == atom(v, "runCode").range.location)301 #expect(v.layer?.sublayers?.contains { $0.name == "sp.flash" } == true)302 #expect(v.scrollToBlock(id: "p000000004", reduceMotion: true)); #expect(v.layer?.sublayers?.filter { $0.name == "sp.flash" }.count == 1)303 }304305 @Test func theOpeningAnimationIsStaggeredAndReducedMotionOnlyFades() {306 let full = NoteTextView.revealPlan(blockCount: 60, reduceMotion: false)307 #expect(full.blocks == 24, "capped at the first 24 blocks"); #expect(full.staggered); #expect(full.rise == 6); #expect(abs(full.duration - 0.240) < 0.001); #expect(abs(full.lastDelay - 23 * 0.018) < 0.0001)308 let reduced = NoteTextView.revealPlan(blockCount: 60, reduceMotion: true)309 #expect(!reduced.staggered); #expect(reduced.rise == 0, "nothing moves"); #expect(reduced.duration <= 0.120); #expect(reduced.lastDelay == 0)310 #expect(NoteTextView.revealPlan(blockCount: 0, reduceMotion: false).blocks == 0)311 // played on a real view: one cover per visible block, no rise under Reduce Motion312 let v = makeNextEditor(FakeResources.standard()); v.enclosingScrollView?.frame = CGRect(x: 0, y: 0, width: 820, height: 700); v.enclosingScrollView?.layoutSubtreeIfNeeded()313 let plan = v.playReveal(reduceMotion: false)314 #expect(plan.blocks > 3); #expect(v.layer?.sublayers?.filter { $0.name == "sp.reveal" }.count == plan.blocks); #expect(v.layer?.animation(forKey: "sp.rise") != nil)315 let w = makeNextEditor(FakeResources.standard()); w.enclosingScrollView?.frame = CGRect(x: 0, y: 0, width: 820, height: 700); let quiet = w.playReveal(reduceMotion: true)316 #expect(quiet.rise == 0); #expect(w.layer?.animation(forKey: "sp.rise") == nil)317 }318}319320@MainActor @Test func snapshotOfEveryNextBlock() throws {321 let out = ProcessInfo.processInfo.environment["SPNOTES_SNAPSHOT_DIR"] ?? NSTemporaryDirectory()322 let d = try NoteDocument(json: Data(next.utf8))323 let size = renderEditor(d, resources: FakeResources.standard(), to: out + "/next-light.png")324 _ = renderEditor(d, dark: true, resources: FakeResources.standard(), to: out + "/next-dark.png")325 #expect(size.height > 1500)326}327