Repository Public
1// SP Notes iOS2// File: Tests/EditorInputTests.swift3// Description: Input ergonomics of the 2.0 editor, driven like a user: Markdown shortcuts and their undo, the slash menu, callout4// kinds, due date and priority of task items, toggles and footnotes, the morphing formatting bar, syntax colours5// of code blocks, and reveal(blockId:).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Testing10import UIKit11import SPNotesCore12@testable import SPNotes1314@MainActor15struct InputHarness {16 let model: NoteEditorModel17 var editor: EditorController { model.controller }18 var textView: NoteTextView { model.controller.textView }1920 init(markdown: String = "", json: String? = nil) throws {21 model = NoteEditorModel(noteId: "0b7f6c0e-3f0a-4d5e-9b0a-aaaaaaaaaaaa", app: try makeApp())22 model.controller.textView.frame = CGRect(x: 0, y: 0, width: 390, height: 800)23 if let json { model.controller.load(try NoteDocument(json: Data(json.utf8))) } else { model.controller.load(NoteDocument(markdown: markdown)) }24 settle()25 }2627 /// Ends the current run-loop turn: the undo manager closes its group, like between two key presses of a user.28 func settle() { RunLoop.current.run(until: Date().addingTimeInterval(0.001)) }2930 /// Types like the keyboard does, one event per character.31 func type(_ text: String) {32 for character in text {33 let s = String(character)34 if editor.textView(textView, shouldChangeTextIn: textView.selectedRange, replacementText: s) { textView.insertText(s) }35 settle()36 }37 }38 func undo() { textView.undoManager?.undo(); settle() }39 func caret(at location: Int) { textView.selectedRange = NSRange(location: location, length: 0); settle() }40 func caret(after needle: String) { let r = (editor.storage.string as NSString).range(of: needle); caret(at: NSMaxRange(r)) }41 func caret(in needle: String) { let r = (editor.storage.string as NSString).range(of: needle); caret(at: r.location + 1) }42 var document: NoteDocument { editor.document() }43 var text: String { editor.storage.string }44 func line(_ index: Int) -> Line { document.lines[index] }45 func plain(_ index: Int) -> String { NoteDocument(lines: [document.lines[index]]).plainText() }46}4748@MainActor49@Suite("Saisie — raccourcis Markdown") struct EditorInputShortcutTests {50 @Test(arguments: [("#", "heading", 1), ("##", "heading", 2), ("###", "heading", 3)])51 func hashesMakeAHeadingAndOneUndoBringsTheTypedCharactersBack(prefix: String, type: String, level: Int) throws {52 let h = try InputHarness()53 h.type(prefix)54 h.type(" ")55 #expect(h.line(0).type == "heading" && h.line(0).attrs["level"] == .int(Int64(level)) && h.plain(0) == "")56 h.type("Titre")57 #expect(h.plain(0) == "Titre" && h.document.schemaViolations(strict: true).isEmpty)58 // undo the typed word (one or several steps), then the shortcut: the paragraph and its characters are back59 while h.plain(0) != "" { h.undo() }60 #expect(h.line(0).type == "heading")61 h.undo()62 #expect(h.line(0).type == "paragraph" && h.plain(0) == prefix)63 }6465 @Test(arguments: [("-", "bulletList", "listItem"), ("*", "bulletList", "listItem"), ("1.", "orderedList", "listItem"), ("[]", "taskList", "taskItem"), ("[ ]", "taskList", "taskItem")])66 func listPrefixesMakeAListItem(prefix: String, list: String, item: String) throws {67 let h = try InputHarness()68 h.type(prefix)69 h.type(" ")70 #expect(h.line(0).path.map(\.type) == [list, item] && h.plain(0) == "")71 if item == "taskItem" { #expect(h.line(0).path.last?.attrs["checked"] == .bool(false)) }72 #expect(h.line(0).path.last?.attrs["id"]?.stringValue?.isEmpty == false)73 h.type("un")74 #expect(h.document.schemaViolations(strict: true).isEmpty, "\(h.document.schemaViolations(strict: true))")75 while h.plain(0) != "" { h.undo() }76 h.undo()77 #expect(h.line(0).path.isEmpty && h.plain(0) == prefix)78 }7980 @Test func aChevronMakesAQuoteThreeBackticksACodeBlockAndThreeDashesARule() throws {81 var h = try InputHarness()82 h.type(">"); h.type(" ")83 #expect(h.line(0).path.map(\.type) == ["blockquote"] && h.plain(0) == "")84 h.undo()85 #expect(h.line(0).path.isEmpty && h.plain(0) == ">")8687 h = try InputHarness()88 h.type("```"); h.type(" ")89 #expect(h.line(0).type == "codeBlock" && h.line(0).attrs["language"] == .string("plaintext"))90 h.undo()91 #expect(h.line(0).type == "paragraph" && h.plain(0) == "```")92 // ```swift + Return: a code block in that language93 h = try InputHarness()94 h.type("```swift"); h.type("\n")95 #expect(h.line(0).type == "codeBlock" && h.line(0).attrs["language"] == .string("swift") && h.plain(0) == "")96 h.undo()97 #expect(h.line(0).type == "paragraph" && h.plain(0) == "```swift")9899 // the third dash100 h = try InputHarness()101 h.type("--"); h.type("-")102 #expect(h.document.lines.map(\.type) == ["horizontalRule", "paragraph"])103 h.undo()104 #expect(h.document.lines.map(\.type) == ["paragraph"] && h.plain(0) == "--")105 // --- then Return (the dashes were pasted or the third one typed in the middle)106 h = try InputHarness(markdown: "avant")107 h.caret(after: "avant")108 h.type("\n")109 h.editor.insertText("---")110 h.settle()111 h.type("\n")112 #expect(h.document.lines.map(\.type) == ["paragraph", "horizontalRule", "paragraph"])113 }114115 @Test func shortcutsNeverFireInACodeBlockNorAwayFromTheStartOfAParagraph() throws {116 // in a code block: the characters are typed as they are117 var h = try InputHarness(json: #"{"type":"doc","content":[{"type":"codeBlock","attrs":{"id":"k1aaaaaaaa","language":"swift"}}]}"#)118 for prefix in ["#", "-", "1.", ">", "[]", "```"] {119 h.type(prefix); h.type(" ")120 }121 h.type("---")122 #expect(h.document.lines.count == 1 && h.line(0).type == "codeBlock")123 #expect(h.plain(0) == "# - 1. > [] ``` ---")124 // after other text: plain characters125 h = try InputHarness(markdown: "abc")126 h.caret(after: "abc")127 h.type(" # x - y")128 #expect(h.line(0).type == "paragraph" && h.plain(0) == "abc # x - y")129 // in a heading: no list130 h = try InputHarness(markdown: "# Titre")131 h.caret(at: 0)132 h.type("-"); h.type(" ")133 #expect(h.line(0).type == "heading" && h.plain(0) == "- Titre")134 // the head of a list item stays a paragraph (schema): no heading there135 h = try InputHarness(markdown: "- un")136 h.caret(at: 0)137 h.type("#"); h.type(" ")138 #expect(h.line(0).type == "paragraph" && h.line(0).path.count == 2 && h.plain(0) == "# un")139 #expect(h.document.schemaViolations(strict: true).isEmpty)140 // switched off: nothing fires141 h = try InputHarness()142 h.editor.markdownShortcutsEnabled = false143 h.type("#"); h.type(" ")144 #expect(h.line(0).type == "paragraph" && h.text == "# \n")145 }146147 @Test func aShortcutKeepsTheRestOfTheParagraph() throws {148 let h = try InputHarness(markdown: "Chapitre un")149 h.caret(at: 0)150 h.type("##"); h.type(" ")151 #expect(h.line(0).type == "heading" && h.line(0).attrs["level"] == .int(2) && h.plain(0) == "Chapitre un")152 #expect(h.textView.selectedRange.location == 0)153 }154}155156@MainActor157@Suite("Saisie — menu slash") struct EditorInputSlashTests {158 @Test func theCatalogueFiltersByTitleKeywordAndWithoutAccents() {159 #expect(InsertCatalog.search("").count == InsertCatalog.slashCommands.count)160 #expect(InsertCatalog.search("gra").first?.id == "chart")161 #expect(InsertCatalog.search("equ").prefix(2).map(\.id) == ["math", "inlinemath"], "titles that start with the query come first")162 #expect(InsertCatalog.search("séparateur").map(\.id) == ["rule"] && InsertCatalog.search("separateur").map(\.id) == ["rule"])163 #expect(InsertCatalog.search("todo").map(\.id) == ["tasks"])164 #expect(InsertCatalog.search("DECISION").map(\.id) == ["callout-decision"])165 #expect(InsertCatalog.search("zzzz").isEmpty)166 // every new block of SPEC §2 can be inserted from the menu and from the Insert menu, in its group167 let ids = Set(InsertCatalog.insertions.map(\.id))168 #expect(ids.isSuperset(of: ["mermaid", "chart", "query", "blockref", "runcode", "bibliography", "canvas", "citation", "pdf", "audio", "drawing", "details", "footnote"]))169 #expect(Set(InsertCatalog.insertions.map(\.group)) == [.media, .structure, .data, .references])170 #expect(InsertCatalog.insertions.first { $0.id == "chart" }?.group == .data && InsertCatalog.insertions.first { $0.id == "citation" }?.group == .references)171 #expect(Set(InsertCatalog.slashCommands.map(\.id)).count == InsertCatalog.slashCommands.count, "ids are unique")172 }173174 @Test func aSlashAtTheStartOfAnEmptyParagraphOpensTheMenuAndTypingFiltersIt() throws {175 let h = try InputHarness()176 h.type("/")177 #expect(h.editor.slash.isActive && h.editor.slash.results.count == InsertCatalog.slashCommands.count)178 #expect(h.editor.slash.view.superview === h.textView && h.editor.slash.view.titles.first == "Titre 1")179 h.type("gra")180 #expect(h.editor.slash.query == "gra" && h.editor.slash.results.first?.id == "chart")181 #expect(h.editor.slash.view.titles == h.editor.slash.results.map(\.title))182 // Return runs the highlighted command: the typed text goes away and the block is there183 h.type("\n")184 #expect(!h.editor.slash.isActive && h.editor.slash.view.superview == nil)185 #expect(h.document.lines.map(\.type) == ["chart", "paragraph"])186 #expect(!h.text.contains("/gra"))187 guard case .blockDetail(let node, _)? = h.model.request else { Issue.record("the chart sheet opens"); return }188 #expect(node.type == "chart")189 // one undo: the chart is gone and the typed characters are back190 h.undo()191 #expect(h.document.lines.map(\.type) == ["paragraph"] && h.plain(0) == "/gra")192 }193194 @Test func theMenuOpensAfterASpaceButNotInsideAWordNorInCode() throws {195 var h = try InputHarness(markdown: "Texte")196 h.caret(after: "Texte")197 h.type("/")198 #expect(!h.editor.slash.isActive, "a slash glued to a word is a slash")199 h.type(" /")200 #expect(h.editor.slash.isActive)201 h.type("tit")202 #expect(h.editor.slash.results.map(\.id) == ["h1", "h2", "h3"])203 // arrows move, the selection wraps204 h.editor.slash.move(1)205 #expect(h.editor.slash.selected?.id == "h2")206 h.editor.slash.move(-2)207 #expect(h.editor.slash.selected?.id == "h3")208 #expect(h.editor.slash.commit())209 #expect(h.line(0).type == "heading" && h.line(0).attrs["level"] == .int(3) && h.text == "Texte/ \n")210211 h = try InputHarness(json: #"{"type":"doc","content":[{"type":"codeBlock","attrs":{"id":"k1aaaaaaaa","language":"swift"}}]}"#)212 h.type("/")213 #expect(!h.editor.slash.isActive && h.plain(0) == "/")214 }215216 @Test func escapeACaretMoveOrAPlainSentenceCloseTheMenuAndKeepTheText() throws {217 let h = try InputHarness()218 h.type("/co")219 #expect(h.editor.slash.isActive)220 h.editor.slash.cancel()221 #expect(!h.editor.slash.isActive && h.plain(0) == "/co")222 // a slash followed by words that match nothing is just text223 h.type(" /")224 #expect(h.editor.slash.isActive)225 h.type("xyz et la suite")226 #expect(!h.editor.slash.isActive && h.plain(0) == "/co /xyz et la suite")227 // moving the caret before the slash closes it228 h.type(" /")229 #expect(h.editor.slash.isActive)230 h.caret(at: 0)231 #expect(!h.editor.slash.isActive)232 // deleting the slash closes it233 h.caret(at: h.editor.storage.length - 1)234 h.type(" /")235 #expect(h.editor.slash.isActive)236 h.textView.deleteBackward()237 h.settle()238 #expect(!h.editor.slash.isActive)239 }240241 @Test func aTapOnARowRunsItsCommand() throws {242 let h = try InputHarness()243 h.type("/code")244 let row = try #require(h.editor.slash.results.first { $0.id == "code" })245 h.editor.slash.view.onChoose?(row)246 #expect(h.line(0).type == "codeBlock" && h.plain(0) == "")247 // hardware keys exist only while the menu is open248 #expect(h.textView.keyCommands?.contains { $0.input == UIKeyCommand.inputEscape } == false)249 let other = try InputHarness()250 other.type("/")251 #expect(other.textView.keyCommands?.contains { $0.input == UIKeyCommand.inputEscape } == true)252 #expect(other.textView.keyCommands?.contains { $0.input == UIKeyCommand.inputDownArrow } == true)253 }254}255256@MainActor257@Suite("Saisie — tâches, encadrés, blocs dépliables, notes de bas de page") struct EditorInputStructureTests {258 @Test func aTaskItemTakesADueDateAndAPriorityAndKeepsThemWhenTicked() throws {259 let h = try InputHarness(markdown: "- [ ] Relire\n- [ ] Écrire")260 h.caret(in: "Relire")261 h.model.perform(.taskDue("2026-11-21"))262 h.model.perform(.taskPriority(.high))263 var item = try #require(h.line(0).path.last)264 #expect(item.attrs["due"] == .string("2026-11-21") && item.attrs["priority"] == .string("high"))265 #expect(h.document.taskAttributes(at: 0)?.due == "2026-11-21" && h.document.taskAttributes(at: 1)?.due == nil)266 let id = item.attrs["id"]267 #expect(h.editor.context().taskDue == "2026-11-21" && h.editor.context().taskPriority == .high && h.editor.context().mode == .task)268 // ticking keeps the id, the date and the priority269 h.editor.toggleTask(at: 0)270 item = try #require(h.line(0).path.last)271 #expect(item.attrs["checked"] == .bool(true) && item.attrs["due"] == .string("2026-11-21") && item.attrs["priority"] == .string("high") && item.attrs["id"] == id)272 #expect(h.document.schemaViolations(strict: true).isEmpty, "\(h.document.schemaViolations(strict: true))")273 // Return makes a new, unchecked item without date, priority or the same id274 h.caret(after: "Relire")275 h.type("\n")276 h.type("Suite")277 let created = try #require(h.line(1).path.last)278 #expect(h.plain(1) == "Suite" && created.attrs["checked"] == .bool(false) && created.attrs["due"] == .null && created.attrs["priority"] == .null)279 #expect(created.attrs["id"] != id && created.attrs["id"]?.stringValue?.isEmpty == false)280 let ids = h.document.lines.compactMap { $0.path.last?.attrs["id"]?.stringValue }281 #expect(Set(ids).count == ids.count, "no two items share an id")282 // clearing283 h.caret(in: "Relire")284 h.model.perform(.taskDue(nil))285 h.model.perform(.taskPriority(nil))286 #expect(h.line(0).path.last?.attrs["due"] == .null && h.line(0).path.last?.attrs["priority"] == .null)287 // outside a task item the commands do nothing288 let plain = try InputHarness(markdown: "Texte")289 plain.model.perform(.taskDue("2026-11-21"))290 #expect(try plain.document.jsonData() == plain.document.jsonData() && plain.line(0).path.isEmpty)291 // the "choose a date" entry asks the screen for the picker with the current value292 h.model.perform(.taskDue("2026-12-01"))293 h.model.request = nil294 h.model.perform(.taskDuePicker)295 #expect(h.model.request == .taskDue(current: "2026-12-01"))296 }297298 @Test func theBadgeWritesThePriorityAndTheDayAndReservesItsRoom() throws {299 #expect(TaskBadge.marks(.low) == "!" && TaskBadge.marks(.medium) == "!!" && TaskBadge.marks(.high) == "!!!")300 let now = try #require(TaskItemDetail.date(from: "2026-11-19T12:00:00Z"))301 let future = try #require(TaskBadge.dueLabel("2026-11-21", now: now)), past = try #require(TaskBadge.dueLabel("2026-11-16", now: now))302 #expect(future.text.contains("21") && !future.overdue && past.overdue)303 #expect(TaskBadge.dueLabel("pas une date") == nil)304 let item = Container(key: 2, type: "taskItem", attrs: ["checked": false, "due": "2026-11-21", "priority": "medium"])305 let style = LineStyle(path: [Container(key: 1, type: "taskList", attrs: [:]), item])306 let badge = try #require(TaskBadge.attributed(for: style))307 #expect(badge.string.hasPrefix("!! ") && badge.string.contains("21"))308 #expect((TaskBadge.reservedWidth(for: style) ?? 0) > 50)309 #expect(TaskBadge.reservedWidth(for: LineStyle(path: [Container(key: 1, type: "taskList", attrs: [:]), Container(key: 2, type: "taskItem", attrs: ["checked": false])])) == nil)310 // the paragraph leaves that room free at its right311 let styler = EditorStyler(atoms: AtomRenderer())312 #expect(styler.paragraphStyle(for: style).tailIndent < -50)313 #expect(TaskDueSheet.initialDate("2026-11-21").formatted(.iso8601.year().month().day().dateSeparator(.dash)).isEmpty == false)314 #expect(TaskItemDetail.dayString(TaskDueSheet.initialDate("2026-11-21")) == "2026-11-21", "the stored day is the day shown, whatever the time zone")315 }316317 @Test func calloutsTakeEveryKindWithItsIconAndAreReTypedInPlace() throws {318 let h = try InputHarness(markdown: "Un choix\n\nAutre")319 h.caret(in: "Un choix")320 for kind in CalloutKind.known {321 h.model.perform(.calloutKind(kind))322 let frame = try #require(h.line(0).path.first)323 #expect(frame.type == "callout" && frame.attrs["kind"] == .string(kind.rawValue) && frame.attrs["icon"] == .string(kind.defaultIcon), "\(kind)")324 #expect(EditorLayoutFragment.calloutIcon(frame) == kind.defaultIcon)325 #expect(h.editor.calloutKind() == kind && h.editor.context().mode == .callout && h.editor.context().calloutKind == kind)326 }327 #expect(CalloutKind.decision.defaultIcon == "⚖️" && CalloutKind.question.defaultIcon == "❓" && CalloutKind.hypothesis.defaultIcon == "🧪")328 #expect(h.document.lines.count == 2 && h.line(1).path.isEmpty)329 #expect(h.document.schemaViolations(strict: true).isEmpty, "\(h.document.schemaViolations(strict: true))")330 // the same kind again changes nothing; removing lifts the block out331 let before = try h.document.jsonData()332 h.model.perform(.calloutKind(.hypothesis))333 #expect(try h.document.jsonData() == before)334 h.model.perform(.removeCallout)335 #expect(h.line(0).path.isEmpty)336 // the style menu's « Encadré » creates a note callout and removes a callout of any kind337 h.model.perform(.callout)338 #expect(h.line(0).path.first?.attrs["kind"] == .string("note"))339 h.model.perform(.calloutKind(.warning))340 h.model.perform(.callout)341 #expect(h.line(0).path.isEmpty)342 // an icon set by another editor is drawn as it is; a kind written by a newer editor is kept343 #expect(EditorLayoutFragment.calloutIcon(Container(key: 1, type: "callout", attrs: ["kind": "idea", "icon": "🎯"])) == "🎯")344 #expect(EditorLayoutFragment.calloutIcon(Container(key: 1, type: "callout", attrs: ["kind": "question"])) == "❓")345 }346347 @Test func aToggleIsCreatedFromAParagraphAndOpensAndCloses() throws {348 let h = try InputHarness(markdown: "Détails du calcul\n\nAprès")349 h.caret(in: "Détails")350 h.model.perform(.insertDetails)351 let document = h.document352 #expect(document.lines.map(\.type) == ["detailsSummary", "paragraph", "paragraph"])353 #expect(document.lines[0].path.map(\.type) == ["details"] && document.lines[1].path.map(\.type) == ["details", "detailsContent"] && document.lines[2].path.isEmpty)354 #expect(document.lines[0].path[0].attrs["open"] == .bool(true) && document.lines[0].path[0].attrs["id"]?.stringValue?.isEmpty == false)355 #expect(h.plain(0) == "Détails du calcul")356 #expect(document.schemaViolations(strict: true).isEmpty, "\(document.schemaViolations(strict: true))")357 // the caret is in the content: typing fills it358 h.type("Le contenu")359 #expect(h.plain(1) == "Le contenu")360 // Return twice at the end of the content leaves the toggle (the empty paragraph moves out, after it)361 h.type("\n")362 #expect(h.document.lines.map { $0.path.count } == [1, 2, 2, 0])363 h.type("\n")364 #expect(h.document.lines.map { $0.path.count } == [1, 2, 0, 0] && h.document.schemaViolations(strict: true).isEmpty)365 h.undo()366 h.textView.deleteBackward(); h.settle()367 #expect(h.document.lines.map { $0.path.count } == [1, 2, 0] && h.plain(1) == "Le contenu")368 // a toggle created on the last paragraph of a note is followed by an empty paragraph369 let last = try InputHarness(markdown: "Seul")370 last.caret(in: "Seul")371 last.model.perform(.insertDetails)372 #expect(last.document.lines.map(\.type) == ["detailsSummary", "paragraph", "paragraph"] && last.document.lines[2].path.isEmpty)373 // closing and opening change the `open` attribute of every line of the toggle, nothing else374 h.editor.toggleDetails(at: 0)375 #expect(h.document.lines[0].path[0].attrs["open"] == .bool(false) && h.document.lines[1].path[0].attrs["open"] == .bool(false))376 #expect(h.document.lines[0].path[0].key == h.document.lines[1].path[0].key)377 // closed: the content is not laid out (the text is shorter), the caret cannot stay in it, nothing is lost378 h.textView.layoutIfNeeded()379 let closedHeight = h.textView.sizeThatFits(CGSize(width: 390, height: CGFloat.greatestFiniteMagnitude)).height380 h.caret(in: "Le contenu")381 #expect(h.editor.paragraphRange(at: h.textView.selectedRange.location).location == 0, "the caret went back to the summary")382 // Backspace at the start of the paragraph after the closed toggle opens it: text is never merged into hidden content383 h.caret(at: (h.text as NSString).range(of: "Après").location)384 h.textView.deleteBackward()385 h.settle()386 #expect(h.document.lines[0].path[0].attrs["open"] == .bool(true) && h.plain(1) == "Le contenu" && h.plain(2) == "Après")387 h.textView.layoutIfNeeded()388 let openHeight = h.textView.sizeThatFits(CGSize(width: 390, height: CGFloat.greatestFiniteMagnitude)).height389 #expect(openHeight > closedHeight + 15, "open \(openHeight) vs closed \(closedHeight)")390 #expect(h.plain(1) == "Le contenu")391 #expect(h.document.schemaViolations(strict: true).isEmpty)392 #expect(h.document.markdown().contains("Détails du calcul") && h.document.markdown().contains("Le contenu"))393 // not from the head of a list item (the schema wants a paragraph there): refused, said, nothing changes394 let list = try InputHarness(markdown: "- un")395 list.caret(in: "un")396 list.model.perform(.insertDetails)397 #expect(list.document.lines.map(\.type) == ["paragraph"] && list.model.app.banner != nil)398 }399400 @Test func aFootnoteIsCreatedWithItsReferenceAndNumbered() throws {401 let h = try InputHarness(markdown: "Une affirmation\n\nSuite")402 h.caret(after: "affirmation")403 h.model.perform(.insertFootnote)404 h.type("La source")405 var document = h.document406 #expect(document.lines.map(\.type) == ["paragraph", "paragraph", "footnote"])407 #expect(document.lines[2].attrs["id"] == .string("1") && h.plain(2) == "La source")408 guard case .inline(let runs) = document.lines[0].content, case .atom(let reference)? = runs.last else { Issue.record("no reference"); return }409 #expect(reference.type == "footnoteRef" && reference.attrs?["id"] == .string("1"))410 #expect(document.schemaViolations(strict: true).isEmpty, "\(document.schemaViolations(strict: true))")411 #expect(document.markdown().contains("affirmation[^1]") && document.markdown().contains("[^1]: La source"))412 // a second one is numbered 2413 h.caret(after: "Suite")414 h.model.perform(.insertFootnote)415 document = h.document416 #expect(document.lines.map(\.type) == ["paragraph", "paragraph", "footnote", "footnote"] && document.lines[3].attrs["id"] == .string("2"))417 #expect(document.schemaViolations(strict: true).isEmpty)418 }419}420421@MainActor422@Suite("Saisie — barre de mise en forme qui se transforme") struct EditorInputMorphTests {423 static let document = #"""424 {"type":"doc","content":[425 {"type":"paragraph","attrs":{"textAlign":null,"id":"p1aaaaaaaa"},"content":[{"type":"text","text":"Texte"}]},426 {"type":"heading","attrs":{"textAlign":null,"level":2,"id":"h1aaaaaaaa"},"content":[{"type":"text","text":"Titre"}]},427 {"type":"bulletList","attrs":{"id":"l1aaaaaaaa"},"content":[{"type":"listItem","attrs":{"id":"i1aaaaaaaa"},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p2aaaaaaaa"},"content":[{"type":"text","text":"Puce"}]}]}]},428 {"type":"taskList","attrs":{"id":"l2aaaaaaaa"},"content":[{"type":"taskItem","attrs":{"checked":false,"id":"i2aaaaaaaa","due":"2026-11-21","priority":"low","taskId":null},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p3aaaaaaaa"},"content":[{"type":"text","text":"Tâche"}]}]}]},429 {"type":"codeBlock","attrs":{"id":"k1aaaaaaaa","language":"python"},"content":[{"type":"text","text":"print(1)"}]},430 {"type":"callout","attrs":{"id":"c1aaaaaaaa","kind":"question","icon":"❓"},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p4aaaaaaaa"},"content":[{"type":"text","text":"Pourquoi"}]}]},431 {"type":"horizontalRule"},432 {"type":"paragraph","attrs":{"textAlign":null,"id":"p5aaaaaaaa"},"content":[{"type":"text","text":"Fin"}]}433 ]}434 """#435436 @Test func theBarShowsWhatAppliesToTheBlockOfTheCaret() throws {437 let h = try InputHarness(json: Self.document)438 let bar = h.model.toolbar439 func visible() -> Set<String> { Set(bar.visibleButtonIdentifiers) }440 let always: Set<String> = ["toolbar-plus.circle.fill", "toolbar-textformat.size", "toolbar-sparkles", "toolbar-arrow.uturn.backward", "toolbar-arrow.uturn.forward"]441 let marks: Set<String> = ["toolbar-bold", "toolbar-italic", "toolbar-underline", "toolbar-strikethrough", "toolbar-highlighter", "toolbar-chevron.left.forwardslash.chevron.right"]442443 h.caret(in: "Texte")444 #expect(bar.morphMode == .text && visible() == always.union(marks).union(["toolbar-checklist", "toolbar-list.bullet", "toolbar-list.number", "toolbar-text.quote", "toolbar-link"]))445 h.caret(in: "Titre")446 #expect(bar.morphMode == .text, "a heading shows the same tools as a paragraph: no morph")447 h.caret(in: "Puce")448 #expect(bar.morphMode == .list && visible().isSuperset(of: ["toolbar-decrease.indent", "toolbar-increase.indent", "toolbar-bold"]))449 #expect(!visible().contains("toolbar-calendar") && !visible().contains("toolbar-flag"))450 h.caret(in: "Tâche")451 #expect(bar.morphMode == .task && visible().isSuperset(of: ["toolbar-calendar", "toolbar-flag", "toolbar-decrease.indent", "toolbar-increase.indent"]))452 #expect(bar.morph.dueButton?.configuration?.title?.contains("21") == true && bar.morph.priorityButton?.configuration?.title == "!")453 h.caret(in: "print")454 // a code block: its language, and no marks455 #expect(bar.morphMode == .code && visible().isDisjoint(with: marks.subtracting(["toolbar-chevron.left.forwardslash.chevron.right"])))456 #expect(!visible().contains("toolbar-bold") && !visible().contains("toolbar-link") && !visible().contains("toolbar-checklist"))457 #expect(bar.morph.languageButton?.isHidden == false && bar.morph.languageButton?.configuration?.title == "python")458 h.caret(in: "Pourquoi")459 #expect(bar.morphMode == .callout && bar.morph.calloutButton?.isHidden == false && bar.morph.calloutButton?.configuration?.title?.contains("Question") == true)460 #expect(visible().isSuperset(of: marks))461 // a block atom: block actions only462 let rule = (h.text as NSString).range(of: EditorCharacter.attachment).location463 h.caret(at: rule)464 #expect(bar.morphMode == .atom && visible() == always.union(["toolbar-slider.horizontal.3", "toolbar-doc.on.doc", "toolbar-trash"]))465 h.caret(in: "Fin")466 #expect(bar.morphMode == .text && visible().isDisjoint(with: ["toolbar-slider.horizontal.3", "toolbar-trash", "toolbar-calendar"]))467 }468469 @Test func theMorphHappensOnAChangeOfBlockTypeOnly() throws {470 let h = try InputHarness(json: Self.document)471 let bar = h.model.toolbar472 h.caret(in: "Texte")473 let start = bar.morph.transitions474 h.caret(after: "Texte")475 h.type(" encore")476 h.editor.toggleMark("bold")477 h.caret(in: "Titre")478 #expect(bar.morph.transitions == start, "typing, marks and moving between text blocks do not morph the bar")479 h.caret(in: "Tâche")480 #expect(bar.morph.transitions == start + 1)481 h.model.perform(.taskPriority(.high))482 #expect(bar.morph.transitions == start + 1 && bar.morph.priorityButton?.configuration?.title == "!!!")483 h.caret(in: "print")484 h.caret(in: "print")485 #expect(bar.morph.transitions == start + 2)486 // motion budget: 240 ms, and a cross-fade of at most 120 ms under Reduce Motion487 #expect(ToolbarMorph.duration(reduceMotion: false) == 0.24 && ToolbarMorph.duration(reduceMotion: true) <= 0.12)488 }489490 @Test func theContextualActionsWork() throws {491 let h = try InputHarness(json: Self.document)492 h.caret(in: "print")493 h.model.perform(.codeLanguage("swift"))494 #expect(h.document.lines.first { $0.type == "codeBlock" }?.attrs["language"] == .string("swift"))495 #expect(h.model.toolbar.morph.languageButton?.configuration?.title == "swift")496 // atom: copy puts its text on the pasteboard path, delete removes it, open goes through the tap path497 let rule = (h.text as NSString).range(of: EditorCharacter.attachment).location498 h.caret(at: rule)499 h.model.perform(.atomOpen)500 #expect(h.model.request == .atomMenu(node: PMNode.horizontalRule(), range: NSRange(location: rule, length: 1)))501 h.model.perform(.atomDelete)502 #expect(!h.document.lines.contains { $0.type == "horizontalRule" })503 }504}505506@MainActor507@Suite("Saisie — coloration du code") struct EditorInputSyntaxTests {508 @Test func theTokenizerFindsKeywordsStringsCommentsAndNumbers() {509 let code = "let total = 42 // somme\nprint(\"ok\")"510 let spans = SyntaxHighlighter.spans(code, language: "swift")511 func kind(_ needle: String) -> TokenKind? {512 let range = (code as NSString).range(of: needle)513 return spans.first { $0.range == range }?.kind514 }515 #expect(kind("let") == .keyword && kind("42") == .number && kind("// somme") == .comment && kind("\"ok\"") == .string && kind("print") == .function)516 #expect(SyntaxHighlighter.spans("SELECT * FROM t -- c", language: "sql").map(\.kind) == [.keyword, .keyword, .comment])517 #expect(SyntaxHighlighter.spans(code, language: "plaintext").isEmpty && SyntaxHighlighter.spans(code, language: nil).isEmpty)518 // ranges are UTF-16: an emoji before a token does not shift it519 let emoji = "x = \"😀\" + 1"520 let last = try? #require(SyntaxHighlighter.spans(emoji, language: "python").last)521 #expect(last?.range == (emoji as NSString).range(of: "1") && last?.kind == .number)522 for kind in [TokenKind.keyword, .string, .comment, .number, .type, .function, .attribute, .punctuation] { #expect(SyntaxHighlighter.colour(for: kind) != nil) }523 }524525 private func colour(_ h: InputHarness, of needle: String) -> UIColor? {526 let range = (h.text as NSString).range(of: needle)527 return h.editor.storage.attribute(.foregroundColor, at: range.location, effectiveRange: nil) as? UIColor528 }529530 @Test func aCodeBlockIsColouredOnLoadAndWhileTypingAndNothingIsStored() throws {531 let json = #"{"type":"doc","content":[{"type":"codeBlock","attrs":{"id":"k1aaaaaaaa","language":"swift"},"content":[{"type":"text","text":"let a = 1\n// note"}]},{"type":"paragraph","attrs":{"textAlign":null,"id":"p1aaaaaaaa"},"content":[{"type":"text","text":"let b"}]}]}"#532 let h = try InputHarness(json: json)533 let before = try h.document.jsonData()534 #expect(colour(h, of: "let a") == SyntaxHighlighter.colour(for: .keyword))535 #expect(colour(h, of: "1") == SyntaxHighlighter.colour(for: .number) && colour(h, of: "// note") == SyntaxHighlighter.colour(for: .comment))536 #expect(colour(h, of: "a =") == h.editor.styler.theme.text)537 #expect(colour(h, of: "let b") == h.editor.styler.theme.text, "text outside a code block is never coloured")538 #expect(try h.document.jsonData() == before, "colours are presentation only")539 // typing a string colours it at once540 h.caret(after: "= 1")541 h.type(" + \"x\"")542 #expect(colour(h, of: "\"x\"") == SyntaxHighlighter.colour(for: .string))543 // changing the language re-colours; plain text has no colours544 h.model.perform(.codeLanguage("plaintext"))545 #expect(colour(h, of: "let a") == h.editor.styler.theme.text)546 h.model.perform(.codeLanguage("python"))547 #expect(colour(h, of: "let a") == h.editor.styler.theme.text, "`let` is not a Python keyword")548 // leaving the code block removes the colours549 h.model.perform(.codeLanguage("swift"))550 h.model.perform(.codeBlock)551 #expect(h.line(0).type == "paragraph" && colour(h, of: "let a") == h.editor.styler.theme.text)552 }553554 @Test func aLargeCodeBlockIsColouredAfterAPauseNotAtEachKeystroke() async throws {555 let body = String(repeating: "let value = 12345 // commentaire\n", count: 260) // > 6 000 UTF-16 units556 let h = try InputHarness(json: #"{"type":"doc","content":[{"type":"codeBlock","attrs":{"id":"k1aaaaaaaa","language":"swift"},"content":[{"type":"text","text":"x"}]}]}"#)557 h.caret(at: 1)558 h.editor.insertText(body)559 #expect(h.editor.storage.length > EditorStyler.immediateColouringLimit)560 h.type("let")561 #expect(!h.editor.styler.pendingCode.isEmpty, "the block waits for the pause")562 let typed = (h.text as NSString).range(of: "let", options: .backwards)563 #expect(h.editor.storage.attribute(.foregroundColor, at: typed.location, effectiveRange: nil) as? UIColor == h.editor.styler.theme.text)564 // loading is never deferred, and the pause colours what was typed565 h.editor.colourPendingCodeNow()566 #expect(h.editor.styler.pendingCode.isEmpty)567 #expect(h.editor.storage.attribute(.foregroundColor, at: typed.location, effectiveRange: nil) as? UIColor == SyntaxHighlighter.colour(for: .keyword))568 let second = (h.text as NSString).range(of: "let value", options: [], range: NSRange(location: 10, length: 200))569 #expect(h.editor.storage.attribute(.foregroundColor, at: second.location, effectiveRange: nil) as? UIColor == SyntaxHighlighter.colour(for: .keyword))570 }571}572573@MainActor574@Suite("Révéler un bloc") struct EditorRevealTests {575 static let document = #"""576 {"type":"doc","content":[577 {"type":"paragraph","attrs":{"textAlign":null,"id":"p1aaaaaaaa"},"content":[{"type":"text","text":"Premier"}]},578 {"type":"bulletList","attrs":{"id":"l1aaaaaaaa"},"content":[579 {"type":"listItem","attrs":{"id":"i1aaaaaaaa"},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p2aaaaaaaa"},"content":[{"type":"text","text":"un"}]},{"type":"paragraph","attrs":{"textAlign":null,"id":"p3aaaaaaaa"},"content":[{"type":"text","text":"suite"}]}]},580 {"type":"listItem","attrs":{"id":"i2aaaaaaaa"},"content":[{"type":"paragraph","attrs":{"textAlign":null,"id":"p4aaaaaaaa"},"content":[{"type":"text","text":"deux"}]}]}]},581 {"type":"mermaid","attrs":{"id":"mmd0000001","code":"graph TD","preview":null,"previewHash":null}},582 {"type":"paragraph","attrs":{"textAlign":null,"id":"p5aaaaaaaa"},"content":[{"type":"text","text":"Dernier"}]}583 ]}584 """#585586 @Test func theRangeOfABlockIsFoundForATextBlockAListItemAListAndAnAtom() throws {587 let h = try InputHarness(json: Self.document)588 let text = h.text as NSString589 #expect(h.editor.rangeOfBlock(id: "p1aaaaaaaa") == text.paragraphRange(for: text.range(of: "Premier")))590 // a list item covers its paragraphs; the list covers its items591 let item = try #require(h.editor.rangeOfBlock(id: "i1aaaaaaaa"))592 #expect(text.substring(with: item) == "un\nsuite\n")593 #expect(text.substring(with: try #require(h.editor.rangeOfBlock(id: "l1aaaaaaaa"))) == "un\nsuite\ndeux\n")594 #expect(text.substring(with: try #require(h.editor.rangeOfBlock(id: "p4aaaaaaaa"))) == "deux\n")595 let atom = try #require(h.editor.rangeOfBlock(id: "mmd0000001"))596 #expect(text.substring(with: atom) == EditorCharacter.attachment + "\n")597 #expect(h.editor.rangeOfBlock(id: "absent0000") == nil)598 }599600 @Test func revealScrollsToTheBlockAndFlashesItAndSaysWhenItIsAbsent() async throws {601 let app = try makeApp()602 var long = try NoteDocument(json: Data(Self.document.utf8))603 long.insert(lines: (0..<80).map { Line.paragraph(text: "Ligne de remplissage \($0)") }, at: 1)604 let id = try await app.createNote(title: "Longue", document: long)605 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 700))606 window.windowScene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first607 let host = UIViewController()608 window.rootViewController = host609 window.makeKeyAndVisible()610 defer { window.isHidden = true }611 let model = NoteEditorModel(noteId: id, app: app)612 model.controller.textView.frame = host.view.bounds613 host.view.addSubview(model.controller.textView)614 // asked before the note is loaded: kept, done at load615 #expect(model.reveal(blockId: "p5aaaaaaaa"))616 #expect(model.pendingRevealBlockId == "p5aaaaaaaa")617 await model.load()618 try await Task.sleep(for: .milliseconds(700))619 #expect(model.pendingRevealBlockId == nil)620 let textView = model.controller.textView621 #expect(textView.contentOffset.y > 800, "scrolled down to the last paragraph (\(textView.contentOffset.y))")622 let flash = try #require(textView.subviews.first { $0.accessibilityIdentifier == EditorController.flashIdentifier })623 let target = try #require(model.controller.rangeOfBlock(id: "p5aaaaaaaa"))624 let start = try #require(textView.position(from: textView.beginningOfDocument, offset: target.location)), end = try #require(textView.position(from: start, offset: 1))625 let rect = textView.firstRect(for: try #require(textView.textRange(from: start, to: end)))626 #expect(flash.frame.intersects(rect) && flash.frame.width > 300, "the flash covers the block (\(flash.frame) vs \(rect))")627 #expect(textView.bounds.intersects(flash.frame), "and it is on screen")628 // once loaded: an atom, a list item, and an absent block629 #expect(model.reveal(blockId: "mmd0000001"))630 #expect(textView.subviews.filter { $0.accessibilityIdentifier == EditorController.flashIdentifier }.count == 1, "one flash at a time")631 #expect(model.reveal(blockId: "i2aaaaaaaa"))632 #expect(model.reveal(blockId: "absent0000") == false)633 #expect(model.saveState == .saved, "revealing never dirties the note")634 // the hand-off used by routes: posted before the note opens, consumed at load; live when the note is open635 BlockRevealRequests.post(noteId: id, blockId: "p1aaaaaaaa")636 try await Task.sleep(for: .milliseconds(700))637 #expect(textView.contentOffset.y < 200, "back at the top (\(textView.contentOffset.y))")638 #expect(BlockRevealRequests.consume(noteId: id) == nil)639 }640641 @Test func theFlashIsAPlainShortFadeUnderReduceMotion() {642 let reduced = EditorController.flashTimings(reduceMotion: true), normal = EditorController.flashTimings(reduceMotion: false)643 #expect(reduced.appear == 0 && reduced.fade <= 0.12)644 #expect(normal.appear == 0.16 && normal.fade == 0.9)645 }646647 @Test func aBlockReferenceOpensItsNoteAtTheBlock() async throws {648 let app = try makeApp()649 let model = NoteEditorModel(noteId: "0b7f6c0e-3f0a-4d5e-9b0a-aaaaaaaaaaaa", app: app)650 model.controller.textView.frame = CGRect(x: 0, y: 0, width: 390, height: 800)651 model.controller.load(try NoteDocument(json: Data(Self.document.utf8)))652 let context = model.blockDetailContext(range: NSRange(location: 0, length: 1), dismiss: {})653 // the route carries the block654 let other = "0b7f6c0e-3f0a-4d5e-9b0a-bbbbbbbbbbbb"655 context.open(.note(other, blockId: "blk0000001"))656 #expect(app.pendingRoute == .note(other, blockId: "blk0000001"), "the shell posts the block to reveal when it handles the route")657 }658}659