Cotton code
372 lines · 21.5 KB · SwiftRaw
// An act's picks asked on the long-press fan (`DeckPicks`): an act that// picks nothing runs at once; one that picks turns the fan into each pick's// answers in the definition's order and runs with them; the close runs// nothing; a quantity never steps below its min. Driven through a scripted// core, asserting what the core was asked.#if os(iOS)import CottonKitimport CottonValuesimport XCTest@testable import CottonUI@MainActorfinal class DeckPicksTests: XCTestCase {    func testEveryVisiblePersonLabelIsOnScreenAndNeverIntersectsANeighbour() throws {        let fan = FanGeometry(scale: Theme.paper.scale).withHub(diameter: 64)        for current in 0..<12 {            let frames = (0..<12).compactMap { fan.labelFrame(index: $0, theta: Double(current) * fan.step, width: 393) }            for (index, frame) in frames.enumerated() {                XCTAssertGreaterThanOrEqual(frame.minX, 0)                XCTAssertLessThanOrEqual(frame.maxX, 393)                XCTAssertGreaterThanOrEqual(frame.minY, 0)                let hub = fan.hub(width: 393, diameter: 64)                XCTAssertFalse(frame.intersects(CGRect(x: hub.x - 32, y: hub.y - 32, width: 64, height: 64)), "hub never hides a label")                for neighbour in frames.dropFirst(index + 1) {                    XCTAssertFalse(frame.intersects(neighbour), "\(frame) overlaps \(neighbour)")                }            }        }    }    private let order: RecordCommand = {        var command = RecordCommand(id: "order", label: "Take an order", verb: "reserve_record", kind: .create)        command.picks = [            RecordCommandPick(argument: "data.customer", kind: .record, table: "person"),            RecordCommandPick(argument: "data.quantity", kind: .number, min: 1, defaultValue: 1),        ]        command.picks?[0].label = "Customer"        command.picks?[1].label = "Quantity"        return command    }()    /// Give subtitles' shape (SUBTITLE FILE): one file pick, run by an app method.    private let give: RecordCommand = {        var command = RecordCommand(id: "give", label: "Give subtitles", kind: .update,                                    pick: RecordCommandPick(argument: "path", kind: .file))        command.pick?.accept = ["srt", "vtt"]        command.method = "films.subtitleFile"        return command    }()    private var definition: TableDefinition {        var definition = TableDefinition(            id: "todo", name: "Todo", plural: "Todos", columns: [ColumnDefinition(key: "title", type: .text)],            title: "title", slip: SlipLayout(title: "title"), tile: TileLayout(face: .slipList), page: [])        definition.commands = [            RecordCommand(id: "complete", label: "Mark done", kind: .update),            order,            RecordCommand(id: "note", label: "Note", verb: "update", kind: .update,                          pick: RecordCommandPick(argument: "note", kind: .text)),            give,        ]        return definition    }    private let target = DeckEditTarget(table: "todo", record: "t1", date: nil)    /// The pick's writes as the core says them, `answers` so far.    nonisolated private static func writes(_ answers: [String]) -> String {        let answered = answers.map { "\"\($0)\"" }.joined(separator: ",")        return #"{"kind":"pick","table":"todo","act":"order","answers":[\#(answered)],"id":"t1"}"#    }    /// A customer pick, then a quantity's stepper at `count`.    nonisolated private static func step(_ request: JSONValue) -> String {        let answers = request["answers"]?.array ?? request["writes"]?["answers"]?.array ?? []        if answers.isEmpty {            let query = request["query"]?.string ?? ""            let ink = request["ink"]?.string ?? ""            let people = [("p-asha", "Asha", "A"), ("p-ravi", "Ravi", "R")].filter { _, name, _ in                (query.isEmpty || name.contains(query)) && (ink.isEmpty || name.lowercased().hasPrefix(ink))            }            let rows = people.map { id, name, initials in                #"{"value":"\#(id)","words":"\#(name)","detail":"Customer","initials":"\#(initials)","does":"answer"}"#            } + [#"{"value":"","words":"Search","does":"search","search":{"editor":"line","words":"\#(query)","hint":"Search","keeps_words":false,"writes":{"kind":"pick_search","table":"todo","act":"order","answers":[]}}}"#]            return #"{"label":"Customer","index":0,"table":"person","writes":\#(writes([])),"rows":[\#(rows.joined(separator: ","))]}"#        }        let count: Double = request["count"]?.double ?? 1        let words: String = String(Int(count))        let rows = [#"{"value":"\#(count)","words":"\#(words)","detail":"Quantity","does":"answer"}"#,                    #"{"value":"","words":"+1","does":"count","count":\#(count + 1)}"#]        let answered = answers.compactMap(\.string)        return #"{"label":"Quantity","index":1,"rest":0,"writes":\#(writes(answered)),"rows":[\#(rows.joined(separator: ","))]}"#    }    /// The core's answers to an act's picks: the step due, the commit's next    /// step or the act run, a search committed.    private func scripted(nothing: Bool = false) -> InputCore {        InputCore { method, request in            switch (method, request["op"]?.string, request["writes"]?["kind"]?.string) {            case ("shell.opened", _, _):                if nothing {                    return .success(InputCore.json(#"{"step":{"label":"Customer","index":0,"writes":\#(Self.writes([])),"rows":[],"nothing":"No one to pick"}}"#))                }                if request["act"]?.string == "give" {                    return .success(InputCore.json(#"{"step":{"label":"A subtitle file","index":0,"writes":{"kind":"pick","table":"todo","act":"give","answers":[],"id":"t1"},"file":{"accept":["srt","vtt"],"hint":"A subtitle file","writes":{"kind":"pick_file","table":"todo","act":"give","answers":[],"id":"t1"}}}}"#))                }                if request["act"]?.string == "note" {                    return .success(InputCore.json(#"{"step":{"label":"Note","index":0,"writes":{"kind":"pick","table":"todo","act":"note","answers":[],"id":"t1"},"words":{"editor":"page","words":"Synthetic notes","title":"Synthetic todo","hint":"Note","keeps_words":true,"writes":{"kind":"pick_words","table":"todo","act":"note","answers":[],"id":"t1"}}}}"#))                }                return .success(InputCore.json(#"{"step":\#(Self.step(request))}"#))            case ("shell.input", "commit", "pick_file"):                let path = request["words"]?.string ?? ""                guard path.hasSuffix(".srt") || path.hasSuffix(".vtt") else {                    return .success(InputCore.json(#"{"refusal":"This takes only a .srt, .vtt file."}"#))                }                return .success(InputCore.json(#"{"ran":{"command":"give","kind":"update","receipt":"Your Mac will add your subtitles to Synthetic film"}}"#))            case ("shell.input", "commit", "pick_search"):                return .success(.object(["query": request["words"] ?? ""]))            case ("shell.input", "commit", _):                let answers = (request["writes"]?["answers"]?.array ?? []) + [request["words"] ?? .null]                if answers.count == 1, request["writes"]?["act"]?.string == "order" {                    return .success(InputCore.json(#"{"step":\#(Self.step(.object(["answers": .array(answers)])))}"#))                }                return .success(InputCore.json(#"{"ran":{"command":"\#(request["writes"]?["act"]?.string ?? "")","kind":"create","receipt":"Ordered"}}"#))            case ("records.command", _, _):                return .success(InputCore.json(#"{"command":"complete","kind":"update","receipt":"Done"}"#))            default:                return .failure(CottonCallError(code: "missing", message: "Not here"))            }        }    }    private func place(_ core: InputCore) throws -> DeckPickPlace {        DeckPickPlace(store: CoreRecords(core: core, bundle: try TestResources.bundle()), core: core,                      definitions: TableDefinitions([definition]))    }    private func opened(_ editor: DeckEditor) -> DeckEditor {        editor.openActs(target, record: TableRecord(id: "t1", values: [:]))        return editor    }    /// RULE: An act that picks nothing runs at once from the deck's fan — one call, nothing picked — and the fan goes back to its tools.    func testAnActThatPicksNothingRunsAtOnce() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        let complete = try XCTUnwrap(definition.commands?.first { $0.id == "complete" })        let outcome = await editor.act(complete, on: target, definition: definition, place: try place(core))        guard case .ran = outcome else { return XCTFail("the act did not run: \(outcome)") }        XCTAssertNil(editor.editing, "the fan is back to its tools")        let sent = core.asked("records.command")        XCTAssertEqual(sent.count, 1)        XCTAssertEqual(sent.first?["command"], "complete")        XCTAssertEqual(sent.first?["picked"], .null)        XCTAssertTrue(core.asked("shell.opened").isEmpty, "nothing is asked")    }    /// RULE: An act with picks asks the core the pick now due and deals its    /// rows on the fan as the core words them; a row tapped is committed with    /// the writes the step said, and the core's next step stands, until the    /// commit it answers with the act run.    func testAnActWithPicksAsksEachOfTheCoreAndRunsOnTheLast() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        let asked = await editor.act(order, on: target, definition: definition, place: try place(core))        XCTAssertEqual(asked, .asking)        XCTAssertEqual(editor.editing, .picks(target))        XCTAssertEqual(editor.pickOptions.map(\.word), ["Asha", "Ravi", "Search"], "the core's rows, in its words")        XCTAssertEqual(editor.pickOptions.first?.detail, "Customer")        XCTAssertEqual(editor.pickOptions.first?.initials, "A")        let first = try XCTUnwrap(core.asked("shell.opened").first)        XCTAssertEqual(first["step"], "pick")        XCTAssertEqual(first["act"], "order")        XCTAssertEqual(first["id"], "t1")        XCTAssertEqual(first["answers"], .array([]))        XCTAssertTrue(core.asked("shell.input").isEmpty, "nothing is committed before a row is tapped")        let customer = await editor.answer(try XCTUnwrap(editor.pickOptions.first { $0.word == "Ravi" }))        XCTAssertEqual(customer, .asking)        let committed = try XCTUnwrap(core.asked("shell.input", op: "commit").first)        XCTAssertEqual(committed["words"], "p-ravi")        XCTAssertEqual(committed["writes"], InputCore.json(Self.writes([])))        XCTAssertEqual(editor.pickOptions.first?.detail, "Quantity", "the core's next step stands")        let up = await editor.answer(try XCTUnwrap(editor.pickOptions.first { $0.does == .count(2) }))        XCTAssertEqual(up, .asking)        XCTAssertEqual(core.asked("shell.opened").last?["count"], .number(2), "the stepper's count is asked of the core")        XCTAssertEqual(core.asked("shell.opened").last?["answers"], .array(["p-ravi"]))        XCTAssertEqual(editor.pickOptions.first?.word, "2")        let ran = await editor.answer(try XCTUnwrap(editor.pickOptions.first))        guard case .ran = ran else { return XCTFail("the act did not run: \(ran)") }        XCTAssertNil(editor.editing)        XCTAssertNil(editor.picking)        XCTAssertEqual(core.asked("shell.input", op: "commit").last?["words"], "2.0")        XCTAssertTrue(core.asked("records.command").isEmpty, "the core runs the act on its commit")    }    /// A synthetic subtitle file at `name`, as the person's Files would hand it.    private func given(_ name: String) throws -> URL {        let folder = FileManager.default.temporaryDirectory.appending(path: "given-\(UUID().uuidString)", directoryHint: .isDirectory)        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)        let file = folder.appending(path: name)        try Data("1\n00:00:01,000 --> 00:00:02,000\nSynthetic line\n".utf8).write(to: file)        return file    }    /// RULE: A file pick (Give subtitles) opens the platform's picker for the core's extensions and draws nothing    /// else; the picked file is copied under its own name, its path committed with the file's own writes, the act    /// runs on the core's answer, and the copy is gone once the commit has answered.    func testAFilePickCommitsTheCopysPathUnderItsOwnName() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        let picked = try given("Synthetic Film.French.srt")        var accepted: [String] = []        var copied: URL?        editor.chooseFile = { accept in            accepted = accept            copied = try PickedFile.copy(picked)            return copied        }        let outcome = await editor.act(give, on: target, definition: definition, place: try place(core))        guard case .ran = outcome else { return XCTFail("the act did not run: \(outcome)") }        XCTAssertEqual(accepted, ["srt", "vtt"])        let committed = try XCTUnwrap(core.asked("shell.input", op: "commit").first)        XCTAssertEqual(committed["writes"]?["kind"], "pick_file", "the file's own writes")        let path = try XCTUnwrap(committed["words"]?.string)        XCTAssertEqual((path as NSString).lastPathComponent, "Synthetic Film.French.srt", "never renamed: the core reads the language from it")        XCTAssertTrue(path.hasPrefix(PickedFile.root.path(percentEncoded: false)), "in a folder of the app's own")        XCTAssertFalse(FileManager.default.fileExists(atPath: try XCTUnwrap(copied).path(percentEncoded: false)), "the copy is removed once the commit answered")        XCTAssertTrue(FileManager.default.fileExists(atPath: picked.path(percentEncoded: false)), "the person's own file stands")        XCTAssertNil(editor.picking)    }    /// RULE: Cancel in the file picker closes the step and sends nothing.    func testCancellingAFilePickSendsNothing() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        editor.chooseFile = { _ in nil }        let outcome = await editor.act(give, on: target, definition: definition, place: try place(core))        XCTAssertEqual(outcome, DeckActOutcome.none)        XCTAssertNil(editor.picking)        XCTAssertTrue(core.asked("shell.input").isEmpty, "nothing is committed")    }    /// RULE: A file of another extension, picked anyway, is committed and refused in the core's words, never    /// filtered silently.    func testAFileOfAnotherKindIsRefusedInTheCoresWords() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        let picked = try given("Synthetic notes.txt")        editor.chooseFile = { _ in try PickedFile.copy(picked) }        let outcome = await editor.act(give, on: target, definition: definition, place: try place(core))        XCTAssertEqual(outcome, .refused("This takes only a .srt, .vtt file."))        XCTAssertEqual(core.asked("shell.input", op: "commit").count, 1, "committed, not filtered")    }    /// RULE: Closing the fan while an act's picks are asked runs nothing, and a stale answer after the close runs nothing either.    func testCancellingAPickRunsNothing() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        _ = await editor.act(order, on: target, definition: definition, place: try place(core))        let asha = try XCTUnwrap(editor.pickOptions.first)        editor.close()        XCTAssertEqual(editor.editing, .acts(target), "one close cancels the pick and restores the acts")        XCTAssertNil(editor.picking)        let stale = await editor.answer(asha)        XCTAssertEqual(stale, DeckActOutcome.none)        XCTAssertTrue(core.asked("shell.input").isEmpty, "a cancelled act is never sent")    }    /// RULE: A record pick's Search asks its words in the shell's writer as    /// the core worded it; committed, the core's search stands and the pick    /// is asked again with it; closing the writer leaves the pick.    func testASearchIsAskedInTheWriterAndAskedOfTheCore() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        _ = await editor.act(order, on: target, definition: definition, place: try place(core))        let search = try XCTUnwrap(editor.pickOptions.last)        _ = await editor.answer(search)        XCTAssertEqual(editor.writing?.kind, "pick_search")        editor.close()        XCTAssertNil(editor.writing)        XCTAssertEqual(editor.editing, .picks(target))        _ = await editor.answer(try XCTUnwrap(editor.pickOptions.last))        editor.commit("Ravi")        try await eventually { editor.pickOptions.map(\.word) == ["Ravi", "Search"] }        XCTAssertEqual(editor.picking?.query, "Ravi")        XCTAssertEqual(core.asked("shell.opened").last?["query"], "Ravi")        XCTAssertTrue(core.asked("shell.input", op: "commit").allSatisfy { $0["writes"]?["kind"] == "pick_search" })    }    /// RULE: Letters written over a record pick are asked of the core, which    /// narrows the rows (`ink_match`); the shell narrows nothing itself.    func testInkOverARecordPickIsAskedOfTheCore() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        _ = await editor.act(order, on: target, definition: definition, place: try place(core))        XCTAssertTrue(editor.picksRecords)        await editor.narrowPick(to: InkLetters(letters: "r", doubted: [false]))        XCTAssertEqual(core.asked("shell.opened").last?["ink"], "r")        XCTAssertEqual(editor.pickOptions.map(\.word), ["Ravi", "Search"])        await editor.narrowPick(to: InkLetters())        XCTAssertNil(core.asked("shell.opened").last?["ink"], "cleared, the pick is asked whole")        XCTAssertEqual(editor.pickOptions.map(\.word), ["Asha", "Ravi", "Search"])    }    /// RULE: A pick with nothing to offer closes the fan and says the core's words.    func testAPickWithNothingSaysSo() async throws {        let editor = opened(DeckEditor.standing())        let none = await editor.act(order, on: target, definition: definition, place: try place(scripted(nothing: true)))        XCTAssertEqual(none, .refused("No one to pick"))        XCTAssertNil(editor.picking)    }    /// RULE: An act that asks free words stands on the fan and asks them in    /// the shell's writer the core names — a todo's Notes on the full screen,    /// holding the notes it has, under its title — and the words committed    /// run it; put away, nothing runs (coordinator, 3 Nov 2026).    func testAnActAskingFreeWordsAsksThemInTheWriter() async throws {        let actions = [            CardAction(id: "order", label: "Take an order", kind: "command"),            CardAction(id: "note", label: "Note", kind: "command"),            CardAction(id: "complete", label: "Mark done", kind: "command"),        ]        XCTAssertEqual(EditingFan.items(of: actions, in: definition).map(\.word), ["Take an order", "Note", "Mark done"])        let core = scripted()        let editor = opened(DeckEditor.standing())        let note = try XCTUnwrap(definition.commands?.first { $0.id == "note" })        let asked = await editor.act(note, on: target, definition: definition, place: try place(core))        XCTAssertEqual(asked, .asking)        XCTAssertEqual(editor.writing?.kind, "pick_words")        XCTAssertEqual(editor.writing?.editor, .page)        XCTAssertEqual(editor.writing?.words, "Synthetic notes")        XCTAssertEqual(editor.writing?.title, "Synthetic todo")        XCTAssertEqual(editor.editing, .acts(target), "the fan stands as it was beneath")        editor.close()        XCTAssertNil(editor.writing)        XCTAssertNil(editor.picking)        XCTAssertTrue(core.asked("shell.input").isEmpty, "an editor put away runs nothing")        _ = await editor.act(note, on: target, definition: definition, place: try place(core))        editor.commit("  Call Ravi back  ")        try await eventually { !core.asked("shell.input", op: "commit").isEmpty && editor.picking == nil }        let sent = try XCTUnwrap(core.asked("shell.input", op: "commit").first)        XCTAssertEqual(sent["words"], "  Call Ravi back  ", "the core trims the words")        XCTAssertEqual(sent["writes"]?["kind"], "pick_words")        XCTAssertNil(editor.writing)    }    /// What the fan held each time it turned.    private final class Seen: @unchecked Sendable { var answers: [Int] = [] }    /// RULE: An act's first pick turns the fan into its answers in one change — never into an empty pick first: the fan turned into the picks before their answers were read unmounted its arc for that moment, and the answers then dealt onto it stood unprinted, so a customer's Book asking Places showed no card, nobody could answer it, and no sign-in ever followed (the walk of 24 Oct 2026, 22-book-picks).    func testTheFanTurnsIntoAPickOnlyWithItsAnswers() async throws {        let core = scripted()        let editor = opened(DeckEditor.standing())        let seen = Seen()        withObservationTracking { _ = editor.editing } onChange: {            MainActor.assumeIsolated { seen.answers.append(editor.picking?.options.count ?? -1) }        }        let asked = await editor.act(order, on: target, definition: definition, place: try place(core))        XCTAssertEqual(asked, .asking)        XCTAssertEqual(editor.editing, .picks(target))        XCTAssertEqual(seen.answers, [3], "the fan turned into the pick before its answers were read")    }}#endif