Cotton code
189 lines · 11.5 KB · SwiftRaw
#if os(iOS)import CottonFacesimport CottonKitimport CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class OpenedActsTests: XCTestCase {    func testEveryVisibleActLabelIsOnScreenAndNeverIntersectsANeighbour() throws {        let fan = FanGeometry(scale: Theme.paper.scale).withHub(diameter: 64)        for current in 0..<12 {            let frames = (0..<12).compactMap { fan.labelFrame(index: $0, theta: Double(current) * fan.step, width: 393) }            for (index, frame) in frames.enumerated() {                XCTAssertGreaterThanOrEqual(frame.minX, 0)                XCTAssertLessThanOrEqual(frame.maxX, 393)                XCTAssertGreaterThanOrEqual(frame.minY, 0)                let hub = fan.hub(width: 393, diameter: 64)                XCTAssertFalse(frame.intersects(CGRect(x: hub.x - 32, y: hub.y - 32, width: 64, height: 64)), "hub never hides a label")                for neighbour in frames.dropFirst(index + 1) {                    XCTAssertFalse(frame.intersects(neighbour), "\(frame) overlaps \(neighbour)")                }            }        }    }    private func table(_ id: String) throws -> TableDefinition {        let json = try SourceSweep.mustRead("crates/cotton-core/kits/personal/tables/" + id + ".json", ownedBy: "deck")        return try JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8))    }    func testTheOpenedCardHasOnlyTheHubCloseAndKeepsPinchIn() throws {        let source = try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/OpenedCard.swift", ownedBy: "deck")        XCTAssertTrue(source.contains("showsBack: false"))        XCTAssertFalse(source.contains("NavCircle("))        XCTAssertTrue(source.contains("pinch.magnification < DeckWholeCardKnobs.closes"))        XCTAssertTrue(source.contains("editor?.presentOpened"))    }    /// RULE: a body is Markdown where the definition says so (the note    /// kit's card), never because a face is named note: a card with the note    /// face whose body says nothing sets it plain.    func testMarkdownIsTheDefinitionsWordNotTheFacesName() throws {        let note = try table("note")        XCTAssertTrue(note.setsMarkdown("body"))        XCTAssertTrue(note.bodySetsMarkdown)        var plain = note        let fields = (note.card?.fields ?? []).map { field in            var field = field            field.markdown = false            return field        }        plain.card?.fields = fields        XCTAssertFalse(plain.setsMarkdown("body"), "the face's name decides nothing")        XCTAssertFalse(plain.bodySetsMarkdown)    }    func testStampRunsTheKitCommandAndLandsItsReceipt() async throws {        let definition = try table("todo")        let record = TableRecord(id: "synthetic", values: ["status": .text("open")])        let command = try XCTUnwrap(definition.commands?.first { $0.object == "stamp" }, "the kit's stamp is a command")        let core = ScriptedCore(["records.command": .ok(#"{"command":"done","kind":"update","receipt":"Marked done"}"#)])        let editor = DeckEditor.standing()        editor.hold(record)        let place = DeckPickPlace(store: CoreRecords(core: core, bundle: try TestResources.bundle()), core: core,                                  definitions: TableDefinitions([definition]))        let outcome = await editor.act(command, on: .init(table: definition.id, record: record.id, date: nil), definition: definition, place: place)        guard case .ran = outcome else { return XCTFail("the stamp did not run") }        XCTAssertEqual(editor.landed?.table, definition.id)        let calls = await core.calls        XCTAssertEqual(calls.filter { $0.method == "records.command" }.count, 1)        let done = try SourceSweep.mustRead("apps/loom/Sources/CottonFaces/Cotton/TodoCardFace.swift", ownedBy: "deck")        XCTAssertTrue(done.contains(".transition(arrival)"))        XCTAssertTrue(done.contains(".facePart(.done)"))    }    /// RULE: a command that asks free words for a column (a title's Rename)    /// stands on the fan as its command; what it asks is the core's    /// (`shell_input_tests.rs`).    func testAFieldEditorIsOfferedOnceItsWordsAskedForItsColumn() throws {        var definition = try table("todo")        let rename = RecordCommand(id: "rename", label: "Rename", kind: .update,                                   pick: RecordCommandPick(argument: "title", kind: .text))        definition.commands?.append(rename)        let acts = EditingFan.items(of: [CardAction(id: "rename", label: "Rename", kind: "command")], in: definition)        XCTAssertEqual(acts.map(\.does), [.command(rename)])    }    /// RULE: The shell's words over a deck grow with Dynamic Type: the top    /// line (position, a view's head, the counter), the crumbs, the empty    /// line and a view tile's name and count are set through `scaledFace` or    /// `TextGrowth`, never at a fixed size alone (claude-books-gaps, 5 Nov 2026).    func testTheDecksShellWordsGrowWithTheTextSize() throws {        let surface = try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/DeckSurface.swift", ownedBy: "deck")        XCTAssertFalse(surface.contains(".font(CottonFonts.type(DeckKnobs."), "the top line and crumbs scale")        let deck = try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/CardDeck.swift", ownedBy: "deck")        XCTAssertFalse(deck.contains(".font(CottonFonts.type(DeckKnobs."))        let empty = try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/DeckEmptyLine.swift", ownedBy: "deck")        XCTAssertFalse(empty.contains(".font(theme.type.body("))        let tiles = try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/Board/FanTiers.swift", ownedBy: "deck")        XCTAssertTrue(tiles.contains("preferred: 13 * growth") && tiles.contains("preferred: 11 * growth"),                      "a view tile's name and count grow")    }    /// RULE: A held highlight carries Recolour, Note and Remove; what each    /// asks is the core's pick (`shell_input_tests.rs`), which acts stand is    /// the core's (`card_actions_tests`).    func testAHeldHighlightsRecolourChoosesAndNoteAsksWords() throws {        let definition = try table("highlight")        let commands = definition.commands ?? []        let recolour = try XCTUnwrap(commands.first { $0.id == "recolour" })        XCTAssertEqual(recolour.pick?.kind, .text)        XCTAssertNotNil(commands.first { $0.id == "note" })        XCTAssertEqual(commands.first { $0.id == "remove" }?.kind, .delete)    }    /// RULE: the opened tier draws the core's answer as it is: its order,    /// the primary act on the fill, the red acts red — the fan ranks and    /// flags nothing itself — every card an object card that keeps its    /// typed handler (`shell.opened`).    func testTheOpenedTierDrawsTheCoresAnswerAsItIs() throws {        let definition = try table("todo")        let answer = try JSONDecoder().decode(OpenedActs.self, from: Data("""            {"acts":[              {"id":"done","label":"Mark done","kind":"command","rank":"main","primary":true,"red":false,"icon":"act-stamp"},              {"id":"set-date","label":"Set date","kind":"command","rank":"more","primary":false,"red":false,"icon":"act-bell","step":"when"},              {"id":"edit-notes","label":"Notes","kind":"command","rank":"more","primary":false,"red":false,"icon":"act-slip"},              {"id":"status","label":"Status","kind":"chooser","rank":"more","primary":false,"red":false,"column":"status","step":"status"},              {"id":"drop","label":"Drop","kind":"command","rank":"away","primary":false,"red":true},              {"id":"delete","label":"Delete","kind":"command","rank":"away","primary":false,"red":true,"icon":"act-bin"}            ]}            """.utf8))        let items = EditingFan.items(of: answer.acts, in: definition)        let cards = items.map { FanTier.Card(item: $0, object: $0.picture, style: .object, red: $0.red, primary: $0.primary) }        XCTAssertEqual(cards.map(\.id), ["command-done", "command-set-date", "command-edit-notes", "act-status", "command-drop", "command-delete"])        XCTAssertEqual(cards.filter(\.red).map(\.id), ["command-drop", "command-delete"])        XCTAssertEqual(cards.filter(\.primary).map(\.id), ["command-done"])        XCTAssertEqual(cards.first?.object, "act-stamp")        XCTAssertEqual(cards[1].handler, .act(.when), "Set date opens the When step")        XCTAssertEqual(cards[2].handler, .command(try XCTUnwrap(definition.commands?.first { $0.id == "edit-notes" })))        XCTAssertEqual(cards[3].handler, .act(.status))        let tiers = FanTiers()        tiers.setRoot(.init(id: "tools", cards: []))        var handler: EditingItem.Does?        tiers.push(.init(id: "acts", cards: cards, raised: cards.first?.id)) { handler = $0.handler }        XCTAssertEqual(tiers.open?.cards, cards)        let first = try XCTUnwrap(cards.first)        tiers.activate(first.id, centred: first.id) { _ in XCTFail("already centred") }        XCTAssertEqual(handler, first.handler)    }    /// RULE (Music 5 walk, 7 Nov 2026): the groups tier is the core's row as    /// it is (`shell.opened {step: group}`): New list first, where the arc    /// rests, then the lists in the core's order with their counts and    /// whether the card is in each; the fan orders and words none of it.    func testTheGroupsTierIsTheCoresRowNewListFirst() throws {        let answer = try JSONDecoder().decode(OpenedStep<GroupChoice>.self, from: Data("""            {"step":{"kind":"group","rows":[              {"value":"new","words":"New group","new":true,"pictogram":"photo:aa"},              {"value":"g1","words":"Night Drives","detail":"5","holds":true,"pictogram":"photo:bb"},              {"value":"g2","words":"Mornings","detail":"0","holds":false}            ]}}            """.utf8))        let items = EditingFan.items(groups: answer.step.rows)        XCTAssertEqual(items.map(\.id), ["group-new", "group-g1", "group-g2"])        XCTAssertEqual(items.map(\.does), [.newGroup, .group("g1"), .group("g2")])        XCTAssertEqual(items.map(\.word), ["New group", "Night Drives", "Mornings"])        XCTAssertEqual(items.map(\.detail), [nil, "5", "0"])        XCTAssertEqual(items.map(\.pictogram), ["photo:aa", "photo:bb", nil])        let fan = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/Shell/EditingFan.swift", ownedBy: "deck"))        XCTAssertFalse(fan.contains("\"group.new\""), "New list's words are the core's")        XCTAssertFalse(fan.contains("role(\"list\")") || fan.contains("role(\"new_list\")"), "the row's pictograms are the core's")    }    /// RULE: the fan keeps no copy of the held card's rules: the acts, their    /// rank, the primary act, the red flag and the statuses are the core's    /// (`shell.opened`), and none of the Swift that rebuilt them is left.    func testTheFanKeepsNoCopyOfTheHeldCardsRules() throws {        let fan = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/Shell/EditingFan.swift", ownedBy: "deck"))        for gone in ["recordActs", "statusCommands", "statusColumn", "PrimaryAct", "resolvedParts", "func ordered", "func away"] {            XCTAssertFalse(fan.contains(gone), "\(gone) is the core's now")        }        let editor = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/Shell/DeckEditor.swift", ownedBy: "deck"))        XCTAssertTrue(editor.contains("CottonMethod.shellOpened"))        XCTAssertFalse(editor.contains("cardsDateChoices") || editor.contains("cardsTimeChoices") || editor.contains("cardsRepeatChoices"))    }}#endif