Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocModelTests/EditingTests.swift3// Description: Editing engine tests: typing, Unicode safety, paragraph splitting and joining, range deletion, formatting, lists, fragments.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Testing8import Foundation9@testable import DocModel1011func makeDoc(_ paragraphs: [String]) -> DocumentModel {12 DocumentModel(body: paragraphs.map { .paragraph(Paragraph($0)) })13}14func texts(_ doc: DocumentModel) -> [String] { doc.body.map { $0.paragraph?.plainText ?? "<\($0.id.isEmpty ? "?" : "block")>" } }15func caret(_ block: Int, _ offset: Int) -> Selection { Selection(caret: Position(block: block, offset: offset)) }16func range(_ b1: Int, _ o1: Int, _ b2: Int, _ o2: Int) -> Selection { Selection(anchor: Position(block: b1, offset: o1), head: Position(block: b2, offset: o2)) }1718@Suite struct TypingTests {19 @Test func insertAtCaretAndAdvance() {20 var e = DocumentEditor(doc: makeDoc(["Hello world"]), selection: caret(0, 5))21 e.insertText(",")22 #expect(texts(e.doc) == ["Hello, world"])23 #expect(e.selection == caret(0, 6))24 }2526 @Test func typingReplacesSelection() {27 var e = DocumentEditor(doc: makeDoc(["Hello world"]), selection: range(0, 6, 0, 11))28 e.insertText("ORIX")29 #expect(texts(e.doc) == ["Hello ORIX"])30 }3132 @Test func newlinesCreateParagraphs() {33 var e = DocumentEditor(doc: makeDoc([""]))34 e.insertText("one\ntwo\r\nthree")35 #expect(texts(e.doc) == ["one", "two", "three"])36 #expect(e.selection == caret(2, 5))37 }3839 @Test func typingInheritsFormattingOnTheLeft() {40 var doc = makeDoc([""])41 doc.body = [.paragraph(Paragraph(runs: [Run("bold", props: CharProps(bold: true)), Run(" plain")]))]42 var e = DocumentEditor(doc: doc, selection: caret(0, 4))43 e.insertText("er")44 let p = e.doc.body[0].paragraph!45 #expect(p.runs.count == 2)46 #expect(p.runs[0].text == "bolder" && p.runs[0].props.bold == true)47 }4849 @Test func pendingFormatAtCaretAppliesToTypedText() {50 var e = DocumentEditor(doc: makeDoc(["ab"]), selection: caret(0, 1))51 e.toggle(.italic)52 e.insertText("X")53 let p = e.doc.body[0].paragraph!54 #expect(p.plainText == "aXb")55 #expect(p.runs.map(\.text) == ["a", "X", "b"])56 #expect(p.runs[1].props.italic == true && p.runs[0].props.italic == nil)57 }5859 @Test func linkDoesNotExtendToTextTypedAfterIt() {60 var doc = makeDoc([""])61 doc.body = [.paragraph(Paragraph(runs: [Run("site", props: CharProps(link: "https://example.org"))]))]62 var e = DocumentEditor(doc: doc, selection: caret(0, 4))63 e.insertText(" next")64 #expect(e.doc.body[0].paragraph!.runs.last?.props.link == nil)65 }66}6768@Suite struct UnicodeTests {69 // Family emoji (ZWJ sequence, 11 UTF-16 units), flag, combining acute, Arabic, CJK outside the BMP.70 let family = "👨👩👧👦", flag = "🇨🇦", combining = "e\u{0301}", astral = "𠮷"7172 @Test func backspaceRemovesWholeComposedCharacters() {73 for cluster in [family, flag, combining, astral, "👍🏽"] {74 var e = DocumentEditor(doc: makeDoc(["a" + cluster + "b"]), selection: caret(0, 1 + cluster.utf16.count))75 e.deleteBackward()76 #expect(texts(e.doc) == ["ab"], "cluster \(cluster)")77 #expect(e.selection == caret(0, 1))78 }79 }8081 @Test func forwardDeleteRemovesWholeComposedCharacters() {82 var e = DocumentEditor(doc: makeDoc(["a" + family + "b"]), selection: caret(0, 1))83 e.deleteForward()84 #expect(texts(e.doc) == ["ab"])85 }8687 @Test func caretMovementNeverLandsInsideACluster() {88 let text = "x" + family + combining + flag + "y"89 let doc = makeDoc([text])90 var pos = Position(block: 0, offset: 0)91 var stops: [Int] = [0]92 while let n = DocumentEditor.position(after: pos, in: doc.body) { pos = n; stops.append(n.offset) }93 #expect(stops == [0, 1, 1 + family.utf16.count, 1 + family.utf16.count + 2, 1 + family.utf16.count + 2 + 4, text.utf16.count])94 var back: [Int] = [pos.offset]95 while let n = DocumentEditor.position(before: pos, in: doc.body) { pos = n; back.append(n.offset) }96 #expect(back == stops.reversed())97 }9899 @Test func clampSnapsOffsetsOntoBoundaries() {100 let doc = makeDoc(["a" + family])101 let p = DocumentEditor.clamp(Position(block: 0, offset: 4), in: doc.body)102 #expect(p.offset == 1)103 }104105 @Test func splitInsideSurrogatePairIsImpossibleThroughTheEditor() {106 var e = DocumentEditor(doc: makeDoc([astral + astral]), selection: Selection(caret: Position(block: 0, offset: 1)))107 #expect(e.selection.head.offset == 0) // sanitised onto a boundary108 e.insertParagraphBreak()109 #expect(texts(e.doc) == ["", astral + astral])110 }111112 @Test func rightToLeftAndMixedTextRoundTripsThroughEdits() {113 let arabic = "مرحبا بالعالم", hebrew = "שלום"114 var e = DocumentEditor(doc: makeDoc([arabic]), selection: caret(0, arabic.utf16.count))115 e.insertText(" " + hebrew + " abc")116 #expect(texts(e.doc) == [arabic + " " + hebrew + " abc"])117 e.deleteBackward(.word)118 #expect(texts(e.doc) == [arabic + " " + hebrew + " "])119 }120121 @Test func wordBoundaries() {122 let s = "Écrire sans limites, l’été."123 #expect(s.wordBoundary(after: 0) == 6)124 #expect(s.wordBoundary(before: 11) == 7)125 #expect(s.wordRange(at: 8) == 7..<11)126 #expect(s.utf16Substring(s.wordRange(at: 22)) == "l’été")127 }128129 @Test func statisticsCountWordsAcrossScripts() {130 let st = DocumentStatistics(text: "Hello, l’été est là — 42 times! 你好")131 #expect(st.words == 7)132 }133}134135@Suite struct ParagraphStructureTests {136 @Test func returnSplitsAndUsesNextStyleAtEnd() {137 var doc = makeDoc([""])138 doc.body = [.paragraph(Paragraph("Title here", style: StyleID.heading(1)))]139 let id = doc.body[0].id140 var e = DocumentEditor(doc: doc, selection: caret(0, 10))141 e.insertParagraphBreak()142 #expect(e.doc.body.count == 2)143 #expect(e.doc.body[0].paragraph!.style == StyleID.heading(1) && e.doc.body[0].id == id)144 #expect(e.doc.body[1].paragraph!.style == StyleID.normal)145 #expect(e.selection == caret(1, 0))146 }147148 @Test func returnInTheMiddleKeepsStyleOnBothHalves() {149 var doc = makeDoc([""])150 doc.body = [.paragraph(Paragraph("Title here", style: StyleID.heading(2)))]151 var e = DocumentEditor(doc: doc, selection: caret(0, 5))152 e.insertParagraphBreak()153 #expect(texts(e.doc) == ["Title", " here"])154 #expect(e.doc.body[1].paragraph!.style == StyleID.heading(2))155 }156157 @Test func returnAtStartKeepsTheIdWithTheContent() {158 let doc = makeDoc(["Target"])159 let id = doc.body[0].id160 var e = DocumentEditor(doc: doc, selection: caret(0, 0))161 e.insertParagraphBreak()162 #expect(texts(e.doc) == ["", "Target"])163 #expect(e.doc.body[1].id == id)164 }165166 @Test func backspaceAtStartJoinsParagraphs() {167 var e = DocumentEditor(doc: makeDoc(["one", "two"]), selection: caret(1, 0))168 e.deleteBackward()169 #expect(texts(e.doc) == ["onetwo"])170 #expect(e.selection == caret(0, 3))171 }172173 @Test func forwardDeleteAtEndJoinsParagraphs() {174 var e = DocumentEditor(doc: makeDoc(["one", "two"]), selection: caret(0, 3))175 e.deleteForward()176 #expect(texts(e.doc) == ["onetwo"])177 }178179 @Test func deletingAcrossParagraphsMergesTheEnds() {180 var e = DocumentEditor(doc: makeDoc(["alpha", "beta", "gamma", "delta"]), selection: range(0, 2, 2, 3))181 e.deleteSelection()182 #expect(texts(e.doc) == ["alma", "delta"])183 #expect(e.selection == caret(0, 2))184 }185186 @Test func selectAllDeleteLeavesOneEmptyParagraph() {187 var e = DocumentEditor(doc: makeDoc(["a", "b", "c"]), selection: range(0, 0, 2, 1))188 e.deleteSelection()189 #expect(texts(e.doc) == [""])190 }191192 @Test func rangeCoveringATableRemovesIt() {193 var doc = makeDoc(["before", "after"])194 doc.body.insert(.table(Table(strings: [["a", "b"], ["c", "d"]], width: 400)), at: 1)195 var e = DocumentEditor(doc: doc, selection: range(0, 3, 2, 2))196 e.deleteSelection()197 #expect(texts(e.doc) == ["befter"])198 }199200 @Test func selectionFromInsideATableToOutsideCoversTheWholeTable() {201 var doc = makeDoc(["before", "after"])202 doc.body.insert(.table(Table(strings: [["a", "b"], ["c", "d"]], width: 400)), at: 1)203 let sel = Selection(anchor: Position(path: ParaPath(block: 1, cell: CellPath(row: 1, cell: 0)), offset: 0), head: Position(block: 2, offset: 2))204 var e = DocumentEditor(doc: doc, selection: sel)205 e.deleteSelection()206 #expect(texts(e.doc) == ["before", "ter"])207 }208209 @Test func backspaceAfterAPageBreakRemovesIt() {210 var doc = makeDoc(["a", "b"])211 doc.body.insert(.pageBreak(BreakBlock()), at: 1)212 var e = DocumentEditor(doc: doc, selection: caret(2, 0))213 e.deleteBackward()214 #expect(texts(e.doc) == ["a", "b"])215 }216217 @Test func insertBlockSplitsTheParagraph() {218 var e = DocumentEditor(doc: makeDoc(["leftright"]), selection: caret(0, 4))219 e.insertBlock(.pageBreak(BreakBlock()))220 #expect(e.doc.body.count == 3)221 #expect(e.doc.body[0].paragraph?.plainText == "left" && e.doc.body[2].paragraph?.plainText == "right")222 #expect(e.selection == caret(2, 0))223 }224225 @Test func documentAlwaysEndsWithAParagraphAfterATable() {226 var e = DocumentEditor(doc: makeDoc([""]))227 e.insertTable(rows: 2, columns: 3, width: 450)228 #expect(e.doc.body.count == 2 && e.doc.body[1].paragraph != nil)229 #expect(e.selection.head.path.cell == CellPath(row: 0, cell: 0))230 }231}232233@Suite struct FormattingTests {234 @Test func toggleBoldOnSelectionSplitsRuns() {235 var e = DocumentEditor(doc: makeDoc(["Hello world"]), selection: range(0, 6, 0, 11))236 e.toggle(.bold)237 let p = e.doc.body[0].paragraph!238 #expect(p.runs.map(\.text) == ["Hello ", "world"])239 #expect(p.runs[1].props.bold == true)240 e.toggle(.bold)241 #expect(e.doc.body[0].paragraph!.runs.count == 1 || e.doc.body[0].paragraph!.runs[1].props.bold == false)242 }243244 @Test func formattingAcrossParagraphs() {245 var e = DocumentEditor(doc: makeDoc(["one", "two", "three"]), selection: range(0, 1, 2, 2))246 e.formatCharacters { $0.color = RGBA(hex: 0xFF0000) }247 let red = RGBA(hex: 0xFF0000)248 #expect(e.doc.body[0].paragraph!.runs.map(\.props.color) == [nil, red])249 #expect(e.doc.body[1].paragraph!.runs.map(\.props.color) == [red])250 #expect(e.doc.body[2].paragraph!.runs.map(\.props.color) == [red, nil])251 }252253 @Test func styleResolutionFollowsTheInheritanceChain() {254 var sheet = StyleSheet.standard()255 sheet.upsert(Style(id: "Lead", name: "Lead", basedOn: StyleID.quote, char: CharProps(fontSize: 15)))256 let c = sheet.charProps(paraStyle: "Lead", charStyle: StyleID.strong, direct: CharProps(underline: true))257 #expect(c.fontSize == 15 && c.italic && c.isBold && c.underline)258 let p = sheet.paraProps(style: "Lead", direct: ParaProps(alignment: .right))259 #expect(p.indentLeft == 28 && p.alignment == .right)260 }261262 @Test func styleCyclesDoNotHang() {263 var sheet = StyleSheet.standard()264 sheet.upsert(Style(id: "A", name: "A", basedOn: "B"))265 sheet.upsert(Style(id: "B", name: "B", basedOn: "A"))266 #expect(sheet.chain("A").count == 2)267 }268269 @Test func setParagraphStyleAndUpdateStyleFromSelection() {270 var e = DocumentEditor(doc: makeDoc(["Heading", "body"]), selection: caret(0, 2))271 e.setParagraphStyle(StyleID.heading(2))272 #expect(e.doc.body[0].paragraph!.style == StyleID.heading(2))273 e.formatParagraphs { $0.props.alignment = .center }274 e.updateStyleFromSelection(StyleID.heading(2))275 #expect(e.doc.styles.style(StyleID.heading(2))!.para.alignment == .center)276 #expect(e.doc.body[0].paragraph!.props.alignment == nil)277 }278279 @Test func themeChangeKeepsCustomStyles() {280 var sheet = StyleSheet.standard(theme: .orix)281 sheet.upsert(Style(id: "Mine", name: "Mine", basedOn: StyleID.normal))282 sheet.applyTheme(.classic)283 #expect(sheet.defaultChar.fontFamily == "Times New Roman")284 #expect(sheet.style("Mine") != nil && sheet.themeName == "Classic")285 }286}287288@Suite struct ListAndNumberingTests {289 @Test func toggleBulletsAndNumbers() {290 var e = DocumentEditor(doc: makeDoc(["a", "b", "c"]), selection: range(0, 0, 2, 1))291 e.toggleList(.numbered)292 var n = Numbering(e.doc)293 #expect(e.doc.body.map { n.listLabels[$0.id] } == ["1.", "2.", "3."])294 e.selection = caret(1, 0)295 e.changeListLevel(by: 1)296 n = Numbering(e.doc)297 #expect(e.doc.body.map { n.listLabels[$0.id] } == ["1.", "a.", "2."])298 e.selection = range(0, 0, 2, 1)299 e.toggleList(.bulleted)300 n = Numbering(e.doc)301 #expect(n.listLabels[e.doc.body[0].id] == "•")302 e.toggleList(.bulleted)303 #expect(e.doc.body.allSatisfy { $0.paragraph?.list == nil })304 }305306 @Test func aNewNumberedListRestartsAtOne() {307 var e = DocumentEditor(doc: makeDoc(["a", "plain", "b"]), selection: caret(0, 0))308 e.toggleList(.numbered)309 e.selection = caret(2, 0)310 e.toggleList(.numbered)311 let n = Numbering(e.doc)312 #expect(n.listLabels[e.doc.body[0].id] == "1." && n.listLabels[e.doc.body[2].id] == "1.")313 }314315 @Test func returnOnEmptyItemLeavesTheList() {316 var e = DocumentEditor(doc: makeDoc(["item"]), selection: caret(0, 4))317 e.toggleList(.bulleted)318 e.insertParagraphBreak()319 #expect(e.doc.body[1].paragraph?.list != nil)320 e.insertParagraphBreak()321 #expect(e.doc.body.count == 2 && e.doc.body[1].paragraph?.list == nil)322 }323324 @Test func headingNumbersCaptionsNotesAndCrossReferences() {325 var doc = DocumentModel()326 var sheet = doc.styles327 for l in 1...3 { var s = sheet.style(StyleID.heading(l))!; s.numbered = true; sheet.upsert(s) }328 doc.styles = sheet329 let h1 = Paragraph("Intro", style: StyleID.heading(1)), h2 = Paragraph("Scope", style: StyleID.heading(2)), h3 = Paragraph("Method", style: StyleID.heading(1))330 let cap = Paragraph(style: StyleID.caption, runs: [Run("Figure "), Run(inline: .field(.sequence("Figure"))), Run(": A chart")])331 let cap2 = Paragraph(style: StyleID.caption, runs: [Run("Figure "), Run(inline: .field(.sequence("Figure"))), Run(": Another")])332 let note = Note(kind: .footnote, paragraphs: [Paragraph("note text")])333 doc.notes[note.id] = note334 let body = Paragraph(runs: [Run("See "), Run(inline: .crossRef(CrossRef(target: cap2.id))), Run(" in "), Run(inline: .crossRef(CrossRef(target: h2.id))),335 Run(inline: .note(NoteRef(kind: .footnote, id: note.id))), Run(inline: .crossRef(CrossRef(target: "nowhere")))])336 doc.body = [.paragraph(h1), .paragraph(h2), .paragraph(cap), .paragraph(h3), .paragraph(cap2), .paragraph(body)]337 let n = Numbering(doc)338 #expect(n.headingNumbers[h1.id] == "1" && n.headingNumbers[h2.id] == "1.1" && n.headingNumbers[h3.id] == "2")339 #expect(n.captions[cap2.id]?.number == 2 && n.captions[cap.id]?.text == "Figure 1: A chart")340 #expect(n.displayText(of: body, document: doc) == "See Figure 2 in Section 1.1??")341 #expect(n.noteNumbers[note.id] == 1)342 #expect(n.outline.map(\.text) == ["Intro", "Scope", "Method"])343 #expect(!n.targetExists("nowhere"))344 }345346 @Test func numberFormats() {347 #expect(NumberFormat.lowerRoman.string(1994) == "mcmxciv")348 #expect(NumberFormat.upperAlpha.string(28) == "AB")349 #expect(NumberFormat.decimal.string(7) == "7")350 }351352 @Test func movingASectionKeepsCrossReferenceTargets() {353 var doc = DocumentModel()354 let a = Paragraph("A", style: StyleID.heading(1)), b = Paragraph("B", style: StyleID.heading(1))355 doc.body = [.paragraph(a), .paragraph(Paragraph("a text")), .paragraph(b), .paragraph(Paragraph("b text"))]356 var e = DocumentEditor(doc: doc)357 e.moveSection(startingAt: 2, before: 0)358 #expect(texts(e.doc) == ["B", "b text", "A", "a text"])359 #expect(e.doc.body[0].id == b.id)360 }361}362363@Suite struct FragmentTests {364 @Test func copyAndPasteWithinAParagraph() {365 var e = DocumentEditor(doc: makeDoc(["Hello world"]), selection: range(0, 0, 0, 5))366 let f = e.copyFragment()!367 #expect(f.isInline && f.plainText == "Hello")368 e.selection = caret(0, 11)369 e.insertFragment(f)370 #expect(texts(e.doc) == ["Hello worldHello"])371 }372373 @Test func pasteMultipleParagraphsInTheMiddle() {374 var e = DocumentEditor(doc: makeDoc(["one", "two", "LEFTRIGHT"]), selection: range(0, 1, 1, 2))375 let f = e.copyFragment()!376 #expect(f.plainText == "ne\ntw")377 e.selection = caret(2, 4)378 e.insertFragment(f)379 #expect(texts(e.doc) == ["one", "two", "LEFTne", "twRIGHT"])380 #expect(e.selection == caret(3, 2))381 #expect(Set(e.doc.body.map(\.id)).count == 4)382 }383384 @Test func pastedNotesGetFreshIds() {385 var e = DocumentEditor(doc: makeDoc(["text"]), selection: caret(0, 4))386 let id = e.insertNote(.footnote)!387 e.selection = range(0, 0, 0, 5)388 let f = e.copyFragment()!389 e.selection = caret(0, 5)390 e.insertFragment(f)391 #expect(e.doc.notes.count == 2)392 #expect(Numbering(e.doc).footnoteOrder.count == 2 && Numbering(e.doc).footnoteOrder.contains(id))393 }394395 @Test func deletingANoteReferenceRemovesTheNote() {396 var e = DocumentEditor(doc: makeDoc(["text"]), selection: caret(0, 4))397 e.insertNote(.footnote)398 #expect(e.doc.notes.count == 1)399 e.deleteBackward()400 #expect(e.doc.notes.isEmpty && texts(e.doc) == ["text"])401 }402403 @Test func fragmentIsCodable() throws {404 var e = DocumentEditor(doc: makeDoc(["a", "b"]), selection: range(0, 0, 1, 1))405 e.toggle(.bold)406 let f = e.copyFragment()!407 let back = try JSONDecoder().decode(DocumentFragment.self, from: JSONEncoder().encode(f))408 #expect(back == f)409 }410411 @Test func documentJSONRoundTrip() throws {412 var doc = makeDoc(["a"])413 doc.body.append(.table(Table(strings: [["x", "y"]], width: 300)))414 doc.body.append(.sectionBreak(SectionBreak(setup: PageSetup(columns: 2))))415 doc.body.append(.toc(TOCBlock()))416 doc.body.append(.paragraph(Paragraph(runs: [Run(inline: .equation(Equation(latex: "x^2", display: true))), Run(inline: .citation(Citation("k")))])))417 doc.bibliography = [BibEntry(key: "k", authors: [PersonName(family: "Doe", given: "J.")], year: 2020, fields: ["title": "T"])]418 let enc = JSONEncoder(); enc.dateEncodingStrategy = .iso8601419 let dec = JSONDecoder(); dec.dateDecodingStrategy = .iso8601420 doc.meta.created = Date(timeIntervalSince1970: 1_700_000_000); doc.meta.modified = doc.meta.created421 let back = try dec.decode(DocumentModel.self, from: enc.encode(doc))422 #expect(back == doc)423 }424}425