Cotton code
299 lines · 13.0 KB · SwiftRaw
// 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.import CottonValuesimport SwiftUI/// What the surface holding the slips does with an act's outcome.@MainActorstruct RecordActSurface {    /// Opens a record's page by its id — one an act made or chose.    var open: @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: OpenURLAction    var 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@Observablefinal class RecordActs {    /// An act that asks first, and the slip it was pressed on (nil: the head).    struct AskedAct: Identifiable {        let action: RecordAction        let 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 = false    private(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 @Observable    final class SlipState {        fileprivate(set) var actions: [RecordAction] = []        fileprivate(set) var problem: String?    }    @ObservationIgnored private var slipStates: [String: SlipState] = [:]    func slipState(_ id: String) -> SlipState {        if let state = slipStates[id] { return state }        let state = SlipState()        slipStates[id] = state        return 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.    private var headAsked = false    init(table: String, where filter: [String: RecordValue] = [:]) {        self.table = table        self.filter = filter    }    /// The head's acts, for this list's scope; nothing for a store that    /// offers none.    func loadHead(_ store: (any Records)?) async {        guard let doer = store as? any ActingRecords else {            canCreate = store != nil            return        }        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 {        guard let 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.    @discardableResult    func tapped(_ action: RecordAction, on record: TableRecord?, store: (any Records)?, surface: RecordActSurface) -> Task<Void, Never>? {        if !action.fields.isEmpty {            answering = AskedAct(action: action, record: record)            return nil        }        if action.confirmation != nil {            asking = AskedAct(action: action, record: record)            return nil        }        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.    @discardableResult    func perform(        _ action: RecordAction, values: [String: String] = [:], on record: TableRecord?, store: (any Records)?,        surface: RecordActSurface    ) -> Task<Void, Never>? {        guard !acting else { return nil }        acting = true        return Task {            defer { acting = false }            if let 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 { return Self.busy }        acting = true        defer { acting = false }        return await run(asked.action, values: values, on: asked.record, store: store, surface: surface) {            if self.answering?.id == asked.id { self.answering = nil }        }    }    /// What a sheet answered while another act runs is told.    static var 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.    private func refuse(_ sentence: String, on record: TableRecord?) {        if let 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.    private func run(        _ action: RecordAction, values: [String: String], on record: TableRecord?, store: (any Records)?,        surface: RecordActSurface, landed: () -> Void = {}    ) async -> String? {        guard let doer = store as? any ActingRecords else { return ShellLines.line("record", "not_done", ["action": "\(action.label)"]) }        if let record { slipState(record.id).problem = nil } else { headProblem = nil }        await store?.recordUsage(kind: "act_fired", tool: table, record: record?.id)        let outcome: ActionOutcome        do {            // A shut vault is opened and the act tried once more.            outcome = try await KeptFlowRetry.once(surface.keptFlow) {                try await doer.perform(action, values: values, table: table, record: record)            }        } catch let refused as ActionRefused {            return refused.sentence        } catch {            // A flow that did not open the vault has said why itself: nothing            // more is said under the act.            return KeptFlowRetry.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).            if let change = value.change { surface.received(change) }        case .flow(let flow):            // Nobody here can run it: say so rather than do nothing.            if let 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?        if case .copy(_, _, .some, _) = outcome {            definition = try? await store?.tableDefinitions().first { $0.id == table }        }        if let change = await RecordActionOutcomes.finish(            outcome, definition: definition, store: store, openURL: surface.openURL, toasts: surface.toasts)        {            surface.received(change)        }        await surface.reread()        if headAsked { await loadHead(store) }        if let record {            await loadSlip(surface.current(record.id) ?? record, store: store)        }        return nil    }}/// 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.struct ActedSlip<Face: View>: View {    let acts: RecordActs    let record: TableRecord    let store: (any Records)?    /// `list-<table>-<id>`: each button's identifier is this and the act's id.    let identifier: String    let onTap: (RecordAction) -> Void    @ViewBuilder let face: () -> Face    var body: some View {        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) }    }}extension View {    /// 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?    ) -> some View {        modifier(AskingFirst(acts: acts, identifier: identifier, onConfirm: onConfirm))            .cottonCard(isPresented: Binding(get: { acts.answering != nil }, set: { if !$0 { acts.answering = nil } })) {                if let asked = acts.answering {                    ActFieldsSheet(action: asked.action, identifier: "\(identifier)-fields") { await onAnswer(asked, $0) }                }            }    }}private struct AskingFirst: ViewModifier {    @Bindable var acts: RecordActs    let identifier: String    let onConfirm: (RecordActs.AskedAct) -> Void    func body(content: Content) -> some View {        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        )    }}