Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/EditorTests/EditorTests.swift3// Description: Headless tests of the native editor: lossless codec, structured typing (Return, Tab, Backspace), block and mark commands, undo/redo, atoms, remote updates, pasteboard.4import AppKit5import Testing6import SPNotesDocument7@testable import SPNotesEditor89@MainActor func makeEditor(_ json: String? = nil) -> NoteTextView {10 let (_, v) = NoteTextView.makeScrollable()11 if let json { v.load(try! NoteDocument(json: Data(json.utf8))) }12 return v13}14func doc(_ blocks: String) -> String { #"{"type":"doc","content":[\#(blocks)]}"# }15func p(_ text: String, id: String? = nil) -> String { #"{"type":"paragraph"\#(id.map { #","attrs":{"id":"\#($0)"}"# } ?? ""),"content":[{"type":"text","text":"\#(text)"}]}"# }16@MainActor func json(_ v: NoteTextView) -> JSONValue { v.document().pmNode().jsonValue }17@MainActor func types(_ v: NoteTextView) -> [String] { v.document().lines.map { ($0.path.map(\.type) + [$0.type]).joined(separator: ">") } }18@MainActor func texts(_ v: NoteTextView) -> [String] { v.document().lines.map { NoteDocument(lines: [Line(type: "paragraph", content: $0.content)]).plainText() } }19@MainActor func type(_ v: NoteTextView, _ s: String) { for ch in s { if ch == "\n" { v.insertNewline(nil) } else { v.insertText(String(ch), replacementRange: NSRange(location: NSNotFound, length: 0)) } } }20/// Ends the current "event": the undo manager closes its automatic group, as it does between two user actions.21@MainActor func step() { RunLoop.current.run(until: Date().addingTimeInterval(0.001)) }22@MainActor func caret(_ v: NoteTextView, _ loc: Int, _ len: Int = 0) { v.setSelectedRange(NSRange(location: loc, length: len)) }2324/// The document without the ids of its list items (the only thing 3.0 adds to a 2.x document at load).25func withoutItemIds(_ v: JSONValue) -> JSONValue {26 switch v {27 case .array(let a): return .array(a.map(withoutItemIds))28 case .object(var o):29 if case .string(let t)? = o["type"], t == "listItem" || t == "taskItem", case .object(var attrs)? = o["attrs"] { attrs["id"] = nil; o["attrs"] = attrs.isEmpty ? nil : .object(attrs) }30 return .object(o.mapValues(withoutItemIds))31 default: return v32 }33}34func itemIds(_ v: JSONValue) -> [String] {35 switch v {36 case .array(let a): return a.flatMap(itemIds)37 case .object(let o):38 var out: [String] = []39 if case .string(let t)? = o["type"], t == "listItem" || t == "taskItem", case .string(let id)? = o["attrs"]?["id"] { out.append(id) }40 return out + o.values.flatMap(itemIds)41 default: return []42 }43}4445let rich = doc(#"""46{"type":"heading","attrs":{"level":2,"id":"hhhhhhhhh1"},"content":[{"type":"text","text":"Titre"}]},47{"type":"paragraph","attrs":{"id":"ppppppppp1"},"content":[{"type":"text","text":"Du "},{"type":"text","text":"gras","marks":[{"type":"bold"}]},{"type":"text","text":" et un "},{"type":"text","text":"lien","marks":[{"type":"link","attrs":{"href":"https://example.org","target":"_blank"}}]},{"type":"hardBreak"},{"type":"mention","attrs":{"id":"6a006b40-d91b-4eb4-93cb-0e644363feeb","label":"Autre note"}},{"type":"text","text":" x"},{"type":"inlineMath","attrs":{"latex":"x^2"}}]},48{"type":"bulletList","attrs":{"id":"lllllllll1"},"content":[{"type":"listItem","content":[{"type":"paragraph","attrs":{"id":"ppppppppp2"},"content":[{"type":"text","text":"un"}]},{"type":"orderedList","attrs":{"start":3,"id":"lllllllll2"},"content":[{"type":"listItem","content":[{"type":"paragraph","attrs":{"id":"ppppppppp3"},"content":[{"type":"text","text":"imbriqué"}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","attrs":{"id":"ppppppppp4"},"content":[{"type":"text","text":"deux"}]}]}]},49{"type":"taskList","attrs":{"id":"lllllllll3"},"content":[{"type":"taskItem","attrs":{"checked":true},"content":[{"type":"paragraph","attrs":{"id":"ppppppppp5"},"content":[{"type":"text","text":"fait"}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","attrs":{"id":"ppppppppp6"},"content":[{"type":"text","text":"à faire"}]}]}]},50{"type":"blockquote","attrs":{"id":"qqqqqqqqq1"},"content":[{"type":"paragraph","attrs":{"id":"ppppppppp7"},"content":[{"type":"text","text":"cité"}]}]},51{"type":"codeBlock","attrs":{"language":"swift","id":"ccccccccc1"},"content":[{"type":"text","text":"let a = 1\nlet b = 2\n\nprint(a + b)"}]},52{"type":"table","attrs":{"id":"ttttttttt1"},"content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1,"colwidth":null},"content":[{"type":"paragraph","attrs":{"id":"cellpara00"},"content":[{"type":"text","text":"A"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1,"colwidth":null},"content":[{"type":"paragraph","attrs":{"id":"cellpara01"},"content":[{"type":"text","text":"B"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1,"colwidth":null},"content":[{"type":"paragraph","attrs":{"id":"cellpara02"},"content":[{"type":"text","text":"1","marks":[{"type":"italic"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1,"colwidth":null},"content":[{"type":"paragraph","attrs":{"id":"cellpara03"},"content":[{"type":"text","text":"2"}]}]}]}]},53{"type":"horizontalRule"},54{"type":"blockMath","attrs":{"latex":"\\int_0^1 x\\,dx","id":"mmmmmmmmm1"}},55{"type":"callout","attrs":{"kind":"warning","icon":"⚠️","id":"kkkkkkkkk1"},"content":[{"type":"paragraph","attrs":{"id":"ppppppppp8"},"content":[{"type":"text","text":"attention"}]}]},56{"type":"image","attrs":{"src":"/api/files/6a006b40-d91b-4eb4-93cb-0e644363feeb","alt":"photo","title":null,"id":"iiiiiiiii1"}},57{"type":"futureBlock","attrs":{"x":1},"content":[{"type":"futureChild","attrs":{"y":[1,2,{"z":null}]}}]},58{"type":"details","attrs":{"open":true,"id":"ddddddddd1"},"content":[{"type":"detailsSummary","content":[{"type":"text","text":"Résumé"}]},{"type":"detailsContent","content":[{"type":"paragraph","attrs":{"id":"ppppppppp9"},"content":[{"type":"text","text":"caché"}]}]}]},59{"type":"paragraph","attrs":{"id":"ppppppppp0"}}60"""#)6162@MainActor @Suite struct CodecTests {63 @Test func everyNodeOfTheWebSchemaSurvivesARoundTripUntouched() throws {64 let v = makeEditor(rich)65 let original = try PMNode(data: Data(rich.utf8)).jsonValue66 // SPEC §7: a 2.x document has no id on its list items; loading gives them one (Core 2.0 `ensureBlockIds`). Apart from67 // those ids nothing is added and nothing is lost.68 #expect(withoutItemIds(json(v)).semanticallyEquals(withoutItemIds(original)), "the fixture carries every other id the server would assign")69 #expect(!json(v).semanticallyEquals(original), "list items received their 3.0 ids")70 let ids = itemIds(json(v)); #expect(ids.count == 5); #expect(Set(ids).count == ids.count); #expect(ids.allSatisfy { $0.count == 10 })71 // the ids given at load are stable: two serialisations are byte-identical, and so is the state after an edit and its undo72 let first = try v.document().jsonData(); #expect(try v.document().jsonData() == first)73 step(); caret(v, 2); type(v, "Z"); step(); v.undoManager?.undo()74 #expect(try v.document().jsonData() == first)75 }76 @Test func loadingADocumentNeverReportsAChange() throws {77 final class Spy: NoteTextViewDelegate {78 var changes = 079 func noteTextViewDidChange(_ view: NoteTextView) { changes += 1 }80 func noteTextViewSelectionDidChange(_ view: NoteTextView) {}81 func noteTextView(_ view: NoteTextView, open link: String) {}82 func noteTextView(_ view: NoteTextView, activate atom: AtomAttachment, at range: NSRange) {}83 func noteTextView(_ view: NoteTextView, receive files: [URL], images: [NSImage], at location: Int) {}84 func noteTextView(_ view: NoteTextView, completionsFor trigger: Character, query: String) -> [CompletionItem] { [] }85 }86 let (_, v) = NoteTextView.makeScrollable(); let spy = Spy(); v.noteDelegate = spy87 v.load(try NoteDocument(json: Data(rich.utf8)))88 #expect(spy.changes == 0, "ids assigned at load are not an edit: the page must not become dirty (SPEC §7)")89 // the same 2.x document arriving again from the server is not a change either, and the local item ids are kept90 let before = try v.document().jsonData()91 v.applyRemote(try NoteDocument(json: Data(rich.utf8)))92 #expect(spy.changes == 0); #expect(try v.document().jsonData() == before)93 type(v, "x"); #expect(spy.changes == 1)94 }95 @Test func theStorageKeepsOneTerminatedParagraphPerLine() {96 let v = makeEditor(doc(p("a") + "," + p("b")))97 #expect(v.storage.string == "a\nb\n")98 caret(v, 99); #expect(v.selectedRange().location == 3, "the caret cannot pass the last terminator")99 let empty = makeEditor(#"{"type":"doc","content":[]}"#)100 #expect(empty.storage.string == "\n")101 }102 @Test func aCodeBlockIsOneNodeWhateverItsNumberOfLines() {103 let v = makeEditor(rich)104 let code = v.document().lines.first { $0.type == "codeBlock" }!105 guard case .inline(let runs) = code.content, case .text(let t, let m) = runs[0] else { Issue.record("no text"); return }106 #expect(runs.count == 1); #expect(t == "let a = 1\nlet b = 2\n\nprint(a + b)"); #expect(m.isEmpty)107 }108 @Test func typingChangesOnlyTheTouchedBlock() throws {109 let v = makeEditor(rich); let before = v.document()110 let loc = (v.storage.string as NSString).range(of: "deux").location111 caret(v, loc + 4); type(v, "!")112 let after = v.document()113 #expect(after.lines.count == before.lines.count)114 let changed = zip(before.lines, after.lines).filter { $0.0.content != $0.1.content }115 #expect(changed.count == 1); #expect(texts(v).contains("deux!"))116 #expect(after.lines.map(\.attrs) == before.lines.map(\.attrs), "block ids are stable")117 }118}119120@MainActor @Suite struct TypingTests {121 @Test func returnSplitsAParagraphAndTheNewBlockGetsItsOwnId() {122 let v = makeEditor(doc(p("abcd", id: "aaaaaaaaaa")))123 caret(v, 2); v.insertNewline(nil)124 #expect(texts(v) == ["ab", "cd"]); #expect(v.selectedRange().location == 3)125 let ids = v.document().lines.map { $0.attrs["id"] }126 #expect(ids[0] == .string("aaaaaaaaaa")); #expect(ids[1] != nil); #expect(ids[1] != ids[0])127 }128 @Test func returnAfterAHeadingStartsAParagraph() {129 let v = makeEditor(doc(#"{"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"T"}]}"#))130 caret(v, 1); type(v, "\nsuite")131 #expect(types(v) == ["heading", "paragraph"]); #expect(texts(v) == ["T", "suite"])132 }133 @Test func markdownShortcutsCreateBlocks() {134 let v = makeEditor()135 type(v, "# Titre\n- un\ndeux\n\n1. premier\n\n[] tâche\n\n> cité\n\n---\n")136 #expect(types(v) == ["heading", "bulletList>listItem>paragraph", "bulletList>listItem>paragraph", "orderedList>listItem>paragraph", "taskList>taskItem>paragraph", "blockquote>paragraph", "horizontalRule", "paragraph"])137 #expect(texts(v).prefix(6) == ["Titre", "un", "deux", "premier", "tâche", "cité"])138 let lists = v.document().pmNode().content!.filter { $0.type == "bulletList" }139 #expect(lists.count == 1); #expect(lists[0].content?.count == 2, "two items in one list")140 }141 @Test func returnOnAnEmptyItemLeavesTheList() {142 let v = makeEditor(); type(v, "- a\n\nb")143 #expect(types(v) == ["bulletList>listItem>paragraph", "paragraph"]); #expect(texts(v) == ["a", "b"])144 }145 @Test func tabNestsAnItemAndShiftTabBringsItBack() {146 let v = makeEditor(); type(v, "- a\nb")147 v.insertTab(nil)148 #expect(types(v) == ["bulletList>listItem>paragraph", "bulletList>listItem>bulletList>listItem>paragraph"])149 let node = v.document().pmNode()150 #expect(node.content?.count == 1); #expect(node.content?[0].content?.count == 1, "b is inside the item of a")151 v.insertBacktab(nil)152 #expect(types(v) == ["bulletList>listItem>paragraph", "bulletList>listItem>paragraph"])153 #expect(v.document().pmNode().content?[0].content?.count == 2)154 }155 @Test func backspaceAtTheStartOfABlockRemovesItsStructureFirst() {156 let v = makeEditor(); type(v, "- a")157 caret(v, 0); v.deleteBackward(nil)158 #expect(types(v) == ["paragraph"]); #expect(texts(v) == ["a"])159 let h = makeEditor(doc(#"{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"T"}]}"#))160 caret(h, 0); h.deleteBackward(nil); #expect(types(h) == ["paragraph"])161 }162 @Test func backspaceJoinsTwoParagraphsAndKeepsTheFirstIdentity() {163 let v = makeEditor(doc(p("ab", id: "aaaaaaaaaa") + "," + p("cd", id: "bbbbbbbbbb")))164 caret(v, 3); v.deleteBackward(nil)165 #expect(texts(v) == ["abcd"]); #expect(v.document().lines[0].attrs["id"] == .string("aaaaaaaaaa"))166 }167 @Test func codeBlocksKeepTypingInsideAndAnEmptyLastLineLeaves() {168 let v = makeEditor(); type(v, "``` ")169 #expect(types(v) == ["codeBlock"])170 type(v, "a\n b\n")171 #expect(v.document().lines[0].content == .inline([.text("a\n b\n ", marks: [])]), "indentation is carried to the next line")172 let w = makeEditor(); type(w, "``` x\n\n")173 #expect(types(w) == ["codeBlock", "paragraph"]); #expect(texts(w)[0] == "x")174 }175 @Test func typingBesideATableOpensAParagraph() {176 let v = makeEditor(); v.insertTable()177 #expect(types(v) == ["table", "paragraph"])178 caret(v, 0); type(v, "avant")179 #expect(types(v) == ["paragraph", "table", "paragraph"]); #expect(texts(v)[0] == "avant")180 }181 @Test func shiftReturnIsAHardBreakNotANewBlock() {182 let v = makeEditor(); type(v, "a"); v.insertLineBreak(nil); type(v, "b")183 let lines = v.document().lines; #expect(lines.count == 1)184 guard case .inline(let runs) = lines[0].content else { return }185 #expect(runs == [.text("a", marks: []), .atom(PMNode(type: "hardBreak")), .text("b", marks: [])])186 }187}188189@MainActor @Suite struct CommandTests {190 @Test func marksToggleOnASelectionAndForTheNextTypedText() {191 let v = makeEditor(doc(p("abcdef")))192 caret(v, 1, 3); v.toggleMark("bold")193 guard case .inline(let runs) = v.document().lines[0].content else { return }194 #expect(runs == [.text("a", marks: []), .text("bcd", marks: [PMMark(type: "bold")]), .text("ef", marks: [])])195 #expect(v.selectionState.marks.contains("bold"))196 v.toggleMark("bold"); #expect(texts(v) == ["abcdef"])197 guard case .inline(let back) = v.document().lines[0].content else { return }; #expect(back == [.text("abcdef", marks: [])])198 caret(v, 6); v.toggleMark("italic"); type(v, "g"); v.toggleMark("italic"); type(v, "h")199 guard case .inline(let r2) = v.document().lines[0].content else { return }200 #expect(r2 == [.text("abcdef", marks: []), .text("g", marks: [PMMark(type: "italic")]), .text("h", marks: [])])201 }202 @Test func linksAreSetChangedAndRemoved() {203 let v = makeEditor(doc(p("voir ici")))204 caret(v, 5, 3); v.setLink("https://a.example")205 #expect(v.link(at: 6)?.href == "https://a.example"); #expect(v.link(at: 6)?.range == NSRange(location: 5, length: 3))206 caret(v, 6); v.setLink("https://b.example"); #expect(v.link(at: 5)?.href == "https://b.example")207 caret(v, 6); v.setLink(nil); #expect(v.link(at: 5) == nil)208 caret(v, 8); type(v, " x"); guard case .inline(let runs) = v.document().lines[0].content else { return }; #expect(runs.count == 1)209 }210 @Test func headingsListsAndQuotesApplyToEverySelectedParagraph() {211 let v = makeEditor(doc(p("a") + "," + p("b") + "," + p("c")))212 caret(v, 0, 5); v.setBlock(.task)213 #expect(types(v) == Array(repeating: "taskList>taskItem>paragraph", count: 3)); #expect(v.document().pmNode().content?.count == 1)214 v.setBlock(.ordered(start: 1)); #expect(types(v) == Array(repeating: "orderedList>listItem>paragraph", count: 3)); #expect(v.document().pmNode().content?.count == 1)215 v.setBlock(.ordered(start: 1)); #expect(types(v) == ["paragraph", "paragraph", "paragraph"])216 caret(v, 0); v.setBlock(.heading(2)); #expect(types(v)[0] == "heading"); #expect(v.selectionState.block == .heading(2))217 v.setBlock(.heading(2)); #expect(types(v)[0] == "paragraph")218 caret(v, 0, 3); v.setBlock(.quote); #expect(types(v) == ["blockquote>paragraph", "blockquote>paragraph", "paragraph"])219 v.setBlock(.quote); #expect(types(v) == ["paragraph", "paragraph", "paragraph"])220 caret(v, 0, 3); v.setBlock(.code); #expect(types(v) == ["codeBlock", "paragraph"]); #expect(texts(v)[0] == "a\nb")221 v.setBlock(.code); #expect(types(v) == ["paragraph", "paragraph", "paragraph"])222 }223 @Test func aCheckBoxTogglesItsItem() {224 let v = makeEditor(); type(v, "[] a")225 step(); v.toggleCheckbox(at: 0)226 #expect(v.document().lines[0].path.last?.attrs["checked"] == .bool(true))227 v.undoManager?.undo(); #expect(v.document().lines[0].path.last?.attrs["checked"] == .bool(false))228 }229 @Test func everyCommandIsOneUndoStepAndRedoBringsItBack() {230 let v = makeEditor(doc(p("a") + "," + p("b")))231 let start = json(v)232 step(); caret(v, 0, 3); v.setBlock(.bullet); let listed = json(v)233 step(); caret(v, 0); v.setBlock(.heading(1))234 step(); v.insertRule(); step()235 v.undoManager?.undo(); v.undoManager?.undo(); #expect(json(v).semanticallyEquals(listed))236 v.undoManager?.undo(); #expect(json(v).semanticallyEquals(start))237 v.undoManager?.redo(); #expect(json(v).semanticallyEquals(listed))238 }239 @Test func blocksMoveUpAndDown() {240 let v = makeEditor(doc(p("a") + "," + p("b") + "," + p("c")))241 caret(v, 2); v.moveBlock(up: true); #expect(texts(v) == ["b", "a", "c"]); #expect(v.selectedRange().location == 0)242 v.moveBlock(up: false); v.moveBlock(up: false); #expect(texts(v) == ["a", "c", "b"])243 }244 @Test func tablesAreEditedThroughTheirModelAndUntouchedCellsKeepTheirContent() throws {245 let v = makeEditor(rich)246 let loc = (0..<v.storage.length).first { (v.storage.attribute(.attachment, at: $0, effectiveRange: nil) as? AtomAttachment)?.node.type == "table" }!247 var node = (v.storage.attribute(.attachment, at: loc, effectiveRange: nil) as! AtomAttachment).node248 #expect(node.tableGrid.count == 2); #expect(node.tableGrid[1][0].text == "1")249 let changed = node.setTableCellText("deux", row: 1, column: 1); let added = node.insertTableRow(at: 2); #expect(changed); #expect(added)250 v.replaceAtom(at: NSRange(location: loc, length: 1), with: node)251 let table = v.document().pmNode().content!.first { $0.type == "table" }!252 #expect(table.attrs?["id"] == .string("ttttttttt1")); #expect(table.content?.count == 3)253 #expect(table.content?[1].content?[0].content?[0].content?[0].marks == [PMMark(type: "italic")], "the untouched cell kept its italic")254 #expect(table.content?[1].content?[1].content?[0].content?[0].text == "deux")255 }256 @Test func markdownIsInsertedAsBlocks() {257 let v = makeEditor(doc(p("avant")))258 step(); caret(v, 5); v.insertMarkdown("## Plan\n\n- un\n- deux\n\nfin **gras**"); step()259 #expect(types(v) == ["paragraph", "heading", "bulletList>listItem>paragraph", "bulletList>listItem>paragraph", "paragraph"])260 v.undoManager?.undo(); #expect(texts(v) == ["avant"])261 }262}263264@MainActor @Suite struct RemoteAndPasteboardTests {265 @Test func aRemoteChangeElsewhereLeavesTheCaretWhereItWas() throws {266 let v = makeEditor(doc(p("un", id: "aaaaaaaaaa") + "," + p("deux", id: "bbbbbbbbbb") + "," + p("trois", id: "cccccccccc")))267 caret(v, 1)268 v.applyRemote(try NoteDocument(json: Data(doc(p("un", id: "aaaaaaaaaa") + "," + p("deux", id: "bbbbbbbbbb") + "," + p("TROIS modifié", id: "cccccccccc") + "," + p("quatre", id: "dddddddddd")).utf8)))269 #expect(texts(v) == ["un", "deux", "TROIS modifié", "quatre"]); #expect(v.selectedRange().location == 1)270 caret(v, 22)271 v.applyRemote(try NoteDocument(json: Data(doc(p("zéro", id: "zzzzzzzzzz") + "," + p("un", id: "aaaaaaaaaa") + "," + p("deux", id: "bbbbbbbbbb") + "," + p("TROIS modifié", id: "cccccccccc") + "," + p("quatre", id: "dddddddddd")).utf8)))272 #expect(texts(v).first == "zéro"); #expect(v.selectedRange().location == 27, "shifted by the inserted line")273 }274 @Test func aRemoteChangeInsideAListKeepsTheListWhole() throws {275 let list = { (b: String) in doc(#"{"type":"bulletList","content":[{"type":"listItem","content":[\#(p("a"))]},{"type":"listItem","content":[\#(p(b))]},{"type":"listItem","content":[\#(p("c"))]}]}"#) }276 let v = makeEditor(list("b"))277 v.applyRemote(try NoteDocument(json: Data(list("B changé").utf8)))278 let node = v.document().pmNode()279 #expect(node.content?.count == 1); #expect(node.content?[0].content?.count == 3); #expect(texts(v) == ["a", "B changé", "c"])280 }281 @Test func copyAndPasteKeepTheStructure() {282 let v = makeEditor(rich)283 let range = NSRange(location: 0, length: v.storage.length - 1)284 let f = NoteFragment(text: v.storage, range: range)285 let w = makeEditor(); w.insert(f.document)286 #expect(types(w).prefix(types(v).count - 1) == types(v).dropLast()[...])287 // inside one block: an inline fragment288 let inline = NoteFragment(text: v.storage, range: NSRange(location: (v.storage.string as NSString).range(of: "deux").location, length: 3))289 #expect(inline.document.lines.count == 1); #expect(inline.document.lines[0].path.isEmpty)290 let x = makeEditor(doc(p("ab"))); caret(x, 1); x.insert(inline.document); #expect(texts(x) == ["adeub"])291 }292 @Test func plainTextIsPastedAsParagraphsAndAsLinesInCode() {293 let v = makeEditor(); v.insertPlain("un\ndeux\n\ntrois")294 #expect(texts(v) == ["un", "deux", "", "trois"])295 let c = makeEditor(); type(c, "``` "); c.insertPlain("a\nb"); #expect(texts(c) == ["a\nb"])296 }297 @Test func foreignRichTextKeepsBoldItalicLinksAndLists() {298 let s = NSMutableAttributedString(string: "Titre gras\n", attributes: [.font: NSFont.boldSystemFont(ofSize: 20)])299 s.append(NSAttributedString(string: "lien\n", attributes: [.font: NSFont.systemFont(ofSize: 12), .link: URL(string: "https://example.org")!]))300 let lines = NoteFragment.lines(fromForeign: s)301 #expect(lines.count == 2)302 #expect(lines[0].content == .inline([.text("Titre gras", marks: [PMMark(type: "bold")])]))303 #expect(lines[1].content == .inline([.text("lien", marks: [PMMark(type: "link", attrs: ["href": .string("https://example.org")])])]))304 }305 @Test func aLongDocumentLoadsAndTypesFast() {306 let blocks = (0..<4000).map { p("Paragraphe numéro \($0) avec assez de texte pour faire une ligne complète dans l'éditeur natif.") }.joined(separator: ",")307 let v = makeEditor()308 let t0 = Date(); v.load(try! NoteDocument(json: Data(doc(blocks).utf8))); let load = Date().timeIntervalSince(t0)309 caret(v, v.storage.length / 2)310 let t1 = Date(); type(v, String(repeating: "x", count: 200)); let typing = Date().timeIntervalSince(t1) / 200311 let t2 = Date(); _ = v.document(); let save = Date().timeIntervalSince(t2)312 print("PERF 4000 blocks: load \(Int(load * 1000)) ms · keystroke \(String(format: "%.2f", typing * 1000)) ms · serialise \(Int(save * 1000)) ms")313 #expect(load < 3); #expect(typing < 0.008); #expect(save < 1.5)314 }315}316317@MainActor @Suite struct CompletionTests {318 @Test func theSlashMenuFiltersAsYouTypeAndInsertsTheChosenBlock() {319 let v = makeEditor()320 type(v, "/")321 #expect(v.completion != nil, "« / » at the start of a block opens the menu")322 type(v, "tabl")323 #expect(v.completion?.panel.selected?.id == "table")324 let committed = v.commitCompletion(); #expect(committed)325 #expect(v.completion == nil); #expect(types(v) == ["table", "paragraph"]); #expect(!v.storage.string.contains("/tabl"))326 step(); v.undoManager?.undo(); #expect(types(v) == ["paragraph"])327 }328 @Test func aSlashInsideAWordOrAnAddressOpensNothing() {329 let v = makeEditor(); type(v, "et/ou")330 #expect(v.completion == nil); #expect(texts(v) == ["et/ou"])331 let w = makeEditor(); type(w, "/zzzz"); #expect(w.completion == nil, "no block matches: the menu closes and the text stays"); #expect(texts(w) == ["/zzzz"])332 }333}334