SPB Git

Repository Public

MaintenanceDetailView.swift 12.9 KB 217 lines swift

1import MCCCore2import SwiftUI34/// Side panel of one occurrence: what, when (user's time zone and the window's own), who, effects, actions, notes.5struct MaintenanceDetailPanel: View {6    @Environment(AppModel.self) private var app7    @Environment(\.mccTheme) private var theme8    let ref: OccurrenceRef9    /// The occurrence as listed by the calendar, when it is in the visible interval.10    let listed: API.MaintenanceOccurrence?11    let onEdit: (API.MaintenanceWindow) -> Void12    let onClose: () -> Void13    @State private var confirmsCancel = false14    @State private var completing = false15    @State private var completionNote = ""16    @State private var notesScope = NotesScope.occurrence17    @State private var actionError: APIError?1819    enum NotesScope: String, CaseIterable, Identifiable { case occurrence, window; var id: String { rawValue } }2021    private var resource: Resource<API.MaintenanceWindow> { app.session.maintenance.window[ref.windowID] }22    private var window: API.MaintenanceWindow? { resource.value ?? listed?.window }2324    var body: some View {25        VStack(alignment: .leading, spacing: 0) {26            HStack {27                Text(tr("maintenance.detail.title")).font(.headline).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)28                Spacer()29                Button(action: onClose) { Image(systemName: "xmark") }30                    .buttonStyle(.borderless).keyboardShortcut(.cancelAction)31                    .accessibilityLabel(tr("action.close")).help(tr("action.close"))32            }33            .padding(Tokens.Space.s4)34            Divider()35            if let w = window {36                ScrollView { content(w).padding(Tokens.Space.s4) }37            } else {38                switch resource.state {39                case .unavailable(let reason, let e): UnavailableStateView(reason: reason, error: e) { Task { await resource.load() } }40                case .failed(let e): ErrorStateView(error: e) { Task { await resource.load() } }41                default: ProgressView(tr("state.loading")).frame(maxWidth: .infinity, maxHeight: .infinity)42                }43            }44        }45        .frame(maxHeight: .infinity, alignment: .top)46        .background(theme.surface)47        .overlay(alignment: .leading) { Rectangle().fill(theme.borderSubtle).frame(width: 1) }48        .task(id: ref.windowID) { await resource.load() }49        .accessibilityElement(children: .contain)50        .accessibilityIdentifier("maintenance-detail")51    }5253    private func status(_ w: API.MaintenanceWindow) -> API.MaintenanceStatus {54        if let listed { return MaintenanceLogic.displayStatus(listed) }55        return w.status56    }5758    @ViewBuilder59    private func content(_ w: API.MaintenanceWindow) -> some View {60        let st = status(w)61        let tz = TimeZone(identifier: w.timezone)62        VStack(alignment: .leading, spacing: Tokens.Space.s4) {63            if resource.isShowingStaleData, let at = resource.receivedAt { StaleDataBanner(receivedAt: at, state: resource.state) }64            VStack(alignment: .leading, spacing: Tokens.Space.s2) {65                HStack(alignment: .firstTextBaseline, spacing: Tokens.Space.s2) {66                    Image(systemName: w.category.symbol).foregroundStyle(theme.textSecondary).accessibilityHidden(true)67                    Text(w.title).font(.title3.weight(.semibold)).foregroundStyle(theme.textPrimary).textSelection(.enabled)68                }69                HStack(spacing: Tokens.Space.s2) {70                    StatusBadge(st.label, tone: st.tone)71                    if listed?.active == true { StatusBadge(tr("maintenance.detail.active"), tone: .maintenance, compact: true) }72                    Text(w.category.label).font(.callout).foregroundStyle(theme.textSecondary)73                }74                if !w.description.isEmpty {75                    Text(verbatim: w.description).font(.callout).foregroundStyle(theme.textPrimary).textSelection(.enabled)76                        .fixedSize(horizontal: false, vertical: true)77                }78            }79            if let error = actionError { InlineErrorView(error) }80            actions(w, status: st)81            Divider()82            VStack(spacing: Tokens.Space.s2) {83                KeyValueRow(tr("maintenance.detail.when"), MaintenanceLogic.timeRange(start: ref.start, end: ref.end))84                KeyValueRow(tr("maintenance.detail.duration"), Format.duration(seconds: ref.end.timeIntervalSince(ref.start)))85                if let tz, tz.secondsFromGMT(for: ref.start) != TimeZone.current.secondsFromGMT(for: ref.start) {86                    KeyValueRow(tr("maintenance.detail.when_in", w.timezone.replacingOccurrences(of: "_", with: " ")),87                                MaintenanceLogic.timeRange(start: ref.start, end: ref.end, timeZone: tz))88                } else {89                    KeyValueRow(tr("maintenance.form.timezone"), w.timezone.replacingOccurrences(of: "_", with: " "))90                }91                KeyValueRow(tr("maintenance.form.recurrence"), MaintenanceLogic.recurrenceSummary(w.recurrence, until: w.recurrenceUntil, timeZone: tz ?? .current))92                if w.recurrence != .none {93                    KeyValueRow(tr("maintenance.detail.first"), Format.dateTime(w.startsAt))94                }95                KeyValueRow(tr("maintenance.flag.mode"), w.setMaintenanceMode ? tr("maintenance.yes") : tr("maintenance.no"))96                KeyValueRow(tr("maintenance.flag.silence"), w.silenceAlerts ? tr("maintenance.yes") : tr("maintenance.no"))97                KeyValueRow(tr("maintenance.detail.created"), [w.createdByDisplayName, Format.dateTime(w.createdAt)].compactMap { $0 }.joined(separator: " · "))98                if w.updatedAt.timeIntervalSince(w.createdAt) > 1 { KeyValueRow(tr("maintenance.detail.updated"), Format.dateTime(w.updatedAt)) }99            }100            Divider()101            VStack(alignment: .leading, spacing: Tokens.Space.s2) {102                Text(tr("maintenance.agenda.nodes", w.scope.nodeIds.count)).font(.headline).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)103                ForEach(w.scope.nodeIds.sorted { (app.session.nodes.alias($0) ?? $0) < (app.session.nodes.alias($1) ?? $1) }, id: \.self) { id in104                    Button { app.openNode(id) } label: {105                        HStack(spacing: Tokens.Space.s2) {106                            Image(systemName: app.session.nodes.node(id)?.kind.symbol ?? "desktopcomputer").foregroundStyle(theme.textSecondary).accessibilityHidden(true)107                            Text(app.session.nodes.alias(id) ?? tr("maintenance.node.unknown")).foregroundStyle(theme.textPrimary)108                            if let n = app.session.nodes.node(id) {109                                if n.maintenance { StatusBadge(tr("maintenance.form.scope.in_maintenance"), tone: .maintenance, compact: true) }110                                Spacer(minLength: 0)111                                StatusLabel(n.freshness.label, tone: n.freshness.tone).font(.caption)112                            } else { Spacer(minLength: 0) }113                            Image(systemName: "arrow.up.forward.square").foregroundStyle(theme.textTertiary).accessibilityHidden(true)114                        }115                        .contentShape(Rectangle())116                    }117                    .buttonStyle(.plain)118                    .help(tr("maintenance.detail.open_node"))119                    .accessibilityHint(tr("maintenance.detail.open_node"))120                }121            }122            Divider()123            notes(w)124        }125        .sheet(isPresented: $completing) { completeSheet(w) }126        .confirmationDialog(tr("maintenance.cancel.title"), isPresented: $confirmsCancel) {127            Button(tr("maintenance.cancel.confirm"), role: .destructive) { run { try await app.session.maintenance.cancelWindow(id: w.id) } }128            Button(tr("maintenance.cancel.keep"), role: .cancel) {}129        } message: {130            Text(w.recurrence == .none ? tr("maintenance.cancel.message") : tr("maintenance.cancel.message.recurring"))131        }132    }133134    /// The server decides which transitions are allowed (409 otherwise); the buttons are only hidden for final states.135    @ViewBuilder136    private func actions(_ w: API.MaintenanceWindow, status: API.MaintenanceStatus) -> some View {137        if w.status == .completed || w.status == .cancelled {138            Text(tr("maintenance.detail.final")).font(.caption).foregroundStyle(theme.textTertiary)139        } else {140            HStack(spacing: Tokens.Space.s2) {141                Button { onEdit(w) } label: { Label(tr("action.edit"), systemImage: "pencil") }142                    .mutation(app, permission: "maintenance.write").accessibilityIdentifier("maintenance-edit")143                Button { completionNote = ""; completing = true } label: { Label(tr("maintenance.complete"), systemImage: "checkmark.circle") }144                    .mutation(app, permission: "maintenance.write").accessibilityIdentifier("maintenance-complete")145                Button(role: .destructive) { confirmsCancel = true } label: { Label(tr("maintenance.cancel.button"), systemImage: "xmark.circle") }146                    .mutation(app, permission: "maintenance.write").accessibilityIdentifier("maintenance-cancel")147            }148            .controlSize(.small)149        }150    }151152    private func notes(_ w: API.MaintenanceWindow) -> some View {153        VStack(alignment: .leading, spacing: Tokens.Space.s3) {154            HStack {155                Text(tr("maintenance.notes.title")).font(.headline).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)156                Spacer()157                if w.recurrence != .none {158                    Picker(tr("maintenance.notes.scope"), selection: $notesScope) {159                        Text(tr("maintenance.notes.scope.occurrence")).tag(NotesScope.occurrence)160                        Text(tr("maintenance.notes.scope.window")).tag(NotesScope.window)161                    }162                    .pickerStyle(.segmented).labelsHidden().fixedSize().controlSize(.small)163                }164            }165            let perOccurrence = w.recurrence != .none && notesScope == .occurrence166            if w.recurrence != .none {167                Text(perOccurrence ? tr("maintenance.notes.scope.occurrence.help", Format.dateTime(ref.start)) : tr("maintenance.notes.scope.window.help"))168                    .font(.caption).foregroundStyle(theme.textTertiary)169            }170            MaintenanceNotesList(query: NotesQuery(windowID: w.id),171                                 target: NoteTarget(windowID: w.id, occurrence: perOccurrence ? ref.start : nil),172                                 showsTarget: !perOccurrence && w.recurrence != .none,173                                 occurrenceFilter: perOccurrence ? ref.start : nil)174        }175    }176177    private func completeSheet(_ w: API.MaintenanceWindow) -> some View {178        VStack(alignment: .leading, spacing: Tokens.Space.s4) {179            Text(tr("maintenance.complete.title")).font(.title3.weight(.semibold)).foregroundStyle(theme.textPrimary).accessibilityAddTraits(.isHeader)180            Text(tr("maintenance.complete.message", w.title)).font(.callout).foregroundStyle(theme.textSecondary)181            TextEditor(text: $completionNote)182                .font(.body).frame(height: 110).scrollContentBackground(.hidden).padding(Tokens.Space.s2)183                .background(theme.inset, in: RoundedRectangle(cornerRadius: Tokens.Radius.md))184                .overlay(RoundedRectangle(cornerRadius: Tokens.Radius.md).strokeBorder(theme.border))185                .accessibilityLabel(tr("maintenance.complete.note"))186                .accessibilityIdentifier("maintenance-complete-note")187            Text(tr("maintenance.complete.note")).font(.caption).foregroundStyle(theme.textTertiary)188            HStack {189                Spacer()190                Button(tr("action.cancel"), role: .cancel) { completing = false }.keyboardShortcut(.cancelAction)191                Button(tr("maintenance.complete")) {192                    let note = completionNote.trimmingCharacters(in: .whitespacesAndNewlines)193                    completing = false194                    run { _ = try await app.session.maintenance.completeWindow(id: w.id, note: note.isEmpty ? nil : note) }195                }196                .keyboardShortcut(.return, modifiers: .command).buttonStyle(.borderedProminent)197                .mutation(app, permission: "maintenance.write")198                .accessibilityIdentifier("maintenance-complete-confirm")199            }200        }201        .padding(Tokens.Space.s6)202        .frame(width: 460)203        .background(theme.surface)204    }205206    /// Runs a transition and shows the server's refusal (for example `409 conflict`) inline, with its correlation id.207    private func run(_ op: @escaping () async throws -> Void) {208        actionError = nil209        Task {210            do { try await op() } catch {211                let e = APIError.from(error)212                if !e.isPasskeyCancelled && !e.isCancelled { actionError = e }213            }214        }215    }216}217
Files main
Menu

Theme