Cotton code
185 lines · 10.8 KB · SwiftRaw
// A whole opens into its parts (66a451ec1): a card's `opens` names the// parts' table, their link back to the whole, the order they are dealt in// and, for a join, the link each part stands for. The nested fan (door)// turns the fan into them (`WholePath`).import CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class WholeOpensTests: XCTestCase {    /// An invented season of an invented series, whose episodes are its parts.    static func season(opens: String = #"{"table":"episode","by":"season_id","order":["number","title"]}"#) throws -> TableDefinition {        let json = """        {"id":"season","name":"Season","plural":"Seasons","builtin":false,         "columns":[{"key":"title","name":"Title","type":"text"}],         "title":"title","date":null,"project":null,"order":null,         "slip":{"title":"title"},"tile":{"face":"slip-list"},"page":[],         "card":{"face":"plain","fields":[{"slot":"title","column":"title"}],"opens":\(opens)},         "tables":[]}        """        return try JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8))    }    private func opens(_ json: String) throws -> DefinitionCardOpens {        try JSONDecoder().decode(DefinitionCardOpens.self, from: Data(json.utf8))    }    private func entries() throws -> TableDefinition {        let json = """        {"id":"entry","name":"Entry","plural":"Entries","builtin":false,         "columns":[{"key":"title","name":"Title","type":"text"},                    {"key":"shelf_id","name":"Shelf","type":"link","link_to":"shelf"},                    {"key":"book_id","name":"Book","type":"link","link_to":"book"}],         "title":"title","date":null,"project":null,"order":null,         "slip":{"title":"title"},"tile":{"face":"slip-list"},"page":[],"tables":[]}        """        return try JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8))    }    private let series = WholeLevel(table: "series", id: "s-1", title: "Invented Horses")    private let season = WholeLevel(table: "season", id: "se-2", title: "Season 2")    private func plural(_ table: String) -> String? {        ["series": "Series", "season": "Seasons", "book": "Books"][table]    }    /// RULE: A card's `opens` reads as the core writes it — the parts' table, their link to the whole, their order and the link each stands for — and a card without one opens into nothing.    func testACardReadsWhatItOpensInto() throws {        let opens = try XCTUnwrap(Self.season().card?.opens)        XCTAssertEqual(opens.table, "episode")        XCTAssertEqual(opens.by, "season_id")        XCTAssertEqual(opens.order, ["number", "title"])        XCTAssertNil(opens.through)        let joined = try XCTUnwrap(Self.season(opens: #"{"table":"entry","by":"shelf_id","through":"book_id"}"#).card?.opens)        XCTAssertEqual(joined.order, [], "no order deals the parts as they are read")        XCTAssertEqual(joined.through, "book_id")        let encoded = try JSONEncoder().encode(Self.season())        XCTAssertEqual(try JSONDecoder().decode(TableDefinition.self, from: encoded).card?.opens, opens, "the block round-trips")        let plain = try JSONDecoder().decode(DefinitionCardFace.self, from: Data(#"{"face":"plain"}"#.utf8))        XCTAssertNil(plain.opens, "a card that names no parts is no whole")    }    /// RULE: A whole's parts are the parts whose `by` link names it, dealt by each `order` column in turn, a blank after a value and a full tie as read; the deck of them sorts by the first two.    func testAWholesPartsAreItsOwnInItsOrder() throws {        let opens = try opens(#"{"table":"episode","by":"season_id","order":["number","title"]}"#)        XCTAssertEqual(WholePath.filter(opens, whole: "se-2"), ["season_id": .text("se-2")])        let read = [            TableRecord(id: "c", values: ["number": .number(2), "title": .text("Bravo")]),            TableRecord(id: "x", values: ["title": .text("Unnumbered")]),            TableRecord(id: "b", values: ["number": .number(2), "title": .text("Alpha")]),            TableRecord(id: "a", values: ["number": .number(1), "title": .text("Zulu")]),            TableRecord(id: "y", values: ["title": .text("Unnumbered")]),        ]        XCTAssertEqual(WholePath.ordered(read, by: opens.order).map(\.id), ["a", "b", "c", "x", "y"])        XCTAssertEqual(WholePath.ordered(read, by: []).map(\.id), read.map(\.id), "no order: as read")        let sort = try XCTUnwrap(WholePath.sort(opens.order))        XCTAssertEqual(sort.column, "number")        XCTAssertEqual(sort.tie, "title")        XCTAssertNil(WholePath.sort([]))        let dealt = WholePath.dealt(try entries(), by: opens)        XCTAssertEqual(dealt.sort?.column, "number", "the deck of the parts is dealt in the whole's order")    }    /// RULE: With `through` each part stands for the record its link names, in the parts' order, and a part linking nothing is left out; without, a part stands for itself.    func testThroughDealsTheLinkedRecords() throws {        let joined = try opens(#"{"table":"entry","by":"shelf_id","through":"book_id"}"#)        let parts = [            TableRecord(id: "e-1", values: ["title": .text("First"), "book_id": .text("t-9")]),            TableRecord(id: "e-2", values: ["title": .text("Empty")]),            TableRecord(id: "e-3", values: ["book_id": .list([.text("t-4")])]),        ]        let standing = WholePath.standing(parts, opens: joined, in: try entries())        XCTAssertEqual(standing.map(\.part), ["e-1", "e-3"])        XCTAssertEqual(standing.map(\.table), ["book", "book"])        XCTAssertEqual(standing.map(\.id), ["t-9", "t-4"])        let plain = try opens(#"{"table":"entry","by":"shelf_id"}"#)        let own = WholePath.standing(parts, opens: plain, in: try entries())        XCTAssertEqual(own.map(\.id), ["e-1", "e-2", "e-3"])        XCTAssertEqual(own.first?.title, "First")        XCTAssertEqual(own.first?.table, "entry")    }    /// RULE: A part's card is entered when the record it stands for is itself a whole, and brought to the front otherwise — decided by the definitions, so a tap made before the part's own parts are read still enters it.    func testAPartThatIsAWholeIsEnteredBeforeItsPartsAreRead() throws {        let definitions = TableDefinitions([try Self.season(), try entries()])        let season = WholePart(part: "se-2", table: "season", id: "se-2", title: "Season 2")        XCTAssertEqual(WholePath.entered(season, in: definitions), WholeLevel(table: "season", id: "se-2", title: "Season 2"))        let entry = WholePart(part: "e-1", table: "entry", id: "e-1", title: "First")        XCTAssertNil(WholePath.entered(entry, in: definitions), "a part that opens into nothing is brought, not entered")        let unknown = WholePart(part: "x", table: "invented", id: "x", title: "Invented")        XCTAssertNil(WholePath.entered(unknown, in: definitions))    }    /// RULE: The crumb line says the tool, the first whole's table, then each whole by its title; every word but the last goes back to its own level, and a table named as the tool is said once.    func testTheCrumbsOfANestedPath() {        let crumbs = WholePath.crumbs(tool: "Films", path: [series, season], plural: plural)        XCTAssertEqual(crumbs.map(\.word), ["Films", "Series", "Invented Horses", "Season 2"])        XCTAssertEqual(crumbs.map(\.depth), [0, 0, 1, nil])        let once = WholePath.crumbs(tool: "Books", path: [WholeLevel(table: "book", id: "p", title: "Invented")], plural: plural)        XCTAssertEqual(once.map(\.word), ["Books", "Invented"])        XCTAssertEqual(WholePath.crumbs(tool: "Films", path: [], plural: plural), [], "no whole, no crumbs")    }    /// RULE: The back card pops one level, and the deck it leaves to opens at the whole just left; a whole opened again is gone back to, never stacked.    func testBackPopsOneLevel() throws {        let path = WholePath.entering(season, WholePath.entering(series, []))        XCTAssertEqual(path, [series, season])        let back = try XCTUnwrap(WholePath.back(path))        XCTAssertEqual(back.path, [series])        XCTAssertEqual(back.opensAt, season)        XCTAssertEqual(WholePath.entering(series, path), [series], "re-opening a whole on the path goes back to it")        XCTAssertNil(WholePath.leaving(path, to: 2), "where the fan stands is no step")    }    /// RULE: Back at the top level leaves the whole: the tile's page is its tool's deck again, opened at the whole's card.    func testBackAtTheTopLevelLeavesTheWhole() {        let navigator = Navigator()        navigator.tile = "films"        navigator.push(.tableRecord(table: "series", id: "s-1"))        navigator.enter(series)        XCTAssertTrue(navigator.stack.isEmpty, "the parts stand over the tool's own page")        navigator.enter(season)        XCTAssertEqual(navigator.shownWholes, [series, season])        navigator.backWhole()        XCTAssertEqual(navigator.shownWholes, [series])        XCTAssertEqual(navigator.bringing, .init(table: "season", id: "se-2"))        navigator.backWhole()        XCTAssertEqual(navigator.shownWholes, [])        XCTAssertNil(navigator.wholes["films"])        XCTAssertEqual(navigator.bringing, .init(table: "series", id: "s-1"))        navigator.bringing = nil        navigator.backWhole()        XCTAssertNil(navigator.bringing, "out of every whole, back does nothing")        navigator.enter(series)        navigator.tile = "todos"        XCTAssertEqual(navigator.shownWholes, [], "each tile's fan keeps its own wholes")        navigator.tile = "films"        XCTAssertEqual(navigator.shownWholes, [series])        navigator.standsAtRoot("films")        XCTAssertEqual(navigator.shownWholes, [], "a card brought to the tool shows its deck")    }    func testWholeTiersHideParentsAndRestoreThePreviousPartsOnHubClose() {        let tiers = FanTiers()        tiers.setRoot(.init(id: "tools", cards: []))        tiers.push(.init(id: "views-films", cards: [.init(id: "all", label: "All")], raised: "all")) { _ in }        let navigator = Navigator()        navigator.fanTiers = tiers        navigator.tile = "films"        navigator.enter(series)        XCTAssertEqual(tiers.open?.id, FanTiers.wholeID(series))        XCTAssertEqual(tiers.visible.map(\.id), [FanTiers.wholeID(series)])        let parts = FanTier(id: FanTiers.wholeID(series), cards: [.init(id: "se-2", label: "Season 2")], raised: "se-2")        tiers.replaceOpen(parts) { _ in }        navigator.enter(season)        XCTAssertEqual(tiers.visible.map(\.id), [FanTiers.wholeID(season)])        navigator.backWhole()        XCTAssertEqual(tiers.open, parts, "close restores the previous dealt cards and raised part")        navigator.backWhole()        XCTAssertEqual(tiers.open?.id, "views-films")        XCTAssertEqual(tiers.visible.map(\.id), ["views-films"])        XCTAssertEqual(navigator.bringing?.id, series.id)    }}