SPB Git

Repository Public

OpsCommon.swift 9.5 KB 236 lines swift

1import MCCCore2import SwiftUI34// Building blocks shared by the Alerts, Services, Models and Jobs sections.56/// Side pane of a list: scrollable detail.7struct InspectorPane<Content: View>: View {8    @Environment(\.mccTheme) private var theme9    @ViewBuilder var content: Content10    var body: some View {11        ScrollView {12            VStack(alignment: .leading, spacing: Tokens.Space.s4) { content }13                .padding(Tokens.Space.s5)14                .frame(maxWidth: .infinity, alignment: .topLeading)15        }16        .background(theme.canvas)17    }18}1920/// Sheet with a title, a form, Cancel (Esc) and a confirming button (⌘↩). `confirm` returns true to close.21struct FormSheet<Content: View>: View {22    @Environment(\.dismiss) private var dismiss23    @Environment(\.mccTheme) private var theme24    let title: String25    let confirmTitle: String26    var canConfirm = true27    var width: CGFloat = 52028    let confirm: () async -> Bool29    @ViewBuilder var content: Content30    @State private var working = false3132    var body: some View {33        VStack(alignment: .leading, spacing: 0) {34            Text(title).font(.title3.weight(.semibold)).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)35                .padding(Tokens.Space.s5)36            Divider()37            ScrollView {38                VStack(alignment: .leading, spacing: Tokens.Space.s4) { content }39                    .padding(Tokens.Space.s5)40                    .frame(maxWidth: .infinity, alignment: .topLeading)41            }42            Divider()43            HStack {44                if working { ProgressView().controlSize(.small) }45                Spacer()46                Button(tr("action.cancel"), role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction)47                Button(confirmTitle) {48                    working = true49                    Task {50                        let ok = await confirm()51                        working = false52                        if ok { dismiss() }53                    }54                }55                .keyboardShortcut(.return, modifiers: .command)56                .buttonStyle(.borderedProminent)57                .disabled(!canConfirm || working)58                .accessibilityIdentifier("sheet-confirm")59            }60            .padding(Tokens.Space.s4)61        }62        .frame(width: width)63        .frame(minHeight: 260, maxHeight: 680)64        .background(theme.surface)65    }66}6768/// Labelled form row.69struct FieldRow<Content: View>: View {70    @Environment(\.mccTheme) private var theme71    let label: String72    var help: String?73    @ViewBuilder var content: Content74    var body: some View {75        VStack(alignment: .leading, spacing: Tokens.Space.s1) {76            Text(label).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary)77            content.accessibilityLabel(label)78            if let help { Text(help).font(.caption).foregroundStyle(theme.textTertiary) }79        }80    }81}8283/// Timeline of an alert or an incident.84struct TimelineList: View {85    @Environment(\.mccTheme) private var theme86    let events: [API.TimelineEvent]87    var body: some View {88        if events.isEmpty {89            Text(tr("alerts.timeline.empty")).font(.callout).foregroundStyle(theme.textSecondary)90        } else {91            VStack(alignment: .leading, spacing: Tokens.Space.s3) {92                ForEach(events.sorted { $0.ts > $1.ts }, id: \.id) { e in93                    VStack(alignment: .leading, spacing: 2) {94                        HStack(spacing: Tokens.Space.s2) {95                            Text(e.kind).font(.caption.weight(.semibold)).foregroundStyle(theme.textPrimary)96                            if let who = e.actorDisplayName { Text(who).font(.caption).foregroundStyle(theme.textSecondary) }97                            Spacer(minLength: 0)98                            Text(Format.dateTime(e.ts)).font(.caption).foregroundStyle(theme.textTertiary)99                        }100                        if !e.body.isEmpty { Text(e.body).font(.callout).foregroundStyle(theme.textPrimary).textSelection(.enabled) }101                    }102                    .accessibilityElement(children: .combine)103                    Divider()104                }105            }106        }107    }108}109110/// One-line comment entry.111struct CommentField: View {112    let placeholder: String113    let submit: (String) async -> Bool114    @State private var text = ""115    @State private var working = false116    var body: some View {117        HStack {118            TextField(placeholder, text: $text, axis: .vertical).textFieldStyle(.roundedBorder).lineLimit(1...4)119                .accessibilityLabel(placeholder)120            Button(tr("alerts.comment.send")) {121                let body = text.trimmingCharacters(in: .whitespacesAndNewlines)122                working = true123                Task {124                    if await submit(body) { text = "" }125                    working = false126                }127            }128            .disabled(working || text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)129        }130    }131}132133/// State of a catalog action for a target kind: the catalog decides what exists and what is enabled.134enum CatalogActionState: Equatable {135    case hidden136    case enabled(title: String, criticality: API.Criticality)137    case disabled(title: String, reason: String?)138139    static func resolve(_ typeName: String, kind: API.ActionTargetKind, in types: [API.ActionType]?) -> CatalogActionState {140        guard let t = types?.first(where: { $0._type == typeName }), t.targetKinds.contains(kind) else { return .hidden }141        return t.available ? .enabled(title: t.title, criticality: t.criticality) : .disabled(title: t.title, reason: t.unavailableReason)142    }143}144145/// Buttons for typed actions on a target. A type absent from the catalog has no button; `available=false` is shown146/// disabled with the server's reason. The request itself goes through the shared action sheet.147struct CatalogActionButtons: View {148    @Environment(AppModel.self) private var app149    @Environment(\.mccTheme) private var theme150    let typeNames: [String]151    let kind: API.ActionTargetKind152    let targetID: String153    let targetLabel: String154155    var body: some View {156        let types = app.session.actions.types.value157        VStack(alignment: .leading, spacing: Tokens.Space.s2) {158            if types == nil {159                if let reason = app.session.actions.types.state.unavailableReason {160                    Text(Self.catalogMessage(reason)).font(.caption).foregroundStyle(theme.textSecondary)161                        .accessibilityIdentifier("actions-catalog-unavailable")162                } else if app.session.actions.types.state.isLoading {163                    ProgressView().controlSize(.small)164                }165            } else {166                let states = typeNames.map { ($0, CatalogActionState.resolve($0, kind: kind, in: types)) }167                if states.allSatisfy({ $0.1 == .hidden }) {168                    Text(tr("services.actions.none")).font(.caption).foregroundStyle(theme.textSecondary)169                } else {170                    FlowButtons(states: states) { name in171                        app.requestAction(name, on: kind, id: targetID, label: targetLabel)172                    }173                    .mutation(app, permission: nil)174                }175            }176        }177        .task {178            if app.session.can("actions.read") { await app.session.actions.types.loadIfNeeded(maxAge: 300) }179        }180    }181182    static func catalogMessage(_ reason: UnavailableReason) -> String {183        switch reason {184        case .notImplemented: tr("services.actions.catalog.not_implemented")185        case .forbidden: tr("services.actions.catalog.forbidden")186        case .offline: tr("services.actions.catalog.offline")187        case .serviceUnavailable: tr("services.actions.catalog.unavailable")188        }189    }190}191192private struct FlowButtons: View {193    @Environment(\.mccTheme) private var theme194    let states: [(String, CatalogActionState)]195    let run: (String) -> Void196    var body: some View {197        VStack(alignment: .leading, spacing: Tokens.Space.s2) {198            ForEach(states, id: \.0) { name, state in199                switch state {200                case .hidden:201                    EmptyView()202                case .enabled(let title, let criticality):203                    HStack(spacing: Tokens.Space.s3) {204                        Button(title) { run(name) }.accessibilityIdentifier("action-\(name)")205                        StatusBadge(criticality.label, tone: criticality.tone, compact: true)206                    }207                case .disabled(let title, let reason):208                    VStack(alignment: .leading, spacing: 1) {209                        Button(title) {}.disabled(true)210                        Text(reason ?? tr("services.actions.disabled")).font(.caption).foregroundStyle(theme.textTertiary)211                    }212                    .accessibilityElement(children: .combine)213                }214            }215        }216    }217}218219/// Parses "a, b c" into distinct tags.220enum TagList {221    static func parse(_ text: String) -> [String] {222        var seen = Set<String>()223        return text.split(whereSeparator: { $0 == "," || $0 == " " || $0 == "\n" }).map { String($0) }.filter { seen.insert($0).inserted }224    }225}226227/// Seconds entered as text; nil when not a non-negative integer.228func parseSeconds(_ text: String) -> Int? {229    guard let n = Int(text.trimmingCharacters(in: .whitespaces)), n >= 0 else { return nil }230    return n231}232233func parseNumber(_ text: String) -> Double? {234    Double(text.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: "."))235}236
Files main
Menu

Theme