Cotton code
329 lines · 17.3 KB · SwiftRaw
// A section of another page draws its records as its table's list does: a// slip's own acts under it, run through the list's one act path (`RecordActs`),// the table's grouped order before its sort, and a heading that counts the// whole of a limited section. Every record and act is invented.import CottonKitimport CottonValuesimport Foundationimport Observationimport SwiftUIimport XCTest@testable import CottonUIfinal class SectionActsTests: XCTestCase {    /// An invented table split by a choice column, newest first within a part.    private func definition() throws -> TableDefinition {        try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"title","type":"text"},{"key":"part","type":"choice","choices":["first","second","third"]},                        {"key":"at","type":"date"}],             "title":"title","slip":{"title":"title"},"tile":{"face":"slip-list"},             "group":{"column":"part","sections":[               {"heading":"First","values":["first"]},{"heading":"Second","values":["second"]},               {"heading":"Third","values":["third"]}]},             "sort":{"column":"at","descending":true},             "page":[{"heading":null,"columns":["title"]}]}            """.utf8))    }    private static func record(_ id: String, part: String, at: String) -> TableRecord {        TableRecord(id: id, values: ["title": .text(id), "part": .text(part), "at": .text(at)])    }    /// A store that pages its rows, offers acts on some slips and says what    /// it was asked to do.    private actor FakeActing: Records, ActingRecords {        var rows: [TableRecord]        let pageSize: Int        /// The acts each slip offers, by record id.        var offered: [String: [RecordAction]]        /// The acts refused, by id, with the sentence.        let refusals: [String: String]        private(set) var performed: [String] = []        private(set) var listed = 0        init(rows: [TableRecord], pageSize: Int = 50, offered: [String: [RecordAction]] = [:], refusals: [String: String] = [:]) {            self.rows = rows            self.pageSize = pageSize            self.offered = offered            self.refusals = refusals        }        func tableDefinitions() async throws -> [TableDefinition] { [] }        func count(table: String) async throws -> Int { rows.count }        func list(table: String, project: String?, query: String?, page: Int, where: [String: RecordValue]) async throws -> RecordPage {            listed += 1            let start = page * pageSize            guard start < rows.count else { return RecordPage(records: [], next: nil, total: rows.count) }            let end = min(rows.count, start + pageSize)            return RecordPage(records: Array(rows[start..<end]), next: end < rows.count ? page + 1 : nil, total: rows.count)        }        /// A page of at most `limit` from the first, as the core answers an        /// asked size: its total counts every row.        func list(            table: String, project: String?, query: String?, page: Int, where: [String: RecordValue], limit: Int        ) async throws -> RecordPage {            guard page == 0 else { return try await list(table: table, project: project, query: query, page: page, where: `where`) }            listed += 1            let end = min(rows.count, limit)            return RecordPage(records: Array(rows[0..<end]), next: end < rows.count ? end : nil, total: rows.count)        }        func get(table: String, id: String) async throws -> TableRecord? { rows.first { $0.id == id } }        func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { throw Refused() }        func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord { throw Refused() }        func delete(table: String, id: String) async throws -> ChangeRecord { throw Refused() }        func reorder(table: String, ids: [String]) async throws -> ChangeRecord { throw Refused() }        func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { throw Refused() }        func undo(change: String) async throws -> ChangeRecord { throw Refused() }        func listActions(table: String) async -> [RecordAction] { [] }        func pageActions(table: String, record: TableRecord) async -> [RecordAction] { [] }        private(set) var slipAsks = 0        nonisolated func offersSlipActions(table: String) -> Bool { table != "without_acts" }        func setOffered(_ actions: [RecordAction], for id: String) { offered[id] = actions }        func slipActions(table: String, record: TableRecord) async -> [RecordAction] {            slipAsks += 1            return offered[record.id] ?? []        }        func perform(_ action: RecordAction, table: String, record: TableRecord?) async throws -> ActionOutcome {            if let sentence = refusals[action.id] { throw ActionRefused(sentence) }            performed.append("\(action.id) \(record?.id ?? "none")")            // Answered once: the slip offers nothing after.            if let id = record?.id { offered[id] = nil }            return action.id == "make" ? .created("example-made") : .said("Done.")        }        struct Refused: Error {}    }    /// What the section's surface was asked to do, for the test to read.    @MainActor    private final class Seen {        var opened: [String] = []        var rereads = 0    }    @MainActor    private func surface(_ seen: Seen) -> RecordActSurface {        RecordActSurface(            open: { seen.opened.append($0) },            reveal: { _ in },            reread: { seen.rereads += 1 },            current: { _ in nil },            keptFlow: nil, navigator: nil, openURL: OpenURLAction { _ in .handled }, toasts: nil)    }    /// RULE: A row appearing never invalidates another row's actions; changed and removed actions still invalidate their own row.    @MainActor    func testSlipObservationBelongsToOneRow() async {        let one = Self.record("one", part: "", at: "")        let two = Self.record("two", part: "", at: "")        let allow = RecordAction(id: "allow", label: "Allow")        let store = FakeActing(rows: [one, two], offered: ["one": [allow], "two": [allow]])        let acts = RecordActs(table: "example")        await acts.loadSlip(one, store: store)        let changed = Seen()        func observeOne() {            withObservationTracking {                _ = acts.slipState(one.id).actions                _ = acts.slipState(one.id).problem            } onChange: { MainActor.assumeIsolated { changed.rereads += 1 } }        }        observeOne()        await acts.loadSlip(one, store: store)        await acts.loadSlip(two, store: store)        XCTAssertEqual(changed.rereads, 0, "unchanged actions and another arriving row leave this row alone")        await store.setOffered([], for: one.id)        await acts.loadSlip(one, store: store)        XCTAssertEqual(changed.rereads, 1)        XCTAssertFalse(acts.drawsActs(one))        observeOne()        await acts.loadSlip(one, store: store)        XCTAssertEqual(changed.rereads, 1, "repeated empty answers do not invalidate the row")        await store.setOffered([allow], for: one.id)        await acts.loadSlip(one, store: store)        XCTAssertEqual(changed.rereads, 2)        XCTAssertTrue(acts.drawsActs(one))    }    /// RULE: A table known to have no inline slip actions never sends per-row action queries while its rows appear.    @MainActor    func testKnownEmptySlipActionsSkipTheStore() async {        let one = Self.record("one", part: "", at: "")        let store = FakeActing(rows: [one])        let acts = RecordActs(table: "without_acts")        await acts.loadSlip(one, store: store)        let asks = await store.slipAsks        XCTAssertEqual(asks, 0)        XCTAssertFalse(acts.drawsActs(one))    }    /// RULE: A section's slip offers its own acts and runs them through the list's one act path — asking first where the act asks, saying a refusal under that slip, opening a record an act made, and reading the section and the slip's acts again after.    @MainActor    func testASectionsSlipRunsItsActsAsTheListDoes() async throws {        let withdraw = RecordAction(            id: "withdraw", label: "Withdraw",            confirmation: WriteConfirmation(title: "Withdraw it?", message: "", confirmLabel: "Withdraw"))        let allow = RecordAction(id: "allow", label: "Allow")        let deny = RecordAction(id: "deny", label: "Deny")        let make = RecordAction(id: "make", label: "Make one")        let one = Self.record("example-1", part: "first", at: "2026-10-01T09:00:00Z")        let two = Self.record("example-2", part: "second", at: "2026-10-01T08:00:00Z")        let three = Self.record("example-3", part: "third", at: "2026-10-01T07:00:00Z")        let store = FakeActing(            rows: [one, two, three],            offered: ["example-1": [allow, withdraw], "example-2": [deny], "example-3": [make]],            refusals: ["deny": "Example: the Mac has gone."])        let acts = RecordActs(table: "example")        let seen = Seen()        for record in [one, two, three] { await acts.loadSlip(record, store: store) }        XCTAssertEqual(acts.slipState("example-1").actions.map(\.id), ["allow", "withdraw"])        XCTAssertTrue(acts.drawsActs(one))        await acts.loadSlip(Self.record("example-4", part: "first", at: "2026-10-01T06:00:00Z"), store: store)        XCTAssertFalse(acts.drawsActs(Self.record("example-4", part: "first", at: "")), "a slip offering none draws none")        // An act that asks, asks first: nothing runs yet.        XCTAssertNil(acts.tapped(withdraw, on: one, store: store, surface: surface(seen)))        XCTAssertEqual(acts.asking?.action.id, "withdraw")        XCTAssertEqual(acts.asking?.record?.id, "example-1")        let none = await store.performed        XCTAssertEqual(none, [])        acts.asking = nil        // One that does not, runs on the slip's record; the section and the        // slip's acts are read again.        await acts.tapped(allow, on: one, store: store, surface: surface(seen))?.value        let ran = await store.performed        XCTAssertEqual(ran, ["allow example-1"])        XCTAssertEqual(seen.rereads, 1)        XCTAssertTrue(acts.slipState("example-1").actions.isEmpty, "the slip's acts are asked for again as it now stands")        // A refusal is said under the slip it was pressed on, not the head.        await acts.perform(deny, on: two, store: store, surface: surface(seen))?.value        XCTAssertEqual(acts.slipState("example-2").problem, "Example: the Mac has gone.")        XCTAssertNil(acts.headProblem)        XCTAssertTrue(acts.drawsActs(two))        // A record the act made opens through the surface.        await acts.perform(make, on: three, store: store, surface: surface(seen))?.value        XCTAssertEqual(seen.opened, ["example-made"])    }    /// RULE: A limited section asks the core for ONE page of its few — never every page of a table that may hold thousands — and says the whole from the answer's count on the row offering the rest ("All 120"), never as a tally in its heading.    /// A section without a limit reads one page at a time and counts what it read with a plus.    @MainActor    func testALimitedSectionReadsOnePageAndCountsTheTotal() async throws {        var definition = try definition()        // Drawn in the store's order: a grouped table reads the store's own page.        definition.group = nil        // Newest first, as the store answers in the table's order.        let rows = (1...120).reversed().map { index in            Self.record("example-\(index)", part: "first", at: String(format: "2026-10-01T%02d:%02d:00Z", index / 60, index % 60))        }        let store = FakeActing(rows: rows, pageSize: 50)        let list = SectionList(table: definition.id, limit: 3)        let core = ListCoreFake()        let limited = RecordListModel(            definition: definition, store: store, core: core, pageSize: RecordsSection.pageSize(list, of: definition), seeds: ListSeeds())        await RecordsSection.read(limited, limit: 3)        XCTAssertEqual(core.asks, 1, "one ask")        XCTAssertEqual(core.asked.first?["limit"] as? Int, 3, "of its few")        XCTAssertEqual(limited.records.count, 3)        XCTAssertEqual(limited.total, 120)        let drawn = RecordsSection.drawn(limited.records, limit: 3)        XCTAssertEqual(drawn.map(\.id), ["example-120", "example-119", "example-118"], "the newest of the whole")        let shown = drawn.map { SectionRow(definition: definition, record: $0) }        XCTAssertNil(            RecordsSection.gatheredCount(list, shown, more: limited.hasMore), "a capped heading carries no tally; its whole row says it")        XCTAssertTrue(RecordsSection.opensWhole(list, total: limited.total))        XCTAssertFalse(RecordsSection.opensWhole(list, total: 3), "all of it is drawn")        // Spec 11's record-page lists name the true total in the heading,        // and retain All n even when this small list fits beneath its record.        XCTAssertNil(RecordsSection.gatheredCount(list, shown, more: limited.hasMore, recordPage: true), "unknown total is never the three visible rows")        XCTAssertTrue(RecordsSection.opensWhole(list, total: 3, recordPage: true))        XCTAssertFalse(RecordsSection.opensWhole(list, total: 0, recordPage: true))        XCTAssertFalse(RecordsSection.opensWhole(list, total: nil, recordPage: true))        XCTAssertNil(RecordsSection.pageSize(list, of: try self.definition()), "a grouped table reads the store's own page")        let whole = RecordListModel(definition: definition, store: store, core: ListCoreFake(), seeds: ListSeeds())        await RecordsSection.read(whole, limit: nil)        XCTAssertEqual(whole.records.count, 50)        XCTAssertTrue(whole.hasMore)        XCTAssertEqual(RecordsSection.count(drawn: 50, read: whole.records.count, more: whole.hasMore), "50+")    }    // ── A table read whole is read once per list ────────────────────────    /// How many times a source was read.    private actor Reads {        private(set) var count = 0        func add() { count += 1 }    }    /// An invented table whose every read answers all of its rows, as each    /// Settings source does, counting the reads.    private struct CountedSource: SettingsTableSource {        let table = "example"        let rows: [TableRecord]        let reads: Reads        func records(_ core: any CottonCalling) async throws -> [TableRecord] {            await reads.add()            return rows        }    }    private func counted(_ count: Int) throws -> (SettingsRecords, Reads) {        let rows = (1...count).map { index in            Self.record("example-\(index)", part: "first", at: String(format: "2026-10-01T%02d:%02d:00Z", index / 60, index % 60))        }        let reads = Reads()        let records = SettingsRecords(            core: ScriptedCore(), definitions: [try definition()], sources: [CountedSource(rows: rows, reads: reads)])        return (records, reads)    }    /// RULE: A Settings table is read whole, so a list's later pages are cut from its first page's read — one project's ten thousand sessions are read once per list, never once per fifty rows.    func testAListReadsAWholeTableOncePerList() async throws {        let (records, reads) = try counted(120)        var seen: [String] = []        var page: Int? = 0        while let current = page {            let answer = try await records.list(table: "example", project: nil, query: nil, page: current, where: [:])            seen += answer.records.map(\.id)            page = answer.next        }        XCTAssertEqual(seen.count, 120)        XCTAssertEqual(Set(seen).count, 120, "every row once, across three pages")        var count = await reads.count        XCTAssertEqual(count, 1, "three pages, one read")        // A first page reads afresh: the list is read again, not its old rows.        _ = try await records.list(table: "example", project: nil, query: nil, page: 0, where: [:])        _ = try await records.list(table: "example", project: nil, query: nil, page: 1, where: [:])        count = await reads.count        XCTAssertEqual(count, 2)        // Another search is another list, so its later pages are not the old ones.        let other = try await records.list(table: "example", project: nil, query: "example-1", page: 1, where: [:])        XCTAssertEqual(other.records.count, 0, "32 rows hold example-1: one page")        count = await reads.count        XCTAssertEqual(count, 3)    }    /// RULE: A limited section over a Settings table counts the whole from one read of it, so a project's Sessions section does not read every session once per page on every sync.    @MainActor    func testALimitedSectionReadsAWholeTableOnce() async throws {        let (records, reads) = try counted(120)        let model = RecordListModel(definition: try definition(), store: records, core: ListCoreFake(), seeds: ListSeeds())        await RecordsSection.read(model, limit: 3)        XCTAssertEqual(model.total, 120, "the whole, from the one read's total")        XCTAssertEqual(model.records.count, 50, "one page, never every page")        let count = await reads.count        XCTAssertEqual(count, 1, "one read")    }}