Cotton code
145 lines · 8.3 KB · SwiftRaw
import CottonKitimport SwiftUIimport XCTest@testable import CottonUI/// Every toast at the top, and the open access window in Account (the owner,/// 17 Nov 2026): the receipt strip and the record/// button's line stand at the toast edge, the top; an allowed window draws no/// standing banner at the foot, Account's Open access card lists it, and End/// closes it. Synthetic rows only.@MainActorfinal class ToastsTopTests: XCTestCase {    private func source(_ path: String) throws -> String {        SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/" + path, ownedBy: "toasts-top"))    }    private static let windows = #"""    {"windows": [       {"grantId": "g-1", "requestId": "req-1", "tables": ["note"], "endsAt": "2099-01-01T00:00:00Z", "said": "Notes · 12 minutes left", "client": "Claude (claude.ai)", "standing": false},       {"grantId": "g-2", "requestId": "req-2", "tables": ["message"], "endsAt": null, "said": "Messages · until you turn it off", "client": null, "standing": true}],     "acts": [{"id": "end", "label": "End now", "receipt": "Ended"}],     "heading": "Open access"}    """#    private func answer(_ json: String) throws -> JSONValue {        try JSONDecoder().decode(JSONValue.self, from: Data(json.utf8))    }    // MARK: 1. The toast edge    /// RULE: The one toast edge is the top: the receipt strip stands there in every presentation that hangs it, under the safe area's top.    func testTheToastEdgeIsTheTop() throws {        XCTAssertEqual(ToastKnobs.edge, .top)        XCTAssertGreaterThan(ToastKnobs.topGap, 0)        let toast = try source("Chrome/Toast.swift")        XCTAssertTrue(toast.contains(".atToastEdge()"), "the strip stands at the toast edge")        XCTAssertTrue(toast.contains(".overlay(alignment: ToastKnobs.edge)"), "the overlay hangs the strip at the toast edge")        XCTAssertFalse(toast.contains("bottomLeading"), "no receipt is hung at the foot")        XCTAssertFalse(toast.contains(".padding(.bottom, 24)"), "no receipt is lifted off the foot")    }    /// RULE: The record button's line (a kept thought's Undo, Opened People) stands at the toast edge too, never just above the fan.    func testTheRecordButtonsLineStandsAtTheTop() throws {        let fan = try source("Surfaces/Board/FanSurface.swift")        let line = try XCTUnwrap(fan.range(of: "FanVoiceLine(toast: toast)"))        let after = String(fan[line.upperBound...].prefix(240))        XCTAssertTrue(after.contains(".atToastEdge()"), "the line stands at the toast edge: \(after)")        XCTAssertFalse(after.contains(".padding(.bottom"), "the line is not lifted off the fan's foot")    }    /// RULE: Every passing receipt card (Home's change and typed thought, the list's, the action chooser's) hangs at the toast edge, and none stands in a bottom inset.    func testEveryReceiptCardHangsAtTheTop() throws {        for path in ["Surfaces/BoardSurface.swift", "Surfaces/RecordListSurface.swift", "Surfaces/RecordActionChooser.swift"] {            let text = try source(path)            XCTAssertTrue(text.contains(".receiptAtToastEdge {"), "\(path) hangs its receipt at the toast edge")        }        let board = try source("Surfaces/BoardSurface.swift")        let inset = try XCTUnwrap(board.range(of: ".safeAreaInset(edge: .bottom"))        let foot = String(board[inset.upperBound...].prefix(400))        XCTAssertFalse(foot.contains("receipt"), "Home's foot holds the record button alone: \(foot)")        let list = try source("Surfaces/RecordListSurface.swift")        XCTAssertFalse(list.contains("} else {\n                    receipt"), "the list's receipt is not a slip above its bar")        XCTAssertFalse(list.contains(".move(edge: .bottom)"), "the list's receipt does not rise from the foot")        let chooser = try source("Surfaces/RecordActionChooser.swift")        XCTAssertFalse(chooser.contains(".safeAreaInset(edge: .bottom)"), "the chooser's receipt is not at the foot")        let input = try source("Surfaces/HomeInput.swift")        XCTAssertFalse(input.contains("HomeThoughtReceipt("), "the box draws no receipt above itself; it hands it up")        XCTAssertTrue(input.contains(".preference(key: HomeReceiptKey.self"))        let toast = try source("Chrome/Toast.swift")        XCTAssertTrue(toast.contains("overlay(alignment: ToastKnobs.edge)"))    }    /// RULE: A toast with Undo still undoes and keeps its window: only the edge moved.    func testUndoAndTheWindowAreUnchanged() {        let center = ToastCenter(scheduler: ImmediateNever())        var undone = false        center.show("Moved to the bin", undo: { undone = true })        XCTAssertEqual(center.current?.message, "Moved to the bin")        center.undo()        XCTAssertTrue(undone)        XCTAssertNil(center.current)    }    // MARK: 2. Open access in Account    /// RULE: An allowed window draws no standing banner: the unlock layer draws only the request's card, and no row or End of an open window.    func testNoStandingBannerForAnOpenWindow() throws {        let layer = try source("Boot/UnlockAsks.swift")        let body = try XCTUnwrap(layer.range(of: "struct UnlockAsksLayer"))        let drawn = String(layer[body.lowerBound...])        XCTAssertFalse(drawn.contains("asks.windows"), "the layer draws no open window")        XCTAssertFalse(drawn.contains("unlock-end-"), "no End stands at the foot")        XCTAssertFalse(drawn.contains("unlock-window-"), "no window row stands at the foot")    }    /// RULE: Account's Open access card lists each open window by its assistant with the core's words (tables, time left) under the core's heading; End on the fan is named by the assistant.    func testAccountListsAnOpenWindow() throws {        let open = try XCTUnwrap(OpenAccess(try answer(Self.windows)))        XCTAssertEqual(open.heading, "Open access")        XCTAssertEqual(open.rows, [            OpenAccess.Row(grantId: "g-1", client: "Claude (claude.ai)", said: "Notes · 12 minutes left"),            OpenAccess.Row(grantId: "g-2", client: nil, said: "Messages · until you turn it off"),        ])        let card = open.drawn        XCTAssertEqual(card.face, "plain")        XCTAssertEqual(card.fields["title"], .text("Open access"))        XCTAssertEqual(card.fields["facts"], .list([            .object(["label": .text("Claude (claude.ai)"), "said": .text("Notes · 12 minutes left")]),            .object(["label": .text(""), "said": .text("Messages · until you turn it off")]),        ]))        XCTAssertEqual(open.rows.map(open.endWord), ["End now · Claude (claude.ai)", "End now"])        XCTAssertEqual(open.end?.receipt, "Ended")    }    /// RULE: No window open, no card: an empty list draws nothing.    func testNoWindowDrawsNothing() throws {        XCTAssertNil(OpenAccess(nil))        XCTAssertNil(OpenAccess(try answer(#"{"windows": [], "acts": [{"id": "end", "label": "End now"}], "heading": "Open access"}"#)))    }    /// RULE: End on a window posts `unlock.end` for its grant; read again, the window is gone and the card with it.    func testEndClosesTheWindow() async throws {        let core = ScriptedCore([CottonMethod.unlockEnd: .ok(#"{"ended": "g-1"}"#)])        let open = try XCTUnwrap(OpenAccess(try answer(Self.windows)))        try await OpenAccess.end(open.rows[0], core: core)        let calls = await core.calls        XCTAssertEqual(calls.first { $0.method == CottonMethod.unlockEnd }?.requestJSON, #"{"grantId":"g-1"}"#)        let after = #"{"windows": [], "acts": [{"id": "end", "label": "End now", "receipt": "Ended"}], "heading": "Open access"}"#        XCTAssertNil(OpenAccess(try answer(after)), "the ended window leaves nothing on screen")    }    /// RULE: Account places Open access among its cards while a window is open, and End stands on its fan.    func testAccountPlacesTheCard() throws {        let page = try source("Surfaces/Board/AccountPage.swift")        XCTAssertTrue(page.contains("if OpenAccess(windows) != nil { items.append(Item(id: Self.openAccessCard)) }"))        XCTAssertTrue(page.contains("id == Self.openAccessCard || id == Self.readsCard"))    }}/// A scheduler that never fires: the window is not what these tests measure.private struct ImmediateNever: ToastScheduler {    struct Ticket: ToastTicket { func cancel() {} }    func schedule(after seconds: TimeInterval, _ work: @escaping @MainActor () -> Void) -> any ToastTicket { Ticket() }}