Cotton code
125 lines · 6.7 KB · SwiftRaw
import CottonKitimport SwiftUIimport XCTest@testable import CottonUI/// Where a deck's "+" goes: the table's own `create.path` when it names one,/// else the blank card (`CreateRoute`).final class DeckAddTests: XCTestCase {    private static func kitTable(_ name: String) throws -> TableDefinition {        let url = SourceSweep.repoRoot.appendingPathComponent("crates/cotton-core/kits/personal/tables/\(name).json")        return try TableDefinition.decode(Data(contentsOf: url))    }    /// RULE: the import People's plus opens covers the whole screen through the one whole-screen cover (`wholeScreen`, the cover a note's reading page opens in), never a card in the deck's frame (owner, 27 Oct 2026: the picker stood narrow inside the deck's card, its right edge cut off): the cover is a full-screen presentation spanning the window, the deck under it out of reach, and the picker's head — Select all and its one close — on screen at a phone's width and at the narrowest.    func testPeoplesPlusOpensTheImportOnTheWholeScreen() async throws {        XCTAssertEqual(Route.parse("/people/import"), .peopleImport)        let flow = SourceSweep.withoutComments(try SourceSweep.mustRead(            "apps/cotton/Sources/CottonUI/Screens/Day/People/PeopleListFlow.swift", ownedBy: "people"))        XCTAssertTrue(flow.contains(".wholeScreen(isPresented: sheetUp, onDismiss: sheetDown) { sheet }"),                      "the People list raises its import through the one whole-screen cover")        XCTAssertFalse(flow.contains(".cottonCard("), "the import is no card inside the deck's frame")        #if os(iOS)        let read = await HostedAccessibility.enable()        XCTAssertTrue(read, "the hosted page's accessibility tree is read")        for width in [402.0, 320.0] {            try await Self.checkTheCover(width: width)        }        #endif    }    #if os(iOS)    @MainActor    private static func checkTheCover(width: CGFloat) async throws {        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: width, height: 874)        let model = PeopleImportModel(core: NoCore(), capabilities: Granted(), book: {            ["Invented Ada", "Invented Bo", "Invented Cy"].enumerated().map { at, name in                DeviceContact(id: "invented-\(at)", fullName: name, phones: ["+00 0000 000\(at)"])            }        })        let deck = Color.clear            .wholeScreen(isPresented: .constant(true)) { PeopleImportSheet(model: model, close: {}) }            .cottonToasts(ToastCenter())        let host = UIHostingController(rootView: deck)        window.rootViewController = host        window.makeKeyAndVisible()        defer { window.isHidden = true }        let cover = try await until("the cover is up at \(width)") { () -> UIViewController? in            guard let shown = host.presentedViewController, shown.transitionCoordinator == nil else { return nil }            return shown        }        // SwiftUI's cover presents over the full screen: a card or a sheet would be a page sheet or nothing at all.        XCTAssertTrue([.fullScreen, .overFullScreen].contains(cover.modalPresentationStyle),                      "a full-screen cover, not a card or a sheet: \(cover.modalPresentationStyle.rawValue)")        XCTAssertEqual(cover.view.frame, window.bounds, "the picker spans the screen at \(width)")        for point in [CGPoint(x: 2, y: 2), CGPoint(x: width / 2, y: 437), CGPoint(x: width - 2, y: 872)] {            let touched = window.hitTest(point, with: nil)            XCTAssertFalse(touched?.isDescendant(of: host.view) ?? false, "the deck under the cover is out of reach at \(point)")        }        for label in [ShellLines.line("people", "import.select_all"), ShellLines.line("people", "import.close")] {            let frame = try await until("\(label) is drawn at \(width)") { Self.frame(of: label, in: cover.view) }            XCTAssertTrue(window.bounds.contains(frame), "\(label) stands inside the screen at \(width): \(frame)")        }        // The title wraps at a phone's width; the line under it starts below it, never over it.        let title = try await until("the title at \(width)") {            Self.frame(of: ShellLines.line("people", "import.choose_who_to_import"), in: cover.view)        }        let under = try await until("the line under the title at \(width)") {            Self.frame(of: ShellLines.line("people", "import.only_the_people_you"), in: cover.view)        }        XCTAssertGreaterThanOrEqual(under.minY, title.maxY - 1, "the title and the line under it overlap at \(width)")    }    /// Polls `read` until it answers, or fails after a few seconds.    @MainActor    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 screen frame of the accessibility element labelled `label` under `root`.    @MainActor    private static func frame(of label: String, in root: UIView) -> CGRect? {        func walk(_ node: NSObject) -> CGRect? {            if node.accessibilityLabel == label { return node.accessibilityFrame }            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)    }    #endif}#if os(iOS)/// A core that answers nothing: the import's own read of who is linked fails/// quietly and every card is offered.private struct NoCore: CottonCalling {    func callRaw(_ method: String, requestJSON: String) async throws -> String {        #"{"ok":false,"error":{"code":"missing","message":"Not here"}}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}/// Contacts access already given.private struct Granted: CapabilityAuthority {    func status(_ capability: DeviceCapability) async -> CapabilityAccess { .authorized }    func ask(_ capability: DeviceCapability) async -> CapabilityAccess { .authorized }}#endif