378 lines · 23.7 KB · SwiftRaw
// The held card's acts from the core (`shell.opened`): drawn in its order,// red and primary as it said; an act with a step opens that step; a command// the definition does not hold, or a kind the fan does not know, is left out// rather than drawn as a dead card.// The fan is drawn on the phone only (`EditingFan.swift` is `#if os(iOS)`),// so these run where it exists, as the Fan tests do.#if os(iOS)import XCTest@testable import CottonUI@MainActorfinal class DeckActionsTests: XCTestCase { func testDeckTopRowHasOnlySearchSendAndPlusAndTheHubPopsToTools() throws { // A tool's deck: the hand where its table offers faces, the search // disc (the ink's pill), Send where the card in view offers it, and +. let deck = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/DeckSurface.swift", ownedBy: "shell")) let deckStart = try XCTUnwrap(deck.range(of: "Spacer()", range: deck.range(of: "deck.position")!.upperBound..<deck.endIndex)) let deckEnd = try XCTUnwrap(deck.range(of: ".padding(.horizontal, DeckKnobs.lineSide)", range: deckStart.upperBound..<deck.endIndex)) let deckRow = String(deck[deckStart.upperBound..<deckEnd.lowerBound]) XCTAssertEqual(deckRow.components(separatedBy: "FaceChoiceControl(").count - 1, 1) XCTAssertEqual(deckRow.components(separatedBy: "InkReadout(").count - 1, 1) XCTAssertEqual(deckRow.components(separatedBy: "NavCircle(").count - 1, 2) XCTAssertTrue(deckRow.contains("acts.contains(EditingAct.send.rawValue)"), "Send stands only where the core offers it on the card in view") let order = try ["FaceChoiceControl(", "InkReadout(", "deck-send", "symbol: \"plus\""].map { try XCTUnwrap(deckRow.range(of: $0)).lowerBound } XCTAssertEqual(order, order.sorted()) for file in ["Deck/CardDeck.swift"] { let source = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/" + file, ownedBy: "shell")) let start = try XCTUnwrap(source.range(of: "Spacer()", range: source.range(of: "deck.position")!.upperBound..<source.endIndex)) let end = try XCTUnwrap(source.range(of: ".padding(.horizontal, DeckKnobs.lineSide)", range: start.upperBound..<source.endIndex)) let row = String(source[start.upperBound..<end.lowerBound]) XCTAssertEqual(row.components(separatedBy: "NavCircle(").count - 1, 2) XCTAssertFalse(row.contains("FaceChoiceControl")) let search = try XCTUnwrap(row.range(of: "magnifyingglass")) let plus = try XCTUnwrap(row.range(of: "symbol: \"plus\"")) XCTAssertLessThan(search.lowerBound, plus.lowerBound) } for file in ["Surfaces/Board/BoardHead.swift", "Surfaces/HomeInput.swift", "Deck/CardDeck.swift", "Deck/DeckSurface.swift"] { let source = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/" + file, ownedBy: "shell")) XCTAssertFalse(source.contains("TrayStackButton"), "no fourth circle in \(file)") } let tiers = FanTiers() tiers.setRoot(.init(id: "tools", cards: [])) tiers.push(.init(id: "views", cards: [])) { _ in } tiers.pop() XCTAssertEqual(tiers.open?.id, "tools") XCTAssertFalse(tiers.closes) } private let 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), RecordCommand(id: "drop", label: "Drop", kind: .update), ] return definition }() func testTheFanIsTheCoresOrderRedAndPrimaryAsItSaid() throws { let answer = try JSONDecoder().decode(OpenedActs.self, from: Data(""" {"acts":[ {"id":"complete","label":"Mark done","kind":"command","rank":"main","primary":true,"red":false,"icon":"act-stamp"}, {"id":"when","label":"When","kind":"chooser","rank":"more","primary":false,"red":false,"column":"due_at","step":"when"}, {"id":"tel:phones","label":"Call","kind":"address","rank":"more","primary":false,"red":false,"icon":"act-handset","url":"tel:+919900000848"}, {"id":"group","label":"Group","kind":"chooser","rank":"more","primary":false,"red":false,"step":"group"}, {"id":"drop","label":"Drop","kind":"command","rank":"away","primary":false,"red":true}, {"id":"bin","label":"Bin","kind":"chooser","rank":"away","primary":false,"red":true} ]} """.utf8)) let items = EditingFan.items(of: answer.acts, in: definition) XCTAssertEqual(items.map(\.word), ["Mark done", "When", "Call", "Group", "Drop", "Bin"]) XCTAssertEqual(items.filter(\.primary).map(\.word), ["Mark done"]) XCTAssertEqual(items.filter(\.red).map(\.word), ["Drop", "Bin"]) XCTAssertEqual(items.first?.picture, "act-stamp") XCTAssertEqual(items[1].does, .act(.when)) XCTAssertEqual(items[2].does, .address(URL(string: "tel:+919900000848")!)) XCTAssertEqual(items[3].does, .act(.group)) XCTAssertEqual(items[5].does, .act(.bin)) } /// RULE: a command that stands for a chooser opens its step (Set date /// the When step, the repeat rule's Repeat the Repeat step) and keeps its /// own words and its command's id. func testACommandWithAStepOpensIt() { let actions = [ CardAction(id: "set-date", label: "Set date", kind: "command", icon: "act-bell", step: "when"), CardAction(id: "open-repeat-rule", label: "Repeat", kind: "command", step: "repeat"), ] let items = EditingFan.items(of: actions, in: definition) XCTAssertEqual(items.map(\.id), ["command-set-date", "command-open-repeat-rule"]) XCTAssertEqual(items.map(\.does), [.act(.when), .act(.repeat)]) } func testWhatTheFanCannotRunIsLeftOut() { let actions = [ CardAction(id: "rename", label: "Rename", kind: "command"), CardAction(id: "frobnicate", label: "Frobnicate", kind: "chooser"), CardAction(id: "bin", label: "Bin", kind: "mystery"), CardAction(id: "tel:phones", label: "Call", kind: "address"), CardAction(id: "repeat", label: "Repeat", kind: "chooser", step: "repeat"), ] XCTAssertEqual(EditingFan.items(of: actions, in: definition).map(\.word), ["Repeat"]) } /// RULE: a held card asks the core for its acts once (`shell.opened /// {table, id, view, face}`), kept for that card alone; another card /// never wears them. func testAHeldCardAsksTheCoreOnceAndKeepsTheAnswerForItself() async throws { let core = ToolActsCore(answers: [:], opened: """ {"acts":[{"id":"complete","label":"Mark done","kind":"command","rank":"main","primary":true,"red":false}]} """) let editor = DeckEditor.standing() let target = DeckEditTarget(table: "todo", record: "synthetic-todo", date: nil) editor.openActs(target, record: TableRecord(id: "synthetic-todo", values: [:]), view: "todos/open", face: "todo.card", core: core) for _ in 0..<200 where editor.actsTarget == nil { try await Task.sleep(for: .milliseconds(10)) } XCTAssertEqual(editor.actsTarget, target) XCTAssertEqual(editor.actions.map(\.label), ["Mark done"]) let asked = await core.opened XCTAssertEqual(asked.count, 1) let request = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(try XCTUnwrap(asked.first).utf8)) as? [String: String]) XCTAssertEqual(request, ["table": "todo", "id": "synthetic-todo", "view": "todos/open", "face": "todo.card", "timezone": TimeZone.current.identifier]) editor.openActs(DeckEditTarget(table: "todo", record: "another", date: nil), record: nil, core: nil) XCTAssertNil(editor.actsTarget, "another card never wears them") } /// RULE: a step's rows are the core's (`shell.opened {step}`): the When /// step opens on No date then the days, each drawn with the picture the /// core named (the shell picks none); the Status step on the verbs it /// said, each run as its definition's command, in the core's picture. func testAStepsRowsAreTheCores() throws { let days = try JSONDecoder().decode(OpenedStep<DateChoice>.self, from: Data(""" {"step":{"kind":"when","rows":[{"value":"none","words":"No date","kind":"none","picture":"act-cross"}, {"value":"today","words":"Today","kind":"today","detail":"Thu 22 Oct","day":"2026-10-22","picture":"edit-value-today"}, {"value":"pick","words":"Pick a date","kind":"pick","picture":"edit-value-day"}]}} """.utf8)).step.rows XCTAssertEqual(days.map(EditingFan.does), [.noDate, .day(days[1]), .pick]) XCTAssertEqual(days.map(\.picture), ["act-cross", "edit-value-today", "edit-value-day"]) let statuses = try JSONDecoder().decode(OpenedStep<OpenedChoice>.self, from: Data(""" {"step":{"kind":"status","rows":[{"value":"complete","words":"Mark done","picture":"act-stamp"},{"value":"gone","words":"Gone"}]}} """.utf8)).step.rows let items = EditingFan.items(statuses: statuses, in: definition) XCTAssertEqual(items.map(\.word), ["Mark done"], "a verb the definition does not hold is left out") XCTAssertEqual(items.first?.picture, "act-stamp", "the core's picture, not one the shell picks") XCTAssertEqual(items.first?.does, .status(try XCTUnwrap(definition.commands?.first))) } /// RULE: a tool's own act stands on the fan as the core answered it (`shell.opened`, kind `tool`): Connect Google Calendar while no account is connected, Disconnect with its account while one is. func testAToolsActStandsAsTheCoreAnsweredIt() throws { let connect = try JSONDecoder().decode(CardActions.self, from: Data(""" {"actions":[{"id":"google_connect","label":"Connect Google Calendar","kind":"tool","tool":"calendar","asks":false}]} """.utf8)).actions let offered = EditingFan.items(of: connect, in: definition) XCTAssertEqual(offered.map(\.word), ["Connect Google Calendar"]) XCTAssertEqual(offered.first?.does, .tool(connect[0])) let disconnect = try JSONDecoder().decode(CardActions.self, from: Data(""" {"actions":[{"id":"google_disconnect","label":"Disconnect Google (owner@example.test, synced)","kind":"tool","tool":"calendar","asks":true,"account":"owner@example.test"}]} """.utf8)).actions XCTAssertEqual(EditingFan.items(of: disconnect, in: definition).map(\.word), ["Disconnect Google (owner@example.test, synced)"]) XCTAssertEqual(disconnect.first?.asks, true) XCTAssertEqual(disconnect.first?.account, "owner@example.test") } /// RULE: a tool's act that names no tool cannot be run, and is left out. func testAToolsActNamingNoToolIsLeftOut() { let actions = [CardAction(id: "google_connect", label: "Connect Google Calendar", kind: "tool")] XCTAssertTrue(EditingFan.items(of: actions, in: definition).isEmpty) } /// RULE: an empty Calendar deck's placeholder held opens the fan on its tool's acts alone (`tools.acts {table}`): Connect Google Calendar, no edit, Bin or Export — there is no record. func testAnEmptyCalendarDecksHoldListsConnectGoogleCalendar() async throws { let core = ToolActsCore(answers: ["event": """ {"actions":[{"id":"google_connect","label":"Connect Google Calendar","kind":"tool","tool":"calendar","asks":false}, {"id":"bin","label":"Bin","kind":"chooser","icon":"edit-act-bin"}]} """]) let acts = await DeckEditor.toolActs(of: "event", core: core) let asked = await core.asked XCTAssertEqual(asked, [CottonMethod.toolsActs + " event"]) XCTAssertEqual(acts.map(\.label), ["Connect Google Calendar"], "only the tool's own acts stand where no card is held") let editor = DeckEditor.standing() editor.openToolActs(acts, for: .emptyDeck(of: "event")) XCTAssertEqual(editor.editing, .toolActs(.emptyDeck(of: "event"))) XCTAssertTrue(editor.holdsActs, "the record button is the fan's close") let items = EditingFan.items(tools: editor.actions) XCTAssertEqual(items.map(\.word), ["Connect Google Calendar"]) XCTAssertEqual(items.first?.does, .tool(acts[0])) } /// RULE: a card opened offers its tools' acts in its one answer /// (`shell.opened`), beside its own, kept for that card alone; it asks /// nothing else (the core's tool acts were lost on the opened card, /// 1adc7a92f5). func testAnOpenedCardOffersItsToolsActs() async throws { let core = ToolActsCore(answers: [:], opened: """ {"acts":[{"id":"google_connect","label":"Connect Google Calendar","kind":"tool","rank":"more","primary":false,"red":false,"tool":"calendar","asks":false}]} """) let editor = DeckEditor.standing() let target = DeckEditTarget(table: "event", record: "synthetic-event", date: nil) editor.openActs(target, record: TableRecord(id: "synthetic-event", values: [:]), core: core) for _ in 0..<200 where editor.actsTarget == nil { try await Task.sleep(for: .milliseconds(10)) } XCTAssertEqual(editor.actsTarget, target) XCTAssertEqual(EditingFan.items(tools: editor.actions).map(\.word), ["Connect Google Calendar"]) let asked = await core.asked XCTAssertEqual(asked, [CottonMethod.shellOpened + " event"], "the held card's tool acts come in its one answer") } /// RULE: an empty Music deck's placeholder held offers Music's acts (`tools.acts {table: song}`) as the core said them, in its order. func testAnEmptyMusicDecksHoldListsMusicsActs() async throws { let core = ToolActsCore(answers: ["song": """ {"actions":[{"id":"music_keep_everything","label":"Keep everything","kind":"tool","tool":"music","asks":false}]} """]) let acts = await DeckEditor.toolActs(of: "song", core: core) let asked = await core.asked XCTAssertEqual(asked, [CottonMethod.toolsActs + " song"]) let editor = DeckEditor.standing() editor.openToolActs(acts, for: .emptyDeck(of: "song")) XCTAssertEqual(editor.editing, .toolActs(.emptyDeck(of: "song"))) let items = EditingFan.items(tools: editor.actions) XCTAssertEqual(items.map(\.word), ["Keep everything"]) XCTAssertEqual(items.first?.does, .tool(acts[0])) } /// RULE: a Music deck offers its account's Sign out as the core said it, and asks first. func testAMusicDeckOffersSignOutAndAsksFirst() async throws { let core = ToolActsCore(answers: ["song": """ {"actions":[{"id":"account_sign_out","label":"Sign out","kind":"tool","tool":"music","asks":true}]} """]) let acts = await DeckEditor.toolActs(of: "song", core: core) XCTAssertEqual(EditingFan.items(tools: acts).map(\.word), ["Sign out"]) XCTAssertEqual(acts.first?.asks, true) XCTAssertNil(acts.first?.account, "the account is the person's one; the act names none") } /// RULE: a tool's connect asks the core for its page (`tools.act {tool, act}`) and opens what it answers. func testAConnectActsPageIsAskedOfTheCore() async throws { let core = ToolActsCore(answers: [:], act: #"{"opens":"https://accounts.example.com/authorize?state=synthetic"}"#) let connect = CardAction(id: "google_connect", label: "Connect Google Calendar", kind: "tool", tool: "calendar") let opens = try await DeckActs.ran(connect, core: core) XCTAssertEqual(opens, .opens(URL(string: "https://accounts.example.com/authorize?state=synthetic")!)) let ran = await core.ran XCTAssertEqual(ran, [#"{"act":"google_connect","tool":"calendar"}"#]) let toolless = CardAction(id: "google_connect", label: "Connect Google Calendar", kind: "tool") let none = try await DeckActs.ran(toolless, core: core) XCTAssertEqual(none, .nothing) let after = await core.ran XCTAssertEqual(after.count, 1, "an act naming no tool asks nothing") } /// RULE: Books' On this phone asks its acts by its view (`tools.acts {table, view}`): the account's, as the core said them. func testOnThisPhoneAsksItsActsByItsView() async throws { let core = ToolActsCore(answers: ["book": """ {"actions":[{"id":"account_back_up","label":"Back up now","kind":"tool","tool":"books","asks":false},{"id":"account_sign_out","label":"Sign out","kind":"tool","tool":"books","asks":false}]} """]) let acts = await DeckEditor.toolActs(of: "book", view: "books/on_phone", core: core) let views = await core.views XCTAssertEqual(views, ["books/on_phone"]) XCTAssertEqual(EditingFan.items(tools: acts).map(\.word), ["Back up now", "Sign out"]) } /// RULE: an account act runs the flow the core answers — Sign out the device row's own signOut, from this device — and Back up now says what it did. func testAnAccountActRunsTheDeviceRowsFlowOrSaysWhatItDid() async throws { let signOut = ToolActsCore(answers: [:], act: """ {"platform_action":"open_flow","flow":"signOut","origin":{"table":"device","id":"this-device"},"database":"synthetic-db"} """) let act = CardAction(id: "account_sign_out", label: "Sign out", kind: "tool", tool: "books") guard case .platform(.openFlow(let flow)) = try await DeckActs.ran(act, core: signOut) else { return XCTFail("Sign out runs a flow") } XCTAssertEqual(flow.flow, .signOut) XCTAssertEqual(flow.origin.table, "device") XCTAssertEqual(flow.origin.id, "this-device") let backUp = ToolActsCore(answers: [:], act: #"{"said":"Backing up now"}"#) let now = CardAction(id: "account_back_up", label: "Back up now", kind: "tool", tool: "books") let said = try await DeckActs.ran(now, core: backUp) XCTAssertEqual(said, .said("Backing up now")) } /// RULE (7 Nov 2026): Export OPML answers the document it wrote: its words are said and the document shared once it comes. func testAnActThatWroteADocumentAnswersIt() async throws { let core = ToolActsCore(answers: [:], act: #"{"document":"doc-1","shows":3,"said":"3 shows in Podcasts 2026-11-07.opml"}"#) let export = CardAction(id: "podcasts_export_opml", label: "Export OPML", kind: "tool", tool: "podcasts") let outcome = try await DeckActs.ran(export, core: core) XCTAssertEqual(outcome, .document("doc-1", said: "3 shows in Podcasts 2026-11-07.opml")) } /// RULE (list-acts, 7 Nov 2026): a list's tile held on the fan asks the core for the list's acts alone (`tools.acts {held: list}`) by the list's deck, and they open on the fan as the core said them — Rename asking its words, Remove list red and asked first. func testAHeldListTileAsksTheListsOwnActs() async throws { let core = ToolActsCore(answers: ["book": """ {"actions":[{"id":"list_rename","label":"Rename","kind":"tool","tool":"books","group":"g1","words":{"prefill":"Synthetic shelf","hint":"List name"}},\ {"id":"list_move_later","label":"Move later","kind":"tool","tool":"books","group":"g1"},\ {"id":"list_remove","label":"Remove list","kind":"tool","tool":"books","group":"g1","red":true,"asks":true}]} """]) let answer = await DeckEditor.toolActsAnswer(of: "book", view: "books/group:g1", held: .list, core: core) let views = await core.views XCTAssertEqual(views, ["books/group:g1"]) XCTAssertEqual(answer.actions.map(\.label), ["Rename", "Move later", "Remove list"]) XCTAssertEqual(answer.actions.first?.words, CardActionWords(prefill: "Synthetic shelf", hint: "List name")) XCTAssertEqual(answer.actions.last?.red, true) XCTAssertEqual(answer.actions.last?.asks, true) let editor = DeckEditor.standing() editor.openToolActs(answer.actions, for: .emptyDeck(of: "book"), tile: answer.tile) XCTAssertEqual(editor.editing, .toolActs(.emptyDeck(of: "book"))) } /// RULE (list-acts, 7 Nov 2026): Rename runs with the words typed (`tools.act {words}`), and an act that wrote answers its receipt with the change its Undo takes back. func testAListActRunsWithItsWordsAndAnswersItsUndo() async throws { let core = ToolActsCore(answers: [:], act: #"{"said":"Renamed Synthetic shelf to Synthetic reads","undo":"change-1"}"#) var rename = CardAction(id: "list_rename", label: "Rename", kind: "tool", tool: "books", group: "g1") rename.words = CardActionWords(prefill: "Synthetic shelf", hint: "List name") let outcome = try await DeckActs.ran(rename, words: "Synthetic reads", core: core) XCTAssertEqual(outcome, .receipt("Renamed Synthetic shelf to Synthetic reads", undo: "change-1")) let ran = await core.ran XCTAssertEqual(ran, [#"{"act":"list_rename","group":"g1","tool":"books","words":"Synthetic reads"}"#]) } /// RULE: an empty deck whose tool offers no act is held to no end: the fan stays on its tools. func testAnEmptyDeckWithNoToolActsOpensNothing() async { let core = ToolActsCore(answers: ["todo": #"{"actions":[]}"#]) let acts = await DeckEditor.toolActs(of: "todo", core: core) XCTAssertTrue(acts.isEmpty) let editor = DeckEditor.standing() editor.openToolActs(acts, for: .emptyDeck(of: "todo")) XCTAssertNil(editor.editing) }}/// A core that answers `tools.acts` by the table asked, and `tools.act` with/// the answer it was given, and says what it was asked.private actor ToolActsCore: CottonCalling { let answers: [String: String] let act: String? /// What `shell.opened` answers, where it is asked. let openedAnswer: String? private(set) var asked: [String] = [] /// Each `shell.opened` request as sent, its keys sorted. private(set) var opened: [String] = [] /// The view each `tools.acts` named, where it named one. private(set) var views: [String] = [] /// Each `tools.act` request as sent, its keys sorted. private(set) var ran: [String] = [] init(answers: [String: String], act: String? = nil, opened: String? = nil) { self.answers = answers self.act = act self.openedAnswer = opened } func callRaw(_ method: String, requestJSON: String) throws -> String { let request = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8))) as? [String: Any] ?? [:] if method == CottonMethod.toolsAct, let act { let sorted = try JSONSerialization.data(withJSONObject: request, options: [.sortedKeys, .withoutEscapingSlashes]) ran.append(String(decoding: sorted, as: UTF8.self)) return #"{"ok":true,"data":\#(act)}"# } let table = request["table"] as? String ?? "" asked.append("\(method) \(table)") if method == CottonMethod.shellOpened, let openedAnswer { let sorted = try JSONSerialization.data(withJSONObject: request, options: [.sortedKeys]) opened.append(String(decoding: sorted, as: UTF8.self)) return #"{"ok":true,"data":\#(openedAnswer)}"# } if let view = request["view"] as? String { views.append(view) } guard method == CottonMethod.toolsActs, let answer = answers[table] else { return #"{"ok":false,"error":{"code":"bad_request","message":"not asked of this core"}}"# } return #"{"ok":true,"data":\#(answer)}"# } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {}}#endif