Cotton code
491 lines · 30.9 KB · SwiftRaw
// The reader a note, a memory or a book opens on (owner, 26 Oct 2026; the centred page and the lamp, 29 Oct): pages// filled by measure, broken only at a sentence's end, a paragraph that fits// never split, a list kept a list, a short body whole, and a memory's one// sentence then its quote; the head centred in the typewriter level with the// ×, the words ranged left and centred in their room, no folio, no binding.// Invented words and tables.#if os(iOS)import CottonFacesimport CottonKitimport CottonPaperimport CottonValuesimport ImageIOimport UIKitimport XCTest@testable import CottonUI@MainActorfinal class ReadPageTests: XCTestCase {    /// `count` words of a sentence, numbered so no two are alike, its first    /// capitalised as a sentence's is.    private func sentence(_ n: Int, words count: Int) -> String {        (1...count).map { ($0 == 1 ? "W" : "w") + "\(n)x\($0)" }.joined(separator: " ") + "."    }    private func paragraph(_ n: Int, sentences: Int, words: Int) -> String {        (1...sentences).map { sentence(n * 100 + $0, words: words) }.joined(separator: " ")    }    /// A phone's safe area with the status bar hidden: 402 by 874, less the    /// island's 62 and the home bar's 34.    private static let phone = CGSize(width: 402, height: 874 - 62 - 34)    // MARK: The measure    /// RULE: A page holds half the words its text block takes — a word being its letters and the space after it — a few sentences with empty paper around them, so a phone's screen at the reader's size holds about 40 to 60.    func testThePageHoldsAComfortableDepth() {        XCTAssertEqual(ReadPages.words(columns: 26, lines: 16), 36)        XCTAssertEqual(ReadPages.words(columns: 24, lines: 12), 25)        XCTAssertEqual(ReadPages.words(columns: 8, lines: 1), 1)    }    /// RULE: On a phone's screen, in Caslon at the reader's size and pitch, the room between the head and the progress line holds between 40 and 60 words.    func testAPhonesScreenHoldsFortyToSixty() {        let room = ReadGeometry(size: Self.phone, byline: false, titled: false).room        let words = ReadPages.words(width: room.width, height: room.height)        XCTAssertTrue((40...60).contains(words), "a page of \(words) words")    }    /// RULE: The reader's words are Libre Caslon at 22 points, their lines 1.45 of that apart, RANGED LEFT (the narrow column justified gave loose lines); print stays at that size whatever the text size.    func testTheWordsAreCaslonRangedLeftAtAReadingSize() throws {        XCTAssertEqual(ReadPageKnobs.bodySize, 22)        XCTAssertEqual(ReadText.font.fontName, "LibreCaslonText-Regular")        XCTAssertEqual(ReadText.pitch, 32)        let set = ReadText.setting("Two sentences. Set as the page sets them.", ink: .black)        let style = try XCTUnwrap(set.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle)        XCTAssertEqual(style.alignment, .natural)        XCTAssertEqual(style.minimumLineHeight, ReadText.pitch)        XCTAssertEqual(style.maximumLineHeight, ReadText.pitch)    }    /// RULE: A list's item is ranged left as every line is, its run-on lines hung under its words; the paragraph around it is not hung.    func testAListsItemIsRangedLeftAndHung() throws {        let set = ReadText.setting("Seeds to sow in the first week:\n- fenugreek, by the kitchen step\n12. long beans, along the wall", ink: .black)        func style(at text: String) throws -> NSParagraphStyle {            let at = (set.string as NSString).range(of: text).location            return try XCTUnwrap(set.attribute(.paragraphStyle, at: at, effectiveRange: nil) as? NSParagraphStyle)        }        XCTAssertEqual(try style(at: "Seeds").alignment, .natural)        XCTAssertEqual(try style(at: "Seeds").headIndent, 0)        let dash = try style(at: "- fenugreek")        XCTAssertEqual(dash.alignment, .natural, "an item is ranged left")        XCTAssertEqual(dash.firstLineHeadIndent, 0)        XCTAssertEqual(dash.headIndent, ("- " as NSString).size(withAttributes: [.font: ReadText.font]).width, accuracy: 0.01, "its run-on lines hang under its words")        XCTAssertEqual(try style(at: "12. long").headIndent, ("12. " as NSString).size(withAttributes: [.font: ReadText.font]).width, accuracy: 0.01)        XCTAssertEqual(set.string, "Seeds to sow in the first week:\n- fenugreek, by the kitchen step\n12. long beans, along the wall", "the words are the page's, unchanged")        XCTAssertEqual(try style(at: "fenugreek").minimumLineHeight, ReadText.pitch, "an item keeps the page's pitch")    }    // MARK: The layout    /// RULE: The running head is centred across the screen at its very top, its middle level with the ×'s, in the typewriter (Courier Prime) at 11 points, clear of the × at both sides; the page has no folio.    func testTheHeadIsCentredInTheTypewriterLevelWithTheClose() throws {        let page = ReadGeometry(size: Self.phone, byline: false)        XCTAssertEqual(page.head.midX, Self.phone.width / 2, accuracy: 0.001, "the head is centred")        XCTAssertEqual(page.head.minY, page.close.maxY + ReadPageKnobs.margin, accuracy: 0.001)        XCTAssertEqual(page.head.minX, ReadPageKnobs.margin)        XCTAssertEqual(ReadText.headFont.fontName, "CourierPrime-Regular")        XCTAssertEqual(ReadText.headFont.pointSize, 11)        let root = SourceSweep.iosSources.deletingLastPathComponent()        let code = try String(contentsOf: root.appendingPathComponent("Sources/CottonUI/Deck/ReadPage.swift"), encoding: .utf8)        XCTAssertFalse(SourceSweep.withoutComments(code).contains("folio"), "the page has no folio")    }    /// RULE: The words stand centred vertically in their room between the head and the progress line — a short note in the middle of the page — and a block taller than the room starts at its top, so it never stands over the head; the room is clear of the head, the byline and the progress line.    func testTheFirstLineStartsBelowTheControlRowAndOneMargin() {        let page = ReadGeometry(size: Self.phone, byline: false)        let room = page.room        XCTAssertGreaterThan(room.minY, page.head.maxY)        XCTAssertGreaterThan(room.minY, page.close.maxY)        XCTAssertLessThan(room.maxY, page.progress.minY)        XCTAssertEqual(room.minX, ReadPageKnobs.margin)        XCTAssertEqual(room.maxX, Self.phone.width - ReadPageKnobs.margin, "the margins are one at either side")        let untitled = ReadGeometry(size: Self.phone, byline: false, titled: false)        XCTAssertEqual(untitled.blockTop(ReadText.pitch), untitled.close.maxY + ReadPageKnobs.margin)        let short = 2 * ReadText.pitch        XCTAssertEqual(page.blockTop(short), room.minY)        let full = room.height / 2        XCTAssertEqual(page.blockTop(full), room.minY)        XCTAssertEqual(page.blockTop(room.height + 100), room.minY, "a block taller than its room starts at the room's top")        let bylined = ReadGeometry(size: Self.phone, byline: true)        XCTAssertGreaterThan(bylined.room.minY, bylined.bylineLine.maxY, "the words never stand over the byline")        XCTAssertEqual(bylined.bylineLine.midX, Self.phone.width / 2, accuracy: 0.001, "the byline is centred under the head")    }    // MARK: The turn    /// RULE: A tap on the right third turns to the next page and on the left third back, the middle third does nothing, and neither end is passed.    func testATapTurnsByTheThirds() {        let width: CGFloat = 402        XCTAssertEqual(ReadTurn.page(after: 380, width: width, at: 1, of: 5), 2)        XCTAssertEqual(ReadTurn.page(after: 20, width: width, at: 1, of: 5), 0)        XCTAssertEqual(ReadTurn.page(after: 201, width: width, at: 1, of: 5), 1)        XCTAssertEqual(ReadTurn.page(after: 380, width: width, at: 4, of: 5), 4)        XCTAssertEqual(ReadTurn.page(after: 20, width: width, at: 0, of: 5), 0)        XCTAssertEqual(ReadTurn.page(after: 380, width: width, at: 0, of: 1), 0)    }    /// RULE: The progress line is the pages read — this one counted — over the pages: a third along on page 1 of 3, whole on the last page or on a page that is the whole body.    func testTheProgressIsThePagesRead() {        XCTAssertEqual(ReadTurn.progress(at: 0, of: 3), 1.0 / 3, accuracy: 0.0001)        XCTAssertEqual(ReadTurn.progress(at: 1, of: 5), 0.4, accuracy: 0.0001)        XCTAssertEqual(ReadTurn.progress(at: 2, of: 3), 1)        XCTAssertEqual(ReadTurn.progress(at: 0, of: 1), 1)        XCTAssertEqual(ReadTurn.progress(at: 0, of: 0), 0)    }    // MARK: The light    /// RULE: The reader follows the theme's appearance: the page in light, the lamp in dark — its ink the off-white and its marks the dim amber.    func testTheLightFollowsTheAppearance() {        XCTAssertEqual(ReadLight.of(.light), .page)        XCTAssertEqual(ReadLight.of(.dark), .lamp)        XCTAssertEqual(ReadLight.lamp.ink, ReaderMaterial.lampInk.colour)        XCTAssertEqual(ReadLight.lamp.marks, ReaderMaterial.amber.colour)        XCTAssertEqual(ReadLight.page.ink, ReaderMaterial.ink.colour)    }    /// RULE: No binding and no stacked page edges: the reader's materials are the page's cream and ink and the lamp's paper, pool, ink and amber, and nothing else.    func testThePageHasNoBindingAndNoEdges() {        XCTAssertEqual(ReaderMaterial.allCases, [.paper, .ink, .night, .pool, .lampInk, .amber])    }    /// RULE: Both papers are tiles in the catalogue, small: under 1 MB together.    func testThePapersAreTilesAndSmall() throws {        for name in ["reader-paper", "reader-night"] {            XCTAssertNotNil(CottonMedia.image(name, scale: 3), "\(name) is not in the catalogue")        }        let bytes = try ["reader-paper", "reader-night"].reduce(0) { sum, name in            let files = try FileManager.default.contentsOfDirectory(at: Self.imageset(name), includingPropertiesForKeys: [.fileSizeKey])            return try sum + files.reduce(0) { $0 + (try $1.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) }        }        XCTAssertLessThan(bytes, 1 << 20)    }    /// RULE: The day paper is a plain cream with the faintest grain, never "paper": its mean the cream's colour, its grain under a level and a half of brightness, and no mottle — the grain averaged over a few points is flat.    func testTheDayPaperIsPlainCreamWithTheFaintestGrain() throws {        let folder = Self.imageset("reader-paper")        let file = try XCTUnwrap(try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil).first { $0.pathExtension != "json" })        let source = try XCTUnwrap(CGImageSourceCreateWithURL(file as CFURL, nil))        let image = try XCTUnwrap(CGImageSourceCreateImageAtIndex(source, 0, nil))        let width = image.width, height = image.height        var pixels = [UInt8](repeating: 0, count: width * height * 4)        let context = try XCTUnwrap(CGContext(data: &pixels, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,                                              space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))        context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))        func brightness(_ x: Int, _ y: Int) -> Double {            let at = (y * width + x) * 4            return 0.2126 * Double(pixels[at]) + 0.7152 * Double(pixels[at + 1]) + 0.0722 * Double(pixels[at + 2])        }        var red = 0.0, green = 0.0, blue = 0.0        for at in stride(from: 0, to: pixels.count, by: 4) {            red += Double(pixels[at]); green += Double(pixels[at + 1]); blue += Double(pixels[at + 2])        }        let count = Double(width * height)        var cream = (red: CGFloat(0), green: CGFloat(0), blue: CGFloat(0), alpha: CGFloat(0))        UIColor(ReaderMaterial.paper.colour).getRed(&cream.red, green: &cream.green, blue: &cream.blue, alpha: &cream.alpha)        XCTAssertEqual(red / count, Double(cream.red) * 255, accuracy: 1, "the tile's mean is the cream")        XCTAssertEqual(green / count, Double(cream.green) * 255, accuracy: 1)        XCTAssertEqual(blue / count, Double(cream.blue) * 255, accuracy: 1)        let all = (0..<height).flatMap { y in (0..<width).map { brightness($0, y) } }        let mean = all.reduce(0, +) / count        let spread = (all.reduce(0) { $0 + ($1 - mean) * ($1 - mean) } / count).squareRoot()        XCTAssertLessThan(spread, 1.5, "the grain is the faintest")        let block = 16        let blocks = stride(from: 0, to: height - block + 1, by: block).flatMap { y in            stride(from: 0, to: width - block + 1, by: block).map { x in                (y..<(y + block)).reduce(0.0) { sum, row in sum + (x..<(x + block)).reduce(0.0) { $0 + brightness($1, row) } } / Double(block * block)            }        }        let blockMean = blocks.reduce(0, +) / Double(blocks.count)        let mottle = (blocks.reduce(0) { $0 + ($1 - blockMean) * ($1 - blockMean) } / Double(blocks.count)).squareRoot()        XCTAssertLessThan(mottle, 0.3, "no mottle: the paper reads as a colour, not as paper")    }    private static func imageset(_ name: String) -> URL {        SourceSweep.repoRoot.appendingPathComponent("apps/loom/Sources/CottonPaper/Media.xcassets/\(name).imageset")    }    // MARK: The rule    /// RULE: A body that fits on a page stands whole, as written.    func testAShortBodyIsOnePage() {        let note = "Call the plumber before Friday. The tap drips."        XCTAssertEqual(ReadPages.cut(note, words: 50), [note])    }    /// RULE: Paragraphs go on a page whole while they fit; one that fits on a page by itself is never split — it starts the next.    func testAParagraphThatFitsIsNeverSplit() {        let one = paragraph(1, sentences: 2, words: 10)        let two = paragraph(2, sentences: 2, words: 10)        let three = paragraph(3, sentences: 2, words: 10)        let pages = ReadPages.cut([one, two, three].joined(separator: "\n\n"), words: 50)        XCTAssertEqual(pages, [one + "\n\n" + two, three])    }    /// RULE: A paragraph too long for any page is poured on a sentence at a time: a page breaks only at a sentence's end, and no sentence is lost or cut.    func testALongParagraphBreaksOnlyAtASentencesEnd() {        let sentences = (1...6).map { sentence($0, words: 15) }        let pages = ReadPages.cut(sentences.joined(separator: " "), words: 50)        XCTAssertEqual(pages, [sentences[0...2].joined(separator: " "), sentences[3...5].joined(separator: " ")])        for page in pages { XCTAssertTrue(page.hasSuffix("."), "a page broke mid-sentence: \(page)") }    }    /// RULE: A sentence longer than a page stands on a page of its own rather than being cut.    func testASentenceLongerThanAPageIsNotCut() {        let long = sentence(1, words: 70)        let short = sentence(2, words: 5)        XCTAssertEqual(ReadPages.cut(short + " " + long + " " + short, words: 50), [short, long, short])    }    /// RULE: A list stays a list: its lines are kept as written, and a list too long for a page turns only between two items.    func testAListStaysAList() {        let short = "Before the trip:\n- passports\n- the charger\n1. book the cab"        XCTAssertEqual(ReadPages.cut(short, words: 50), [short])        let items = (1...12).map { "- " + (1...6).map { "i\($0)y\($0)" }.joined(separator: " ") + " \($0)" }        let pages = ReadPages.cut((["Pack:"] + items).joined(separator: "\n"), words: 30)        XCTAssertGreaterThan(pages.count, 1)        for page in pages {            for line in page.components(separatedBy: "\n") {                XCTAssertTrue(line == "Pack:" || line.hasPrefix("- "), "an item was cut: \(line)")            }        }        XCTAssertEqual(pages.flatMap { $0.components(separatedBy: "\n") }, ["Pack:"] + items)    }    /// RULE: Every body starts its own pages: a memory's one sentence is its first page and the quote behind it the next.    func testAMemoryIsItsSentenceThenItsQuote() {        let said = "Lunch with the team moves to Thursdays."        let quote = "From the standup: \u{201C}Thursdays work better for everyone.\u{201D}"        XCTAssertEqual(ReadPages.pages([said, quote], words: 50), [said, quote])    }    // MARK: The slots    private static func note() throws -> TableDefinition {        try DeckFullScreenTests.table(            "jotting_example", title: "caption", columns: #",{"key":"words","name":"Words","type":"longtext"}"#,            slip: #"{"title":"caption"}"#,            card: #"{"face":"note.page","fields":[{"slot":"title","column":"caption"},{"slot":"body","column":"words"}]}"#)    }    private static func memory() throws -> TableDefinition {        try DeckFullScreenTests.table(            "remembered_example", title: "said",            columns: #",{"key":"said","name":"Said","type":"longtext"},{"key":"quote","name":"Quote","type":"longtext"},{"key":"area","name":"Area","type":"text"},{"key":"state","name":"State","type":"choice"}"#,            slip: #"{"title":"said","byline":{"column":"state","words":{"held":"waiting for your review"}}}"#,            card: #"{"face":"memory","fields":[{"slot":"title","column":"caption"},{"slot":"body","column":"quote"},{"slot":"subtitle","column":"area"}]}"#)    }    /// RULE: A note reads its title column as the line at the top and its card's body column as the body.    func testANoteReadsItsTitleAndBody() throws {        XCTAssertEqual(ReadSlots.of(try Self.note()), ReadSlots(title: "caption", bodies: ["words"]))    }    /// RULE: A memory's title column is long text — its one sentence — so it is the first body, the quote behind it the next, and the line at the top is the column its card's subtitle says (its project).    func testAMemoryReadsItsSentenceThenItsQuote() throws {        let memory = try Self.memory()        let slots = try XCTUnwrap(ReadSlots.of(memory))        XCTAssertEqual(slots, ReadSlots(title: "area", bodies: ["said", "quote"]))        let record = TableRecord(id: "m1", values: [            "said": .text("Lunch moves to Thursdays."), "quote": .text("\u{201C}Thursdays work.\u{201D}"),            "area": .text("team"), "state": .text("held"),        ])        let card = DeckCard(face: "memory", corner: nil, pressing: false, pace: nil, plate: nil, fields: ["subtitle": .text("Team")])        let document = ReadDocument(record: record, card: card, slots: slots, definition: memory)        XCTAssertEqual(document, ReadDocument(title: "Team", byline: "waiting for your review",                                              bodies: ["Lunch moves to Thursdays.", "\u{201C}Thursdays work.\u{201D}"]))    }    /// RULE: A memory with no project heads its page with its card's date.    func testAMemoryWithNoProjectIsHeadedByItsDate() throws {        let memory = try DeckFullScreenTests.table(            "kept_example", title: "said",            columns: #",{"key":"said","name":"Said","type":"longtext"},{"key":"area","name":"Area","type":"text"},{"key":"on","name":"On","type":"date"}"#,            slip: #"{"title":"said"}"#,            card: #"{"face":"memory","fields":[{"slot":"subtitle","column":"area"},{"slot":"date","column":"on"}]}"#)        let slots = try XCTUnwrap(ReadSlots.of(memory))        XCTAssertEqual(slots, ReadSlots(title: "area", date: "on", bodies: ["said"]))        let record = TableRecord(id: "m2", values: ["said": .text("The walk is better early."), "on": .text("2026-08-14")])        let card = DeckCard(face: "memory", corner: nil, pressing: false, pace: nil, plate: nil, fields: ["date": .text("Thursday 14 August")])        XCTAssertEqual(ReadDocument(record: record, card: card, slots: slots, definition: memory).title, "Thursday 14 August")        // Kept today, the card says no date: the head is bare, never the stamp.        let today = TableRecord(id: "m5", values: ["said": .text("The walk is better early."), "on": .text("2026-10-29T13:55:00.000Z")])        let undated = DeckCard(face: "memory", corner: nil, pressing: false, pace: nil, plate: nil, fields: [:])        XCTAssertNil(ReadDocument(record: today, card: undated, slots: slots, definition: memory).title)        XCTAssertNil(ReadDocument(record: today, card: nil, slots: slots, definition: memory).title)    }    /// RULE: A note with no title is headed by its first sentence, as its torn page titles it; its words are read whole.    func testAnUntitledNoteStartsWithItsBody() throws {        let note = try Self.note()        let slots = try XCTUnwrap(ReadSlots.of(note))        let words = "Buy the ink before Friday. The shop shuts early."        let record = TableRecord(id: "n1", values: ["words": .text(words)])        let document = ReadDocument(record: record, card: nil, slots: slots, definition: note)        XCTAssertEqual(document, ReadDocument(title: nil, bodies: [words]))    }    private static func book() throws -> TableDefinition {        try DeckFullScreenTests.table(            "volume_example", title: "caption",            columns: #",{"key":"writer","name":"Writer","type":"text"},{"key":"cover","name":"Cover","type":"photo"},{"key":"thoughts","name":"Thoughts","type":"longtext"},{"key":"line","name":"Line","type":"longtext"}"#,            slip: #"{"title":"caption","subtitle":"writer","photo":"cover"}"#,            card: #"{"face":"book.hardback","fields":[{"slot":"photo","column":"cover"},{"slot":"title","column":"caption"},{"slot":"subtitle","column":"writer"},{"slot":"quote","column":"line"},{"slot":"body","column":"thoughts"}]}"#)    }    /// RULE: A book reads its notes, then its favourite quote, each on its own pages, under the running head "title · author"; its cover does not stop it.    func testABookReadsItsNotesThenItsQuote() throws {        let book = try Self.book()        let slots = try XCTUnwrap(ReadSlots.of(book))        XCTAssertEqual(slots, ReadSlots(title: "caption", with: "writer", bodies: ["thoughts", "line"]))        XCTAssertEqual(FullScreenRoute.of(book), .reading(slots))        let record = TableRecord(id: "b1", values: [            "caption": .text("The Keeper's Year"), "writer": .text("A. Writer"),            "thoughts": .text("Slow, and better for it."), "line": .text("He did not envy them."),        ])        XCTAssertEqual(ReadDocument(record: record, card: nil, slots: slots, definition: book),                       ReadDocument(title: "The Keeper's Year · A. Writer", bodies: ["Slow, and better for it.", "He did not envy them."]))    }    /// RULE: A book with neither notes nor a quote has nothing to read: it stays its whole card.    func testABookWithNothingToReadStaysWhole() throws {        let book = try Self.book()        let bare = TableRecord(id: "b2", values: ["caption": .text("Unread"), "writer": .text("B. Writer")])        guard case .whole = DeckOpening.of(bare, card: nil, in: [bare], definition: book, presenter: nil) else {            return XCTFail("a book with nothing to read opened the reader")        }        let noted = TableRecord(id: "b3", values: ["caption": .text("Read"), "thoughts": .text("Kept me up.")])        guard case .reading(let document) = DeckOpening.of(noted, card: nil, in: [noted], definition: book, presenter: nil) else {            return XCTFail("a book with notes did not open the reader")        }        XCTAssertEqual(document.bodies, ["Kept me up."])    }    /// RULE: A pictured note (a studio's class on its photograph) and a card of any other kind open no reading page.    func testOtherCardsOpenNoReadingPage() throws {        let pictured = try DeckFullScreenTests.table(            "class_example", columns: #",{"key":"about","name":"About","type":"longtext"},{"key":"picture","name":"Picture","type":"photo"}"#,            slip: #"{"title":"caption"}"#,            card: #"{"face":"note.page","fields":[{"slot":"photo","column":"picture"},{"slot":"title","column":"caption"},{"slot":"body","column":"about"}]}"#)        XCTAssertNil(ReadSlots.of(pictured))        let chore = try DeckFullScreenTests.table(            "chore_example", columns: #",{"key":"notes","name":"Notes","type":"longtext"}"#, slip: #"{"title":"caption"}"#,            card: #"{"face":"todo.card","fields":[{"slot":"title","column":"caption"},{"slot":"body","column":"notes"}]}"#)        XCTAssertNil(ReadSlots.of(chore))    }    /// RULE: Every word the reader says is the record's or the definition's: it writes no sentence of its own, and the page count VoiceOver hears is the cards' own line.    func testTheReadingPageSaysNoWordsOfItsOwn() throws {        let root = SourceSweep.iosSources.deletingLastPathComponent()        var code = ""        for path in ["Deck/ReadPage.swift", "Deck/Reader/ReadLight.swift", "Deck/Reader/ReadGround.swift", "Deck/Reader/ReadText.swift"] {            let file = try String(contentsOf: root.appendingPathComponent("Sources/CottonUI/" + path), encoding: .utf8)            code += SourceSweep.withoutComments(file)        }        XCTAssertTrue(try SourceSweep.matches(#"\b(Text|Button|accessibilityLabel)\("[A-Za-z]"#, in: code).isEmpty, "the reader writes its own words")        XCTAssertTrue(code.contains(#"ShellLines.line("cards", "note.page""#))    }    // MARK: Writing from the page    /// RULE: Each page knows the body it was cut from, so a long press writes the column the page shows: a memory's sentence on its first pages, its quote on the next.    func testEachPageKnowsItsBody() {        let long = (1...6).map { paragraph($0, sentences: 2, words: 8) }.joined(separator: "\n\n")        let cuts = ReadPages.cuts([long, "The quote."], words: 40)        XCTAssertGreaterThan(cuts.count, 2)        XCTAssertEqual(cuts.last, ReadCut(body: 1, text: "The quote."))        XCTAssertTrue(cuts.dropLast().allSatisfy { $0.body == 0 })        XCTAssertEqual(cuts.map(\.text), ReadPages.pages([long, "The quote."], words: 40))    }    /// RULE: A long press writes the page's column, read off the slots, never a table's name; whether a person writes it on this record is the core's (`shell.input` refuses a read-only column or a closed record), and over the reader a refused one opens nothing and says nothing.    func testALongPressAsksTheCoreForThePagesColumn() async throws {        let memory = try DeckFullScreenTests.table(            "kept_example", title: "said",            columns: #",{"key":"said","name":"Said","type":"longtext"},{"key":"quote","name":"Quote","type":"longtext","readonly":true},{"key":"area","name":"Area","type":"text"},{"key":"keeper","name":"Keeper","type":"text","readonly":true}"#,            slip: #"{"title":"said"}"#,            card: #"{"face":"memory","fields":[{"slot":"subtitle","column":"area"},{"slot":"body","column":"quote"}]}"#)        let slots = try XCTUnwrap(ReadSlots.of(memory))        let record = TableRecord(id: "m3", values: ["said": .text("The walk is better early."), "quote": .text("\u{201C}Early.\u{201D}")])        let source = ReadSource(record: record, card: nil, slots: slots, definition: memory)        XCTAssertEqual(source.columns, ["said", "quote"])        XCTAssertEqual(source.written(body: 0), "said")        XCTAssertEqual(source.written(body: 1), "quote")        XCTAssertNil(source.written(body: 2), "no such page")        let refusing = InputCore { _, _ in .failure(CottonCallError(code: "refused", message: "Quote is not written here.")) }        let editor = DeckEditor.standing()        editor.write(source.target, column: "quote", store: nil, core: refusing) { _ in }        try await eventually { !refusing.asked("shell.input").isEmpty }        try await Task.sleep(for: .milliseconds(100))        XCTAssertNil(editor.writing, "a column the core refuses opens nothing")        XCTAssertNil(editor.refusal, "and the long press says nothing")    }    /// RULE: The long press opens the shell's full-screen editor over the reader, on the page's column under its head, as the core answers it; Done writes it and hands the record back, and the page is read again from the new words; a cancel writes nothing.    func testDoneReturnsToTheReaderReadAgain() async throws {        let note = try Self.note()        let slots = try XCTUnwrap(ReadSlots.of(note))        let record = TableRecord(id: "n7", values: ["caption": .text("Spare key"), "words": .text("Under the **blue** pot.")])        let source = ReadSource(record: record, card: nil, slots: slots, definition: note)        let column = try XCTUnwrap(source.written(body: 0))        let core = InputCore { method, request in            switch request["op"]?.string {            case "ask":                return .success(InputCore.json(#"{"editor":"page","words":"Under the **blue** pot.","title":"Spare key","keeps_words":false,"writes":{"kind":"column","table":"\#(note.id)","id":"n7","column":"\#(column)"}}"#))            case "commit":                let words = request["words"]?.string ?? ""                return .success(InputCore.json(#"{"change":{"id":"c7","byline":"You","record_id":"n7","undoable":true,"after":{"\#(column)":"\#(words)"}},"record":{"id":"n7","data":{"caption":"Spare key","\#(column)":"\#(words)"}}}"#))            default:                return .failure(CottonCallError(code: "missing", message: "Not here"))            }        }        let editor = DeckEditor.standing()        var read: ReadDocument?        editor.write(source.target, column: column, store: nil, core: core) { read = source.reading($0) }        try await eventually { editor.writing != nil }        let writing = try XCTUnwrap(editor.writing)        XCTAssertEqual(writing.editor, .page)        XCTAssertTrue(writing.overReader, "the reader presents it, not the stack's layer")        XCTAssertEqual(writing.words, "Under the **blue** pot.")        XCTAssertEqual(writing.title, "Spare key")        editor.dismissWriting()        try await Task.sleep(for: .milliseconds(100))        XCTAssertNil(read, "a cancel writes nothing")        editor.write(source.target, column: column, store: nil, core: core) { read = source.reading($0) }        try await eventually { editor.writing != nil }        editor.commit("Under the blue pot. Tell Ravi before Friday.")        XCTAssertNil(editor.writing, "Done puts the editor away")        try await eventually { read != nil }        XCTAssertEqual(read, ReadDocument(title: "Spare key", bodies: ["Under the blue pot. Tell Ravi before Friday."]))        XCTAssertEqual(read?.source?.record["words"].text, "Under the blue pot. Tell Ravi before Friday.", "a second long press writes the new words")    }}extension ReadPageTests {    func testMarkdownReadingKeepsRunsAcrossPageCuts() {        let raw = "**One sentence. Another sentence.**\n\n```text\n**literal**\n```"        let set = FaceMarkdown.set(raw, theme: .paper)        let cuts = ReadPages.cuts([String(set.characters)], words: 2)        let pages = cuts.enumerated().map { index, cut in            ReadPage.setting(cut, in: [set], before: Array(cuts.prefix(index)))        }        XCTAssertEqual(pages.map { String($0.characters) }, cuts.map(\.text))        XCTAssertTrue(pages[1].runs.contains { $0.inlinePresentationIntent?.contains(.stronglyEmphasized) == true })        let typed = ReadText.setting(String(set.characters), ink: .black, set: set)        XCTAssertEqual(typed.string, String(set.characters))    }}#endif