Cotton code
347 lines · 16.2 KB · SwiftRaw
// 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)import CottonFacesimport CottonKitimport CottonValuesimport SwiftUIimport UIKitimport XCTest@testable import CottonUI@MainActorfinal class DeckWritingLayoutTests: XCTestCase {    private let key = "invented-db\u{1F}todos"    private let target = DeckEditTarget(table: "todo", record: "t1", date: "due_at")    private let record = TableRecord(id: "t1", values: ["title": .text("Buy rice"), "notes": .text("Two kilos")])    override func tearDown() async throws {        DeckEditor.session.dismissWriting()        DeckEditor.session.keyboard(shown: false)        try await super.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() async throws {        let cuts = Cuts()        let seen = Seen()        let navigator = Navigator()        navigator.tile = key        let stack = TileStack(key: key, navigator: navigator)        var environment = EnvironmentValues()        environment.facePageCutter = CountingCutter(cuts: cuts)        let window = try Self.window(stack)        defer { window.isHidden = true }        stack.update(root: AnyView(Probe(seen: seen)), rootTitle: "Todos", routes: [], titles: [:], environment: environment)        let standing = try await Self.until("the card stands") { seen.frame.height > 0 ? seen.frame : nil }        let pages = try await Self.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()        _ = try await Self.until("the host makes room for a keyboard with no writer") {            seen.frame.height < standing.height - 1 ? seen.frame : nil        }        field.resignFirstResponder()        _ = try await Self.until("the keyboard goes") { heard.shown ? nil : true }        _ = try await Self.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)        _ = try await Self.until("the writer stands") { DeckEditor.session.writing != nil ? true : nil }        field.becomeFirstResponder()        _ = try await Self.until("the writer's keyboard rises") { heard.shown ? true : nil }        try await Task.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")        try await Task.sleep(for: .milliseconds(200))        XCTAssertEqual(seen.frame, standing, "the card did not rise to the keyboard as it went")        field.resignFirstResponder()        _ = try await Self.until("the writer's keyboard goes and lets go") {            !heard.shown && !DeckEditor.session.holdsKeyboard ? true : nil        }        try await Task.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() async throws {        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")        try await eventually { editor.writing != nil }        editor.dismissWriting()        XCTAssertFalse(editor.holdsKeyboard)    }    /// RULE: a writer put away before the core answers its ask never stands.    func testAWriterPutAwayBeforeItsAskNeverStands() async throws {        let editor = DeckEditor.standing()        let core = InputCore.asking("line", words: "Buy rice")        editor.write(target, column: "title", store: nil, core: core)        editor.dismissWriting()        try await eventually { !core.asked("shell.input").isEmpty }        try await Task.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() async throws {        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 = try Self.window(host)        defer { window.isHidden = true }        let wide = try await Self.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.        try await Task.sleep(for: .milliseconds(120))        room.width = Room.wide        try await Task.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() async throws {        let ref = "invented-db/documents/\(UUID().uuidString)"        let store = try FixtureStore(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 = try Self.window(deck)        defer { window.isHidden = true }        _ = try await Self.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 = page        let aspect = try await Self.until("the first page is drawn") { shape.aspect > 0 ? shape.aspect : nil }        XCTAssertEqual(aspect, 0.5, accuracy: 0.02)    }    // MARK: Fixtures    private static func 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"}]}}        """        return try 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.    private static func 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.    private static func until<T>(_ what: String, _ read: () -> T?) async throws -> T {        let deadline = Date().addingTimeInterval(5)        while Date() < deadline {            if let found = read() { return found }            try await Task.sleep(for: .milliseconds(20))        }        return try XCTUnwrap(read(), "\(what): never")    }    /// The page label ("2 / 3") drawn under `root`.    private static func pageLabel(in root: UIView) -> String? {        func walk(_ node: NSObject) -> String? {            if let 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 }            }            if let view = node as? UIView { children += view.subviews }            for child in children { if let found = walk(child) { return found } }            return nil        }        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 private final class KeyboardHeard {    private(set) var shown = false    private var tokens: [NSObjectProtocol] = []    init() {        let center = NotificationCenter.default        tokens.append(center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] _ in            MainActor.assumeIsolated {                self?.shown = true                DeckEditor.session.keyboard(shown: true)            }        })        tokens.append(center.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: .main) { [weak self] _ in            MainActor.assumeIsolated {                self?.shown = false                DeckEditor.session.keyboard(shown: false)            }        })    }    func stop() { tokens.forEach(NotificationCenter.default.removeObserver) }}/// Where the probe card stood.@MainActor private final class Seen {    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.private struct Probe: View {    let seen: Seen    var body: some View {        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.private final class Cuts: @unchecked Sendable {    private let lock = NSLock()    private var counts: [Int] = []    func add(_ count: Int) { lock.withLock { counts.append(count) } }    var last: Int? { lock.withLock { counts.last } }}private struct CountingCutter: FacePageCutter {    let cuts: Cuts    func cut(_ text: String, columns: Int, first: Int, rest: Int) async -> [NotePage] {        let pages = await PlainPageCutter().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.private struct SlowNarrowCutter: FacePageCutter {    static let delay = 600    func cut(_ text: String, columns: Int, first: Int, rest: Int) async -> [NotePage] {        if columns < 20 {            await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in                DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(Self.delay)) { done.resume() }            }        }        return await PlainPageCutter().cut(text, columns: columns, first: first, rest: rest)    }}@MainActor @Observable private final class Room {    static let wide: CGFloat = 340    var width: CGFloat = wide}private struct RoomProbe: View {    let room: Room    let card: DeckCard    var body: some View {        NoteCard(card: card).frame(width: room.width, height: 520)    }}/// The aspect a first page tells its card.@MainActor private final class PageShape {    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.private final class FixtureStore: AttachmentStore, @unchecked Sendable {    let ref: String    let file: URL    private let lock = NSLock()    private var asked: Set<String> = []    init(ref: String, size: CGSize) throws {        self.ref = ref        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)        try FileManager.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) async throws -> URL? {        lock.withLock { _ = asked.insert(ref) }        return ref == self.ref ? file : nil    }    func store(fileAt url: URL, name: String?, for type: ColumnType) async throws -> AttachmentValue {        throw CocoaError(.featureUnsupported)    }}#endif