Cotton code
108 lines · 6.5 KB · SwiftRaw
// One door to a record (door row 13): every record and blank opens on its// table's deck — a thread's on its chat. The deck of cards is the whole UI// (owner, 23 Oct 2026): the old record page is gone, the Bin, albums and// faces to confirm with it.import CottonKitimport CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class RecordOpeningTests: XCTestCase {    /// The shipped tables with their cards, as the app's bundle carries them.    private func shipped() throws -> [TableDefinition] {        let definitions = try SurfaceStackTests.bundledDefinitions()        XCTAssertFalse(definitions.isEmpty, "the bundled definitions are where the guard expects them")        return definitions    }    private func definition(_ id: String) throws -> TableDefinition {        try XCTUnwrap(try shipped().first { $0.id == id }, "no shipped \(id) table")    }    /// RULE: The Bin and albums are decks like every table, their lists their decks, and a table with no face of its own (This Device, Settings) is drawn plain on its deck; a face to confirm opens on its deck, drawn plain until its kind has a face.    func testTheBinAlbumsAndPlainTablesAreDecks() throws {        XCTAssertEqual(RecordOpening.lands(try definition("face"), opens: .record("f-1", nil)), .deck)        for id in ["bin", "album", "device", "settings", "backup", "theme"] {            let table = try definition(id)            XCTAssertNotNil(table.card, "\(id) carries the core's card")            XCTAssertTrue(DeckSwitch.draws(table, view: nil, plain: true), "\(id)'s list is its deck")        }        for id in ["device", "settings", "backup", "theme"] {            XCTAssertEqual(try definition(id).card?.face, .plain, "\(id) carries the core's plain card")        }        XCTAssertTrue(DeckFace.draws(DeckCard(face: .plain, fields: ["title": .text("Invented phone")])))    }    /// RULE (Calendar after Plus, #294): a record's or a blank's deck names no view; it asks the core to land it (`lands`, with the ring's choices), stands on the view answered, and reads that view from then on. Nothing in the door decides a view.    func testADeckThatLandsStandsOnTheViewTheCoreNames() async throws {        let core = LandingCore()        let asked = DeckReading.Asked(table: "event", view: nil, filter: [:], opensOn: nil, database: nil, lands: true)        let reading = DeckReading(asked: asked, core: core, store: nil)        reading.chosen = ["calendar": "upcoming"]        await reading.reload()        XCTAssertEqual(reading.landedView?.name, "calendar/upcoming", "the view the core named, read as the ring reads it")        XCTAssertEqual(reading.landedView?.filter, ["kind": .text("invented")], "with its own columns")        await reading.reload()        XCTAssertEqual(core.requests.count, 2)        XCTAssertEqual(core.requests[0]["lands"] as? Bool, true)        XCTAssertEqual(core.requests[0]["chosen"] as? [String: String], ["calendar": "upcoming"])        XCTAssertNil(core.requests[0]["view"] as? String, "the deck names none of its own")        XCTAssertEqual(core.requests[1]["view"] as? String, "calendar/upcoming", "landed once: the view is read by name")        XCTAssertNil(core.requests[1]["lands"] as? Bool)        let opening = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/RecordOpening.swift", ownedBy: "deck"))        XCTAssertFalse(opening.contains("ToolViews"), "the door reads no ring: the core lands the deck")        XCTAssertFalse(opening.contains("drawnRead"), "the door names no view")    }    /// RULE (Plus on Calendar stood on blank felt, walk of 9 Nov 2026): a route that reads before it draws hangs its task on something drawn; a task on a Group holding nothing never starts.    func testANewEventsReadStartsBeforeAnythingIsDrawn() throws {        let route = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/TableRoute.swift", ownedBy: "deck"))        let body = try XCTUnwrap(route.range(of: "struct NewEventRoute").map { String(route[$0.lowerBound...].prefix(700)) })        XCTAssertTrue(body.contains("ZStack {"), "the read's task stands on a view that exists before it answers")        XCTAssertFalse(body.contains("Group {"))    }    /// RULE: A blank that lands composes after the core has named its view, so the record it makes holds that view's own values.    func testABlankComposesOnceItHasLanded() throws {        let surface = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/DeckSurface.swift", ownedBy: "deck"))        XCTAssertTrue(surface.contains("if composesOnArrival, !lands, definition.create != nil { compose() }"), "only a deck that names its own view composes as it appears")        XCTAssertTrue(surface.contains("if composesOnArrival, lands, !composedOnLanding, definition.create != nil"))    }    /// RULE: The plain face says the core's facts, each under its column's label, in order; one with no words is left out.    func testThePlainFaceSaysItsFactsUnderTheirLabels() {        let card = DeckCard(face: .plain, fields: [            "title": .text("No recent copy"),            "facts": .list([                .object(["label": .text("Copies kept"), "said": .text("4")]),                .object(["label": .text("Last copied"), "said": .text("")]),                .object(["label": .text("Kept on"), "said": .text("Invented Mac")]),            ]),        ])        let facts = PlainFace(card: card).facts        XCTAssertEqual(facts.map(\.label), ["Copies kept", "Kept on"])        XCTAssertEqual(facts.map(\.said), ["4", "Invented Mac"])    }}private final class LandingCore: CottonCalling, @unchecked Sendable {    private(set) var requests: [[String: Any]] = []    func callRaw(_ method: String, requestJSON: String) async throws -> String {        requests.append((try JSONSerialization.jsonObject(with: Data(requestJSON.utf8)) as? [String: Any]) ?? [:])        return #"""        {"ok":true,"data":{"table":"event","view":"calendar/upcoming",         "landed":{"id":"upcoming","label":"Upcoming","default":false,"read":{"table":"event","where":{"kind":"invented"}}},         "cards":[],"acts":{},"labels":{"by_slot":{},"by_column":{}},"count":0,"head":null,"empty":null,         "hand":[],"worn":null,"hand_next":null,"plus":{"does":"none","label":null,"doors":[]},"visitor":null,"next":null}}        """#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}    func close() {}}