Cotton code
282 lines · 11.5 KB · SwiftRaw
// Relationships and existing engine commands are definition data. An engine// adapter implements the command protocol; fixture stores cannot run commands.import CottonValuesimport Foundationimport CottonKitpublic typealias RelatedRecords = DefinitionRelatedRecordsextension DefinitionRelatedRecords {  public init(    label: String, table: String, column: String? = nil, filter: [String: RecordValue]? = nil, new: Bool? = nil,    archived: Bool? = nil, open: String? = nil, title: String? = nil, empty: EmptyWords? = nil,    when: [String: RecordValue]? = nil  ) {    self.init(_generated: (), label: label, table: table)    self.column = column    self.filter = filter    self.new = new    self.archived = archived    self.open = open    self.title = title    self.empty = empty    self.when = when  }  public func applies(to record: TableRecord) -> Bool {    (when ?? [:]).allSatisfy { key, wanted in record[key] == wanted }  }  /// The table as this list draws it: under its own title and empty words,  /// with none of the table's list-level links or its "+" — those belong to  /// the table's own list, and an archive that offered "Archived chats" again  /// would lead to itself.  public func listed(_ definition: TableDefinition) -> TableDefinition {    guard title != nil || empty != nil else { return definition }    var copy = definition    if let title { copy.plural = title }    if let empty { copy.empty = empty }    copy.related = definition.related?.filter { $0.column != nil }    copy.create = nil    return copy  }  public func whereValues(parent: TableRecord) -> [String: RecordValue] {    var values = filter ?? [:]    if let column { values[column] = .text(parent.id) }    return values  }}/// What a command is: the core's closed list (`commands.rs`).public typealias CommandKind = DefinitionCommandKind/// What an act does to its record — the definition's `does` — which decides/// its card's colour the same way in every tool, so a person learns it once/// (architect, 13 Oct 2026): it completes or affirms, moves the record in/// time, moves it in place or hands it over, destroys it, or puts it away./// Everything else is said by no word at all.public typealias CommandDoes = DefinitionCommandDoesprivate enum CommandConditionOperator: String { case not }/// One value the command asks the person to choose before the engine runs./// The engine binds `argument`; Swift sends only the chosen value as `picked`.public typealias RecordCommandPick = DefinitionCommandPickextension DefinitionCommandPick {  public typealias Kind = DefinitionPickKind  /// The filter a record pick lists its choices by, for an act on the record  /// `id`: a value `"$id"` is that record's own id (a dish's Order offers its  /// own menu days) — the core's `CommandPick::accepts_on`.  public func filter(on id: String?) -> [String: RecordValue] {    func at(_ value: RecordValue) -> RecordValue {      if case .text("$id") = value, let id { return .text(id) }      return value    }    return (filter ?? [:]).mapValues { value in      if case .list(let any) = value { return .list(any.map(at)) }      return at(value)    }  }  public init(    argument: String, kind: Kind, table: String? = nil, filter: [String: RecordValue]? = nil,    choicesFrom: String? = nil, databaseBy: String? = nil, optional: Bool? = nil,    min: Double? = nil, defaultValue: Double? = nil, max: Double? = nil  ) {    self.init(_generated: (), argument: argument, kind: kind)    self.table = table    self.filter = filter    self.choicesFrom = choicesFrom    self.databaseBy = databaseBy    self.optional = optional    self.min = min    self.defaultValue = defaultValue    self.max = max  }  public func database(in record: TableRecord?) throws -> String? {    guard let databaseBy else { return nil }    let id = databaseBy == "$id" ? record?.id : record?[databaseBy].text    guard let id, !id.isEmpty else { throw ActionRefused(ShellLines.line("definitions", "refused.no_database")) }    return id  }}/// A list's act: offered at the head of the list while at least this many/// listed rows are ones its `when` holds on (`RecordCommand::list`).public typealias RecordCommandList = DefinitionCommandListextension DefinitionCommandList {  public init(atLeast: Int = 1) { self.init(_generated: (), atLeast: atLeast) }}public typealias RecordCommand = DefinitionRecordCommandextension RecordCommand {  public static var copySealed: String { "$sealed" }  public init(id: String, label: String, sheet: String? = nil, verb: String? = nil, method: String? = nil, kind: CommandKind? = nil, opens: String? = nil, copies: String? = nil, receipt: String? = nil, undo: String? = nil, data: [String: RecordValue]? = nil, destructive: Bool? = nil, confirm: String? = nil, bindings: [String: String]? = nil, when: [String: RecordValue]? = nil, pickTable: String? = nil, pick: RecordCommandPick? = nil, picks: [RecordCommandPick]? = nil, doesWord: String? = nil, object: String? = nil, form: Bool? = nil, reveals: RecordCommandReveal? = nil) {    self.init(_generated: (), id: id, label: label)    self.id = id    self.label = label    self.sheet = sheet    self.verb = verb    self.method = method    self.kind = kind    self.opens = opens    self.copies = copies    self.receipt = receipt    self.undo = undo    self.data = data    self.destructive = destructive    self.confirm = confirm    self.bindings = bindings    self.when = when    self.pickTable = pickTable    self.pick = pick    self.picks = picks    self.doesWord = doesWord    self.object = object    self.form = form    self.reveals = reveals  }  public var needsPick: Bool { pickTable != nil || pick != nil || picks?.isEmpty == false }  public var isForm: Bool { form == true }  public var does: CommandDoes? { doesWord.flatMap(CommandDoes.init(rawValue:)) }  /// Where a list act's words say how many rows it is for.  public static var countWord: String { "{count}" }  /// How many of a list's `rows` this list act is for, when it is offered  /// over them: those its `when` holds on, at least `list.atLeast` of them  /// (`RecordCommand::offered_over`). `nil` for a record's act.  public func offered(over rows: [TableRecord]) -> Int? {    guard let list else { return nil }    var record = self    record.list = nil    let count = rows.filter(record.applies(to:)).count    return count >= list.atLeast ? count : nil  }  /// `words` saying `count` where they say `{count}`.  public static func counted(_ words: String, _ count: Int) -> String {    words.replacingOccurrences(of: countWord, with: String(count))  }  /// Offered while every `when` holds — and, for an `open`, while its  /// column holds something to open (the core refuses it otherwise).  public func applies(to record: TableRecord) -> Bool {    // The form's act is the form's alone: a kept record never offers it,    // and a list's act is the list's.    if isForm || list != nil { return false }    if kind == .open, opens.map({ RecordValue.isBlank(record[$0]) }) != false { return false }    if kind == .copy, let copies, copies != Self.copySealed, RecordValue.isBlank(record[copies]) { return false }    return (when ?? [:]).allSatisfy { key, wanted in      let held = record[key]      let matches = { (value: RecordValue) in        held == value || (held == .null && value == .bool(false))      }      if case .object(let object) = wanted, object.count == 1, let excluded = object[CommandConditionOperator.not.rawValue] {        if case .list(let choices) = excluded { return !choices.contains(where: matches) }        return !matches(excluded)      }      if case .list(let choices) = wanted { return choices.contains(where: matches) }      return matches(wanted)    }  }  /// Whether the command asks before it runs: every delete, and any command  /// its definition marks destructive, confirmed or as one that destroys.  /// The one way a surface learns it — no surface reads `destructive` itself.  public var asksFirst: Bool { kind == .delete || destructive == true || confirm != nil || does == .destroys }  public func arguments(for record: TableRecord) -> [String: RecordValue] {    var args = data ?? [:]    for (argument, column) in bindings ?? [:] {      if column == "$id_list" {        args[argument] = .list([.text(record.id)])      } else {        args[argument] = column == "$id" ? .text(record.id) : record[column]      }    }    return args  }}/// What a command shows once from its method's answer: the answer's key,/// the heading over the value and why it will not be shown again.public typealias RecordCommandReveal = DefinitionCommandRevealextension DefinitionCommandReveal {  public init(answer: String, title: String, note: String) {    self.init(_generated: (), answer: answer, title: title, note: note)  }}public protocol RecordCommands: Records {  /// The engine owns atomic provenance, validation and change receipts.  /// `picked` is the chosen table, record id, or ISO 8601 instant.  func command(table: String, id: String, command: RecordCommand, picked: String?) async throws -> ChangeRecord  /// Ordered answers for a package act; the writer resolves their typed arguments.  func command(table: String, id: String, command: RecordCommand, pickedValues: [String]) async throws -> ChangeRecord  /// An app method's own way back (`CommandTaken.undoCall`). A store that  /// runs no app methods has none to take.  func undo(_ call: CommandUndoCall, taken: CommandTaken) async throws -> ChangeRecord}extension RecordCommands {  public func command(table: String, id: String, command: RecordCommand) async throws -> ChangeRecord {    try await self.command(table: table, id: id, command: command, picked: nil)  }  public func command(table: String, id: String, command: RecordCommand, pickedValues: [String]) async throws -> ChangeRecord {    throw ActionRefused(ShellLines.line("definitions", "refused.not_here"))  }  public func undo(_ call: CommandUndoCall, taken: CommandTaken) async throws -> ChangeRecord {    throw ChangeUndoError.unavailable  }}extension TableDefinition {  /// Native commands and typed package acts both run through records.command.  public var canRunCommands: Bool {    (engine != nil || !(acts ?? []).isEmpty) && !(commands ?? []).isEmpty  }  /// The command this table binds to `mark` drawn over a card (`marks`),  /// while it applies to `record` as it stands: nil where the table binds  /// nothing to it, or the record is past it (a todo already done).  func command(forMark mark: String, on record: TableRecord) -> RecordCommand? {    guard canRunCommands, let id = marks?[mark] else { return nil }    return ((commands ?? []) + (acts ?? [])).first { $0.id == id && $0.applies(to: record) }  }}extension RecordCommand {  /// What a command that did not run says: the core's own sentence  /// ("“Open person” is not offered on this record as it stands now."),  /// else the plain one.  static func refusal(_ error: Error) -> String {    if let refused = error as? ActionRefused, !refused.sentence.isEmpty { return refused.sentence }    if let refused = error as? CottonCallError, !refused.message.isEmpty { return refused.message }    return ShellLines.line("definitions", "refused.not_completed")  }  /// The menu line's symbol, by what the command is called.  var symbol: String? {    switch id {    case "pin": "pin"    case "unpin": "pin.slash"    case "mute": "bell.slash"    case "unmute": "bell"    case "archive": "archivebox"    case "unarchive": "tray.and.arrow.up"    case "clear": "trash"    default: nil    }  }}