Cotton code
178 lines · 12.6 KB · SwiftRaw
import CottonKitimport CottonValuesimport PhotosUIimport UniformTypeIdentifiersimport XCTest@testable import CottonUI/// Plus on the Books deck is a choice tier (the coordinator, 4 Nov 2026):/// Find a book · Add a file · Bring Goodreads in, the same tier the empty/// deck offers held (`DeckDoors`).final class DeckDoorsTests: XCTestCase {    private static func book() throws -> TableDefinition {        let url = SourceSweep.repoRoot.appendingPathComponent("crates/cotton-core/kits/personal/tables/book.json")        return try TableDefinition.decode(Data(contentsOf: url))    }    /// RULE: A door's files go through the share sheet's own intake (`ShareIntake.intake`, staged as a share is), and a book the intake lands on opens on the fan's deck at its card where the fan holds its table, never a page over the deck.    func testAFilesDoorIsTheShareSheetsIntake() throws {        let doors = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/Shell/DeckDoors.swift", ownedBy: "deck"))        XCTAssertTrue(doors.contains("stageForIntake(urls"), "the chosen files are staged as a share is")        XCTAssertTrue(doors.contains("await intake.intake(staged)"), "and handed to the share sheet's intake")        let root = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Boot/RootView.swift", ownedBy: "boot"))        XCTAssertTrue(root.contains(".environment(\\.shareIntake, shares)"), "the window hands the deck its intake")        XCTAssertTrue(root.contains("window.navigator.fanBrings?(table, id, landing.many) == true"), "a landed book opens at its card on the fan")    }    /// RULE (7 Nov 2026): an OPML door's picker takes OPML, plain XML and every type `.opml` is known by (Reeder and Overcast claim it under their own); any other door's takes its types alone. Books' folder door brings a tree in as books.    func testAnOpmlDoorAlsoTakesXmlAndAFolderDoorIsBooks() throws {        let opml = DeckDoors.types(DefinitionCreateFiles(_generated: (), types: ["org.opml.opml"]))        XCTAssertTrue(opml.contains(.xml), "a list saved as .xml can be picked")        // The test host declares no OPML type (Cotton's plist imports it), so it is the XML and the extension's here.        XCTAssertTrue(opml.contains { $0.preferredFilenameExtension == "opml" } || UTType("org.opml.opml") == nil)        XCTAssertEqual(Set(opml).count, opml.count, "each type once")        XCTAssertEqual(DeckDoors.types(DefinitionCreateFiles(_generated: (), types: ["public.folder"])), [.folder])        let doors = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/Shell/DeckDoors.swift", ownedBy: "deck"))        XCTAssertTrue(doors.contains("if table == bookTable { return await intake.intake(staged, foldersAreBooks: true) }"))    }    /// RULE (Photos, 12 Nov 2026): a picture door's accepts carry its pick; Choose photos opens the system's photo picker with no limit for a door that takes many, filtered to the kinds it names, and Take a photo opens the camera, filming too when the door takes a clip; what either brings goes through the share sheet's intake as a door's files do.    func testAPictureDoorPicksThroughTheSystemsPickers() throws {        let plus = """        {"does": "doors", "label": "Add photos", "doors": [          {"id": "library", "label": "Choose photos", "picture": "act-sheet",           "accepts": {"pick": {"source": "library", "kinds": ["photo", "video"], "many": true}}},          {"id": "camera", "label": "Take a photo", "picture": "act-camera",           "accepts": {"pick": {"source": "camera", "kinds": ["photo"]}}}]}        """        let read = try JSONDecoder().decode(DeckAnswer.Plus.self, from: Data(plus.utf8))        let library = try XCTUnwrap(read.doors[0].accepts.pick)        let camera = try XCTUnwrap(read.doors[1].accepts.pick)        XCTAssertNil(read.doors[0].accepts.files)        XCTAssertEqual(library.source, .library)        XCTAssertNil(DeckDoors.limit(library), "as many as the person picks")        XCTAssertEqual(DeckDoors.limit(camera), 1)        XCTAssertEqual(DeckDoors.filter([.photo]), .images)        XCTAssertEqual(DeckDoors.filter([.video]), .videos)        XCTAssertNotEqual(DeckDoors.filter([.photo, .video]), .images, "a door taking both takes clips too")        XCTAssertTrue(DeckDoors.films(library))        XCTAssertFalse(DeckDoors.films(camera), "a door that takes photos alone never films")        let doors = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/Shell/DeckPictureDoors.swift", ownedBy: "deck"))        XCTAssertTrue(doors.contains("await DeckDoors.bring(urls, for: table, through: shareIntake, toasts: toasts, core: core)"),                      "what is picked or taken lands where a share of it lands")        for surface in ["Deck/DeckSurface.swift", "Surfaces/RecordListSurface.swift"] {            let source = try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/\(surface)", ownedBy: "deck")            XCTAssertTrue(source.contains(".doorPictures($"), "\(surface) opens a picture door")        }    }    /// RULE (books-4-walk, 6 Nov 2026: Find a book's card never stood on an empty Reading): a landed record is brought into the deck's reading held now whenever it reads the table — the surface the landing captured read the view before the record's arrival changed its count, so its gated `model` is nil — and never into another table's.    @MainActor    func testALandingBringsIntoTheReadingHeldNow() {        let asked = DeckReading.Asked(table: "book", view: "books/reading", filter: [:], opensOn: nil, database: nil)        let held = DeckReading(asked: asked, core: nil, store: nil)        XCTAssertTrue(DeckLanding.reading(held, table: "book") === held)        XCTAssertNil(DeckLanding.reading(held, table: "todo"))        XCTAssertNil(DeckLanding.reading(nil, table: "book"))        let surface = SourceSweep.withoutComments(            (try? SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/DeckSurface.swift", ownedBy: "deck")) ?? "")        XCTAssertTrue(surface.contains("let model = DeckLanding.reading(heldModel, table: definition.id)"), "bring asks the reading held now, never the view-gated model")    }    /// RULE (books-4-walk, 6 Nov 2026: Find a book's card stood on Reading, then an EPUB added left Reading blank): once a read lands, the deck's visitor is the record it stands on as answered, over one it held before; a held visitor the reading answers anew is refreshed; one it does not answer is kept only when nothing stands for the front.    func testTheVisitorIsTheRecordTheDeckStandsOn() {        let found = TableRecord(id: "found", values: ["title": .text("Winter's Orbit")])        let added = TableRecord(id: "added", values: ["title": .text("The Yellow Wallpaper")])        let none: (String) -> TableRecord? = { _ in nil }        XCTAssertEqual(DeckLanding.visitor(holding: found, front: "added", answered: none, brought: added)?.id, "added",                       "the raced read left Find a book's card held: the added book stands")        XCTAssertEqual(DeckLanding.visitor(holding: nil, front: "added", answered: none, brought: added)?.id, "added")        let fresh = TableRecord(id: "found", values: ["title": .text("Winter's Orbit, covered")])        XCTAssertEqual(DeckLanding.visitor(holding: found, front: "found", answered: { $0 == "found" ? fresh : nil }, brought: nil)?.values["title"], .text("Winter's Orbit, covered"))        XCTAssertEqual(DeckLanding.visitor(holding: found, front: "found", answered: none, brought: nil)?.id, "found", "kept while its read is out")        XCTAssertNil(DeckLanding.visitor(holding: nil, front: "added", answered: none, brought: found), "another record's visitor never stands for the front")        let surface = SourceSweep.withoutComments(            (try? SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/DeckSurface.swift", ownedBy: "deck")) ?? "")        XCTAssertTrue(surface.contains("visitor = model?.visitor.flatMap { $0.id == id ? $0.record.record : nil } ?? seen"), "bring takes only the record it brought")    }    /// The core's Find a book: its words asked under the door's label, and    /// the object's answer landing on the book it names where `lands` is said.    private static func finding(lands: Bool) -> InputCore {        InputCore { method, request in            switch (method, request["op"]?.string) {            case ("tools.acts", _):                return .success(InputCore.json(#"{"actions":[]}"#))            case ("shell.input", "ask"):                return .success(InputCore.json(#"{"editor":"line","words":"","hint":"Find a book","keeps_words":false,"writes":{"kind":"act","table":"book","name":"find_book","argument":"query","lands":"book"}}"#))            case ("shell.input", "commit"):                return .success(lands ? InputCore.json(#"{"lands":{"id":"b-1"}}"#) : .object([:]))            default:                return .failure(CottonCallError(code: "missing", message: "Not here"))            }        }    }    /// RULE: A door's act asks its words of the core under the door it is (`shell.input {kind: act, door}`), and lands on the record the core's answer names; an answer that names none lands nowhere.    @MainActor    func testFindABookLandsOnTheBookItAnswers() async throws {        let core = Self.finding(lands: true)        let editor = DeckEditor.standing()        var landed: [String] = []        editor.ask(table: "book", door: "find", core: core) { landed.append($0) }        try await eventually { editor.writing != nil }        XCTAssertEqual(core.asked("shell.input", op: "ask").first?["door"], "find")        XCTAssertEqual(editor.writing?.hint, "Find a book")        editor.commit("winter orbits")        try await eventually { !landed.isEmpty }        XCTAssertEqual(core.asked("shell.input", op: "commit").first?["words"], "winter orbits")        XCTAssertEqual(landed, ["b-1"])        let nowhere = Self.finding(lands: false)        editor.ask(table: "book", door: "find", core: nowhere) { landed.append($0) }        try await eventually { editor.writing != nil }        editor.commit("winter orbits")        try await eventually { !nowhere.asked("shell.input", op: "commit").isEmpty }        try await Task.sleep(for: .milliseconds(100))        XCTAssertEqual(landed, ["b-1"], "an answer that names no record lands nowhere")    }    /// RULE: Before sign-in Find a book asks no words it cannot send: its own words ("Sign in to find books by name") stand until the next tap and the fan offers the Account card's acts (Sign in alone); signed in, its words are asked in the shell's input and nothing is said.    @MainActor    func testFindABookBeforeSignInSaysSoAndOffersSignIn() async throws {        var act = DefinitionCreateAct(name: "find_book", argument: "query", lands: "book")        act.signedOut = "Sign in to find books by name"        let toasts = ToastCenter(scheduler: ManualToastScheduler())        let editor = DeckEditor.standing()        editor.askDoor(act, door: "find", table: "book", core: SignInCore(), toasts: toasts)        for _ in 0..<50 where toasts.current == nil { try await Task.sleep(for: .milliseconds(20)) }        XCTAssertEqual(toasts.current?.message, "Sign in to find books by name")        XCTAssertEqual(toasts.current?.untilTap, true, "the line stands until the next tap")        XCTAssertEqual(editor.actions.map(\.id), ["account_sign_in"])        XCTAssertEqual(editor.editing, .toolActs(.emptyDeck(of: "book")))        XCTAssertNil(editor.writing, "no words are asked")        toasts.tapped()        XCTAssertNil(toasts.current, "the next tap takes it away")        let signedIn = DeckEditor.standing()        signedIn.askDoor(act, door: "find", table: "book", core: Self.finding(lands: true), toasts: toasts)        for _ in 0..<50 where signedIn.writing == nil { try await Task.sleep(for: .milliseconds(20)) }        XCTAssertNotNil(signedIn.writing, "signed in, the words are asked")        XCTAssertNil(toasts.current)    }}/// The core as `shell.account` answers a phone not signed in: Sign in alone.private final class SignInCore: CottonCalling, @unchecked Sendable {    func callRaw(_ method: String, requestJSON: String) async throws -> String {        #"{"ok":true,"data":{"key":"account","name":"Account","line":"Signed out","stand":"local","card":{"title":"Account","subtitle":"Signed out","facts":[]},"actions":[{"id":"account_sign_in","label":"Sign in","kind":"tool","tool":"books"}]}}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}    func close() {}}