Cotton code
167 lines · 10.0 KB · SwiftRaw
// The keys the Mood conversion restored what the Mood screen showed through,// each drawn once for any table: a several-choice column, a list split by day,// a slip table's own grid, the chips that make a record, and a slip's byline// (`Definitions/ListKeys.swift`). Every record is invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class ListKeysTests: XCTestCase {    private static var utc: Calendar {        var calendar = Calendar(identifier: .gregorian)        calendar.timeZone = TimeZone(identifier: "UTC")!        return calendar    }    /// 1 October 2026, 09:30 UTC.    private static let now = Date(timeIntervalSince1970: 1_790_847_000)    private func decode(_ extra: String, slip: String = "") throws -> TableDefinition {        try TableDefinition.decode(Data("""            {"id":"example","name":"Example","plural":"Examples","builtin":false,             "columns":[{"key":"line","type":"text"},                        {"key":"words","type":"choice","multiple":true,"choices":["calm","hopeful","tired"]},                        {"key":"by","type":"choice","choices":["user","assistant"]},                        {"key":"at","type":"date"},{"key":"day","type":"date"}],             "title":"line","date":"at","slip":{"title":"line","subtitle":"words"\(slip)},"tile":{"face":"slip-list"},             "page":[{"heading":null,"columns":["line","words"]}]\(extra)}            """.utf8))    }    /// `heading`: the core's heading for the day the moment stands under    /// (its `at`'s when it has one, else its `day`'s), as a read carries it.    private func moment(_ id: String, day: String?, at: String? = nil, words: RecordValue = .null, heading: String? = nil) -> TableRecord {        var values: [String: RecordValue] = ["line": .text("An example moment \(id)"), "words": words]        if let day { values["day"] = .text(day) }        if let at { values["at"] = .text(at) }        let record = TableRecord(id: id, values: values)        guard let heading, let stood = at.map({ String($0.prefix(10)) }) ?? day else { return record }        return CoreSaid.read(record, days: [at == nil ? "day" : "at": CoreSaid.day(stood, heading: heading)])    }    /// RULE: A definition decodes a column's multiple, by_day, grid, chips and a slip's byline, and one that leaves them out reads as before — a single choice, one section, no grid, no chips, no byline.    func testTheListKeysDecodeAndTheirAbsenceReadsAsBefore() throws {        let bare = try decode("")        XCTAssertNil(bare.byDay)        XCTAssertNil(bare.grid)        XCTAssertNil(bare.chips)        XCTAssertNil(bare.slip.byline)        XCTAssertFalse(try XCTUnwrap(bare.column("by")).multiple)        XCTAssertTrue(try XCTUnwrap(bare.column("words")).multiple)        let full = try decode(            #","by_day":"day","grid":{"columns":2},"chips":{"column":"words","sends":{"by":"user"}}"#,            slip: #","byline":{"column":"by","words":{"assistant":"named by the assistant"}}"#)        XCTAssertEqual(full.byDay, "day")        XCTAssertEqual(full.grid, ListGrid(columns: 2))        XCTAssertEqual(full.chips, ChipRow(column: "words", sends: ["by": .text("user")]))        XCTAssertEqual(full.slip.byline, SlipByline(column: "by", words: ["assistant": "named by the assistant"]))        let again = try JSONDecoder().decode(TableDefinition.self, from: JSONEncoder().encode(full))        XCTAssertEqual(again, full)    }    /// The Mood slip printed `["calm","hopeful"]` raw, since the engine keeps    /// the list as JSON in text.    /// RULE: A several-choice value reads as its words joined by a middle dot, from a list or from a JSON array written into text.    func testASeveralChoiceValueReadsAsItsWords() throws {        let column = try XCTUnwrap(try decode("").column("words"))        XCTAssertEqual(FaceText.line(.list([.text("calm"), .text("hopeful")]), column: column), "calm \u{00B7} hopeful")        XCTAssertEqual(FaceText.line(.text(#"["tired"]"#), column: column), "tired")        XCTAssertEqual(FaceText.slipLine(.text(#"["calm","hopeful"]"#), column: column), "calm \u{00B7} hopeful")        XCTAssertNil(FaceText.line(.list([]), column: column))        XCTAssertNil(FaceText.line(.text("[]"), column: column))        XCTAssertNil(FaceText.line(.null, column: column))    }    /// The chips under the Mood composer named a moment with no assistant.    /// RULE: The chips make a record holding the chosen words in the column's own order, the row's fixed values, now in the date column and today in the by_day column; with nothing chosen they make none.    func testTheChipsMakeARecordOfTheChosenWords() throws {        let definition = try decode(#","by_day":"day","chips":{"column":"words","sends":{"by":"user"}}"#)        XCTAssertNil(definition.chipRecord([], now: Self.now, calendar: Self.utc))        let data = try XCTUnwrap(definition.chipRecord(["tired", "calm", "not-a-choice"], now: Self.now, calendar: Self.utc))        XCTAssertEqual(data["words"], .list([.text("calm"), .text("tired")]))        XCTAssertEqual(data["by"], .text("user"))        XCTAssertEqual(data["day"], .text("2026-10-01"))        XCTAssertEqual(data["at"].flatMap { CottonDate.instant($0.text) }, Self.now)    }    /// RULE: A record made from the chips is written through create, the list reads it back, and its undo takes it away.    func testAChipRecordIsCreatedAndUndone() async throws {        let definition = try decode(#","by_day":"day","chips":{"column":"words","sends":{"by":"user"}}"#)        let store = FixtureRecords(definitions: [definition], records: ["example": [moment("a", day: "2026-09-30")]])        let model = RecordListModel(definition: definition, store: store, core: ListCoreFake(), seeds: ListSeeds())        await model.reload(project: nil, query: "")        let data = try XCTUnwrap(definition.chipRecord(["calm"]))        let change = try await model.create(data)        XCTAssertNil(change.before)        XCTAssertEqual(model.records.count, 2)        XCTAssertTrue(model.records.contains { $0.values["words"] == .list([.text("calm")]) })        try await model.undo()        XCTAssertEqual(model.records.map(\.id), ["a"])    }    /// A chip record made on a list narrowed to one conversation, or under a    /// project, used to be written without what narrowed it, and vanished    /// from the list the moment it was read again.    /// RULE: A record made from the chips holds the list's filter values and the current project, where the chips name none, so it stands in the list that made it.    func testAChipRecordHoldsWhatNarrowsTheList() throws {        let definition = try decode(#","project":"project","chips":{"column":"words"}"#)        let data = try XCTUnwrap(definition.chipRecord(["calm"], now: Self.now, calendar: Self.utc))        let narrowed = RecordListModel.narrowed(data, filter: ["by": .text("user")], project: "garden", in: definition)        XCTAssertEqual(narrowed["by"], .text("user"))        XCTAssertEqual(narrowed["project"], .text("garden"))        XCTAssertEqual(narrowed["words"], .list([.text("calm")]))        let kept = RecordListModel.narrowed(["by": .text("assistant")], filter: ["by": .text("user")], project: nil, in: try decode(""))        XCTAssertEqual(kept["by"], .text("assistant"), "the chips' own value is not overwritten")        XCTAssertNil(kept["project"], "a table filed under no project is given none")    }    /// RULE: A card's When writes the column the core names: the card's date place, else its first corner, else the table's date (a trip names its days by its date place alone).    func testAWhenWritesTheCardsDatePlaceElseItsCornerElseTheTablesDate() throws {        let placed = try decode(#","card":{"face":"event","fields":[{"slot":"title","column":"line"},{"slot":"date","column":"day"}],"corner":[{"column":"at","form":"relative"}]}"#)        XCTAssertEqual(placed.whenColumn, "day")        let cornered = try decode(#","card":{"face":"event","fields":[{"slot":"title","column":"line"}],"corner":[{"column":"day","form":"relative"}]}"#)        XCTAssertEqual(cornered.whenColumn, "day")        XCTAssertEqual(try decode("").whenColumn, "at")    }    /// RULE: Only a filter naming one value is held by a record made under it: a list (any one of) or an operator (a day from today, a set of values) narrows the read and is never written.    func testANewRecordHoldsNoFilterThatIsNotOneValue() throws {        let filter: [String: RecordValue] = [            "ends": .object(["on": .text("from_today")]), "kind": .list([.text("ticket"), .text("stay")]),            "status": .object(["values": .list([.text("open")])]), "by": .text("user"),        ]        let narrowed = RecordListModel.narrowed(["title": .text("Nara")], filter: filter, project: nil, in: try decode(""))        XCTAssertEqual(narrowed, ["title": .text("Nara"), "by": .text("user")])    }    /// RULE: A several-choice value written as a JSON array holding something besides words reads as its words, never as the raw text.    func testAJSONArrayWithANullReadsAsItsWords() throws {        XCTAssertEqual(FaceText.choices(.text(#"["calm",null,"tired"]"#)), ["calm", "tired"])        XCTAssertEqual(FaceText.choices(.text(#"[null]"#)), [])        XCTAssertEqual(FaceText.choices(.text("calm")), ["calm"])    }}/// What the Mood conversion taught every table list.final class MoodConversionTests: XCTestCase {    /// A slip that opens nothing leaves its record read-only and impossible    /// to remove — the Mood list's first cut did that.    /// RULE: No table list is handed an open that does nothing: a slip always opens its record's page.    func testNoTableListOpensNothing() throws {        let pattern = try NSRegularExpression(pattern: #"TableListRoute\([^)]*\)\s*\{\s*_\s+in\s*\}"#)        for (name, text) in try AppSources.all() {            let code = SourceSweep.withoutComments(text)            let hits = pattern.numberOfMatches(in: code, range: NSRange(code.startIndex..., in: code))            XCTAssertEqual(hits, 0, "\(name) hands a table list an open that does nothing")        }    }}