Cotton code
58 lines · 2.2 KB · SwiftRaw
import Foundation/// What a page act answers beside its own keys (Spec 11 (c), the shared/// rules): the receipt in the page's words and the call that takes the act/// back. The core decides both — the device and member acts/// (`methods/page_acts.rs`), a theme's save, a Mac's host switches — so a phone and a Mac say the same sentence and undo the same way.public struct ActAnswer: Sendable, Equatable {    /// "Renamed to Studio Mac", "Removed Rhyn from this database".    public var receipt: String?    /// The call that puts it back; `nil` where nothing can (a removed device    /// asks to join again).    public var undo: ActUndo?    public static let none = ActAnswer(receipt: nil, undo: nil)    public init(receipt: String?, undo: ActUndo?) {        self.receipt = receipt        self.undo = undo    }    /// Read off an act's answer. An answer that says `undoable: false` offers    /// no undo whatever else it carries; one with no `undoable` key (a    /// database's rename) is undoable when it names its undo.    public init(_ answer: JSONValue) {        receipt = answer["receipt"]?.string.flatMap { $0.isEmpty ? nil : $0 }        guard answer["undoable"]?.bool != false,            let undo = answer["undo"], let method = undo["method"]?.string, !method.isEmpty        else {            self.undo = nil            return        }        self.undo = ActUndo(method: method, args: undo["args"] ?? .object([:]))    }}/// `undo {method, args}`: the act that takes another back, called as given.public struct ActUndo: Sendable, Equatable {    public let method: String    public let args: JSONValue    public init(method: String, args: JSONValue) {        self.method = method        self.args = args    }}extension CottonCalling {    /// Run an act and read its receipt and undo.    public func pageAct(_ method: String, _ request: some Encodable) async throws -> ActAnswer {        ActAnswer(try await callJSON(method, request))    }    /// Take an act back: its undo, called as the core named it. Answers the    /// undo's own receipt and undo (an undone rename can be redone).    public func takeBack(_ undo: ActUndo) async throws -> ActAnswer {        ActAnswer(try await callJSON(undo.method, undo.args))    }}