Cotton code
288 lines · 18.0 KB · SwiftRaw
// What the one input SENDS the core for a line of words and how it carries// the answer (`shell.input {op: line}` then `{op: commit}`): what the words// write is the core's, held in Rust (shell_input_tests.rs). What the "+"// attached still goes through the fixture verbs. The clock is pinned to// Thursday 1 October 2026, noon UTC, in Berlin. Every record is invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class OneInputModelTests: XCTestCase {    private static let berlin = TimeZone(identifier: "Europe/Berlin")!    private static func playing(_ role: TableRole, _ definition: TableDefinition) -> TableDefinition {        var played = definition        played.role = role        return played    }    private static let noon = Date(timeIntervalSince1970: 1_790_856_000)  // 2026-10-01T12:00:00Z    private static let todo = playing(.todo, TableDefinition(        id: "todo", name: "Todo", plural: "Todos",        columns: [            ColumnDefinition(key: "title", type: .text, required: true),            ColumnDefinition(key: "status", type: .choice, choices: ["open", "done", "dropped"]),            ColumnDefinition(key: "due_date", type: .date),            ColumnDefinition(key: "due_time", type: .time),            ColumnDefinition(key: "person", type: .link, linkTo: "person"),            ColumnDefinition(key: "project", type: .link, linkTo: "project"),        ],        title: "title", date: "due_date", project: "project",        slip: SlipLayout(title: "title", toggle: "status"), tile: TileLayout(face: .slipList),        page: [PageSection(heading: nil, columns: ["title", "due_date", "due_time", "person", "project"])]))    /// A table whose date holds the time, as the built-in todo's `due_at` does.    private static let chore = TableDefinition(        id: "chore", name: "Chore", plural: "Chores",        columns: [            ColumnDefinition(key: "title", type: .text, required: true),            ColumnDefinition(key: "due_at", type: .date),        ],        title: "title", date: "due_at",        slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList),        page: [PageSection(heading: nil, columns: ["title", "due_at"])])    private static let project = playing(.project, TableDefinition(        id: "project", name: "Project", plural: "Projects",        columns: [ColumnDefinition(key: "name", type: .text, required: true)], title: "name",        slip: SlipLayout(title: "name"), tile: TileLayout(face: .capGrid),        page: [PageSection(heading: nil, columns: ["name"])]))    private static let person = playing(.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"])]))    private var store: FixtureRecords!    override func setUp() async throws {        store = FixtureRecords(            definitions: [Self.todo, Self.chore, Self.project, Self.person],            records: [                "project": [                    TableRecord(id: "p-allotment", values: ["name": .text("Allotment")]),                    TableRecord(id: "p-home", values: ["name": .text("Home")]),                ],                "person": [TableRecord(id: "person-sam", values: ["full_name": .text("Sam")])],                "todo": [                    TableRecord(                        id: "todo-milk",                        values: ["title": .text("buy milk"), "status": .text("open"), "due_date": .text("2026-10-05"),                                 TableRecord.saidKey: .object(["slip": .object(["name": .text("buy milk")])])]),                    TableRecord(                        id: "todo-bread", values: ["title": .text("buy bread"), "status": .text("open"),                                                   "project": .text("p-home"),                                                   TableRecord.saidKey: .object(["slip": .object(["name": .text("buy bread")])])]),                ],                "chore": [],            ], thoughtsKept: true)    }    private func model(_ place: OneInputModel.Place, core: InputCore = InputCore { _, _ in .success(.object([:])) })        -> OneInputModel    {        OneInputModel(            place: place, core: core, records: store,            definitions: TableDefinitions([Self.todo, Self.chore, Self.project, Self.person]),            now: { Self.noon }, timeZone: Self.berlin)    }    private func todo(_ id: String) async throws -> TableRecord? { try await store.get(table: "todo", id: id) }    /// A core that reads every line as `read` and answers a commit with    /// `committed`.    private static func core(read: JSONValue, committed: JSONValue = .object([:])) -> InputCore {        InputCore { method, request in            guard method == CottonMethod.shellInput else { return .failure(CottonCallError(code: "missing", message: "Not here")) }            return .success(request["op"]?.string == "line" ? read : committed)        }    }    // ── The core reads the line ──    /// RULE: The input sends the core where it stands and the words as typed — a list with its project and holding, a page with its record, a blank page with its preset, a thought about a record — and hands the writes the core answered to its commit exactly as they came.    func testTheLineIsSentWhereItStandsAndItsWritesCommittedAsTheyCame() async throws {        let writes: JSONValue = .array([.object(["kind": "update", "table": "todo", "id": "todo-milk", "patch": .object(["status": "done"])])])        let core = Self.core(            read: .object(["words": "done milk", "writes": writes, "said": "Ticked buy milk"]),            committed: .object(["change": .object(["id": "c1", "record_id": "todo-milk", "undoable": .bool(true),                                                    "after": .object(["status": "done"])])]))        let result = await model(.list(table: Self.todo, project: "p-home", holding: ["project": .text("p-home")]), core: core)            .submit("  done milk ")        let line = try XCTUnwrap(core.asked(CottonMethod.shellInput, op: "line").first)        XCTAssertEqual(line["words"]?.string, "done milk")        XCTAssertEqual(line["at"]?["list"]?["table"]?.string, "todo")        XCTAssertEqual(line["at"]?["list"]?["project"]?.string, "p-home")        XCTAssertEqual(line["at"]?["list"]?["holding"]?["project"]?.string, "p-home")        XCTAssertEqual(line["timezone"]?.string, "Europe/Berlin")        XCTAssertNil(line["spoken"])        XCTAssertEqual(core.asked(CottonMethod.shellInput, op: "commit").first?["writes"], writes, "the writes go to commit as the core said them")        XCTAssertEqual(result.change?.after?["status"], .text("done"))        XCTAssertEqual(result.table?.id, "todo")        XCTAssertEqual(result.said, "Ticked buy milk")        for (place, key) in [            (OneInputModel.Place.page(table: Self.todo, id: "todo-milk", project: nil), "page"),            (.blank(table: Self.todo, preset: ["status": .text("open")], project: nil), "page"),            (.about(table: Self.todo, id: "todo-milk"), "about"),            (.board(project: nil), "board"),        ] {            let at = Self.core(read: .object(["writes": .array([])]))            _ = await model(place, core: at).submit("tomorrow", spoken: true)            let sent = try XCTUnwrap(at.asked(CottonMethod.shellInput, op: "line").first)            XCTAssertNotNil(sent["at"]?[key], "\(place)")            XCTAssertEqual(sent["spoken"], .bool(true))        }    }    /// RULE: A refusal the core answers is said and nothing is committed; a line whose words name two records or more asks which, offering the candidates, and the one chosen is sent again with the same words.    func testARefusalIsSaidAndWhichIsAskedOfThePerson() async throws {        let refusing = Self.core(read: .object(["writes": .array([]), "refusal": "No todos matched milk", "said": "No todos matched milk"]))        let refused = await model(.list(table: Self.todo, project: nil), core: refusing).submit("done milk")        XCTAssertEqual(refused.said, "No todos matched milk")        XCTAssertEqual(refused.saidKind, .notDone)        XCTAssertTrue(refusing.asked(CottonMethod.shellInput, op: "commit").isEmpty, "nothing is written")        let candidates: JSONValue = .array([            .object(["table": "todo", "id": "todo-milk", "title": "buy milk"]),            .object(["table": "todo", "id": "todo-oat", "title": "buy oat milk"]),        ])        let asking = Self.core(read: .object(["writes": .array([]), "asks": .array([.object(["kind": "which", "candidates": candidates])])]))        let input = model(.list(table: Self.todo, project: nil), core: asking)        let which = await input.submit("done milk")        XCTAssertEqual(which.which?.map(\.id), ["todo-milk", "todo-oat"])        XCTAssertNil(which.change)        XCTAssertTrue(asking.asked(CottonMethod.shellInput, op: "commit").isEmpty, "nothing is guessed")        _ = await input.submit("done milk", record: "todo-oat")        XCTAssertEqual(asking.asked(CottonMethod.shellInput, op: "line").last?["record"]?.string, "todo-oat")    }    /// RULE: Where the core opens a tool or a record the input carries it as a route and writes nothing; where it asks the model, the change is the whole answer and nothing is sent to a session (the session inbox is gone).    func testOpensIsFollowedAndAModelAskSendsNothing() async throws {        let opening = Self.core(read: .object(["writes": .array([]), "opens": .object(["table": "todo"])]))        let opened = await model(.board(project: nil), core: opening).submit("open todos", spoken: true)        XCTAssertEqual(opened.open, BoardLayout.listRoute(forTable: "todo"))        let record = Self.core(read: .object(["writes": .array([]), "opens": .object(["table": "todo", "id": "todo-milk"])]))        let page = await model(.list(table: Self.todo, project: nil), core: record).submit("open buy milk", spoken: true)        XCTAssertEqual(page.open, .tableRecord(table: "todo", id: "todo-milk"))        let create: JSONValue = .object(["kind": "create", "table": "todo", "data": .object(["title": "repaint the garden fence"])])        let making = Self.core(            read: .object(["writes": .array([create]),                           "asks": .array([.object(["kind": "model", "words": "repaint the garden fence", "table": "todo",                                                    "record_of": .number(0), "project": "p-home"])])]),            committed: .object(["change": .object(["id": "c2", "record_id": "todo-new", "undoable": .bool(true)]),                                "record": .object(["id": "todo-new", "data": .object(["title": "repaint the garden fence"])])]))        let made = await model(.list(table: Self.todo, project: "p-home"), core: making).submit("repaint the garden fence")        XCTAssertNotNil(made.change)        XCTAssertNil(made.said, "the receipt is the whole answer")        XCTAssertEqual(making.asked(CottonMethod.shellInput, op: "commit").count, 1, "only the commit is called")    }    // ── The "+": one attach act everywhere (architect 6 Oct 07:25Z) ──    private static let photo = CapturedPicture(kind: .photo, recordId: "photo-1", key: "media/photo-1.jpg")    private static let scan = CapturedPicture(kind: .document, recordId: "document-1", key: "media/document-1.pdf")    /// RULE: On a record's page what the "+" attached goes with the words onto that record through a thought said on it, and the receipt says "Added a photo to" the record by its title.    func testThePlusOnAPageAddsToThatRecord() async throws {        let result = await model(.page(table: Self.todo, id: "todo-bread", project: nil))            .submit("the rye from the corner shop", attaching: [Self.photo])        XCTAssertTrue(result.change?.said?.said.contains("buy bread") == true, "the receipt names the record by its title")        XCTAssertEqual(result.change?.after?["said_table"], .text("todo"))        XCTAssertEqual(result.change?.after?["said_record_id"], .text("todo-bread"))        XCTAssertEqual(            result.change?.after?["attachments"], .list([.object(["kind": .text("photo"), "id": .text("photo-1")])]))        XCTAssertNil(OneInputNote.of(result))        let bread = try await todo("todo-bread")        XCTAssertEqual(bread?["title"], .text("buy bread"), "the record itself is not written")    }    /// RULE: A picture the "+" attached with no words beside it sends nothing: a thought is something said, as on the database page's box.    func testAPictureAloneSendsNothing() async throws {        let result = await model(.page(table: Self.todo, id: "todo-bread", project: nil)).submit(" ", attaching: [Self.photo])        XCTAssertNil(result.change)        XCTAssertNil(OneInputNote.of(result), "nothing was sent, so nothing is said")    }    /// RULE: Words sent with what the "+" attached are never read as a change: "done" beside a photo is the photo's words, and the record stays open.    func testWordsBesideAnAttachmentAreItsWords() async throws {        let result = await model(.page(table: Self.todo, id: "todo-milk", project: nil))            .submit("done", attaching: [Self.photo, Self.scan])        XCTAssertEqual(result.change?.after?["raw_text"], .text("done"))        XCTAssertTrue(result.change?.said?.said.contains("buy milk") == true, "the receipt names the record by its title")        let milk = try await todo("todo-milk")        XCTAssertEqual(milk?["status"], .text("open"))    }    /// RULE: On a list what the "+" attached goes onto a thought said in that tool, with no record named, whatever the list takes by typing.    func testThePlusOnAListAddsToAThoughtSaidThere() async throws {        let result = await model(.list(table: Self.todo, project: nil))            .submit("milk for the week", attaching: [Self.photo, Self.photo])        XCTAssertNotNil(result.change?.said?.said)        XCTAssertEqual(result.change?.after?["said_table"], .text("todo"))        XCTAssertNil(result.change?.after?.values["said_record_id"])        let todos = try await store.list(table: "todo", project: nil, query: nil, page: 0)        XCTAssertEqual(todos.records.count, 2, "no todo is made of the words beside a photo")    }    /// RULE: On a list that takes files (Photos, Videos, Documents) the pick already made each file's own record, so the words beside it become that record's caption in its own table — never a thought kept there — and the receipt offers no Undo, as the files stay.    func testOnAFileTakingListTheWordsAreTheCaption() async throws {        var photo = TableDefinition(            id: "photo", name: "Photo", plural: "Photos", builtin: true, engine: "media",            columns: [ColumnDefinition(key: "key", type: .photo, readonly: true), ColumnDefinition(key: "caption", type: .text)],            title: "caption", slip: SlipLayout(title: "caption"), tile: TileLayout(face: .polaroidGrid),            page: [PageSection(heading: nil, columns: ["caption"])])        photo.takesFiles = true        let document = TableDefinition(            id: "document", name: "Document", plural: "Documents", builtin: true, engine: "documents",            columns: [ColumnDefinition(key: "title", type: .text)], title: "title",            slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList),            page: [PageSection(heading: nil, columns: ["title"])])        let files = FixtureRecords(            definitions: [photo, document],            records: [                "photo": [TableRecord(id: "photo-1", values: [:])],                "document": [TableRecord(id: "document-1", values: [:])],            ], thoughtsKept: true)        let model = OneInputModel(            place: .list(table: photo, project: nil), core: InputCore { _, _ in .success(.object([:])) }, records: files, definitions: TableDefinitions([photo, document]),            now: { Self.noon }, timeZone: Self.berlin)        XCTAssertTrue(OneInputModel.takesFiles(photo))        XCTAssertFalse(OneInputModel.takesFiles(Self.todo))        let result = await model.submit("the allotment shed in June", attaching: [Self.photo, Self.scan])        XCTAssertNotNil(result.change?.said?.said)        XCTAssertEqual(result.change?.undoable, false, "the files stay; the receipt offers no Undo")        XCTAssertNil(OneInputNote.of(result))        let shot = try await files.get(table: "photo", id: "photo-1")        XCTAssertEqual(shot?["caption"], .text("the allotment shed in June"))        let scan = try await files.get(table: "document", id: "document-1")        XCTAssertEqual(scan?["title"], .text("the allotment shed in June"), "a file picked on Photos is captioned in its own table")        XCTAssertNil(result.change?.after?.values["raw_text"], "no thought is kept of the words")        XCTAssertEqual(result.table?.id, "document", "the receipt is the last file's table, never a thought's")    }    /// RULE: The receipt names what the "+" attached by kind and count, and the place it went — a single item carries no figure, several carry their count, and each kind (or a mix) reads differently.    func testTheAttachReceiptNamesWhatWasAdded() {        XCTAssertTrue(ThoughtKept.added([.photo], to: "Pick up the slides").contains("Pick up the slides"))        XCTAssertFalse(ThoughtKept.added([.photo], to: "Chores").contains("1"))        XCTAssertTrue(ThoughtKept.added([.photo, .photo], to: "Chores").contains("2"))        XCTAssertTrue(ThoughtKept.added([.document, .document, .document], to: "Chores").contains("3"))        let kinds = [            ThoughtKept.added([.photo], to: "Chores"), ThoughtKept.added([.video], to: "Chores"),            ThoughtKept.added([.document], to: "Chores"),        ]        XCTAssertEqual(Set(kinds).count, kinds.count, "each kind is named for itself")        XCTAssertNotEqual(            ThoughtKept.added([.photo, .video], to: "Chores"), ThoughtKept.added([.photo, .photo], to: "Chores"),            "a mix is not named as one kind")    }}