Cotton code
170 lines · 11.6 KB · SwiftRaw
// Full screen is the thing, not a bigger card (owner, 26 Oct 2026): a tap on// a photo card's print or a film card's still, or a pinch out on either,// opens the one viewer over the deck's records in deck order. Invented// tables and records.import CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class DeckFullScreenTests: XCTestCase {    static func table(_ id: String, title: String = "caption", columns: String, slip: String, viewer: Bool = false, card: String,                      page: String = "[]") throws -> TableDefinition {        let json = """        {"id":"\(id)","name":"\(id)","plural":"\(id)s","builtin":false,         "columns":[{"key":"caption","name":"Caption","type":"text"}\(columns)],         "title":"\(title)","date":null,"project":null,"order":null,         "slip":\(slip),"tile":{"face":"slip-list"},"page":\(page),"tables":[],         \(viewer ? #""viewer":{},"# : "")         "card":\(card)}        """        return try JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8))    }    static func photos() throws -> TableDefinition {        try table("snapshot_example", columns: #",{"key":"key","name":"Picture","type":"photo"}"#,                  slip: #"{"title":"caption","photo":"key"}"#, viewer: true,                  card: #"{"face":"photo.print","fields":[{"slot":"photo","column":"key"},{"slot":"title","column":"caption"}]}"#)    }    static func films() throws -> TableDefinition {        try table("clip_example", columns: #",{"key":"file","name":"File","type":"file"},{"key":"poster","name":"Poster","type":"photo"}"#,                  slip: #"{"title":"caption","photo":"poster","player":"file"}"#,                  card: #"{"face":"video","fields":[{"slot":"photo","column":"poster"},{"slot":"title","column":"caption"}]}"#)    }    private static func record(_ id: String, _ values: [String: RecordValue]) -> TableRecord {        TableRecord(id: id, values: values)    }    /// RULE: A photo card's open reaches the one viewer with the deck's pictures in deck order, standing on the card tapped, so a swipe sideways walks the deck.    func testAPhotoCardsOpenReachesThePresenterWithTheDecksSet() throws {        let photos = try Self.photos()        let deck = ["c", "a", "b"].map { Self.record($0, ["key": .text("photo:\($0)"), "caption": .text("Shore \($0)")]) }        let presenter = ViewerPresenter()        XCTAssertTrue(DeckViewer.open("a", in: deck, definition: photos, presenter: presenter))        let set = try XCTUnwrap(presenter.current)        XCTAssertEqual(set.items.map(\.id), ["snapshot_example/c", "snapshot_example/a", "snapshot_example/b"])        XCTAssertEqual(set.items.map(\.kind), [.photo, .photo, .photo])        XCTAssertEqual(set.start, 1)        XCTAssertEqual(presenter.showing, DeckViewer.itemID(photos, "a"))    }    /// RULE: a pinch opens the viewer at once on the cards dealt, and the    /// deck's whole read grows it where it stands (it waited on the whole    /// table before opening, 315ce03df9).    func testTheViewerOpensAtOnceAndGrowsIntoTheWholeDeck() async throws {        let photos = try Self.photos()        let all = (0..<150).map { Self.record("p\($0)", ["key": .text("photo:\($0)")]) }        let presenter = ViewerPresenter()        let opening = DeckOpening.of(all[3], card: nil, in: Array(all.prefix(50)), definition: photos,                                     presenter: presenter, readAll: { all })        opening.viewer?()        XCTAssertEqual(presenter.current?.items.count, 50, "open at once on what was dealt")        let id = presenter.current?.id        for _ in 0..<200 where presenter.current?.items.count != 150 { try await Task.sleep(for: .milliseconds(5)) }        XCTAssertEqual(presenter.current?.items.count, 150)        XCTAssertEqual(presenter.current?.id, id, "the same viewer, grown")        XCTAssertEqual(presenter.showing, DeckViewer.itemID(photos, "p3"))    }    /// RULE: a viewer closed before the deck's whole read lands stays    /// closed: the read stops with it (the uncancelled read opened it again).    func testAClosedViewerStaysClosedWhenTheReadLands() async throws {        let photos = try Self.photos()        let all = (0..<150).map { Self.record("p\($0)", ["key": .text("photo:\($0)")]) }        let presenter = ViewerPresenter()        let opening = DeckOpening.of(all[0], card: nil, in: Array(all.prefix(50)), definition: photos, presenter: presenter,                                     readAll: { try? await Task.sleep(for: .milliseconds(100)); return all })        opening.viewer?()        presenter.current = nil        try await Task.sleep(for: .milliseconds(300))        XCTAssertNil(presenter.current)    }    /// RULE: A film card's play reaches the one viewer the same way: its table's slip names the column it plays from, the set is the deck's films in deck order.    func testAFilmCardsPlayReachesThePresenterWithTheDecksSet() throws {        let films = try Self.films()        let deck = ["x", "y"].map { Self.record($0, ["file": .text("file:\($0)"), "poster": .text("photo:\($0)")]) }        let presenter = ViewerPresenter()        XCTAssertTrue(DeckViewer.open("y", in: deck, definition: films, presenter: presenter))        let set = try XCTUnwrap(presenter.current)        XCTAssertEqual(set.items.map(\.id), ["clip_example/x", "clip_example/y"])        XCTAssertEqual(set.items.map(\.kind), [.video, .video])        XCTAssertEqual(set.items[1].key, "file:y")        XCTAssertEqual(set.start, 1)    }    /// RULE: A table whose records the viewer does not show opens nothing in it.    func testATableTheViewerDoesNotShowOpensNothing() throws {        let notes = try Self.table("jotting_example", columns: "", slip: #"{"title":"caption"}"#,                                   card: #"{"face":"note.page","fields":[{"slot":"title","column":"caption"}]}"#)        let presenter = ViewerPresenter()        XCTAssertFalse(DeckViewer.open("a", in: [Self.record("a", ["caption": .text("A line")])], definition: notes, presenter: presenter))        XCTAssertNil(presenter.current)    }    /// RULE: One function decides what a pinch out on a record's card opens, from its definition alone: a table with the viewer (a picture, a document) or a film's player opens the viewer, a note or a memory its reading page, and every other card — or a record with no definition — the whole card.    func testTheRouteDecidesFromTheDefinition() throws {        XCTAssertEqual(FullScreenRoute.of(try Self.photos()), .viewer)        XCTAssertEqual(FullScreenRoute.of(try Self.films()), .viewer)        let papers = try Self.table("paper_example", columns: #",{"key":"file","name":"File","type":"file"}"#,                                    slip: #"{"title":"caption"}"#, viewer: true,                                    card: #"{"face":"document","fields":[{"slot":"title","column":"caption"}]}"#)        XCTAssertEqual(FullScreenRoute.of(papers), .viewer)        let notes = try Self.table("jotting_example", columns: #",{"key":"words","name":"Words","type":"longtext"}"#,                                   slip: #"{"title":"caption"}"#,                                   card: #"{"face":"note.page","fields":[{"slot":"title","column":"caption"},{"slot":"body","column":"words"}]}"#)        XCTAssertEqual(FullScreenRoute.of(notes), .reading(ReadSlots(title: "caption", bodies: ["words"])))        let memories = try Self.table("kept_example", title: "said",                                      columns: #",{"key":"said","name":"Said","type":"longtext"},{"key":"quote","name":"Quote","type":"longtext"},{"key":"area","name":"Area","type":"text"}"#,                                      slip: #"{"title":"said"}"#,                                      card: #"{"face":"memory","fields":[{"slot":"body","column":"quote"},{"slot":"subtitle","column":"area"}]}"#)        XCTAssertEqual(FullScreenRoute.of(memories), .reading(ReadSlots(title: "area", bodies: ["said", "quote"])))        let chores = try Self.table("chore_example", columns: #",{"key":"notes","name":"Notes","type":"longtext"}"#,                                    slip: #"{"title":"caption"}"#,                                    card: #"{"face":"todo.card","fields":[{"slot":"title","column":"caption"},{"slot":"body","column":"notes"}]}"#)        XCTAssertEqual(FullScreenRoute.of(chores), .whole)        XCTAssertEqual(FullScreenRoute.of(nil), .whole)    }    /// RULE: The deck and the search deck both ask the one route what a card opens, and a tap on a photo's print or a film's still is the viewer's own act from it.    func testTheDecksAskTheOneRoute() throws {        let root = SourceSweep.iosSources.deletingLastPathComponent()        for path in ["Sources/CottonUI/Deck/DeckSurface.swift", "Sources/CottonUI/Screens/Search/SearchDeck.swift"] {            let code = try String(contentsOf: root.appendingPathComponent(path), encoding: .utf8)            XCTAssertTrue(code.contains("DeckOpening.of("), "\(path) decides its own full screen")            XCTAssertTrue(code.contains(".deckZoned(zones, move:"), "\(path) leaves the card's tap unhosted")            if path.hasSuffix("DeckSurface.swift") {                // The core says the card opens in the viewer (`tap.card`); the deck opens the one it hosts.                XCTAssertTrue(code.contains("case .viewer:\n                guard let viewer = opening.viewer else { return openAtRest(record) }"),                              "\(path) leaves the viewer route dead")            } else {                XCTAssertTrue(code.contains("else if opening.viewer != nil { opening.viewer?() }"), "\(path) leaves the viewer route dead")            }        }    }    /// RULE: The deck routes a tap on a photo's print or a film's still — their faces' `picture` part — to the act that opens the viewer, never a dead tap, and the card is the tile the viewer grows out of; only a picture whose card chooses a column with it (an event's kind) turns the fan instead.    func testTheDeckOpensAPhotoOrAFilmFromItsPicture() throws {        let root = SourceSweep.iosSources.deletingLastPathComponent()        let face = try String(contentsOf: root.appendingPathComponent("Sources/CottonUI/Deck/DeckFace.swift"), encoding: .utf8)        XCTAssertTrue(face.contains("open: opens ? open : nil,"))        let parts = try String(contentsOf: root.appendingPathComponent("Sources/CottonUI/Deck/Shell/DeckFaceParts.swift"), encoding: .utf8)        XCTAssertTrue(parts.contains("case .picture:\n                AnyView(content.modifier(DeckPicturePart(open: acts.open)))"))        // A picture the core's tap map says chooses nothing (`viewer`) is the viewer's.        XCTAssertTrue(parts.contains("DeckFaceParts.tapped(AnyView(content), open)"))        let faces = SourceSweep.loomSources.appendingPathComponent("CottonFaces/Cotton")        for name in ["PhotoPrintFace", "VideoFace", "FilmVHSFace"] {            let source = try String(contentsOf: faces.appendingPathComponent("\(name).swift"), encoding: .utf8)            XCTAssertTrue(source.contains(".facePart(.picture)"), "\(name) does not tag its picture")        }        let surface = try String(contentsOf: root.appendingPathComponent("Sources/CottonUI/Deck/DeckSurface.swift"), encoding: .utf8)        // d2c830d22: the card's zoned tap owns opening; a picture no        // longer needs a second open closure threaded through DeckFace.        XCTAssertTrue(surface.contains(".deckZoned(zones, move:"))        XCTAssertTrue(surface.contains("case .viewer:\n                guard let viewer = opening.viewer else { return openAtRest(record) }\n                haptics.select()\n                viewer()"))        XCTAssertTrue(surface.contains(".viewerSource(DeckViewer.itemID(own(record), record.id))"))    }}