import Foundation import XCTest @testable import DocsKit #if os(macOS) import AppKit #else import UIKit #endif /// A `DocumentSurface` driven by hand: hooks that record, a model state the /// tests set, and helpers to build projections and publications. @MainActor final class SurfaceState { var pending = false var allowed: UInt64 = 1 var selection = NSRange(location: 0, length: 0) var acknowledgements: [UInt64] = [] var commands: [[String: JSONValue]] = [] var accept = true var markPendingOnEdit = true let surface = DocumentSurface() let text: DocsTextView var revision: UInt64 = 0 init(width: CGFloat = 500) { #if os(macOS) text = DocsTextView(frame: CGRect(x: 0, y: 0, width: width, height: 700)) #else text = DocsTextView(frame: CGRect(x: 0, y: 0, width: width, height: 700)) #endif var hooks = DocumentSurface.Hooks() hooks.edit = { [unowned self] command in if markPendingOnEdit { pending = true } commands.append(command); return accept } hooks.canRender = { [unowned self] generation in !pending && allowed == generation } hooks.currentSelection = { [unowned self] in selection } hooks.didRender = { [unowned self] generation in acknowledgements.append(generation) } hooks.selectionChanged = { [unowned self] range in selection = range } surface.hooks = hooks surface.isEditable = true surface.attach(text) } /// Publishes `projection` as the next revision. func publish(_ projection: CRDTProjection, generation: UInt64, dirty: Set?) { revision += 1 surface.apply(DocumentSurface.Publication(generation: generation, projection: projection, revision: revision, dirty: dirty)) } var string: String { surface.content.string } } enum SurfaceFixture { /// A long document the way fixtures/generate-large-doc.mjs builds one: /// five paragraphs with bold and italic runs a page, a heading every /// second page and a list every fifth. static func pages(_ count: Int) -> [CRDTNode] { var nodes: [CRDTNode] = [] let words = "water reservoir council minutes engineer filtration mains survey creek dam pumps cistern records town summer fever population".split(separator: " ") for page in 0.. CRDTNode { CRDTNode(id: id, type: "paragraph", attrs: attrs, children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text, marks: marks)])]) } static func heading(_ id: String, _ text: String, level: Int = 1) -> CRDTNode { CRDTNode(id: id, type: "heading", attrs: ["level": String(level)], children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text)])]) } static func list(_ id: String, _ type: String, _ items: [String]) -> CRDTNode { CRDTNode(id: id, type: type, children: items.enumerated().map { index, item in CRDTNode(id: "\(id)i\(index)", type: "list_item", children: [paragraph("\(id)p\(index)", item)]) }) } static func quote(_ id: String, _ items: [String]) -> CRDTNode { CRDTNode(id: id, type: "blockquote", children: items.enumerated().map { index, item in paragraph("\(id)p\(index)", item) }) } static func projection(_ nodes: [CRDTNode]) -> CRDTProjection { CRDTProjection(children: nodes, canUndo: false, canRedo: false) } /// Whether `storage` draws what a whole render of `projection` draws, /// attribute for attribute (lists and attachments by what they draw). @MainActor static func assertMatchesWholeRender(_ storage: NSAttributedString, _ projection: CRDTProjection, images: [String: DocsPlatformImage] = [:], _ message: String = "", file: StaticString = #filePath, line: UInt = #line) { // As a text view's storage holds it: TextKit fixes attributes (a // CJK character's font falls back, and UIKit notes the original), // so compare with the storage a whole render makes in a fresh one. let oracle = DocsTextView(frame: CGRect(x: 0, y: 0, width: 640, height: 700)) let whole = Keyboard.storage(of: oracle) whole.setAttributedString(NativeTextProjection.render(projection, images: images)) XCTAssertEqual(storage.string, whole.string, "text: \(message)", file: file, line: line) if storage.string == whole.string { let equivalent = DocumentRenderReconciliation.isEquivalent(storage, whole) if !equivalent { print("FIRST DIFFERENCE (\(message)): \(firstDifference(storage, whole))") } XCTAssertTrue(equivalent, "attributes differ from a whole render: \(message)", file: file, line: line) } } @MainActor static func firstDifference(_ a: NSAttributedString, _ b: NSAttributedString) -> String { var location = 0 while location < min(a.length, b.length) { var ra = NSRange(), rb = NSRange() let x = a.attributes(at: location, effectiveRange: &ra), y = b.attributes(at: location, effectiveRange: &rb) let single = NSAttributedString(string: (a.string as NSString).substring(with: NSRange(location: location, length: 1)), attributes: x) let other = NSAttributedString(string: (b.string as NSString).substring(with: NSRange(location: location, length: 1)), attributes: y) if !DocumentRenderReconciliation.isEquivalent(single, other) { return "at \(location) (\((a.string as NSString).substring(with: NSRange(location: location, length: 1)).debugDescription)):\n \(x)\n vs\n \(y)" } location = min(NSMaxRange(ra), NSMaxRange(rb)) } return "lengths \(a.length) / \(b.length)" } } /// The keyboard's path into a real `DocsTextView`, on both platforms. @MainActor enum Keyboard { static func select(_ range: NSRange, in text: DocsTextView) { #if os(macOS) text.setSelectedRange(range) #else text.selectedRange = range text.delegate?.textViewDidChangeSelection?(text) #endif } static func selection(_ text: DocsTextView) -> NSRange { #if os(macOS) text.selectedRange() #else text.selectedRange #endif } /// Types `characters` at the caret, one at a time, Return included. static func type(_ characters: String, in text: DocsTextView) { for character in characters { let piece = String(character) #if os(macOS) if piece == "\n" { text.insertNewline(nil) } else { text.insertText(piece, replacementRange: text.selectedRange()) } #else // UITextView.insertText from code skips the delegate: take the // keyboard's path by hand. let range = text.selectedRange if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: piece) ?? true { text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: piece, attributes: text.typingAttributes)) text.selectedRange = NSRange(location: range.location + piece.utf16.count, length: 0) text.delegate?.textViewDidChange?(text) } #endif } } static func backspace(in text: DocsTextView) { #if os(macOS) text.deleteBackward(nil) #else let caret = text.selectedRange guard caret.location > 0 || caret.length > 0 else { return } let range = caret.length > 0 ? caret : NSRange(location: caret.location - 1, length: 1) if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: "") ?? true { text.textStorage.replaceCharacters(in: range, with: "") text.selectedRange = NSRange(location: range.location, length: 0) text.delegate?.textViewDidChange?(text) } #endif } /// A rich paste of `blocks` at the selection, as `DocsTextView.paste` /// does it once the clipboard is read. static func paste(_ blocks: [JSONValue], in text: DocsTextView, surface: DocumentSurface) { let range = selection(text) guard let replacement = DocumentClipboardInsertion.attributed(blocks: blocks, in: surface.content, range: range), surface.clipboardEdit(blocks: blocks, range: range, replacement: replacement.string) else { return } storage(of: text).replaceCharacters(in: range, with: replacement) select(NSRange(location: range.location + replacement.length, length: 0), in: text) } /// A cut of the selection, as `DocsTextView.cut` does it once the /// clipboard is written. static func cutSelection(in text: DocsTextView, surface: DocumentSurface) { let range = selection(text) guard range.length > 0, surface.clipboardEdit(blocks: nil, range: range, replacement: "") else { return } storage(of: text).replaceCharacters(in: range, with: "") select(NSRange(location: range.location, length: 0), in: text) } static func storage(of text: DocsTextView) -> NSTextStorage { #if os(macOS) text.textStorage! #else text.textStorage #endif } } #if os(iOS) extension DocsTextView { func string() -> String { text } } #endif