SPB Git

Repository Public

ActionRequestSheet.swift 10.8 KB 194 lines swift

1import MCCCore2import SwiftUI34/// One line describing an action: type, target, state, who and when.5struct ActionRow: View {6    @Environment(\.mccTheme) private var theme7    let action: API.Action8    var body: some View {9        HStack(alignment: .firstTextBaseline, spacing: Tokens.Space.s3) {10            Image(systemName: action.state.tone.symbol).foregroundStyle(action.state.tone.color(theme)).accessibilityHidden(true)11            VStack(alignment: .leading, spacing: 1) {12                Text(action._type).font(.callout.weight(.medium).monospaced()).foregroundStyle(theme.textPrimary).lineLimit(1)13                Text([action.targetLabel ?? action.nodeAlias, action.requestedByDisplayName, Format.relative(action.createdAt)].compactMap { $0 }.joined(separator: " · "))14                    .font(.caption).foregroundStyle(theme.textSecondary).lineLimit(1)15            }16            Spacer(minLength: Tokens.Space.s2)17            if action.outcomeUnknown { StatusBadge(tr("actions.outcome_unknown.short"), tone: .warning, compact: true) }18            StatusBadge(action.state.label, tone: action.state.tone, compact: true)19        }20        .contentShape(Rectangle())21        .accessibilityElement(children: .ignore)22        .accessibilityLabel("\(action._type), \(action.targetLabel ?? action.nodeAlias ?? "")")23        .accessibilityValue(action.state.label + (action.outcomeUnknown ? ", " + tr("actions.outcome_unknown.short") : ""))24    }25}2627/// Request form of a typed action, generated from the catalog (`GET /action-types`). It shows what the server28/// declares (criticality, step-up, justification, confirmation, approval) and collects the inputs; every check is29/// made by the server when the request is sent.30struct ActionRequestSheet: View {31    @Environment(AppModel.self) private var app32    @Environment(\.mccTheme) private var theme33    @Environment(\.dismiss) private var dismiss34    let intent: ActionIntent35    @State private var model: ActionFormModel?3637    var body: some View {38        VStack(alignment: .leading, spacing: 0) {39            content40        }41        .frame(width: 560)42        .frame(minHeight: 320)43        .background(theme.surface)44        .task { await prepare() }45    }4647    private func prepare() async {48        await app.session.actions.types.loadIfNeeded(maxAge: 60)49        if model == nil, let type = app.session.actions.type(named: intent.typeName) {50            model = ActionFormModel(type: type, target: .init(kind: intent.targetKind, id: intent.targetID), targetLabel: intent.targetLabel,51                                    presetParams: intent.presetParams)52        }53    }5455    @ViewBuilder private var content: some View {56        let types = app.session.actions.types57        if let model {58            ActionForm(model: model) { dismiss() } onCreated: { action in59                dismiss()60                app.openAction(action.id)61            }62        } else if types.value != nil {63            // The catalog is loaded and does not list this type: the server does not offer it.64            VStack(spacing: Tokens.Space.s4) {65                EmptyStateView(tr("actions.type_missing.title"), message: tr("actions.type_missing.message", intent.typeName), systemImage: "bolt.slash")66                Button(tr("action.close")) { dismiss() }.keyboardShortcut(.cancelAction)67            }68            .padding(Tokens.Space.s6)69        } else if let reason = types.state.unavailableReason {70            VStack(spacing: Tokens.Space.s4) {71                UnavailableStateView(reason: reason, error: types.state.error) { Task { await types.load(); await prepare() } }72                Button(tr("action.close")) { dismiss() }.keyboardShortcut(.cancelAction)73            }74            .padding(Tokens.Space.s6)75            .accessibilityIdentifier("actions-unavailable")76        } else if let e = types.state.error {77            VStack(spacing: Tokens.Space.s4) {78                ErrorStateView(error: e) { Task { await types.load(); await prepare() } }79                Button(tr("action.close")) { dismiss() }.keyboardShortcut(.cancelAction)80            }81            .padding(Tokens.Space.s6)82        } else {83            ProgressView(tr("state.loading")).frame(maxWidth: .infinity, minHeight: 240)84        }85    }86}8788private struct ActionForm: View {89    @Environment(AppModel.self) private var app90    @Environment(\.mccTheme) private var theme91    @Bindable var model: ActionFormModel92    let onCancel: () -> Void93    let onCreated: (API.Action) -> Void9495    var body: some View {96        let type = model.type97        VStack(alignment: .leading, spacing: 0) {98            VStack(alignment: .leading, spacing: Tokens.Space.s2) {99                HStack(alignment: .firstTextBaseline) {100                    Text(type.title).font(.title2.weight(.semibold)).foregroundStyle(theme.textPrimary)101                    Spacer()102                    StatusBadge(tr("actions.criticality", type.criticality.label), tone: type.criticality.tone)103                }104                Text(type._type).font(.caption.monospaced()).foregroundStyle(theme.textTertiary)105                Text(type.description).font(.callout).foregroundStyle(theme.textSecondary)106            }107            .padding(Tokens.Space.s6)108            Divider()109            ScrollView {110                VStack(alignment: .leading, spacing: Tokens.Space.s5) {111                    KeyValueRow(tr("actions.target"), "\(model.target.kind.label) · \(model.targetLabel)")112                    requirements(type)113                    if !type.available {114                        InfoBanner(tone: .warning, title: tr("actions.unavailable.title"), message: type.unavailableReason ?? tr("actions.unavailable.message"))115                    }116                    VStack(alignment: .leading, spacing: Tokens.Space.s3) {117                        Text(tr("actions.parameters")).font(.headline).foregroundStyle(theme.textPrimary)118                        SchemaFormView(fields: model.fields, values: $model.values, rawJSON: $model.rawJSON,119                                       missing: model.missingFields, invalid: model.invalidJSONFields)120                    }121                    if type.requiresJustification {122                        VStack(alignment: .leading, spacing: Tokens.Space.s1) {123                            Text(tr("actions.justification")).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)124                            TextEditor(text: $model.justification)125                                .font(.body)126                                .frame(minHeight: 60)127                                .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.sm).strokeBorder(theme.border))128                                .accessibilityLabel(tr("actions.justification"))129                                .accessibilityIdentifier("action-justification")130                            Text(tr("actions.justification.help")).font(.caption).foregroundStyle(theme.textTertiary)131                        }132                    }133                    if type.requiresConfirmation {134                        VStack(alignment: .leading, spacing: Tokens.Space.s1) {135                            Text(tr("actions.confirm.title")).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)136                            Text(tr("actions.confirm.help", model.targetLabel)).font(.callout).foregroundStyle(theme.textSecondary)137                            TextField(model.targetLabel, text: $model.confirmation)138                                .textFieldStyle(.roundedBorder)139                                .font(.body.monospaced())140                                .autocorrectionDisabled()141                                .accessibilityLabel(tr("actions.confirm.title"))142                                .accessibilityIdentifier("action-confirmation")143                            Text(tr("actions.confirm.server")).font(.caption).foregroundStyle(theme.textTertiary)144                        }145                    }146                    if let e = model.error {147                        VStack(alignment: .leading, spacing: Tokens.Space.s2) {148                            InlineErrorView(APIError(status: e.status, code: e.code, message: ErrorText.friendly(e), correlationID: e.correlationID))149                            if let check = e.details?["check"]?.stringValue { Text(tr("actions.precheck", check)).font(.caption).foregroundStyle(theme.textSecondary) }150                            if let holder = e.details?["action_id"]?.stringValue {151                                Button(tr("actions.open_holder")) { app.openAction(holder) }.buttonStyle(.textLink)152                            }153                        }154                    }155                }156                .padding(Tokens.Space.s6)157            }158            Divider()159            HStack {160                if let blocker = app.mutationBlocker(permission: type.permission) {161                    Label(blocker, systemImage: "lock").font(.caption).foregroundStyle(theme.textSecondary)162                }163                Spacer()164                Button(tr("action.cancel"), action: onCancel).keyboardShortcut(.cancelAction).accessibilityIdentifier("action-cancel")165                Button {166                    Task { if let action = await model.submit(using: app.session.actions) { onCreated(action) } }167                } label: {168                    if model.isSubmitting { ProgressView().controlSize(.small) } else { Text(type.requiresApproval ? tr("actions.submit.approval") : tr("actions.submit")) }169                }170                .buttonStyle(.borderedProminent)171                .tint(type.criticality.rank >= 2 ? StatusTone.critical.color(theme) : theme.accent)172                .keyboardShortcut(.return, modifiers: .command)173                .disabled(!model.canSubmit || app.mutationBlocker(permission: type.permission) != nil)174                .accessibilityIdentifier("action-submit")175            }176            .padding(Tokens.Space.s5)177        }178    }179180    /// What the server declares it will require for this type.181    private func requirements(_ type: API.ActionType) -> some View {182        VStack(alignment: .leading, spacing: Tokens.Space.s2) {183            if type.requiresStepUp { Label(tr("actions.requires.step_up"), systemImage: "person.badge.key") }184            if type.requiresJustification { Label(tr("actions.requires.justification"), systemImage: "text.bubble") }185            if type.requiresConfirmation { Label(tr("actions.requires.confirmation"), systemImage: "keyboard") }186            if type.requiresApproval { Label(tr("actions.requires.approval"), systemImage: "person.2.badge.gearshape") }187            Label(tr("actions.requires.timeout", Format.duration(seconds: Double(type.timeoutS))), systemImage: "timer")188            Label(tr("actions.requires.permission", ([type.permission] + (type.extraPermissions ?? [])).joined(separator: ", ")), systemImage: "checkmark.shield")189        }190        .font(.callout)191        .foregroundStyle(theme.textSecondary)192    }193}194
Files main
Menu

Theme