Repository Public
1// SP Notes iOS2// File: Tests/EditorTests.swift3// Description: The native editor engine driven like a user would (typing, Enter, Backspace, commands, undo) and read back as a document.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Testing8import UIKit9import SPNotesCore10@testable import SPNotes1112/// A document covering what the editor handles: marks, lists, tasks, quote, callout, code, atoms, a table and unknown nodes.13let sampleDocumentJSON = #"""14{"type":"doc","content":[15 {"type":"heading","attrs":{"textAlign":null,"level":1,"id":"h1aaaaaaaa"},"content":[{"type":"text","text":"Plan du cours"}]},16 {"type":"paragraph","attrs":{"textAlign":null,"id":"p1aaaaaaaa"},"content":[{"type":"text","text":"Un "},{"type":"text","marks":[{"type":"bold"}],"text":"mot gras"},{"type":"text","text":" puis "},{"type":"text","marks":[{"type":"link","attrs":{"href":"https://example.org","target":"_blank","rel":"noopener noreferrer nofollow","class":null,"title":null}},{"type":"italic"}],"text":"un lien"},{"type":"text","text":" et "},{"type":"mention","attrs":{"id":"0b7f6c0e-3f0a-4d5e-9b0a-111111111111","label":"Autre note","mentionSuggestionChar":"@"}},{"type":"hardBreak"},{"type":"text","text":"suite "},{"type":"inlineMath","attrs":{"latex":"x^2"}}]},17 {"type":"bulletList","attrs":{"id":"l1aaaaaaaa"},"content":[18 {"type":"listItem","content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p2aaaaaaaa"},"content":[{"type":"text","text":"Premier"}]},19 {"type":"orderedList","attrs":{"id":"l2aaaaaaaa","start":1,"type":null},"content":[20 {"type":"listItem","content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p3aaaaaaaa"},"content":[{"type":"text","text":"Sous-point"}]}]}]}]},21 {"type":"listItem","content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p4aaaaaaaa"},"content":[{"type":"text","text":"Second"}]}]}]},22 {"type":"taskList","attrs":{"id":"l3aaaaaaaa"},"content":[23 {"type":"taskItem","attrs":{"checked":true},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p5aaaaaaaa"},"content":[{"type":"text","text":"Fait"}]}]},24 {"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p6aaaaaaaa"},"content":[{"type":"text","text":"À faire"}]}]}]},25 {"type":"blockquote","attrs":{"id":"q1aaaaaaaa"},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p7aaaaaaaa"},"content":[{"type":"text","text":"Une citation"}]}]},26 {"type":"callout","attrs":{"id":"c1aaaaaaaa","kind":"info","icon":"💡"},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p8aaaaaaaa"},"content":[{"type":"text","text":"À retenir"}]}]},27 {"type":"codeBlock","attrs":{"id":"k1aaaaaaaa","language":"swift"},"content":[{"type":"text","text":"let a = 1\nlet b = 2"}]},28 {"type":"image","attrs":{"id":"i1aaaaaaaa","src":"/api/files/0b7f6c0e-3f0a-4d5e-9b0a-222222222222","alt":"photo.png","title":"photo.png","width":null,"height":null}},29 {"type":"table","attrs":{"id":"t1aaaaaaaa"},"content":[{"type":"tableRow","content":[30 {"type":"tableHeader","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"align":null},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p9aaaaaaaa"},"content":[{"type":"text","text":"A"}]}]},31 {"type":"tableHeader","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"align":null},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"pAaaaaaaaa"},"content":[{"type":"text","text":"B"}]}]}]}]},32 {"type":"horizontalRule"},33 {"type":"blockMath","attrs":{"id":"m1aaaaaaaa","latex":"E = mc^2"}},34 {"type":"mysteryBlock","attrs":{"foo":1},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"pBaaaaaaaa"},"content":[{"type":"text","marks":[{"type":"sparkle","attrs":{"n":2}}],"text":"inconnu"}]}]},35 {"type":"paragraph","attrs":{"textAlign":null,"id":"pCaaaaaaaa"}}36]}37"""#3839@MainActor40struct EditorHarness {41 let editor = EditorController()42 var textView: NoteTextView { editor.textView }4344 init(_ json: String? = nil) throws {45 editor.textView.frame = CGRect(x: 0, y: 0, width: 390, height: 800)46 if let json { editor.load(try NoteDocument(json: Data(json.utf8))) }47 }4849 /// Types like the keyboard does: the delegate may veto or handle the edit, otherwise the text view inserts.50 func type(_ text: String) {51 for character in text {52 let s = String(character)53 if editor.textView(textView, shouldChangeTextIn: textView.selectedRange, replacementText: s) { textView.insertText(s) }54 }55 }56 func backspace() { textView.deleteBackward() }57 func caret(at location: Int) { textView.selectedRange = NSRange(location: location, length: 0) }58 func select(_ needle: String) {59 let range = (editor.storage.string as NSString).range(of: needle)60 precondition(range.location != NSNotFound, "not found: \(needle)")61 textView.selectedRange = range62 }63 func caret(after needle: String) { let r = (editor.storage.string as NSString).range(of: needle); caret(at: NSMaxRange(r)) }64 func caret(before needle: String) { let r = (editor.storage.string as NSString).range(of: needle); caret(at: r.location) }65 var document: NoteDocument { editor.document() }66 func line(containing text: String) -> Line? { document.lines.first { NoteDocument(lines: [$0]).plainText().contains(text) } }67 func lineIndex(containing text: String) -> Int? { document.lines.firstIndex { NoteDocument(lines: [$0]).plainText().contains(text) } }68}6970/// The JSON tree without the `id` attribute of list items and task items (assigned at load since Core 2.0).71func withoutItemIds(_ data: Data) throws -> NSDictionary {72 func strip(_ value: Any) -> Any {73 if let array = value as? [Any] { return array.map(strip) }74 guard var object = value as? [String: Any] else { return value }75 if let type = object["type"] as? String, type == "listItem" || type == "taskItem", var attrs = object["attrs"] as? [String: Any] {76 attrs["id"] = nil77 object["attrs"] = attrs.isEmpty ? nil : attrs78 }79 if let content = object["content"] { object["content"] = strip(content) }80 return object81 }82 return (strip(try JSONSerialization.jsonObject(with: data)) as? NSDictionary) ?? [:]83}8485@MainActor86@Suite("Éditeur natif") struct EditorTests {87 @Test func roundTripKeepsEveryNode() throws {88 // Core 2.0: list items receive a fresh block id at load (SPEC §7). Everything else is untouched: the documents are89 // compared without the ids of list items, and a second pass through the editor is the identity.90 let original = try NoteDocument(json: Data(sampleDocumentJSON.utf8))91 let harness = try EditorHarness(sampleDocumentJSON)92 let back = harness.document93 #expect(try withoutItemIds(back.jsonData()) == withoutItemIds(original.jsonData()))94 #expect(try withoutItemIds(back.jsonData()) != (JSONSerialization.jsonObject(with: back.jsonData()) as? NSDictionary), "list items received ids")95 let again = try EditorHarness(String(decoding: back.jsonData(), as: UTF8.self)).document96 #expect(again.isStructurallyEqual(to: back))97 #expect(try JSONValue(data: again.jsonData()) == JSONValue(data: back.jsonData()))98 #expect(back.schemaViolations().filter { !$0.contains("mysteryBlock") && !$0.contains("sparkle") }.isEmpty)99 }100101 @Test func typingKeepsMarksAndIdentity() throws {102 let harness = try EditorHarness(sampleDocumentJSON)103 harness.caret(after: "mot gras")104 harness.type("!")105 let line = try #require(harness.line(containing: "mot gras!"))106 guard case .inline(let runs) = line.content else { Issue.record("not inline"); return }107 #expect(runs.contains { if case .text("mot gras!", let marks) = $0 { return marks.map(\.type) == ["bold"] } else { return false } })108 #expect(line.attrs["id"] == .string("p1aaaaaaaa"))109 }110111 @Test func enterSplitsParagraphWithNewId() throws {112 let harness = try EditorHarness(sampleDocumentJSON)113 let before = harness.document.lines.count114 harness.caret(after: "Une cita")115 harness.type("\n")116 let doc = harness.document117 #expect(doc.lines.count == before + 1)118 let first = try #require(harness.lineIndex(containing: "Une cita"))119 #expect(NoteDocument(lines: [doc.lines[first + 1]]).plainText() == "tion")120 #expect(doc.lines[first].attrs["id"] != doc.lines[first + 1].attrs["id"])121 #expect(doc.lines[first + 1].path.map(\.type) == ["blockquote"]) // still in the quote122 #expect(doc.schemaViolations().filter { !$0.contains("mysteryBlock") && !$0.contains("sparkle") }.isEmpty)123 }124125 @Test func enterInListCreatesItemThenLeavesList() throws {126 let harness = try EditorHarness(sampleDocumentJSON)127 harness.caret(after: "Second")128 harness.type("\n")129 harness.type("Troisième")130 var doc = harness.document131 let second = try #require(harness.lineIndex(containing: "Second"))132 let third = try #require(harness.lineIndex(containing: "Troisième"))133 #expect(third == second + 1)134 #expect(doc.lines[third].path.count == 2)135 #expect(doc.lines[third].path[0].key == doc.lines[second].path[0].key) // same list136 #expect(doc.lines[third].path[1].key != doc.lines[second].path[1].key) // another item137 harness.type("\n") // new empty item138 harness.type("\n") // Enter on the empty item leaves the list139 harness.type("Hors liste")140 doc = harness.document141 let outside = try #require(harness.line(containing: "Hors liste"))142 #expect(outside.path.isEmpty)143 #expect(doc.schemaViolations().filter { !$0.contains("mysteryBlock") && !$0.contains("sparkle") }.isEmpty)144 }145146 @Test func newTaskItemIsUnchecked() throws {147 let harness = try EditorHarness(sampleDocumentJSON)148 harness.caret(after: "Fait")149 harness.type("\n")150 harness.type("Nouveau")151 let line = try #require(harness.line(containing: "Nouveau"))152 #expect(line.path.last?.type == "taskItem")153 #expect(line.path.last?.attrs["checked"] == .bool(false))154 }155156 @Test func backspaceAtStartOfHeadingMakesParagraph() throws {157 let harness = try EditorHarness(sampleDocumentJSON)158 harness.caret(at: 0)159 harness.backspace()160 #expect(harness.document.lines[0].type == "paragraph")161 #expect(NoteDocument(lines: [harness.document.lines[0]]).plainText() == "Plan du cours")162 harness.backspace() // start of the document: nothing happens, nothing is lost163 #expect(NoteDocument(lines: [harness.document.lines[0]]).plainText() == "Plan du cours")164 }165166 @Test func backspaceMergesParagraphs() throws {167 let harness = try EditorHarness(#"{"type":"doc","content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"aaaaaaaaaa"},"content":[{"type":"text","text":"Un"}]},{"type":"paragraph","attrs":{"textAlign":null,"id":"bbbbbbbbbb"},"content":[{"type":"text","text":"Deux"}]}]}"#)168 harness.caret(before: "Deux")169 harness.backspace()170 let doc = harness.document171 #expect(doc.lines.count == 1)172 #expect(doc.plainText() == "UnDeux")173 #expect(doc.lines[0].attrs["id"] == .string("aaaaaaaaaa"))174 }175176 @Test func toggleBoldOnSelectionAndUndo() throws {177 let harness = try EditorHarness(sampleDocumentJSON)178 let original = harness.document179 harness.select("Second")180 harness.editor.toggleMark("bold")181 let line = try #require(harness.line(containing: "Second"))182 guard case .inline(let runs) = line.content else { Issue.record("not inline"); return }183 #expect(runs == [.text("Second", marks: [PMMark(type: "bold", attrs: nil)])])184 harness.textView.undoManager?.undo()185 #expect(harness.document.isStructurallyEqual(to: original))186 harness.textView.undoManager?.redo()187 #expect(harness.line(containing: "Second")?.content == line.content)188 }189190 @Test func codeMarkExcludesOthers() throws {191 let harness = try EditorHarness(sampleDocumentJSON)192 harness.select("mot gras")193 harness.editor.toggleMark("code")194 let line = try #require(harness.line(containing: "mot gras"))195 guard case .inline(let runs) = line.content else { Issue.record("not inline"); return }196 #expect(runs.contains(.text("mot gras", marks: [PMMark(type: "code", attrs: nil)])))197 }198199 @Test func pendingMarkAppliesToTypedText() throws {200 let harness = try EditorHarness(#"{"type":"doc","content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"aaaaaaaaaa"},"content":[{"type":"text","text":"Bonjour "}]}]}"#)201 harness.caret(after: "Bonjour ")202 harness.editor.toggleMark("italic")203 harness.type("toi")204 guard case .inline(let runs) = harness.document.lines[0].content else { Issue.record("not inline"); return }205 #expect(runs == [.text("Bonjour ", marks: []), .text("toi", marks: [PMMark(type: "italic", attrs: nil)])])206 }207208 @Test func linkSetAndRemoved() throws {209 let harness = try EditorHarness(sampleDocumentJSON)210 harness.select("Premier")211 harness.editor.setLink(EditorController.normalizedLink("spboucher.ai"))212 #expect(harness.editor.linkAtSelection()?.href == "https://spboucher.ai")213 harness.editor.setLink(nil)214 #expect(harness.editor.linkAtSelection() == nil)215 #expect(EditorController.normalizedLink("javascript:alert(1)") == nil)216 }217218 @Test func listCommandsStayValid() throws {219 let harness = try EditorHarness(sampleDocumentJSON)220 harness.select("Une citation")221 harness.editor.toggleList(.task)222 #expect(harness.line(containing: "Une citation")?.path.last?.type == "taskItem")223 harness.caret(after: "Second")224 harness.editor.indent()225 #expect(harness.line(containing: "Second")?.path.count == 4)226 harness.editor.outdent()227 #expect(harness.line(containing: "Second")?.path.count == 2)228 harness.select("Plan du cours")229 harness.editor.toggleBlockquote()230 #expect(harness.line(containing: "Plan du cours")?.path.first?.type == "blockquote")231 harness.editor.toggleList(.bullet)232 let violations = harness.document.schemaViolations().filter { !$0.contains("mysteryBlock") && !$0.contains("sparkle") }233 #expect(violations.isEmpty, "\(violations)")234 harness.textView.undoManager?.undo()235 harness.textView.undoManager?.undo()236 #expect(harness.line(containing: "Plan du cours")?.path.isEmpty == true)237 }238239 @Test func headingToggle() throws {240 let harness = try EditorHarness(sampleDocumentJSON)241 harness.caret(after: "À retenir")242 harness.editor.setBlockType("heading", level: 2)243 let line = try #require(harness.line(containing: "À retenir"))244 #expect(line.type == "heading")245 #expect(line.attrs["level"] == .int(2))246 #expect(line.attrs["id"] == .string("p8aaaaaaaa"))247 harness.editor.setBlockType("heading", level: 2)248 #expect(harness.line(containing: "À retenir")?.type == "paragraph")249 }250251 @Test func codeBlockKeepsNewlinesInOneLine() throws {252 let harness = try EditorHarness(sampleDocumentJSON)253 harness.caret(after: "let b = 2")254 harness.type("\n")255 harness.type("let c = 3")256 let line = try #require(harness.line(containing: "let a = 1"))257 #expect(line.type == "codeBlock")258 #expect(line.content == .inline([.text("let a = 1\nlet b = 2\nlet c = 3", marks: [])]))259 // Enter on an empty last line leaves the block260 harness.type("\n")261 harness.type("\n")262 harness.type("Après")263 #expect(harness.line(containing: "Après")?.type == "paragraph")264 #expect(harness.line(containing: "let a = 1")?.content == .inline([.text("let a = 1\nlet b = 2\nlet c = 3", marks: [])]))265 }266267 @Test func checkboxToggles() throws {268 let harness = try EditorHarness(sampleDocumentJSON)269 let location = (harness.editor.storage.string as NSString).range(of: "À faire").location270 harness.editor.toggleTask(at: location)271 #expect(harness.line(containing: "À faire")?.path.last?.attrs["checked"] == .bool(true))272 harness.textView.undoManager?.undo()273 #expect(harness.line(containing: "À faire")?.path.last?.attrs["checked"] == .bool(false))274 }275276 @Test func atomsInsertTypeAroundAndDelete() throws {277 let harness = try EditorHarness(#"{"type":"doc","content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"aaaaaaaaaa"},"content":[{"type":"text","text":"Avant"}]}]}"#)278 harness.caret(after: "Avant")279 harness.editor.insertBlockAtom(PMNode(type: "horizontalRule", attrs: nil, content: nil, text: nil, marks: nil, extra: [:]))280 var doc = harness.document281 #expect(doc.lines.map(\.type) == ["paragraph", "horizontalRule", "paragraph"])282 harness.type("Après")283 doc = harness.document284 #expect(doc.plainText().contains("Après"))285 #expect(doc.lines.map(\.type) == ["paragraph", "horizontalRule", "paragraph"])286 // typing right before the atom opens a paragraph above it, the atom stays alone in its line287 let atomLocation = (harness.editor.storage.string as NSString).range(of: EditorCharacter.attachment).location288 harness.caret(at: atomLocation)289 harness.type("x")290 doc = harness.document291 #expect(doc.lines.map(\.type) == ["paragraph", "paragraph", "horizontalRule", "paragraph"])292 // Backspace at the start of the paragraph after the atom removes the atom, not the text293 harness.caret(before: "Après")294 harness.backspace()295 doc = harness.document296 #expect(doc.lines.map(\.type) == ["paragraph", "paragraph", "paragraph"])297 #expect(doc.schemaViolations().isEmpty)298 }299300 @Test func selectAllAndDeleteLeavesOneEmptyParagraph() throws {301 let harness = try EditorHarness(sampleDocumentJSON)302 harness.textView.selectedRange = NSRange(location: 0, length: harness.editor.storage.length)303 #expect(harness.textView.selectedRange.length == harness.editor.storage.length - 1) // the terminator is never selected304 if harness.editor.textView(harness.textView, shouldChangeTextIn: harness.textView.selectedRange, replacementText: "") { harness.textView.deleteBackward() }305 let doc = harness.document306 #expect(doc.lines.count == 1)307 #expect(doc.plainText().isEmpty)308 #expect(doc.schemaViolations().isEmpty)309 harness.type("Recommencer")310 #expect(harness.document.plainText() == "Recommencer")311 }312313 @Test func pasteMultipleLinesCreatesParagraphs() throws {314 let harness = try EditorHarness(#"{"type":"doc","content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"aaaaaaaaaa"}}]}"#)315 harness.editor.insertText("un\ndeux\ntrois")316 let doc = harness.document317 #expect(doc.lines.count == 3)318 #expect(Set(doc.lines.compactMap { $0.attrs["id"] }).count == 3)319 #expect(doc.plainText() == "un\ndeux\ntrois")320 }321322 @Test func longDocumentLoadsAndTypesQuickly() throws {323 var lines: [Line] = []324 for i in 0..<3000 { lines.append(Line(path: [], type: "paragraph", attrs: ["textAlign": .null], content: .inline([.text("Paragraphe numéro \(i) avec un peu de texte pour occuper la ligne et vérifier la fluidité.", marks: [])]))) }325 let harness = try EditorHarness()326 let clock = ContinuousClock()327 let load = clock.measure { harness.editor.load(NoteDocument(lines: lines)) }328 harness.caret(at: 40)329 let typing = clock.measure { harness.type("abcdefghij") }330 let read = clock.measure { _ = harness.document }331 print("éditeur 3000 paragraphes — chargement: \(load), 10 frappes: \(typing), relecture: \(read)")332 #expect(load < .seconds(3))333 #expect(typing < .milliseconds(300))334 #expect(harness.document.lines.count == 3000)335 }336}337338