SPB Git

Repository Public

CommandTests.swift 29.4 KB 569 lines swift

1// SP Notes Core2// File: Tests/SPNotesDocumentTests/CommandTests.swift3// Description: Editing commands: every command, re-serialized and checked against the schema, plus a random4//              command fuzzer over random valid documents.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10@testable import SPNotesDocument1112@Suite struct LineTypeTests {13    @Test func paragraphHeadingCode() {14        var d = md("un **gras** et $x$\n\ndeux")15        check(d.setLineType(.heading(level: 2), at: 0..<1))16        #expect(sexp(d) == #"h2("un " "gras"[bold] " et " inlineMath) p("deux")"#)17        check(d.lines[0].attrs.keys.sorted() == ["id", "level", "textAlign"])18        expectValid(d)19        let id = d.lines[0].attrs["id"]20        check(d.setLineType(.heading(level: 9), at: 0..<1))21        check(d.lines[0].attrs["level"] == 3 && d.lines[0].attrs["id"] == id)22        check(d.setLineType(.codeBlock(language: "swift"), at: 0..<2))23        #expect(sexp(d) == #"code("un gras et x") code("deux")"#)24        check(d.lines[0].attrs == ["id": id!, "language": "swift"])25        expectValid(d)26        check(!d.setLineType(.codeBlock(language: "swift"), at: 0..<2))27        d.replaceText(in: 2..<2, at: 0, with: "\n")28        check(d.setLineType(.paragraph, at: 0..<9))29        #expect(sexp(d) == #"p("un" br " gras et x") p("deux")"#)30        check(d.lines[0].attrs == ["id": id!, "textAlign": nil])31        expectValid(d)32        check(d.setLineType(.codeBlock(language: nil), at: 1..<2) && d.lines[1].attrs["language"] == "plaintext")33    }3435    @Test func listItemHeadStaysAParagraph() {36        var d = md("- a\n\n  b\n- c")37        check(!d.setLineType(.heading(level: 1), at: 0..<1))38        check(d.setLineType(.heading(level: 1), at: 0..<3))39        #expect(sexp(d) == #"ul(li(p("a") h1("b")) li(p("c")))"#)40        expectValid(d)41        var atom = NoteDocument(lines: [Line(blockAtom: .horizontalRule())])42        check(!atom.setLineType(.heading(level: 1), at: 0..<5))43    }44}4546@Suite struct ListTests {47    @Test func wrapUnwrapAndJoin() {48        var d = md("a\n\nb\n\nc")49        check(d.toggleList(.bullet, at: 0..<2))50        #expect(sexp(d) == #"ul(li(p("a")) li(p("b"))) p("c")"#)51        expectValid(d)52        check(d.listKind(at: 0) == .bullet && d.listKind(at: 2) == nil && d.listDepth(at: 1) == 1 && d.isListItemHead(at: 1))53        check(d.toggleList(.bullet, at: 2..<3))54        #expect(sexp(d) == #"ul(li(p("a")) li(p("b")) li(p("c")))"#)55        check(d.toggleList(.bullet, at: 1..<2))56        #expect(sexp(d) == #"ul(li(p("a"))) p("b") ul(li(p("c")))"#)57        expectValid(d)58        // The two lists are now distinct nodes with distinct ids.59        check(d.lines[0].path[0].key != d.lines[2].path[0].key && d.lines[0].path[0].attrs["id"] != d.lines[2].path[0].attrs["id"])60        check(d.toggleList(.bullet, at: 1..<2))61        #expect(sexp(d) == #"ul(li(p("a")) li(p("b")) li(p("c")))"#)62        expectValid(d)63    }6465    @Test func convertBetweenKinds() {66        var d = md("- a\n- b")67        check(d.toggleList(.ordered, at: 0..<1))68        #expect(sexp(d) == #"ol(li(p("a")) li(p("b")))"#)69        check(d.lines[0].path[0].attrs.keys.sorted() == ["id", "start", "type"] && d.listItemNumber(at: 1) == 2)70        expectValid(d)71        check(d.toggleList(.task, at: 1..<2))72        #expect(sexp(d) == #"tl(ti[ ](p("a")) ti[ ](p("b")))"#)73        check(d.lines[0].path[0].attrs.keys.sorted() == ["id"])74        expectValid(d)75        check(d.setTaskChecked(true, at: 1) && !d.setTaskChecked(true, at: 1) && d.isTaskChecked(at: 1) == true && d.isTaskChecked(at: 0) == false)76        #expect(sexp(d) == #"tl(ti[ ](p("a")) ti[x](p("b")))"#)77        check(d.toggleList(.bullet, at: 0..<2))78        #expect(sexp(d) == #"ul(li(p("a")) li(p("b")))"#)79        check(d.lines[1].path[1].attrs.keys.sorted() == ["id"] && d.isTaskChecked(at: 1) == nil && !d.setTaskChecked(true, at: 1))80        expectValid(d)81    }8283    @Test func headingsBecomeItemsAndOtherBlocksAreSkipped() {84        var d = md("# T\n\n```\nx\n```\n\n---\n\np")85        check(d.toggleList(.ordered, at: 0..<4))86        #expect(sexp(d) == #"ol(li(p("T"))) code("x") hr ol(li(p("p")))"#)87        expectValid(d)88        var none = md("---")89        check(!none.toggleList(.bullet, at: 0..<1) && !none.toggleList(.bullet, at: 5..<9))90    }9192    @Test func wrapInsideAQuoteAndMixedSelection() {93        var d = md("> a\n>\n> b\n\n- x\n\ny")94        check(d.toggleList(.bullet, at: 0..<4))95        #expect(sexp(d) == #"bq(ul(li(p("a")) li(p("b")))) ul(li(p("x")) li(p("y")))"#)96        expectValid(d)97    }9899    @Test func indentAndOutdent() {100        var d = md("- a\n- b\n- c")101        check(!d.indentListItems(at: 0..<1))102        check(d.indentListItems(at: 1..<2))103        #expect(sexp(d) == #"ul(li(p("a") ul(li(p("b")))) li(p("c")))"#)104        check(d.listDepth(at: 1) == 2)105        expectValid(d)106        check(d.indentListItems(at: 2..<3))107        #expect(sexp(d) == #"ul(li(p("a") ul(li(p("b")) li(p("c")))))"#)108        expectValid(d)109        check(d.indentListItems(at: 2..<3))110        #expect(sexp(d) == #"ul(li(p("a") ul(li(p("b") ul(li(p("c")))))))"#)111        check(!d.indentListItems(at: 2..<3))112        // Outdent b: c follows it as its child.113        check(d.outdentListItems(at: 1..<2))114        #expect(sexp(d) == #"ul(li(p("a")) li(p("b") ul(li(p("c")))))"#)115        expectValid(d)116        check(d.outdentListItems(at: 1..<3))117        #expect(sexp(d) == #"ul(li(p("a"))) p("b") ul(li(p("c")))"#)118        expectValid(d)119    }120121    @Test func outdentTakesFollowingSiblingsAlong() {122        var d = md("1. a\n   1. b\n   2. c\n   3. d\n2. e")123        #expect(sexp(d) == #"ol(li(p("a") ol(li(p("b")) li(p("c")) li(p("d")))) li(p("e")))"#)124        check(d.outdentListItems(at: 2..<3))125        #expect(sexp(d) == #"ol(li(p("a") ol(li(p("b")))) li(p("c") ol(li(p("d")))) li(p("e")))"#)126        expectValid(d)127        check(d.listItemNumber(at: 2) == 2 && d.listItemNumber(at: 3) == 1 && d.listItemNumber(at: 4) == 3 && d.listItemNumber(at: 0) == 1)128    }129130    @Test func indentSeveralItemsAndMixedKinds() {131        var d = md("- a\n- b\n- c\n- d")132        check(d.indentListItems(at: 1..<3))133        #expect(sexp(d) == #"ul(li(p("a") ul(li(p("b")) li(p("c")))) li(p("d")))"#)134        expectValid(d)135        var t = md("- [x] a\n  - b\n  - c")136        #expect(sexp(t) == #"tl(ti[x](p("a") ul(li(p("b")) li(p("c")))))"#)137        check(t.outdentListItems(at: 1..<2))138        #expect(sexp(t) == #"tl(ti[x](p("a")) ti[ ](p("b") ul(li(p("c")))))"#)139        expectValid(t)140        // An item selected together with its parent moves with it.141        var p = md("- a\n- b\n  - c")142        check(p.indentListItems(at: 1..<3))143        #expect(sexp(p) == #"ul(li(p("a") ul(li(p("b") ul(li(p("c")))))))"#)144        expectValid(p)145    }146147    @Test func toggleOffInsideANestedList() {148        var d = md("- a\n  - b\n  - c\n  - d")149        check(d.toggleList(.bullet, at: 2..<3))150        #expect(sexp(d) == #"ul(li(p("a") ul(li(p("b"))) p("c") ul(li(p("d")))))"#)151        expectValid(d)152    }153}154155@Suite struct WrapperTests {156    @Test func blockquote() {157        var d = md("a\n\nb\n\nc")158        check(d.toggleBlockquote(at: 0..<2))159        #expect(sexp(d) == #"bq(p("a") p("b")) p("c")"#)160        check(d.lines[0].path[0].attrs.keys.sorted() == ["id"])161        expectValid(d)162        check(d.toggleBlockquote(at: 0..<1))163        #expect(sexp(d) == #"p("a") bq(p("b")) p("c")"#)164        expectValid(d)165        check(d.toggleBlockquote(at: 0..<3))166        #expect(sexp(d) == #"bq(p("a") bq(p("b")) p("c"))"#)167        expectValid(d)168        check(!d.toggleBlockquote(at: 7..<9))169    }170171    @Test func aPartiallySelectedListIsWrappedWhole() {172        var d = md("- a\n- b\n  - c\n\nz")173        check(d.toggleBlockquote(at: 2..<3))174        #expect(sexp(d) == #"ul(li(p("a")) li(p("b") bq(ul(li(p("c")))))) p("z")"#)175        expectValid(d)176        check(d.toggleBlockquote(at: 2..<3))177        #expect(sexp(d) == #"ul(li(p("a")) li(p("b") ul(li(p("c"))))) p("z")"#)178        check(d.toggleBlockquote(at: 0..<1))179        #expect(sexp(d) == #"bq(ul(li(p("a")) li(p("b") ul(li(p("c")))))) p("z")"#)180        expectValid(d)181        check(d.toggleBlockquote(at: 1..<3))182        #expect(sexp(d) == #"ul(li(p("a")) li(p("b") ul(li(p("c"))))) p("z")"#)183        expectValid(d)184        // A second block of an item can be quoted inside the item.185        var e = md("- a\n\n  b")186        check(e.toggleBlockquote(at: 1..<2))187        #expect(sexp(e) == #"ul(li(p("a") bq(p("b"))))"#)188        expectValid(e)189    }190191    @Test func callout() {192        var d = md("a\n\nb")193        check(d.toggleCallout(kind: "warning", icon: "⚠️", at: 0..<2))194        #expect(sexp(d) == #"callout(p("a") p("b"))"#)195        check(d.lines[0].path[0].attrs["kind"] == "warning" && d.lines[0].path[0].attrs["icon"] == "⚠️" && d.lines[0].path[0].attrs["id"]?.stringValue?.count == 10)196        expectValid(d)197        check(d.toggleCallout(kind: "info", icon: "ℹ️", at: 1..<2))198        #expect(sexp(d) == #"callout(p("a") p("b"))"# && d.lines[0].path[0].attrs["kind"] == "info" && d.lines[1].path[0].attrs["icon"] == "ℹ️")199        check(d.toggleCallout(kind: "info", icon: "ℹ️", at: 1..<2))200        #expect(sexp(d) == #"callout(p("a")) p("b")"#)201        expectValid(d)202    }203204    @Test func detailsSummaryWrapsTheWholeDetails() throws {205        var d = try Fixture.doc("rich")206        let i = try #require(d.lines.firstIndex { $0.type == "detailsSummary" })207        check(d.toggleBlockquote(at: i..<(i + 1)))208        check(d.lines[i].path.map(\.type) == ["blockquote", "details"] && d.lines[i + 2].path.map(\.type) == ["blockquote", "details", "detailsContent", "taskList", "taskItem"])209        expectValid(d)210    }211}212213@Suite struct SplitMergeTests {214    @Test func splitParagraphAndHeading() {215        var d = md("ab **cd** ef")216        check(d.splitLine(at: 0, offset: 4) == InlinePosition(line: 1, offset: 0))217        #expect(sexp(d) == #"p("ab " "c"[bold]) p("d"[bold] " ef")"#)218        check(d.lines[0].attrs["id"] != d.lines[1].attrs["id"])219        expectValid(d)220        var h = md("# Titre")221        check(h.splitLine(at: 0, offset: 5) == InlinePosition(line: 1, offset: 0))222        #expect(sexp(h) == #"h1("Titre") p"#)223        check(h.splitLine(at: 0, offset: 2) == InlinePosition(line: 1, offset: 0))224        #expect(sexp(h) == #"h1("Ti") h1("tre") p"#)225        check(h.splitLine(at: 0, offset: -4) == InlinePosition(line: 1, offset: 0))226        #expect(sexp(h) == #"h1 h1("Ti") h1("tre") p"#)227        expectValid(h)228    }229230    @Test func splitInLists() {231        var d = md("- ab\n  - child\n\n* [x] cd")232        check(d.splitLine(at: 0, offset: 1) == InlinePosition(line: 1, offset: 0))233        #expect(sexp(d) == #"ul(li(p("a")) li(p("b") ul(li(p("child"))))) tl(ti[x](p("cd")))"#)234        expectValid(d)235        check(d.splitLine(at: 3, offset: 1) == InlinePosition(line: 4, offset: 0))236        #expect(sexp(d) == #"ul(li(p("a")) li(p("b") ul(li(p("child"))))) tl(ti[x](p("c")) ti[ ](p("d")))"#)237        expectValid(d)238        // Enter on an empty item leaves the list, one level at a time.239        var e = md("- a\n  - b")240        check(e.splitLine(at: 1, offset: 1) == InlinePosition(line: 2, offset: 0))241        #expect(sexp(e) == #"ul(li(p("a") ul(li(p("b")) li(p))))"#)242        check(e.splitLine(at: 2, offset: 0) == InlinePosition(line: 2, offset: 0))243        #expect(sexp(e) == #"ul(li(p("a") ul(li(p("b")))) li(p))"#)244        expectValid(e)245        check(e.splitLine(at: 2, offset: 0) == InlinePosition(line: 2, offset: 0))246        #expect(sexp(e) == #"ul(li(p("a") ul(li(p("b"))))) p"#)247        expectValid(e)248        // A second paragraph of an item splits in place.249        var s = md("- a\n\n  bc")250        check(s.splitLine(at: 1, offset: 1) == InlinePosition(line: 2, offset: 0))251        #expect(sexp(s) == #"ul(li(p("a") p("b") p("c")))"#)252        expectValid(s)253    }254255    @Test func splitCodeQuoteAtomSummary() throws {256        var c = md("```\nab\n```")257        check(c.splitLine(at: 0, offset: 1) == InlinePosition(line: 0, offset: 2))258        check(c.lines.count == 1 && c.lines[0].runs == [.text("a\nb", marks: [])])259        expectValid(c)260        var q = md("> a")261        check(q.splitLine(at: 0, offset: 1) == InlinePosition(line: 1, offset: 0))262        #expect(sexp(q) == #"bq(p("a") p)"#)263        check(q.splitLine(at: 1, offset: 0) == InlinePosition(line: 1, offset: 0))264        #expect(sexp(q) == #"bq(p("a")) p"#)265        expectValid(q)266        var a = md("---")267        check(a.splitLine(at: 0, offset: 0) == InlinePosition(line: 1, offset: 0))268        #expect(sexp(a) == "hr p")269        expectValid(a)270        var d = try Fixture.doc("rich")271        let i = try #require(d.lines.firstIndex { $0.type == "detailsSummary" })272        let before = d273        check(d.splitLine(at: i, offset: 3) == InlinePosition(line: i, offset: 3) && d == before)274        check(d.splitLine(at: 999, offset: 0).line == d.lines.count - 1 && d == before)275    }276277    @Test func mergeParagraphs() {278        var d = md("ab\n\n**cd**\n\n# Titre")279        check(d.mergeWithPrevious(at: 0) == nil)280        check(d.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 2))281        #expect(sexp(d) == #"p("ab" "cd"[bold]) h1("Titre")"#)282        check(d.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 4))283        #expect(sexp(d) == #"p("ab" "cd"[bold] "Titre")"#)284        expectValid(d)285        check(d.mergeWithPrevious(at: 7) == nil)286    }287288    @Test func backspaceLiftsOutOfListsAndQuotesFirst() {289        var d = md("- a\n- b\n  - c")290        check(d.mergeWithPrevious(at: 2) == InlinePosition(line: 2, offset: 0))291        #expect(sexp(d) == #"ul(li(p("a")) li(p("b")) li(p("c")))"#)292        check(d.mergeWithPrevious(at: 1) == InlinePosition(line: 1, offset: 0))293        #expect(sexp(d) == #"ul(li(p("a"))) p("b") ul(li(p("c")))"#)294        expectValid(d)295        check(d.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 1))296        #expect(sexp(d) == #"ul(li(p("ab"))) ul(li(p("c")))"#)297        expectValid(d)298        var q = md("> a\n>\n> b")299        check(q.mergeWithPrevious(at: 0) == InlinePosition(line: 0, offset: 0))300        #expect(sexp(q) == #"p("a") bq(p("b"))"#)301        check(q.mergeWithPrevious(at: 1) == InlinePosition(line: 1, offset: 0))302        #expect(sexp(q) == #"p("a") p("b")"#)303        expectValid(q)304        var inside = md("> a\n>\n> b")305        check(inside.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 1))306        #expect(sexp(inside) == #"bq(p("ab"))"#)307    }308309    @Test func mergeWithCodeAtomsAndBoundaries() throws {310        var c = md("```\nab\n```\n\n**x** $y$")311        check(c.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 2))312        check(c.lines.count == 1 && c.lines[0].runs == [.text("abx y", marks: [])])313        expectValid(c)314        var fromCode = md("a\n\n```\nb\nc\n```")315        check(fromCode.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 1))316        #expect(sexp(fromCode) == #"p("ab" br "c")"#)317        expectValid(fromCode)318        var a = md("---\n\nx")319        check(a.mergeWithPrevious(at: 1) == nil)320        a.replaceText(in: 0..<1, at: 1, with: "")321        check(a.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 0))322        #expect(sexp(a) == "hr")323        check(a.mergeWithPrevious(at: 0) == nil)324        var d = try Fixture.doc("rich")325        let i = try #require(d.lines.firstIndex { $0.type == "detailsSummary" })326        let before = d327        check(d.mergeWithPrevious(at: i + 1) == nil && d == before)328        // A second paragraph of an item joins the first.329        var s = md("- a\n\n  b")330        check(s.mergeWithPrevious(at: 1) == InlinePosition(line: 0, offset: 1))331        #expect(sexp(s) == #"ul(li(p("ab")))"#)332    }333}334335@Suite struct BlockAtomTests {336    @Test func insertEveryKind() throws {337        var d = md("a\n\n- b")338        check(d.insertBlockAtom(.image(src: "/api/files/11111111-2222-4333-8444-555555555555", alt: "A", title: nil), after: 0) == 1)339        check(d.insertBlockAtom(.fileBlock(src: "/api/files/11111111-2222-4333-8444-555555555555", name: "f.pdf", size: 2048, mime: "application/pdf", attachmentId: "11111111-2222-4333-8444-555555555555"), after: 1) == 2)340        check(d.insertBlockAtom(.horizontalRule(), after: nil) == 0)341        check(d.insertBlockAtom(.blockMath(latex: "x^2"), after: 4) == 5)342        check(d.insertBlockAtom(.table(rows: 2, cols: 3, withHeaderRow: true), after: 99) == 6)343        #expect(sexp(d) == #"hr p("a") image fileBlock ul(li(p("b") blockMath table(tableRow(tableHeader(p) tableHeader(p) tableHeader(p)) tableRow(tableCell(p) tableCell(p) tableCell(p)))))"#)344        expectValid(d)345        check(d.lines[2].attrs == ["id": d.lines[2].attrs["id"]!, "src": "/api/files/11111111-2222-4333-8444-555555555555", "alt": "A", "title": nil, "width": nil, "height": nil])346        check(d.lines[3].attrs["size"] == 2048 && d.lines[3].attrs["name"] == "f.pdf" && d.lines[3].attrs["mime"] == "application/pdf")347        let cell = try #require(d.lines[6].atomNode?.content?[0].content?[0])348        check(cell.attrs == ["colspan": 1, "rowspan": 1, "colwidth": nil, "align": nil])349        check(cell.content?[0].attrs?["id"]?.stringValue?.count == 10 && cell.content?[0].attrs?["textAlign"] == .some(nil))350        check(d.attachmentReferences() == ["11111111-2222-4333-8444-555555555555"])351        var empty = NoteDocument(lines: [])352        check(empty.insertBlockAtom(.horizontalRule(), after: 3) == 0)353    }354355    @Test func insertAfterADetailsSummaryGoesIntoTheBody() throws {356        var d = try Fixture.doc("rich")357        let i = try #require(d.lines.firstIndex { $0.type == "detailsSummary" })358        check(d.insertBlockAtom(.horizontalRule(), after: i) == i + 1)359        check(d.lines[i + 1].path.map(\.type) == ["details", "detailsContent"])360        expectValid(d)361    }362363    @Test func replaceKeepsTheBlockId() throws {364        var d = NoteDocument(lines: [Line(blockAtom: .table(rows: 1, cols: 1, withHeaderRow: false))])365        let id = d.lines[0].attrs["id"]366        var table = try #require(d.lines[0].atomNode)367        check(table.insertTableRow(at: 1))368        table.attrs?["id"] = "zzzzzzzzzz"369        check(d.replaceBlockAtom(at: 0, with: table))370        check(d.lines[0].attrs["id"] == id && d.lines[0].atomNode?.content?.count == 2 && d.pmNode().content?[0].attrs?["id"] == id)371        check(!d.replaceBlockAtom(at: 0, with: d.lines[0].atomNode!) && !d.replaceBlockAtom(at: 4, with: table))372        expectValid(d)373    }374375    @Test func deleteLine() {376        var d = md("a\n\n---\n\n- b\n\n  c\n- d")377        check(d.deleteLine(at: 1))378        #expect(sexp(d) == #"p("a") ul(li(p("b") p("c")) li(p("d")))"#)379        check(!d.deleteLine(at: 1), "the first paragraph of an item with other content stays")380        check(d.deleteLine(at: 2) && d.deleteLine(at: 1))381        #expect(sexp(d) == #"p("a") ul(li(p("d")))"#)382        check(d.deleteLine(at: 1) && d.deleteLine(at: 0) && !d.deleteLine(at: 3))383        #expect(sexp(d) == "p")384        expectValid(d)385    }386}387388@Suite struct InlineCommandTests {389    @Test func toggleMarks() {390        var d = md("hello world")391        check(d.toggleMark(.bold, in: 0..<5, at: 0))392        #expect(sexp(d) == #"p("hello"[bold] " world")"#)393        check(d.hasMark(.bold, in: 0..<5, at: 0) && !d.hasMark(.bold, in: 0..<6, at: 0) && !d.hasMark(.bold, in: 2..<2, at: 0))394        check(d.toggleMark(.italic, in: 3..<8, at: 0))395        #expect(sexp(d) == #"p("hel"[bold] "lo"[bold,italic] " wo"[italic] "rld")"#)396        check(d.toggleMark(.bold, in: 0..<11, at: 0))397        #expect(sexp(d) == #"p("hello"[bold] " wo"[bold,italic] "rld"[bold])"# || sexp(d) == #"p("hel"[bold] "lo wo"[bold,italic] "rld"[bold])"#)398        check(d.toggleMark(.bold, in: 0..<11, at: 0))399        #expect(sexp(d) == #"p("hel" "lo wo"[italic] "rld")"#)400        expectValid(d)401        check(!d.toggleMark(.bold, in: 4..<4, at: 0) && !d.toggleMark(.bold, in: 0..<3, at: 9))402    }403404    @Test func marksAreKeptInSchemaOrder() {405        var d = md("abc")406        for kind in [MarkKind.superscript, .highlight, .underline, .strike, .italic, .bold, .subscript] { d.toggleMark(kind, in: 0..<3, at: 0) }407        d.setLink(href: "https://example.org", in: 0..<3, at: 0)408        #expect(sexp(d) == #"p("abc"[link,bold,italic,strike,underline,highlight,subscript,superscript])"#)409        expectValid(d)410    }411412    @Test func codeExcludesEveryOtherMark() {413        var d = md("**gras** [lien](https://example.org) fin")414        check(d.toggleMark(.code, in: 0..<9, at: 0))415        #expect(sexp(d) == #"p("gras lien"[code] " fin")"#)416        check(!d.toggleMark(.bold, in: 0..<9, at: 0), "no other mark on code")417        check(!d.setLink(href: "https://example.org", in: 0..<4, at: 0))418        check(d.toggleMark(.bold, in: 5..<13, at: 0))419        #expect(sexp(d) == #"p("gras lien"[code] " fin"[bold])"#)420        check(d.hasMark(.bold, in: 0..<13, at: 0), "text that cannot take the mark is ignored")421        expectValid(d)422        check(d.toggleMark(.code, in: 0..<9, at: 0))423        #expect(sexp(d) == #"p("gras lien" " fin"[bold])"#)424        var code = md("```\nabc\n```")425        check(!code.toggleMark(.bold, in: 0..<3, at: 0) && !code.setLink(href: "x", in: 0..<3, at: 0))426    }427428    @Test func links() {429        var d = md("voir la page ici")430        check(d.setLink(href: "/p/0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d", in: 8..<12, at: 0))431        #expect(sexp(d) == #"p("voir la " "page"[link] " ici")"#)432        check(d.lines[0].runs[1].marks[0].attrs == ["href": "/p/0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d", "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil, "title": nil])433        check(d.pageReferences() == ["0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"])434        expectValid(d)435        check(d.linkRange(at: 10, line: 0) == 8..<12 && d.linkRange(at: 12, line: 0) == 8..<12 && d.linkRange(at: 3, line: 0) == nil)436        d.toggleMark(.bold, in: 10..<12, at: 0)437        check(d.linkRange(at: 9, line: 0) == 8..<12)438        check(d.setLink(href: "https://example.org", in: 5..<10, at: 0))439        #expect(sexp(d) == #"p("voir " "la pa"[link] "ge"[link,bold] " ici")"#)440        check(d.linkRange(at: 6, line: 0) == 5..<10 && d.linkRange(at: 11, line: 0) == 10..<12)441        check(d.removeLink(in: 0..<16, at: 0) && !d.removeLink(in: 0..<16, at: 0))442        #expect(sexp(d) == #"p("voir la pa" "ge"[bold] " ici")"#)443        expectValid(d)444    }445446    @Test func typingInheritsMarksAndCountsUTF16() {447        var d = md("a**b**c")448        check(d.marks(at: 2, line: 0).map(\.type) == ["bold"] && d.marks(at: 1, line: 0).isEmpty && d.marks(at: 0, line: 0).isEmpty)449        check(d.replaceText(in: 2..<2, at: 0, with: "😀"))450        #expect(sexp(d) == #"p("a" "b😀"[bold] "c")"#)451        check(d.lines[0].inlineLength == 5 && d.lines[0].displayString.utf16.count == 5)452        check(d.replaceText(in: 2..<4, at: 0, with: "") && sexp(d) == #"p("a" "b"[bold] "c")"#)453        check(d.replaceText(in: 3..<3, at: 0, with: "x", marks: [.mark(.italic), .mark(.bold)]))454        #expect(sexp(d) == #"p("a" "b"[bold] "c" "x"[bold,italic])"#)455        check(d.replaceText(in: 0..<99, at: 0, with: "un\ndeux") && sexp(d) == #"p("un" br "deux")"#)456        check(d.lines[0].inlineLength == 7 && d.lines[0].displayString == "un\u{2028}deux")457        check(!d.replaceText(in: 1..<1, at: 0, with: "") && !d.replaceText(in: 0..<1, at: 5, with: "x"))458        expectValid(d)459        // A link is not continued by typing after it; inside it is.460        let l = md("[ab](https://example.org)c")461        check(l.marks(at: 2, line: 0).isEmpty && l.marks(at: 1, line: 0).map(\.type) == ["link"])462        // An offset inside a surrogate pair moves back to the scalar boundary.463        var e = md("😀")464        check(e.replaceText(in: 1..<1, at: 0, with: "x") && sexp(e) == #"p("x😀")"#)465        var code = md("```\nab\n```")466        check(code.replaceText(in: 1..<1, at: 0, with: "\n\t") && code.lines[0].runs == [.text("a\n\tb", marks: [])])467        expectValid(code)468    }469470    @Test func inlineAtoms() throws {471        var d = md("ab")472        check(d.insertInlineAtom(.mention(id: "3f2b8c1e-7a4d-4e9b-9c1a-5d6e7f8a9b0c", label: "Page"), at: 1, line: 0))473        check(d.insertInlineAtom(.inlineMath(latex: "x"), at: 3, line: 0) && d.insertInlineAtom(.hardBreak(), at: 0, line: 0))474        #expect(sexp(d) == #"p(br "a" mention "b" inlineMath)"#)475        check(d.lines[0].inlineLength == 5 && d.lines[0].displayString == "\u{2028}a\u{FFFC}b\u{FFFC}")476        check(d.pageReferences() == ["3f2b8c1e-7a4d-4e9b-9c1a-5d6e7f8a9b0c"])477        expectValid(d)478        check(d.toggleMark(.bold, in: 0..<5, at: 0) && sexp(d) == #"p(br "a"[bold] mention "b"[bold] inlineMath)"#)479        check(d.replaceText(in: 1..<4, at: 0, with: "") && sexp(d) == "p(br inlineMath)")480        var code = md("```\nab\n```")481        check(!code.insertInlineAtom(.hardBreak(), at: 1, line: 0))482        var rich = try Fixture.doc("rich")483        let i = try #require(rich.lines.firstIndex { $0.type == "detailsSummary" })484        check(!rich.insertInlineAtom(.hardBreak(), at: 1, line: i))485        check(rich.replaceText(in: 0..<0, at: i, with: "a\nb") && rich.lines[i].runs.first == .text("a bDétails ", marks: []))486        expectValid(rich)487    }488}489490@Suite struct TableTests {491    @Test func gridAndCellText() throws {492        var table = try #require(try Fixture.doc("rich").lines.first { $0.type == "table" }?.atomNode)493        let grid = table.tableGrid494        check(grid.map { $0.map(\.text) } == [["Poste", "Montant ($)", "Note"], ["Loyer | brut", "1 200", "ligne 1\nligne 2"], ["Fichier", ""]])495        check(grid[0].allSatisfy(\.isHeader) && !grid[1][0].isHeader && grid[2][1].colspan == 2 && grid[0][0].rowspan == 1)496        let untouched = table497        check(!table.setTableCellText("1 200", row: 1, column: 1) && !table.setTableCellText("ligne 1\nligne 2", row: 1, column: 2) && table == untouched)498        check(!table.setTableCellText("x", row: 9, column: 0) && !table.setTableCellText("x", row: 2, column: 2))499        let oldId = table.content?[1].content?[1].content?[0].attrs?["id"]500        check(table.setTableCellText("1 300\nnet", row: 1, column: 1))501        #expect(sexp(table.content![1].content![1]) == #"tableCell(p("1 300" br "net"))"#)502        check(table.content?[1].content?[1].content?[0].attrs?["id"] == oldId && table.tableGrid[1][1].text == "1 300\nnet")503        check(table.setTableCellText("", row: 0, column: 0) && sexp(table.content![0].content![0]) == "tableHeader(p)")504        check(table.setTableCellText("img", row: 2, column: 1) && table.tableGrid[2][1].text == "img")505        check(PMNode(type: "doc", content: [table]).schemaViolations(strict: true).isEmpty)506        check(PMNode.paragraph("x").tableGrid.isEmpty)507    }508509    @Test func rowsAndColumns() {510        var t = PMNode.table(rows: 2, cols: 2, withHeaderRow: true)511        func shape() -> String { t.tableGrid.map { $0.map { $0.isHeader ? "H" : "c" }.joined() }.joined(separator: "/") }512        check(shape() == "HH/cc")513        check(t.insertTableRow(at: 2) && t.insertTableRow(at: 0) && shape() == "cc/HH/cc/cc")514        check(t.deleteTableRow(at: 0) && shape() == "HH/cc/cc")515        check(t.insertTableColumn(at: 1) && t.insertTableColumn(at: 99) && shape() == "HHHH/cccc/cccc")516        t.setTableCellText("x", row: 1, column: 3)517        check(t.deleteTableColumn(at: 0) && shape() == "HHH/ccc/ccc" && t.tableGrid[1][2].text == "x")518        check(!t.deleteTableColumn(at: 3) && !t.deleteTableRow(at: 3) && !t.deleteTableRow(at: -1))519        check(t.toggleTableHeaderRow() && shape() == "ccc/ccc/ccc" && t.toggleTableHeaderRow() && shape() == "HHH/ccc/ccc")520        check(t.deleteTableRow(at: 1) && t.deleteTableRow(at: 1) && !t.deleteTableRow(at: 0) && shape() == "HHH")521        check(t.insertTableRow(at: 1) && shape() == "HHH/ccc", "a table made of a header row gets plain rows")522        check(t.deleteTableColumn(at: 1) && t.deleteTableColumn(at: 1) && !t.deleteTableColumn(at: 0) && shape() == "H/c")523        check(PMNode(type: "doc", content: [t]).schemaViolations(strict: true).isEmpty)524        var notTable = PMNode.paragraph("x")525        check(!notTable.insertTableRow(at: 0) && !notTable.insertTableColumn(at: 0) && !notTable.toggleTableHeaderRow())526        let minimal = PMNode.table(rows: 0, cols: 0, withHeaderRow: false)527        check(minimal.tableGrid.count == 1 && minimal.tableGrid[0].count == 1)528    }529}530531@Suite struct FuzzTests {532    @Test func randomValidDocumentsAreValid() {533        var r = SplitMix64(seed: 7)534        for i in 0..<200 { expectValid(Random.validDocument(&r), "generated \(i)") }535    }536537    @Test func randomCommandsKeepTheDocumentValid() {538        var r = SplitMix64(seed: 42)539        for i in 0..<400 {540            var d = Random.validDocument(&r)541            var trail: [String] = []542            for _ in 0..<12 {543                let before = d544                trail.append(Random.command(&d, &r))545                let issues = d.schemaViolations(strict: true)546                if !issues.isEmpty || d.lines.isEmpty {547                    Issue.record("document \(i) after \(trail): \(issues.prefix(3))\nbefore: \(sexp(before))\nafter: \(sexp(d))")548                    break549                }550            }551            expectValid(d, "document \(i) after \(trail)")552            var withIds = d553            withIds.ensureBlockIds()554            check(withIds == d, "document \(i) after \(trail): commands must leave unique block ids")555        }556    }557558    @Test func commandsOnTheRichFixture() throws {559        var r = SplitMix64(seed: 99)560        let rich = try Fixture.doc("rich")561        for i in 0..<300 {562            var d = rich563            var trail: [String] = []564            for _ in 0..<8 { trail.append(Random.command(&d, &r)) }565            expectValid(d, "rich \(i) after \(trail)")566        }567    }568}569
Files main
Menu

Theme