Cotton code
169 lines · 9.5 KB · SwiftRaw
// The fan hovers over the page (owner, 12 Nov 2026): in every app the fan// is the one menu, and opening or closing it moved the card on the page by// some 2–3% of the screen. The deck stood its card above the bloomed fan's// cover (`FanCover.edge`), which is nil while the fan is closed into the hub,// so a closed fan handed the card the whole page and it grew; opened, it// shrank back. The card now stands above the standing fan's top// (`FanCover.standingEdge`), which no fold moves.//// The whole fan is hosted here, as an app draws it: Books' (one tool, the// fan opening on its views) and Cotton's (many tools), each with a tool's// deck as its page, and the page above the fan pictured with the fan open,// closed and open again.#if os(iOS)import CottonValuesimport SwiftUIimport UIKitimport XCTest@testable import CottonUI@MainActorfinal class FanHoversTests: XCTestCase {    /// RULE: in a one-tool app whose fan opens on its views (Books), closing the fan into the hub and opening it again moves and resizes the deck's card by not a single point.    func testABooksFanOpensAndClosesOverAStillCard() async throws {        let views = ToolViews()        views.take(try FanAnswerFixtures.books())        let tiles = [FanTile(key: "books", name: "Books", picture: nil, stock: .tan, ringed: true)]        try await assertTheCardStandsStill(tiles: tiles, opens: 0, views: views, app: "Books")    }    /// RULE: in a many-tool app (Cotton), closing the fan into the hub and opening it again moves and resizes the deck's card by not a single point.    func testACottonFanOpensAndClosesOverAStillCard() async throws {        let views = ToolViews()        views.take(try FanAnswerFixtures.cotton())        let tiles = ["calendar", "home", "todos", "tools", "settings"].map {            FanTile(key: $0, name: $0.capitalized, picture: nil, stock: .tan, ringed: true)        }        try await assertTheCardStandsStill(tiles: tiles, opens: 2, views: views, app: "Cotton")    }    /// RULE: the standing fan's top reads nothing the fan does: only the page area's foot and the standing fan's room.    func testTheStandingEdgeIgnoresTheFansState() {        XCTAssertEqual(FanRoom.standingEdge(areaFoot: 800, standingRoom: 260), 540)        XCTAssertNil(FanRoom.standingEdge(areaFoot: nil, standingRoom: 260), "no page area measured yet")        // The cover goes as the fan closes; the standing edge stays.        XCTAssertNil(FanRoom.cover(collapsed: true, tucked: false, keyboardUp: false, areaFoot: 540))        XCTAssertEqual(FanRoom.cover(collapsed: false, tucked: false, keyboardUp: false, areaFoot: 540), 540)    }    /// RULE: no page lays itself out from the bloomed fan's cover — it only takes covered rows out of the accessibility tree.    func testNoDeckLaysItsCardOnTheBloomedCover() throws {        for path in ["Deck/DeckSurface.swift", "Deck/CardDeck.swift"] {            let code = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/" + path, ownedBy: "fan hovers"))            XCTAssertFalse(code.contains("cover?.edge"), "\(path) lays its card on the bloomed fan's cover")            XCTAssertTrue(code.contains("cover?.standingEdge"), "\(path) does not stand its card on the standing fan's top")        }    }    // MARK: The fan over a deck    /// The fan over a deck of three notes, its page as an app draws it; the    /// page above the standing fan pictured open, closed into the hub and    /// open again: every pixel the same.    private func assertTheCardStandsStill(tiles: [FanTile], opens: Int, views: ToolViews, app: String) async throws {        let table = "note-\(UUID().uuidString.prefix(8).lowercased())"        let note = try DeckNewNoteTests.note(table)        let store = NotebookRecords(note, titles: ["Seeds to buy", "Gate code", "Lamp repair"])        let collapse = FanCollapse()        let cover = FanCover()        let host = UIHostingController(rootView: AnyView(            FanHome(tiles: tiles, page: { _ in AnyView(DeckSurface(definition: note, filter: [:], view: nil)) },                    collapse: collapse, opens: opens, shellCover: cover, fan: views)                .environment(\.records, store)                .environment(\.cottonCore, store)))        let window = try Self.window(host)        defer { window.isHidden = true }        let open = try await Self.settledPage(of: cover, "\(app): the page under the open fan") {            cover.edge != nil        }        collapse.fold(animation: nil)        let closed = try await Self.settledPage(of: cover, "\(app): the page under the closed fan") {            collapse.collapsed && cover.edge == nil        }        XCTAssertEqual(closed.rect, open.rect, "\(app): closing the fan moved the standing fan's top")        XCTAssertTrue(closed.pixels == open.pixels, "\(app): closing the fan moved or resized the card (\(Self.changed(open.pixels, closed.pixels)) bytes differ)")        collapse.swipedUp(animation: nil)        let reopened = try await Self.settledPage(of: cover, "\(app): the page under the reopened fan") {            !collapse.collapsed && cover.edge != nil        }        XCTAssertTrue(reopened.pixels == open.pixels, "\(app): opening the fan moved or resized the card (\(Self.changed(open.pixels, reopened.pixels)) bytes differ)")    }    /// A phone whose card, under the open fan, is bounded by the room's    /// height rather than its width, as on an iPhone 16 (393 x 852 less its    /// status bar and home indicator): there a card given more room grows.    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: 740)        window.rootViewController = root        window.makeKeyAndVisible()        return window    }    /// The page above the standing fan's top, short of the tiles that lean    /// over it, pictured once `ready` holds and the picture has stood still    /// over several frames.    private static func settledPage(of cover: FanCover, _ what: String, ready: () -> Bool) async throws -> (rect: CGRect, pixels: [UInt8]) {        let deadline = Date().addingTimeInterval(8)        var last: [UInt8]?        var still = 0        while Date() < deadline {            if ready(), let edge = cover.standingEdge, edge > FanHoversKnobs.leaning {                let rect = CGRect(x: 0, y: 0, width: 402, height: edge - FanHoversKnobs.leaning)                if let image = PagePictures.capture(rect, scale: 1) {                    let pixels = PagePictures.pixels(image)                    still = pixels == last ? still + 1 : 0                    last = pixels                    if still >= 4 { return (rect, pixels) }                }            }            try await Task.sleep(for: .milliseconds(50))        }        return try XCTUnwrap(nil as (CGRect, [UInt8])?, "\(what): never stood still (standing edge \(String(describing: cover.standingEdge)))")    }    private static func changed(_ a: [UInt8], _ b: [UInt8]) -> Int {        guard a.count == b.count else { return max(a.count, b.count) }        return zip(a, b).filter { $0 != $1 }.count    }}private enum FanHoversKnobs {    /// How far over the standing fan's top its raised tiles may lean: the    /// page is compared above it.    static let leaning: CGFloat = 100}/// The fan's first tier as the core answers it for Books and for Cotton/// (`shell.fan`), as `FanRootTests` reads them.enum FanAnswerFixtures {    static func books() throws -> FanAnswer {        try JSONDecoder().decode(FanAnswer.self, from: Data(#"""        {"opens": {"tier": "views", "tool": "books", "view": "reading"},         "root": {"id": "views-books", "cards": ["reading", "want", "all"], "raised": "reading"},         "tiles": [{"key": "books", "name": "Books", "kind": "tool", "tool": "books", "stock": "tan", "ringed": true, "poster": false,                    "views_table": "book", "counted": true, "current": "reading",                    "views": [{"id": "reading", "label": "Reading", "count": 3, "default": true, "read": {"table": "book"}},                              {"id": "want", "label": "Want to read", "count": 0, "default": false, "read": {"table": "book"}},                              {"id": "all", "label": "All", "count": 3, "default": false, "read": {"table": "book"}}]}]}        """#.utf8))    }    static func cotton() throws -> FanAnswer {        try JSONDecoder().decode(FanAnswer.self, from: Data(#"""        {"opens": {"tier": "tools", "tool": "todos"},         "root": {"id": "tools", "cards": ["calendar", "home", "todos", "tools", "settings"], "raised": "todos"},         "tiles": [{"key": "calendar", "name": "Calendar", "kind": "tool", "tool": "calendar", "ringed": true, "poster": false, "counted": false, "views": []},                   {"key": "home", "name": "Home", "kind": "home", "ringed": false, "poster": false, "counted": false, "views": []},                   {"key": "todos", "name": "Todos", "kind": "tool", "tool": "todos", "ringed": true, "poster": false, "counted": false, "views": []},                   {"key": "tools", "name": "Tools", "kind": "tools", "ringed": true, "poster": false, "counted": false, "views": []},                   {"key": "settings", "name": "Settings", "kind": "settings", "ringed": true, "poster": false, "counted": false, "views": []}]}        """#.utf8))    }}#endif