// The acts a store offers on a table's slips and at a list's head, and the// running of one — shared by the two places a table's slips are drawn: the// list (`RecordListSurface`) and a section of another page (`RecordsSection`,// a project's Sessions). So a session waiting for a permission offers Allow// under its slip on `/code` and on its project's page alike, asks first where// the act asks, and says why one was not done under the slip it was pressed on.//// What an act answers is done here where it is the same everywhere (a page// pushed, a flow run, an address opened, a sentence said); what only the// surface can do — open a record's page, show a value once, read itself again// — the surface hands in (`RecordActSurface`). An act the vault refused opens// the vault (the surface's kept flow) and is tried once more (`KeptFlowRetry`).// After every act the rows are read again and the slip's acts are asked for// again, as it now stands.//// An act with `fields` asks for them first, on one sheet (`ActFieldsSheet`),// and runs with what was typed; that sheet is its question, so it is not// asked a second time. The sheet stays up until the act lands (`answer`), and// a refusal is said inside it, under what was typed — never under the list,// with the words gone.importCottonValuesimportSwiftUI/// What the surface holding the slips does with an act's outcome.@MainActorstructRecordActSurface {/// Opens a record's page by its id — one an act made or chose.varopen: @MainActor (String) -> Void/// Shows a value once (an assistant's new key).var reveal: @MainActor (RevealedValue) -> Void/// A sign-in is open in the browser: the surface may read itself again/// while it waits.var signingIn: @MainActor () -> Void = {}/// A change an act made, for the surface's receipt.var received: @MainActor (ChangeRecord) -> Void = { _ in }/// Reads the rows again after an act.var reread: @MainActor () async -> Void/// A slip's record as it stands after the read, by id.var current: @MainActor (String) -> TableRecord?var keptFlow: KeptFlowRunner?var navigator: Navigator?var openURL: OpenURLActionvar toasts: ToastCenter?}/// The acts on one table's list: the head's and each slip's, the act asking/// first, and why the last one was not done.@MainActor@ObservablefinalclassRecordActs {/// An act that asks first, and the slip it was pressed on (nil: the head).structAskedAct: Identifiable {let action: RecordActionlet record: TableRecord?var id: String { "\(record?.id ?? "")/\(action.id)" } }let table: String/// The column values the list is narrowed to, which the head's acts are/// asked for with.let filter: [String: RecordValue]private(set) var head: [RecordAction] = []private(set) var canCreate = falseprivate(set) var headProblem: String?/// The store's typed line about the table (`ActingRecords.listNote`),/// drawn over the head's acts.private(set) var note: String?/// Observation belongs to the row, so a new row cannot invalidate the/// visible rows through a shared dictionary write. @MainActor @ObservablefinalclassSlipState {fileprivate(set) var actions: [RecordAction] = []fileprivate(set) var problem: String? } @ObservationIgnored privatevar slipStates: [String: SlipState] = [:]func slipState(_ id: String) -> SlipState {iflet state = slipStates[id] { return state }let state = SlipState() slipStates[id] = statereturn state }/// The act asking first, while it asks.var asking: AskedAct?/// The act asking for its fields, while its sheet is up.var answering: AskedAct?/// An act is running; a second tap while it runs does nothing.private(set) var acting = false/// Whether the head's acts were asked for, so an act asks for them again.privatevar headAsked = falseinit(table: String, where filter: [String: RecordValue] = [:]) {self.table = tableself.filter = filter }/// The head's acts, for this list's scope; nothing for a store that/// offers none.func loadHead(_ store: (any Records)?) async {guardlet doer = store as? any ActingRecordselse { canCreate = store != nilreturn } headAsked = true head = await doer.listActions(table: table, where: filter) canCreate = await doer.permitsCreation(table: table, where: filter) note = await doer.listNote(table: table) }/// One slip's acts, as the store offers them for the record drawn.func loadSlip(_ record: TableRecord, store: (any Records)?) async {guardlet doer = store as? any ActingRecords, doer.offersSlipActions(table: table) else { return }let offered = await doer.slipActions(table: table, record: record)let state = slipState(record.id)if state.actions != offered { state.actions = offered } }/// Whether a slip draws a row of acts: it offers one, or one was refused.func drawsActs(_ record: TableRecord) -> Bool {let state = slipState(record.id)return !state.actions.isEmpty || state.problem != nil }/// Asks for its fields, or asks first where the act asks, else runs it —/// the run, or nil. @discardableResultfunc tapped(_ action: RecordAction, on record: TableRecord?, store: (any Records)?, surface: RecordActSurface) -> Task<Void, Never>? {if !action.fields.isEmpty { answering = AskedAct(action: action, record: record)returnnil }if action.confirmation != nil { asking = AskedAct(action: action, record: record)returnnil }return perform(action, on: record, store: store, surface: surface) }/// Runs one act — the head's, or a slip's — with what its fields were/// answered with, and does what its outcome asks of the surface. Why it/// was not done is said where it was pressed. The run, or nil while/// another runs. @discardableResultfunc perform( _ action: RecordAction, values: [String: String] = [:], on record: TableRecord?, store: (any Records)?, surface: RecordActSurface ) -> Task<Void, Never>? {guard !acting else { returnnil } acting = truereturnTask {defer { acting = false }iflet sentence = await run(action, values: values, on: record, store: store, surface: surface) { refuse(sentence, on: record) } } }/// The fields' sheet answered: runs its act with what was typed. Nil once/// the act was done — the sheet is let go of as it lands — else the/// sentence why not, for the sheet to print while it stays up with every/// word typed in it; a sheet answered while another act runs is told so/// rather than closed on nothing.func answer(_ asked: AskedAct, values: [String: String], store: (any Records)?, surface: RecordActSurface) async -> String? {guard !acting else { returnSelf.busy } acting = truedefer { acting = false }returnawait run(asked.action, values: values, on: asked.record, store: store, surface: surface) {ifself.answering?.id == asked.id { self.answering = nil } } }/// What a sheet answered while another act runs is told.staticvar busy: String { ShellLines.line("record", "act_busy") }/// Why an act was not done, said under the slip it was pressed on, or/// the head's.privatefunc refuse(_ sentence: String, on record: TableRecord?) {iflet record { slipState(record.id).problem = sentence } else { headProblem = sentence } }/// The act itself: nil once it was done and its outcome finished — after/// `landed`, the moment the store answered yes — else why it was not.privatefunc run( _ action: RecordAction, values: [String: String], on record: TableRecord?, store: (any Records)?, surface: RecordActSurface, landed: () -> Void = {} ) async -> String? {guardlet doer = store as? any ActingRecordselse { returnShellLines.line("record", "not_done", ["action": "\(action.label)"]) }iflet record { slipState(record.id).problem = nil } else { headProblem = nil }await store?.recordUsage(kind: "act_fired", tool: table, record: record?.id)let outcome: ActionOutcomedo {// A shut vault is opened and the act tried once more. outcome = tryawaitKeptFlowRetry.once(surface.keptFlow) {tryawait doer.perform(action, values: values, table: table, record: record) } } catchlet refused asActionRefused {return refused.sentence } catch {// A flow that did not open the vault has said why itself: nothing// more is said under the act.returnKeptFlowRetry.said(error, runner: surface.keptFlow) ? nil : ShellLines.line("record", "not_done", ["action": "\(action.label)"]) } landed()switch outcome {case .created(let id): surface.open(id)case .reveal(let value): surface.reveal(value)// The act that made it wears its receipt too (a mint's Undo).iflet change = value.change { surface.received(change) }case .flow(let flow):// Nobody here can run it: say so rather than do nothing.iflet keptFlow = surface.keptFlow { _ = await keptFlow(flow) } else { refuse(ShellLines.line("record", "not_done", ["action": "\(action.label)"]), on: record) }case .opened: surface.signingIn()case .change(let change): surface.received(change)case .navigate(let route): surface.navigator?.push(route)case .copy, .said, .refused, .shared: break }var definition: TableDefinition?ifcase .copy(_, _, .some, _) = outcome { definition = try? await store?.tableDefinitions().first { $0.id == table } }iflet change = awaitRecordActionOutcomes.finish( outcome, definition: definition, store: store, openURL: surface.openURL, toasts: surface.toasts) { surface.received(change) }await surface.reread()if headAsked { await loadHead(store) }iflet record {await loadSlip(surface.current(record.id) ?? record, store: store) }returnnil }}/// A slip with its own acts under it: each acts on this record and never/// opens it — the slip itself does that. The acts are asked for whenever the/// record drawn changes.structActedSlip<Face: View>: View {let acts: RecordActslet record: TableRecordlet store: (any Records)?/// `list-<table>-<id>`: each button's identifier is this and the act's id.let identifier: Stringlet onTap: (RecordAction) -> Void @ViewBuilder let face: () -> Facevar body: someView { VStack(alignment: .leading, spacing: 6) { face()if acts.drawsActs(record) {RecordActionButtons( actions: acts.slipState(record.id).actions, problem: acts.slipState(record.id).problem, identifier: identifier, onTap: onTap ) .padding(.horizontal, 4) } } .task(id: record) { await acts.loadSlip(record, store: store) } }}extensionView {/// The question an act asks before it runs, while it asks — or the/// sheet of its fields, which runs it with the values typed and stays up/// with them until `onAnswer` says it was done (nil) or why it was not.func askingFirst( _ acts: RecordActs, identifier: String, onConfirm: @escaping (RecordActs.AskedAct) -> Void, onAnswer: @escaping @MainActor (RecordActs.AskedAct, [String: String]) async -> String? ) -> someView { modifier(AskingFirst(acts: acts, identifier: identifier, onConfirm: onConfirm)) .cottonCard(isPresented: Binding(get: { acts.answering != nil }, set: { if !$0 { acts.answering = nil } })) {iflet asked = acts.answering {ActFieldsSheet(action: asked.action, identifier: "\(identifier)-fields") { await onAnswer(asked, $0) } } } }}privatestructAskingFirst: ViewModifier { @Bindable var acts: RecordActslet identifier: Stringlet onConfirm: (RecordActs.AskedAct) -> Voidfunc body(content: Content) -> someView { content.confirmDecision( item: $acts.asking, title: { $0.action.confirmation?.title ?? $0.action.label }, message: { $0.action.confirmation?.message ?? "" }, confirmLabel: { $0.action.confirmation?.confirmLabel ?? $0.action.label }, tone: acts.asking?.action.confirmation?.destructive == false ? .primary : .danger, identifier: identifier, onConfirm: onConfirm ) }}