// What stands under the shell's writer, and what a card's parts route to// (walk 332, 28 Oct 2026): the one-line input and the full-screen editor// raised a keyboard that Home's host made room for, so the fan rose over it// and the deck's card squeezed into a strip, its note cut again for that// width and left there; a thread's last line opened the input holding the// message; a document card stood blank on a phone without its bytes.#if os(iOS)importCottonFacesimportCottonKitimportCottonValuesimportSwiftUIimport UIKitimport XCTest@testable importCottonUI@MainActorfinalclassDeckWritingLayoutTests: XCTestCase {privatelet key = "invented-db\u{1F}todos"privatelet target = DeckEditTarget(table: "todo", record: "t1", date: "due_at")privatelet record = TableRecord(id: "t1", values: ["title": .text("Buy rice"), "notes": .text("Two kilos")])overridefunc tearDown() asyncthrows {DeckEditor.session.dismissWriting()DeckEditor.session.keyboard(shown: false)tryawaitsuper.tearDown() }/// RULE: while the shell's writer stands — from the moment it opens until the keyboard it raised has gone — no page host under it lays its page out for the keyboard: a card over the fan's room keeps its frame and its pages, as it stood before the writer, through the keyboard rising and going; with no writer the same host still makes room for a keyboard (a search's).func testNothingUnderTheWriterMovesForItsKeyboard() asyncthrows {let cuts = Cuts()let seen = Seen()let navigator = Navigator() navigator.tile = keylet stack = TileStack(key: key, navigator: navigator)var environment = EnvironmentValues() environment.facePageCutter = CountingCutter(cuts: cuts)let window = trySelf.window(stack)defer { window.isHidden = true } stack.update(root: AnyView(Probe(seen: seen)), rootTitle: "Todos", routes: [], titles: [:], environment: environment)let standing = tryawaitSelf.until("the card stands") { seen.frame.height > 0 ? seen.frame : nil }let pages = tryawaitSelf.until("the card is cut") { cuts.last } XCTAssertGreaterThan(pages, 1, "a card of more than one page")// A real keyboard, raised by a field in the same window; the shell's// layer hears it as `DeckWritingLayer` does.let field = UITextField(frame: CGRect(x: 16, y: 60, width: 200, height: 32))// A fixed software input view exercises UIKit's real keyboard safe// area without depending on the simulator's hardware-keyboard link. field.inputView = UIView(frame: CGRect(x: 0, y: 0, width: 402, height: 300)) window.addSubview(field)let heard = KeyboardHeard()defer { heard.stop() }// The host makes room for a keyboard with no writer standing: what// the writer must stop. field.becomeFirstResponder() _ = tryawaitSelf.until("the host makes room for a keyboard with no writer") { seen.frame.height < standing.height - 1 ? seen.frame : nil } field.resignFirstResponder() _ = tryawaitSelf.until("the keyboard goes") { heard.shown ? nil : true } _ = tryawaitSelf.until("the card stands again") { seen.frame == standing ? true : nil }// The writer opens; its keyboard rises.DeckEditor.session.write(target, column: "title", store: nil, core: InputCore.asking("line", words: "Buy rice")) XCTAssertTrue(DeckEditor.session.holdsKeyboard) _ = tryawaitSelf.until("the writer stands") { DeckEditor.session.writing != nil ? true : nil } field.becomeFirstResponder() _ = tryawaitSelf.until("the writer's keyboard rises") { heard.shown ? true : nil }tryawaitTask.sleep(for: .milliseconds(500)) XCTAssertEqual(seen.frame, standing, "the card under the writer kept its frame") XCTAssertEqual(cuts.last, pages, "the card under the writer kept its pages")// Dismissed: the page stands still until the keyboard has gone.DeckEditor.session.dismissWriting() XCTAssertTrue(DeckEditor.session.holdsKeyboard, "held while the keyboard is still up")tryawaitTask.sleep(for: .milliseconds(200)) XCTAssertEqual(seen.frame, standing, "the card did not rise to the keyboard as it went") field.resignFirstResponder() _ = tryawaitSelf.until("the writer's keyboard goes and lets go") { !heard.shown && !DeckEditor.session.holdsKeyboard ? true : nil }tryawaitTask.sleep(for: .milliseconds(200)) XCTAssertEqual(seen.frame, standing) XCTAssertEqual(cuts.last, pages) }/// RULE: a writer dismissed with no keyboard up (a hardware keyboard) lets the pages answer the keyboard again at once.func testAWriterWithNoKeyboardLetsGoAtOnce() asyncthrows {let editor = DeckEditor.standing() editor.write(target, column: "notes", store: nil, core: InputCore.asking("page")) XCTAssertTrue(editor.holdsKeyboard, "held from the moment it is asked")tryawait eventually { editor.writing != nil } editor.dismissWriting() XCTAssertFalse(editor.holdsKeyboard) }/// RULE: a writer put away before the core answers its ask never stands.func testAWriterPutAwayBeforeItsAskNeverStands() asyncthrows {let editor = DeckEditor.standing()let core = InputCore.asking("line", words: "Buy rice") editor.write(target, column: "title", store: nil, core: core) editor.dismissWriting()tryawait eventually { !core.asked("shell.input").isEmpty }tryawaitTask.sleep(for: .milliseconds(100)) XCTAssertNil(editor.writing) XCTAssertFalse(editor.holdsKeyboard) }/// RULE: a note's pages are cut again whenever its room changes, and only the cut for the room it stands in is shown: a cut asked for a room since left — the narrow strip's, slow, landing after the wide one's — never replaces it (walk 332: a note left at "1 / 2,738" once its width came back).func testANoteIsCutForTheRoomItStandsIn() asyncthrows { XCTAssertTrue(HostedAccessibility.enable(), "the hosted page's accessibility tree is read")let room = Room()let card = DeckCard(face: .notePage, fields: ["title": .text("Invented trip"),"body": .text(String(repeating: "We walked the invented hills until the rain came down on us. ", count: 30)), ])let host = UIHostingController(rootView: AnyView(RoomProbe(room: room, card: card).environment(\.facePageCutter, SlowNarrowCutter())))let window = trySelf.window(host)defer { window.isHidden = true }let wide = tryawaitSelf.until("the wide note is cut") { Self.pageLabel(in: host.view) } room.width = 60// The narrow cut is asked, and is slow; the width comes back before it lands.tryawaitTask.sleep(for: .milliseconds(120)) room.width = Room.widetryawaitTask.sleep(for: .milliseconds(SlowNarrowCutter.delay + 400)) XCTAssertEqual(Self.pageLabel(in: host.view), wide, "the note shows the cut for its own width") }/// RULE: a document's card draws its first page off the record's own file (`storage_path` → the card's file → `faceFilePage` → `DeckFirstPage`), fetching the bytes when they are not on this phone: the card asks for its file, and the page drawn tells the card its shape.func testADocumentCardDrawsItsFirstPage() asyncthrows {let ref = "invented-db/documents/\(UUID().uuidString)"let store = tryFixtureStore(ref: ref, size: CGSize(width: 120, height: 240))// The chain from the record: the deck's card asks for its file.let record = TableRecord(id: "d1", values: ["title": .text("Invented bill"), "storage_path": .text(ref)])let card = DeckCard(face: .document, fields: ["title": .text("Invented bill")])let deck = UIHostingController(rootView: AnyView(DeckFace.view(for: card, record: record, toggle: {}) .frame(width: 340, height: 480) .environment(\.attachmentStore, store)))let window = trySelf.window(deck)defer { window.isHidden = true } _ = tryawaitSelf.until("the document card fetched its file") { store.fetched.contains(ref) ? true : nil }// The page drawn off the fixture tells its card the page's shape.let shape = PageShape()let page = UIHostingController(rootView: AnyView(DeckFirstPage(ref: ref, aspect: Binding(get: { shape.aspect }, set: { shape.aspect = $0 })) .frame(width: 200, height: 300) .environment(\.attachmentStore, store))) window.rootViewController = pagelet aspect = tryawaitSelf.until("the first page is drawn") { shape.aspect > 0 ? shape.aspect : nil } XCTAssertEqual(aspect, 0.5, accuracy: 0.02) }// MARK: Fixturesprivatestaticfunc todo() throws -> TableDefinition {let json = """ {"id":"todo","name":"Todo","plural":"Todos","builtin":false, "columns":[{"key":"title","name":"Title","type":"text"},{"key":"notes","name":"Notes","type":"longtext"}, {"key":"due_at","name":"Due","type":"date"}], "title":"title","date":"due_at","project":null,"order":null, "slip":{"title":"title"},"tile":{"face":"slip-list"},"page":[],"commands":[],"tables":[], "create":{"label":"New todo"}, "card":{"face":"todo.card","fields":[{"slot":"title","column":"title"},{"slot":"body","column":"notes"}]}} """returntry JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8)) }/// A window of the app's own scene: since iOS 26 a window with no scene is never put on screen.privatestaticfunc window(_ root: UIViewController) throws -> UIWindow {let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first,"the host app has no window scene")let window = UIWindow(windowScene: scene) window.frame = CGRect(x: 0, y: 0, width: 402, height: 874) window.rootViewController = root window.makeKeyAndVisible()return window }/// Polls `read` until it answers, or fails after a few seconds.privatestaticfunc until<T>(_ what: String, _ read: () -> T?) asyncthrows -> T {let deadline = Date().addingTimeInterval(5)whileDate() < deadline {iflet found = read() { return found }tryawaitTask.sleep(for: .milliseconds(20)) }returntry XCTUnwrap(read(), "\(what): never") }/// The page label ("2 / 3") drawn under `root`.privatestaticfunc pageLabel(in root: UIView) -> String? {func walk(_ node: NSObject) -> String? {iflet label = node.accessibilityLabel, label.wholeMatch(of: /\d[\d,]* \/ \d[\d,]*/) != nil { return label }var children: [NSObject] = (node.accessibilityElements as? [NSObject]) ?? []let count = node.accessibilityElementCount()if children.isEmpty, count > 0, count != NSNotFound { children = (0..<count).compactMap { node.accessibilityElement(at: $0) as? NSObject } }iflet view = node as? UIView { children += view.subviews }for child in children { iflet found = walk(child) { return found } }returnnil }return walk(root) }}/// The keyboard as the shell's writing layer hears it (`DeckWritingLayer`):/// up at its will-show, gone at its did-hide, told to the session's editor.@MainActor privatefinalclassKeyboardHeard {private(set) var shown = falseprivatevar tokens: [NSObjectProtocol] = []init() {let center = NotificationCenter.default tokens.append(center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated {self?.shown = trueDeckEditor.session.keyboard(shown: true) } }) tokens.append(center.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated {self?.shown = falseDeckEditor.session.keyboard(shown: false) } }) }func stop() { tokens.forEach(NotificationCenter.default.removeObserver) }}/// Where the probe card stood.@MainActor privatefinalclassSeen {var frame = CGRect.zero}/// A page in miniature as the deck stands: a card of more than one page/// filling the room above the fan's, the fan's room at the foot.privatestructProbe: View {let seen: Seenvar body: someView { VStack(spacing: 0) {FacePages(text: String(repeating: "Invented words on an invented card, line after line. ", count: 40), size: 14) .frame(maxWidth: .infinity, maxHeight: .infinity) .onGeometryChange(for: CGRect.self, of: { $0.frame(in: .global) }) { seen.frame = $0 }Color.clear.frame(height: 220) } }}/// How many pages each cut made, the last one last.privatefinalclassCuts: @unchecked Sendable {privatelet lock = NSLock()privatevar counts: [Int] = []func add(_ count: Int) { lock.withLock { counts.append(count) } }var last: Int? { lock.withLock { counts.last } }}privatestructCountingCutter: FacePageCutter {let cuts: Cutsfunc cut(_ text: String, columns: Int, first: Int, rest: Int) async -> [NotePage] {let pages = awaitPlainPageCutter().cut(text, columns: columns, first: first, rest: rest) cuts.add(pages.count)return pages }}/// The plain cut, slow for a narrow room and deaf to cancelling, as the/// core's call is: a narrow cut lands after a wide one asked later.privatestructSlowNarrowCutter: FacePageCutter {staticlet delay = 600func cut(_ text: String, columns: Int, first: Int, rest: Int) async -> [NotePage] {if columns < 20 {await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) inDispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(Self.delay)) { done.resume() } } }returnawaitPlainPageCutter().cut(text, columns: columns, first: first, rest: rest) }}@MainActor @Observable privatefinalclassRoom {staticlet wide: CGFloat = 340var width: CGFloat = wide}privatestructRoomProbe: View {let room: Roomlet card: DeckCardvar body: someView {NoteCard(card: card).frame(width: room.width, height: 520) }}/// The aspect a first page tells its card.@MainActor privatefinalclassPageShape {var aspect: CGFloat = 0}/// A phone without a document's bytes: nothing here, and the fixture/// document — a page twice as tall as wide — fetched when asked.privatefinalclassFixtureStore: AttachmentStore, @unchecked Sendable {let ref: Stringlet file: URLprivatelet lock = NSLock()privatevar asked: Set<String> = []init(ref: String, size: CGSize) throws {self.ref = reflet folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)tryFileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) file = folder.appendingPathComponent("invented-bill.jpg")let page = UIGraphicsImageRenderer(size: size).image { context in UIColor.white.setFill() context.fill(CGRect(origin: .zero, size: size)) UIColor.black.setFill() context.fill(CGRect(x: 10, y: 10, width: size.width - 20, height: 8)) }try XCTUnwrap(page.jpegData(compressionQuality: 0.8)).write(to: file) }var fetched: Set<String> { lock.withLock { asked } }func localURL(for ref: String) async -> URL? { nil }func ensure(for ref: String) asyncthrows -> URL? { lock.withLock { _ = asked.insert(ref) }return ref == self.ref ? file : nil }func store(fileAt url: URL, name: String?, for type: ColumnType) asyncthrows -> AttachmentValue {throwCocoaError(.featureUnsupported) }}#endif