| 1 | import Foundation |
| 2 | import XCTest |
| 3 | @testable import DocsKit |
| 4 | #if os(macOS) |
| 5 | import AppKit |
| 6 | #else |
| 7 | import UIKit |
| 8 | #endif |
| 9 | |
| 10 | /// A `DocumentSurface` driven by hand: hooks that record, a model state the |
| 11 | /// tests set, and helpers to build projections and publications. |
| 12 | @MainActor final class SurfaceState { |
| 13 | var pending = false |
| 14 | var allowed: UInt64 = 1 |
| 15 | var selection = NSRange(location: 0, length: 0) |
| 16 | var acknowledgements: [UInt64] = [] |
| 17 | var commands: [[String: JSONValue]] = [] |
| 18 | var accept = true |
| 19 | var markPendingOnEdit = true |
| 20 | let surface = DocumentSurface() |
| 21 | let text: DocsTextView |
| 22 | var revision: UInt64 = 0 |
| 23 | |
| 24 | init(width: CGFloat = 500) { |
| 25 | #if os(macOS) |
| 26 | text = DocsTextView(frame: CGRect(x: 0, y: 0, width: width, height: 700)) |
| 27 | #else |
| 28 | text = DocsTextView(frame: CGRect(x: 0, y: 0, width: width, height: 700)) |
| 29 | #endif |
| 30 | var hooks = DocumentSurface.Hooks() |
| 31 | hooks.edit = { [unowned self] command in |
| 32 | if markPendingOnEdit { pending = true } |
| 33 | commands.append(command); return accept |
| 34 | } |
| 35 | hooks.canRender = { [unowned self] generation in !pending && allowed == generation } |
| 36 | hooks.currentSelection = { [unowned self] in selection } |
| 37 | hooks.didRender = { [unowned self] generation in acknowledgements.append(generation) } |
| 38 | hooks.selectionChanged = { [unowned self] range in selection = range } |
| 39 | surface.hooks = hooks |
| 40 | surface.isEditable = true |
| 41 | surface.attach(text) |
| 42 | } |
| 43 | |
| 44 | /// Publishes `projection` as the next revision. |
| 45 | func publish(_ projection: CRDTProjection, generation: UInt64, dirty: Set<String>?) { |
| 46 | revision += 1 |
| 47 | surface.apply(DocumentSurface.Publication(generation: generation, projection: projection, revision: revision, dirty: dirty)) |
| 48 | } |
| 49 | |
| 50 | var string: String { surface.content.string } |
| 51 | } |
| 52 | |
| 53 | enum SurfaceFixture { |
| 54 | /// A long document the way fixtures/generate-large-doc.mjs builds one: |
| 55 | /// five paragraphs with bold and italic runs a page, a heading every |
| 56 | /// second page and a list every fifth. |
| 57 | static func pages(_ count: Int) -> [CRDTNode] { |
| 58 | var nodes: [CRDTNode] = [] |
| 59 | let words = "water reservoir council minutes engineer filtration mains survey creek dam pumps cistern records town summer fever population".split(separator: " ") |
| 60 | for page in 0..<count { |
| 61 | if page % 2 == 0 { nodes.append(SurfaceFixture.heading("h\(page)", "Section \(page / 2 + 1): the works in year \(1880 + page)", level: 2)) } |
| 62 | for paragraph in 0..<5 { |
| 63 | var runs: [CRDTRun] = [] |
| 64 | for sentence in 0..<6 { |
| 65 | let text = (0..<16).map { String(words[(page * 31 + paragraph * 7 + sentence * 3 + $0) % words.count]) }.joined(separator: " ") + ". " |
| 66 | let marks: [String: JSONValue]? = sentence == 2 ? ["strong": .object([:])] : sentence == 4 ? ["em": .object([:])] : nil |
| 67 | runs.append(CRDTRun(insert: text, marks: marks)) |
| 68 | } |
| 69 | nodes.append(CRDTNode(id: "p\(page)-\(paragraph)", type: "paragraph", children: [CRDTNode(id: "p\(page)-\(paragraph)t", type: "text", runs: runs)])) |
| 70 | } |
| 71 | if page % 5 == 4 { nodes.append(SurfaceFixture.list("l\(page)", "bullet_list", (1...4).map { "Item \($0) on page \(page + 1)" })) } |
| 72 | } |
| 73 | return nodes |
| 74 | } |
| 75 | |
| 76 | static func paragraph(_ id: String, _ text: String, marks: [String: JSONValue]? = nil, attrs: [String: String]? = nil) -> CRDTNode { |
| 77 | CRDTNode(id: id, type: "paragraph", attrs: attrs, children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text, marks: marks)])]) |
| 78 | } |
| 79 | static func heading(_ id: String, _ text: String, level: Int = 1) -> CRDTNode { |
| 80 | CRDTNode(id: id, type: "heading", attrs: ["level": String(level)], children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text)])]) |
| 81 | } |
| 82 | static func list(_ id: String, _ type: String, _ items: [String]) -> CRDTNode { |
| 83 | CRDTNode(id: id, type: type, children: items.enumerated().map { index, item in |
| 84 | CRDTNode(id: "\(id)i\(index)", type: "list_item", children: [paragraph("\(id)p\(index)", item)]) |
| 85 | }) |
| 86 | } |
| 87 | static func quote(_ id: String, _ items: [String]) -> CRDTNode { |
| 88 | CRDTNode(id: id, type: "blockquote", children: items.enumerated().map { index, item in paragraph("\(id)p\(index)", item) }) |
| 89 | } |
| 90 | static func projection(_ nodes: [CRDTNode]) -> CRDTProjection { CRDTProjection(children: nodes, canUndo: false, canRedo: false) } |
| 91 | |
| 92 | /// Whether `storage` draws what a whole render of `projection` draws, |
| 93 | /// attribute for attribute (lists and attachments by what they draw). |
| 94 | @MainActor static func assertMatchesWholeRender(_ storage: NSAttributedString, _ projection: CRDTProjection, images: [String: DocsPlatformImage] = [:], _ message: String = "", file: StaticString = #filePath, line: UInt = #line) { |
| 95 | // As a text view's storage holds it: TextKit fixes attributes (a |
| 96 | // CJK character's font falls back, and UIKit notes the original), |
| 97 | // so compare with the storage a whole render makes in a fresh one. |
| 98 | let oracle = DocsTextView(frame: CGRect(x: 0, y: 0, width: 640, height: 700)) |
| 99 | let whole = Keyboard.storage(of: oracle) |
| 100 | whole.setAttributedString(NativeTextProjection.render(projection, images: images)) |
| 101 | XCTAssertEqual(storage.string, whole.string, "text: \(message)", file: file, line: line) |
| 102 | if storage.string == whole.string { |
| 103 | let equivalent = DocumentRenderReconciliation.isEquivalent(storage, whole) |
| 104 | if !equivalent { print("FIRST DIFFERENCE (\(message)): \(firstDifference(storage, whole))") } |
| 105 | XCTAssertTrue(equivalent, "attributes differ from a whole render: \(message)", file: file, line: line) |
| 106 | } |
| 107 | } |
| 108 | @MainActor static func firstDifference(_ a: NSAttributedString, _ b: NSAttributedString) -> String { |
| 109 | var location = 0 |
| 110 | while location < min(a.length, b.length) { |
| 111 | var ra = NSRange(), rb = NSRange() |
| 112 | let x = a.attributes(at: location, effectiveRange: &ra), y = b.attributes(at: location, effectiveRange: &rb) |
| 113 | let single = NSAttributedString(string: (a.string as NSString).substring(with: NSRange(location: location, length: 1)), attributes: x) |
| 114 | let other = NSAttributedString(string: (b.string as NSString).substring(with: NSRange(location: location, length: 1)), attributes: y) |
| 115 | if !DocumentRenderReconciliation.isEquivalent(single, other) { |
| 116 | return "at \(location) (\((a.string as NSString).substring(with: NSRange(location: location, length: 1)).debugDescription)):\n \(x)\n vs\n \(y)" |
| 117 | } |
| 118 | location = min(NSMaxRange(ra), NSMaxRange(rb)) |
| 119 | } |
| 120 | return "lengths \(a.length) / \(b.length)" |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// The keyboard's path into a real `DocsTextView`, on both platforms. |
| 125 | @MainActor enum Keyboard { |
| 126 | static func select(_ range: NSRange, in text: DocsTextView) { |
| 127 | #if os(macOS) |
| 128 | text.setSelectedRange(range) |
| 129 | #else |
| 130 | text.selectedRange = range |
| 131 | text.delegate?.textViewDidChangeSelection?(text) |
| 132 | #endif |
| 133 | } |
| 134 | static func selection(_ text: DocsTextView) -> NSRange { |
| 135 | #if os(macOS) |
| 136 | text.selectedRange() |
| 137 | #else |
| 138 | text.selectedRange |
| 139 | #endif |
| 140 | } |
| 141 | /// Types `characters` at the caret, one at a time, Return included. |
| 142 | static func type(_ characters: String, in text: DocsTextView) { |
| 143 | for character in characters { |
| 144 | let piece = String(character) |
| 145 | #if os(macOS) |
| 146 | if piece == "\n" { text.insertNewline(nil) } else { text.insertText(piece, replacementRange: text.selectedRange()) } |
| 147 | #else |
| 148 | // UITextView.insertText from code skips the delegate: take the |
| 149 | // keyboard's path by hand. |
| 150 | let range = text.selectedRange |
| 151 | if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: piece) ?? true { |
| 152 | text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: piece, attributes: text.typingAttributes)) |
| 153 | text.selectedRange = NSRange(location: range.location + piece.utf16.count, length: 0) |
| 154 | text.delegate?.textViewDidChange?(text) |
| 155 | } |
| 156 | #endif |
| 157 | } |
| 158 | } |
| 159 | static func backspace(in text: DocsTextView) { |
| 160 | #if os(macOS) |
| 161 | text.deleteBackward(nil) |
| 162 | #else |
| 163 | let caret = text.selectedRange |
| 164 | guard caret.location > 0 || caret.length > 0 else { return } |
| 165 | let range = caret.length > 0 ? caret : NSRange(location: caret.location - 1, length: 1) |
| 166 | if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: "") ?? true { |
| 167 | text.textStorage.replaceCharacters(in: range, with: "") |
| 168 | text.selectedRange = NSRange(location: range.location, length: 0) |
| 169 | text.delegate?.textViewDidChange?(text) |
| 170 | } |
| 171 | #endif |
| 172 | } |
| 173 | /// A rich paste of `blocks` at the selection, as `DocsTextView.paste` |
| 174 | /// does it once the clipboard is read. |
| 175 | static func paste(_ blocks: [JSONValue], in text: DocsTextView, surface: DocumentSurface) { |
| 176 | let range = selection(text) |
| 177 | guard let replacement = DocumentClipboardInsertion.attributed(blocks: blocks, in: surface.content, range: range), |
| 178 | surface.clipboardEdit(blocks: blocks, range: range, replacement: replacement.string) else { return } |
| 179 | storage(of: text).replaceCharacters(in: range, with: replacement) |
| 180 | select(NSRange(location: range.location + replacement.length, length: 0), in: text) |
| 181 | } |
| 182 | /// A cut of the selection, as `DocsTextView.cut` does it once the |
| 183 | /// clipboard is written. |
| 184 | static func cutSelection(in text: DocsTextView, surface: DocumentSurface) { |
| 185 | let range = selection(text) |
| 186 | guard range.length > 0, surface.clipboardEdit(blocks: nil, range: range, replacement: "") else { return } |
| 187 | storage(of: text).replaceCharacters(in: range, with: "") |
| 188 | select(NSRange(location: range.location, length: 0), in: text) |
| 189 | } |
| 190 | static func storage(of text: DocsTextView) -> NSTextStorage { |
| 191 | #if os(macOS) |
| 192 | text.textStorage! |
| 193 | #else |
| 194 | text.textStorage |
| 195 | #endif |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | #if os(iOS) |
| 200 | extension DocsTextView { |
| 201 | func string() -> String { text } |
| 202 | } |
| 203 | #endif |
| 204 | |