Cotton code
255 lines · 16.7 KB · SwiftRaw
// The shared pieces a list of ledgers and their entries is drawn with, held// as logic, never as wording or layout: a link with no route drawn on the list// and counted from its read's total, a capped section's one-page read and its// whole, a page that captures another table's record holding itself, the// store's question before a record is made, and the names the bar reads only// where they could be written. Every table and record is invented.import CottonKitimport CottonValuesimport Foundationimport SwiftUIimport XCTest@testable import CottonUI@MainActorfinal class ListLinksAndCaptureTests: XCTestCase {    private static let noon = Date(timeIntervalSince1970: 1_790_856_000)  // 2026-10-01T12:00:00Z    /// An invented ledger whose own columns are its engine's, but one switch,    /// whose list's and page's bar make an entry of `entry` holding it.    private static func ledger(extra: String = "") throws -> TableDefinition {        try TableDefinition.decode(Data("""            {"id":"ledger","name":"Ledger","plural":"Ledgers","builtin":false,"delete":false,             "columns":[{"key":"name","type":"text","readonly":true},{"key":"kind","type":"choice","choices":["own","other"],"readonly":true},                        {"key":"usual","type":"bool"}],             "title":"name","slip":{"title":"name"},"tile":{"face":"slip-list"},             "shows":{"kind":"own"},             "capture":{"table":"entry","placeholder":"What moved","link":"ledger_id"},             "links":[{"label":"Others","table":"ledger","where":{"kind":["other","closed"]}},                      {"label":"Waiting","table":"entry","where":{"state":"waiting"},"lead":true},                      {"label":"Import","table":"entry","path":"/settings"}],             "lists":[{"heading":"Recent","list":{"table":"entry","limit":10,"where":{"state":["done","waiting"]},"whole":"All entries"}}],             "page":[{"heading":null,"columns":["name","usual"]},                     {"heading":"More","role":"side","columns":["kind"]},                     {"heading":"Entries","role":"side","list":{"table":"entry","link":"ledger_id"}}]\(extra)}            """.utf8))    }    private static let entry = TableDefinition(        id: "entry", name: "Entry", plural: "Entries",        columns: [            ColumnDefinition(key: "title", type: .text, required: true),            ColumnDefinition(key: "state", type: .choice, choices: ["done", "waiting"]),            ColumnDefinition(key: "ledger_id", type: .link, linkTo: "ledger"),        ],        title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList),        page: [PageSection(heading: nil, columns: ["title", "state", "ledger_id"])])    private static let person = TableDefinition(        id: "person", name: "Person", plural: "People",        columns: [ColumnDefinition(key: "full_name", type: .text, required: true)], title: "full_name",        slip: SlipLayout(title: "full_name"), tile: TileLayout(face: .polaroidGrid),        page: [PageSection(heading: nil, columns: ["full_name"])])    // ── The keys ──    /// RULE: A link with no route is a list link — drawn on the list, leading or in its row — and its `where` carries an array of values (any of them) through decoding unchanged; a link with a route stays a menu line.    func testAListLinkNeedsNoRouteAndCarriesAnyOf() throws {        let ledger = try Self.ledger()        let others = try XCTUnwrap(ledger.links.first { $0.label == "Others" })        XCTAssertNil(others.path)        XCTAssertTrue(others.isListLink)        XCTAssertFalse(others.lead)        XCTAssertEqual(others.where["kind"], .list([.text("other"), .text("closed")]))        XCTAssertTrue(try XCTUnwrap(ledger.links.first { $0.label == "Waiting" }).lead)        let menu = try XCTUnwrap(ledger.links.first { $0.label == "Import" })        XCTAssertFalse(menu.isListLink)        XCTAssertEqual(menu.path, "/settings")        XCTAssertEqual(try TableDefinition.decode(JSONEncoder().encode(ledger)), ledger)    }    // ── What is drawn ──    /// RULE: A capped section offers its whole only when the whole holds more than it draws, counted from the stores' totals (a merged table's too), and a store with no total offers none.    func testACappedSectionOpensItsWholeOnlyWhenThereIsMore() throws {        let list = SectionList(table: "entry", limit: 10)        XCTAssertTrue(RecordsSection.opensWhole(list, total: 11))        XCTAssertFalse(RecordsSection.opensWhole(list, total: 10))        XCTAssertFalse(RecordsSection.opensWhole(list, total: nil))        XCTAssertFalse(RecordsSection.opensWhole(SectionList(table: "entry"), total: 500), "an uncapped section draws all")        XCTAssertEqual(RecordsSection.wholeLabel(SectionList(table: "entry", limit: 10, whole: "Every entry"), total: 40), "Every entry")        XCTAssertEqual(RecordsSection.pageSize(list, of: Self.entry), 10)    }    /// RULE: The list a link opens is the table's list named by where it was opened from — by the whole words heading that page, however long — without that table's own other lists and links; a table whose list's bar writes into another table takes nothing typed there.    func testTheOpenedListIsTheTablesNarrowedList() throws {        XCTAssertEqual(FilteredListOpening.title("Lines", of: "Ferry Line"), "Lines \u{00B7} Ferry Line")        XCTAssertEqual(FilteredListOpening.title("Lines", of: nil), "Lines")        XCTAssertEqual(FilteredListOpening.title("Lines", of: "  "), "Lines")        XCTAssertEqual(            FilteredListOpening.title("Lines", of: "Carrying parcels between the two harbours"),            "Lines \u{00B7} Carrying parcels between the two harbours", "a long name is kept, never dropped to fit")        let opened = FilteredListOpening.listed(try Self.ledger())        XCTAssertTrue(opened.lists.isEmpty)        XCTAssertTrue(opened.links.isEmpty)        XCTAssertFalse(opened.listTakesCapture, "a ledger is never typed")        XCTAssertEqual(FilteredListOpening.listed(Self.entry).listTakesCapture, Self.entry.listTakesCapture)    }    /// RULE: A capped section's whole list is called by the section's own `whole` words less a leading "All", capitalised, else by its heading.    func testAWholeListIsCalledByItsWholeWords() throws {        let heading = "Recent"        XCTAssertEqual(FilteredListOpening.wholeTitle(SectionList(table: "entry", limit: 10, whole: "All entries"), heading: heading), "Entries")        XCTAssertEqual(FilteredListOpening.wholeTitle(SectionList(table: "entry", limit: 10, whole: "all entries"), heading: heading), "Entries")        XCTAssertEqual(FilteredListOpening.wholeTitle(SectionList(table: "entry", limit: 10, whole: "Every entry"), heading: heading), "Every entry")        XCTAssertEqual(FilteredListOpening.wholeTitle(SectionList(table: "entry", limit: 10), heading: heading), "Recent")        XCTAssertEqual(FilteredListOpening.wholeTitle(SectionList(table: "entry", limit: 10, whole: "All "), heading: heading), "Recent")        let recent = try XCTUnwrap(try Self.ledger().lists.first?.list)        XCTAssertEqual(            FilteredListOpening.title(FilteredListOpening.wholeTitle(recent, heading: heading), of: "Ledgers"),            "Entries \u{00B7} Ledgers")    }    /// RULE: A narrowed list is a route on the navigator's path — its table, its `where` as JSON with sorted keys, its title and its search — that reads back as the very opening that wrote it; a `where` that is not a JSON object of values opens nothing rather than the whole table.    func testANarrowedListIsARouteOnThePath() throws {        let opening = FilteredListOpening(            table: "entry", filter: ["state": .list([.text("done"), .text("waiting")]), "ledger_id": .text("ledger-1")],            title: "Entries \u{00B7} Ferry Line & Sons", query: "quay 50%")        let route = opening.route        guard case .tableList(let table, let filter, let title, let query, _, _, _)? = Route.parse(route.path) else {            return XCTFail("\(route.path) did not read back as a narrowed list")        }        XCTAssertEqual(Route.parse(route.path), route)        XCTAssertEqual(filter, #"{"ledger_id":"ledger-1","state":["done","waiting"]}"#, "one opening is one path")        XCTAssertEqual(FilteredListOpening(table: table, filter: filter, title: title, query: query), opening)        // Narrowed by nothing, searched by nothing: no query parameters at all.        let whole = FilteredListOpening(table: "entry", filter: [:], title: "Entries")        XCTAssertEqual(whole.route, .tableList(table: "entry", filter: nil, title: "Entries", query: nil))        XCTAssertEqual(whole.route.path, "/lists/entry?title=Entries")        XCTAssertNil(FilteredListOpening(table: "entry", filter: "not json", title: nil, query: nil))        XCTAssertNil(FilteredListOpening(table: "entry", filter: #"["a"]"#, title: nil, query: nil))        XCTAssertEqual(Route.tableList(table: "entry", filter: nil, title: nil, query: nil).tier, .list)        XCTAssertNil(Route.tableList(table: "entry", filter: nil, title: nil, query: nil).recordId)    }    /// RULE: An empty list searched says "nothing matches" only once every other list drawn with it has read the search and found nothing; unsearched, or with no other lists, it says its empty words at once.    func testNothingMatchesOnlyWhenNoSectionFoundIt() {        let none = SectionFinds(holds: false, pending: false)        let found = SectionFinds(holds: true, pending: false)        let reading = SectionFinds(holds: false, pending: true)        XCTAssertTrue(RecordListSurface.saysNothingMatches(query: "", sections: found, hasSections: true))        XCTAssertTrue(RecordListSurface.saysNothingMatches(query: "quay", sections: reading, hasSections: false))        XCTAssertTrue(RecordListSurface.saysNothingMatches(query: "quay", sections: none, hasSections: true))        XCTAssertFalse(RecordListSurface.saysNothingMatches(query: "quay", sections: found, hasSections: true))        XCTAssertFalse(RecordListSurface.saysNothingMatches(query: "quay", sections: reading, hasSections: true))        // Sections fold together: one that found it, or one still reading, holds the words back.        var folded = none        SectionFindsKey.reduce(value: &folded) { found }        SectionFindsKey.reduce(value: &folded) { none }        XCTAssertEqual(folded, SectionFinds(holds: true, pending: false))        var waiting = none        SectionFindsKey.reduce(value: &waiting) { reading }        XCTAssertEqual(waiting, SectionFinds(holds: false, pending: true))    }    /// RULE: A list's own section, searched, is headed by its `whole` words, else its heading; unsearched, or on a page, by its heading.    func testASearchedSectionIsHeadedByItsWholeWords() {        let recent = SectionList(table: "entry", limit: 10, whole: "All entries")        XCTAssertEqual(RecordsSection.heading("Recent", of: recent, topLevel: true, query: "quay"), "Entries")        XCTAssertEqual(RecordsSection.heading("Recent", of: recent, topLevel: true, query: ""), "Recent")        XCTAssertEqual(RecordsSection.heading("Recent", of: recent, topLevel: false, query: "quay"), "Recent")        XCTAssertEqual(RecordsSection.heading("Recent", of: SectionList(table: "entry", limit: 10), topLevel: true, query: "quay"), "Recent")    }    /// RULE: An array asked for in a `where` matches any of its values, as the core reads it.    func testAnArrayInAWhereIsAnyOf() async throws {        let store = FixtureRecords(definitions: [Self.entry], records: ["entry": [            TableRecord(id: "a", values: ["title": .text("a"), "state": .text("done")]),            TableRecord(id: "b", values: ["title": .text("b"), "state": .text("waiting")]),            TableRecord(id: "c", values: ["title": .text("c")]),        ]])        let page = try await store.list(table: "entry", project: nil, query: nil, page: 0, where: ["state": .list([.text("done"), .text("waiting")])])        XCTAssertEqual(Set(page.records.map(\.id)), ["a", "b"])        XCTAssertEqual(page.total, 2)        let total = try await store.total(table: "entry", where: ["state": .text("waiting")])        XCTAssertEqual(total, 1)    }    /// RULE: The core's create may answer a question in place of a change; it is thrown with the create it was asked about, and a list's total is read from the answer.    func testTheCoreAnswersAQuestionAndATotal() async throws {        let core = ScriptedCore([            "records.create": .ok(#"{"ask":{"question":"Which one?","column":"ledger_id","options":[{"id":"l-one","label":"One"}]}}"#),            "records.list": .ok(#"{"records":[{"id":"one","data":{"title":"Read"}}],"next_page":1,"total":15595}"#),        ])        let store = CoreRecords(core: core, bundle: try TestResources.bundle())        do {            _ = try await store.create(table: "todo", data: ["title": .text("coffee")])            XCTFail("a question makes nothing")        } catch let question as CreateQuestion {            XCTAssertEqual(question.options, [CreateQuestion.Option(id: "l-one", label: "One")])            XCTAssertEqual(question.table, "todo")            XCTAssertEqual(question.answered(question.options[0])["ledger_id"], .text("l-one"))            XCTAssertEqual(question.answered(question.options[0])["title"], .text("coffee"))        }        let page = try await store.list(table: "todo", project: nil, query: nil, page: 0, where: [:], limit: 1)        XCTAssertEqual(page.total, 15595)        let sent = await core.calls.last?.requestJSON ?? ""        XCTAssertTrue(sent.contains(#""limit":1"#), sent)    }    // ── A page headed by its own column, its facts in red, its main list ──    /// An invented sheet: its slip titled by its period, its page headed by    /// another column, a facts line with a red check, a red section, and its    /// entries as the page's main list.    private static func sheet() throws -> TableDefinition {        try TableDefinition.decode(Data("""            {"id":"sheet","name":"Sheet","plural":"Sheets","builtin":false,             "columns":[{"key":"period","type":"text","readonly":true},{"key":"heading","type":"text","readonly":true},                        {"key":"check","type":"choice","choices":["agree","off"],"red_when":["off"],"readonly":true},                        {"key":"gap","type":"text","readonly":true}],             "title":"period","heads":"heading","slip":{"title":"period"},"tile":{"face":"slip-list"},             "page":[{"heading":null,"columns":["period","heading"]},                     {"heading":null,"role":"facts","columns":["heading","check","gap"]},                     {"heading":null,"role":"facts","ink":"red","columns":["gap"],"when":{"column":"check","values":["off"]}},                     {"heading":null,"role":"main","list":{"table":"entry","link":"sheet_id","limit":5,"empty":"No entries"}}]}            """.utf8))    }    /// RULE: A page's main list is the page's own list and pages on, so its `limit` never caps it; any other section keeps its limit.    func testAMainListIsNeverCapped() throws {        let main = try Self.sheet().page[3]        XCTAssertEqual(main.list?.limit, 5)        XCTAssertNil(main.drawnList?.limit)        XCTAssertEqual(main.drawnList?.empty, "No entries")        var other = main        other.role = nil        XCTAssertEqual(other.drawnList?.limit, 5)    }    /// RULE: `{title}` in a page section's words is the page record's heading words — what its lists are named by — or "this <name>" while it has none; `{first}` still reads the first word of its title.    func testAPagesEmptyWordsNameItsRecord() throws {        let ledger = try Self.ledger()        let ferry = TableRecord(id: "l", values: ["name": .text("Ferry Line"), TableRecord.saidKey: .object(["slip": .object(["name": .text("Ferry Line")])])])        XCTAssertEqual(ledger.words("No entries in {title} yet", for: ferry), "No entries in Ferry Line yet")        XCTAssertEqual(ledger.words("No entries in {title} yet", for: TableRecord(id: "l", values: [:])), "No entries in this ledger yet")        XCTAssertEqual(ledger.words("No entries in {title} yet", for: nil), "No entries in this ledger yet")        XCTAssertEqual(ledger.words("Is this {first}?", for: ferry), "Is this Ferry?")        XCTAssertNil(ledger.words(nil, for: ferry))    }    /// RULE: A table's delete act is called by its `deletion.label` in every place it is drawn, and what it did by "removed" for any word but Delete; without one it is Delete, deleted.    func testADeleteIsCalledByTheTablesWord() throws {        let ledger = try Self.ledger()        XCTAssertNotEqual(ledger.deleteWord, "Remove", "the table's own word, not another's")        let removing = try Self.ledger(extra: #", "deletion":{"label":"Remove","confirm":"Remove"}"#)        XCTAssertEqual(removing.deleteWord, "Remove")        XCTAssertEqual(removing.deletedWord, "removed")    }}