// A card's words are cut into pages that fill before they break and never// leave a lone line on the last (real-data walk: a long todo's page 2 ended// half empty and page 3 held one word, "unreviewed.").importCottonKitimport XCTest@testable importCottonUI/// A core that cuts into pages of `rest` lines, each line `columns` long,/// and remembers what it was asked.private actor PagingCore: CottonCalling {let lines: Intprivate(set) var asked: [Int] = []init(lines: Int) { self.lines = lines }func callRaw(_ method: String, requestJSON: String) throws -> String {let request = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8))) as? [String: Any] ?? [:]let rest = request["rest"] as? Int ?? 1 asked.append(rest)// `lines` one-word lines, `rest` to a page.let words = (0..<lines).map { "w\($0)" }let pages = stride(from: 0, to: words.count, by: rest).map { words[$0..<min($0 + rest, words.count)].joined(separator: "\n") }let body = pages.map { #"{"text":"\#($0.replacingOccurrences(of: "\n", with: "\\n"))","label":""}"# }.joined(separator: ",")return #"{"ok":true,"data":{"pages":[\#(body)]}}"# }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}func close() {}}finalclassNotePagesWidowTests: XCTestCase {/// RULE: A cut whose last page would be one lone line is cut again a line shorter a page, so the last page holds more than one.func testALoneLastLineIsPulledBackOntoItsPage() async {// 9 lines at 4 a page: 4, 4, 1 — a lone line. At 3: 3, 3, 3.let core = PagingCore(lines: 9)let pages = awaitNotePages.cut(core, text: "", columns: 20, first: 4, rest: 4) XCTAssertEqual(pages.count, 3) XCTAssertFalse(NotePages.lone(pages, columns: 20))let asked = await core.asked XCTAssertEqual(asked, [4, 3]) }/// RULE: A cut with no lone last line is the core's own, asked once.func testAFullLastPageIsAskedOnce() async {let core = PagingCore(lines: 8)let pages = awaitNotePages.cut(core, text: "", columns: 20, first: 4, rest: 4) XCTAssertEqual(pages.count, 2)let asked = await core.asked XCTAssertEqual(asked, [4]) }}