Cotton code
348 lines · 19.9 KB · SwiftRaw
// The writing surface against a scripted core: it draws the spans it is// answered (the rule's own vectors among them) and nothing it is not, writes// a key's answer back as one undoable change, sends Return to the core, hides// a table's text behind its grid, and stays quick to type in on a 50,000// character note.@testable import CottonWritingimport UIKitimport XCTest/// A core that answers what the test set.private final class ScriptedRules: WritingRules, @unchecked Sendable {    var styler: (String, Int?) -> WritingStyled = { _, _ in WritingStyled() }    var presser: (WritingAsk) -> WritingChange = { _ in .nothing }    private(set) var asks: [WritingAsk] = []    private(set) var styleAsks = 0    func style(_ text: String, cursor: Int?) async throws -> WritingStyled {        styleAsks += 1        return styler(text, cursor)    }    func press(_ ask: WritingAsk) async throws -> WritingChange {        asks.append(ask)        return presser(ask)    }    func tags(_ prefix: String) async throws -> [WritingTagOffer] { [] }    func written(_ tag: String) -> String { "#" + tag }}private struct NoMedia: WritingMedia {    func image(_ src: String, width: CGFloat) async -> UIImage? { nil }    func add(_ file: URL, text: String, selection: NSRange) async throws -> WritingChange { .nothing }}@MainActorfinal class WritingEditorTests: XCTestCase {    private var windows: [UIWindow] = []    static let theme = WritingTheme(id: "t", name: "Test", dark: false, colours: .init(        ground: "#FFFFFF", text: "#2E2E31", heading: "#1C1C1E", secondary: "#8A8A8F", accent: "#D2453A", rule: "#E7E7E9",        highlight: "#FFE7A3", codeGround: "#F4F4F5", selection: "#F7D4D0"))    static let type = WritingType(face: "sans", size: 17, lineHeight: 1.5, width: 72)    static let words = WritingWords(        bar: [WritingKey(id: "undo", label: "Undo", icon: "undo"), WritingKey(id: "format", label: "Formatting", icon: "format")],        panel: [WritingKey(id: "bold", label: "Bold", glyph: "B", style: "bold", action: WritingAction("bold"))],        shortcuts: [WritingShortcut(key: "b", does: "bold")],        words: ["hint": "Start writing", "add_row": "Add a row", "add_column": "Add a column"])    private func editor(_ rules: ScriptedRules) -> WritingEditor {        let editor = WritingEditor(rules: rules, media: NoMedia(), words: Self.words, look: WritingLook(theme: Self.theme, type: Self.type))        let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first!        let window = UIWindow(windowScene: scene)        window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)        windows.append(window)        editor.textView.frame = window.bounds        window.addSubview(editor.textView)        window.isHidden = false        return editor    }    private func settle(_ editor: WritingEditor, until: @escaping () -> Bool) async {        for _ in 0..<300 where !until() { try? await Task.sleep(for: .milliseconds(10)) }        editor.textView.layoutIfNeeded()    }    private func attribute(_ editor: WritingEditor, _ key: NSAttributedString.Key, at index: Int) -> Any? {        editor.textView.textStorage.attribute(key, at: index, effectiveRange: nil)    }    private func font(_ editor: WritingEditor, at index: Int) -> UIFont? { attribute(editor, .font, at: index) as? UIFont }    // MARK: The rule's own vectors    /// `crates/cotton-rules/src/writing/vectors.json`, read where it lies in the checkout.    private static func vectors() throws -> [[String: Any]] {        let here = URL(fileURLWithPath: #filePath)        let file = here.deletingLastPathComponent().appendingPathComponent("../../../../crates/cotton-rules/src/writing/vectors.json").standardized        let all = try JSONSerialization.jsonObject(with: Data(contentsOf: file)) as? [String: Any]        return all?["style"] as? [[String: Any]] ?? []    }    /// "0-2 mark dim", "2-7 title text 1", "16-22 mark glyph box", "28-31 image text" as a span.    private static func span(_ said: String) -> WritingSpan {        let parts = said.split(separator: " ").map(String.init)        let ends = parts[0].split(separator: "-").compactMap { Int($0) }        var span = WritingSpan(start: ends[0], end: ends[1], style: parts[1], look: parts[2])        if parts.count > 3 {            if let level = Int(parts[3]) { span.level = level } else { span.glyph = parts[3] }        }        return span    }    /// "0-7 heading 0 level1 title", "26-41 picture 0 src=media:x" as a block.    private static func block(_ said: String) -> WritingBlock {        let parts = said.split(separator: " ").map(String.init)        let ends = parts[0].split(separator: "-").compactMap { Int($0) }        var block = WritingBlock(start: ends[0], end: ends[1], kind: parts[1], depth: Int(parts[2]) ?? 0)        for part in parts.dropFirst(3) {            if part.hasPrefix("level") { block.level = Int(part.dropFirst(5)) }            if part == "title" { block.title = true }            if part == "open" { block.checked = false }            if part == "ticked" { block.checked = true }            if part.hasPrefix("src=") { block.src = String(part.dropFirst(4)) }            if part.hasPrefix("n"), let n = Int(part.dropFirst()) { block.number = n }        }        return block    }    func testEveryStyleVectorIsDrawnAsTheRuleSays() async throws {        let vectors = try Self.vectors()        XCTAssertFalse(vectors.isEmpty, "the rule's vectors are read")        for vector in vectors {            let name = vector["name"] as? String ?? "?"            let text = vector["text"] as? String ?? ""            let spans = (vector["spans"] as? [String] ?? []).map(Self.span)            let blocks = (vector["blocks"] as? [String] ?? []).map(Self.block)            let tables = try (vector["tables"] as? [Any]).map {                try JSONDecoder().decode([WritingTable].self, from: JSONSerialization.data(withJSONObject: $0))            } ?? []            let rules = ScriptedRules()            rules.styler = { _, _ in WritingStyled(blocks: blocks, spans: spans, tables: tables) }            let editor = editor(rules)            editor.load(text)            await settle(editor) { editor.drawn != nil }            XCTAssertNotNil(editor.drawn, name)            let inBlock = { (at: Int) in                tables.contains { at >= $0.start && at < $0.end } || blocks.contains { $0.kind == "picture" && at >= $0.start && at < $0.end }            }            // A span's own look shows where no hidden or glyph mark lies over it.            let marked = spans.filter { $0.look == "hidden" || $0.look == "glyph" }            let shown = { (span: WritingSpan) -> Int? in                if span.look != "text" { return span.start }                return (span.start..<span.end).first { at in !marked.contains { $0.start <= at && at < $0.end } }            }            for span in spans where span.end > span.start && !inBlock(span.start) {                guard let at = shown(span) else { continue }                let colour = attribute(editor, .foregroundColor, at: at) as? UIColor                switch span.look {                case "hidden":                    XCTAssertEqual(colour, .clear, "\(name): \(span.start)-\(span.end) \(span.style) is hidden")                    XCTAssertLessThan(font(editor, at: at)?.pointSize ?? 99, 1, "\(name): a hidden mark takes no room")                case "dim":                    XCTAssertEqual(colour, Self.theme.faint, "\(name): \(span.start)-\(span.end) is dim at the cursor")                case "glyph":                    XCTAssertEqual(attribute(editor, .writingGlyph, at: at) as? String, span.glyph, "\(name): a glyph is drawn")                default:                    switch span.style {                    case "bold": XCTAssertTrue(font(editor, at: at)?.fontDescriptor.symbolicTraits.contains(.traitBold) == true, "\(name): bold")                    case "italic": XCTAssertTrue(font(editor, at: at)?.fontDescriptor.symbolicTraits.contains(.traitItalic) == true, "\(name): italic")                    case "title": XCTAssertGreaterThan(font(editor, at: at)?.pointSize ?? 0, editor.look.body.pointSize * 1.3, "\(name): the title is large")                    case "tag": XCTAssertNotNil(attribute(editor, .writingChip, at: at), "\(name): a tag wears its chip")                    case "highlight": XCTAssertEqual(attribute(editor, .backgroundColor, at: at) as? UIColor, Self.theme.highlight, "\(name): highlight")                    default: break                    }                }            }            for table in tables {                XCTAssertNotNil(attribute(editor, .writingBlock, at: table.start), "\(name): a table's text is behind its grid")                XCTAssertTrue(editor.textView.subviews.contains { $0 is WritingTableBlock }, "\(name): the table is a grid")            }            for block in blocks where block.kind == "picture" {                XCTAssertNotNil(attribute(editor, .writingBlock, at: block.start), "\(name): a picture stands in for its line")            }        }    }    /// RULE (FEEDBACK-4 C1): a tap on a tag's chip names the tag (its marks off) for the host to open its list; a tap    /// on other words names none, and a host that opens no tags is never asked.    func testATappedTagIsNamed() async {        let text = "Market day\nBring #errands and #two words# home"        let ns = text as NSString        let one = ns.range(of: "#errands"), two = ns.range(of: "#two words#")        let rules = ScriptedRules()        rules.styler = { _, _ in WritingStyled(spans: [            WritingSpan(start: one.location, end: NSMaxRange(one), style: "tag"),            WritingSpan(start: two.location, end: NSMaxRange(two), style: "tag"),        ]) }        let editor = editor(rules)        editor.load(text)        await settle(editor) { editor.drawn != nil }        func centre(of range: NSRange) -> CGPoint {            let layout = editor.textView.layoutManager, inset = editor.textView.textContainerInset            let glyphs = layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil)            let rect = layout.boundingRect(forGlyphRange: glyphs, in: editor.textView.textContainer)            return CGPoint(x: rect.midX + inset.left, y: rect.midY + inset.top)        }        XCTAssertNil(editor.tappedTag(at: centre(of: one)), "a host that opens no tags is not asked")        editor.onOpenTag = { _ in }        XCTAssertEqual(editor.tappedTag(at: centre(of: one)), "errands")        XCTAssertEqual(editor.tappedTag(at: centre(of: two)), "two words")        XCTAssertNil(editor.tappedTag(at: centre(of: ns.range(of: "Bring"))), "other words are no tag")        XCTAssertEqual(WritingEditor.tagName("#home/garden"), "home/garden")        XCTAssertNil(WritingEditor.tagName("#"))    }    /// RULE (FEEDBACK-4 C2): the bar's `#` types `#` at the caret (a space first when it would join a word), so the tag    /// goes on in the text and its offers stand in the bar; nothing is raised over the text.    func testTheTagKeyTypesAHash() async {        let rules = ScriptedRules()        let editor = editor(rules)        editor.load("Market day\nBring")        await settle(editor) { editor.drawn != nil }        editor.textView.selectedRange = NSRange(location: editor.text.utf16.count, length: 0)        editor.press(WritingKey(id: "tag", label: "Tag", icon: "tag"))        XCTAssertEqual(editor.text, "Market day\nBring #")        editor.textView.insertText("\n")        editor.press(WritingKey(id: "tag", label: "Tag", icon: "tag"))        XCTAssertEqual(editor.text, "Market day\nBring #\n#", "a line's start takes no space")    }    /// RULE (launch-ios walk, 22 Nov 2026): a list item's words start a clear gap after its bullet, box or number,    /// and a wrapped line starts exactly under the first line's words.    func testAListItemsWordsHangUnderTheirFirstWord() async {        let long = "words enough to wrap onto a second line on a phone of any width at all"        let text = "- \(long)\n- [ ] \(long)\n12. \(long)"        let check = 3 + long.count        let numbered = check + 7 + long.count        let rules = ScriptedRules()        rules.styler = { _, _ in WritingStyled(blocks: [            WritingBlock(start: 0, end: 2 + long.count, kind: "bullet", content: 2),            WritingBlock(start: check, end: check + 6 + long.count, kind: "check", content: check + 6, checked: false),            WritingBlock(start: numbered, end: numbered + 4 + long.count, kind: "numbered", content: numbered + 4, number: 12),        ], spans: [            WritingSpan(start: 0, end: 2, style: "mark", look: "glyph", glyph: "bullet"),            WritingSpan(start: check, end: check + 6, style: "mark", look: "glyph", glyph: "box"),            WritingSpan(start: numbered, end: numbered + 4, style: "number"),        ], tables: []) }        let editor = editor(rules)        editor.load(text)        await settle(editor) { editor.drawn != nil }        let layout = editor.textView.layoutManager        for (start, content) in [(0, 2), (check, check + 6), (numbered, numbered + 4)] {            let style = attribute(editor, .paragraphStyle, at: start) as? NSParagraphStyle            let first = layout.location(forGlyphAt: layout.glyphIndexForCharacter(at: content)).x            let lineFragment = layout.lineFragmentRect(forGlyphAt: layout.glyphIndexForCharacter(at: content), effectiveRange: nil)            let padding = editor.textView.textContainer.lineFragmentPadding            XCTAssertEqual(lineFragment.minX + first - padding, style?.headIndent ?? -1, accuracy: 0.6, "item at \(start): the first word starts where wrapped lines do")            XCTAssertGreaterThanOrEqual(style?.headIndent ?? 0, editor.look.size * 1.6 - 0.5, "item at \(start): a clear gap after the marker")            if start != numbered { XCTAssertEqual(style?.headIndent ?? 0, editor.look.size * 1.6, accuracy: 0.5, "item at \(start): a bullet and a box line up") }            let wrapped = layout.lineFragmentUsedRect(forGlyphAt: layout.glyphIndexForCharacter(at: content + long.count - 2), effectiveRange: nil)            XCTAssertGreaterThan(wrapped.minY, lineFragment.minY, "item at \(start): the line wraps")        }    }    /// RULE (launch-ios walk, 22 Nov 2026): a theme's sample in Settings draws its checklist's box, its bullet, as symbols:    /// a label cannot draw the editor's glyphs, and the sample showed struck words with no box.    func testASampleDrawsItsMarksAsSymbols() {        let text = "- [x] Checklist\n- Bullet"        let styled = WritingStyled(blocks: [            WritingBlock(start: 0, end: 15, kind: "check", content: 6, checked: true),            WritingBlock(start: 16, end: 24, kind: "bullet", content: 18),        ], spans: [            WritingSpan(start: 0, end: 6, style: "mark", look: "glyph", glyph: "ticked"),            WritingSpan(start: 6, end: 15, style: "done"),            WritingSpan(start: 16, end: 18, style: "mark", look: "glyph", glyph: "bullet"),        ], tables: [])        let drawn = writingAttributed(text, styled: styled, look: WritingLook(theme: Self.theme, type: Self.type))        var attachments = 0        drawn.enumerateAttribute(.attachment, in: NSRange(location: 0, length: drawn.length)) { value, _, _ in if value != nil { attachments += 1 } }        XCTAssertEqual(attachments, 2, "a box and a bullet, drawn")        XCTAssertFalse(drawn.string.contains("[x]"), "the mark's characters are gone: \(drawn.string)")        XCTAssertTrue(drawn.string.contains("Checklist") && drawn.string.contains("Bullet"))    }    // MARK: Keys    func testAKeyIsTheCoresAndUndoTakesItBack() async {        let rules = ScriptedRules()        rules.presser = { ask in            XCTAssertEqual(ask.action.name, "bold")            return WritingChange(text: "a **b** c", replace: WritingReplace(start: 2, end: 3, with: "**b**"), selection: WritingSelection(start: 4, end: 5))        }        let editor = editor(rules)        editor.load("a b c")        editor.textView.selectedRange = NSRange(location: 2, length: 1)        editor.press(Self.words.panel[0])        await settle(editor) { editor.text == "a **b** c" }        XCTAssertEqual(editor.text, "a **b** c")        XCTAssertEqual(rules.asks.first.map { [$0.start, $0.end] }, [2, 3])        XCTAssertEqual(editor.textView.selectedRange, NSRange(location: 4, length: 1))        editor.textView.undoManager?.undo()        XCTAssertEqual(editor.text, "a b c")    }    func testReturnIsTheCores() async {        let rules = ScriptedRules()        rules.presser = { ask in            WritingChange(text: ask.text + "\n- ", replace: WritingReplace(start: ask.start, end: ask.end, with: "\n- "),                          selection: WritingSelection(start: ask.start + 3, end: ask.start + 3))        }        let editor = editor(rules)        editor.load("- milk")        editor.textView.becomeFirstResponder()        editor.textView.selectedRange = NSRange(location: 6, length: 0)        _ = editor.textView(editor.textView, shouldChangeTextIn: NSRange(location: 6, length: 0), replacementText: "\n")        await settle(editor) { editor.text == "- milk\n- " }        XCTAssertEqual(rules.asks.map(\.action.name), ["return"])        XCTAssertEqual(editor.text, "- milk\n- ", "the list goes on, as the core said")    }    // MARK: Fifty thousand characters    /// Typing on a 50,000 character note: each keystroke and each restyle, measured.    func testTypingStaysQuickOnFiftyThousandCharacters() async {        let paragraph = "Some words with **bold** and a #tag in them, then more words to read.\n"        let text = String(repeating: paragraph, count: 50_000 / paragraph.count + 1)        let unit = paragraph.utf16.count        let rules = ScriptedRules()        rules.styler = { text, _ in            let count = text.utf16.count / unit            var spans: [WritingSpan] = []            var blocks: [WritingBlock] = []            for i in 0..<count {                let at = i * unit                blocks.append(WritingBlock(start: at, end: at + unit - 1, kind: "paragraph"))                spans += [WritingSpan(start: at + 16, end: at + 18, style: "mark", look: "hidden"), WritingSpan(start: at + 18, end: at + 22, style: "bold"),                          WritingSpan(start: at + 22, end: at + 24, style: "mark", look: "hidden"), WritingSpan(start: at + 31, end: at + 35, style: "tag")]            }            return WritingStyled(blocks: blocks, spans: spans)        }        let editor = editor(rules)        editor.load(text)        await settle(editor) { !editor.restyleTimes.isEmpty }        editor.textView.becomeFirstResponder()        editor.textView.selectedRange = NSRange(location: 25_000, length: 0)        await settle(editor) { editor.restyleTimes.count > 1 }        var typed: [Double] = []        for letter in "quick brown fox" {            let before = CACurrentMediaTime()            editor.textView.insertText(String(letter))            editor.textView.layoutIfNeeded()            typed.append((CACurrentMediaTime() - before) * 1000)            let drawn = editor.restyleTimes.count            await settle(editor) { editor.restyleTimes.count > drawn }        }        let restyles = Array(editor.restyleTimes.dropFirst(2))        let worstKey = typed.max() ?? 0        let worstRestyle = restyles.max() ?? 0        let figure = "WRITING-50K chars=\(text.utf16.count) keys_ms=\(typed.map { String(format: "%.2f", $0) }.joined(separator: ",")) restyles_ms=\(restyles.map { String(format: "%.2f", $0) }.joined(separator: ",")) first_draw_ms=\(String(format: "%.1f", editor.restyleTimes.first ?? 0))"        print(figure)        // Where the run asked for the figure (`TEST_RUNNER_WRITING_MEASURE=<path>`), it is written there too.        if let path = ProcessInfo.processInfo.environment["WRITING_MEASURE"] { try? figure.write(toFile: path, atomically: true, encoding: .utf8) }        XCTAssertLessThan(worstKey, 16, "a keystroke lands within a frame")        XCTAssertLessThan(worstRestyle, 16, "a restyle after a keystroke fits in a frame")    }}