SPB Git

Repository Public

MainWindowView.swift 11.4 KB 267 lines swift

1import MCCCore2import SwiftUI34/// The cockpit: sidebar, section content, toolbar (global state, period, search), command palette, action sheet.5struct MainWindowView: View {6    @Environment(AppModel.self) private var app7    @Environment(\.mccTheme) private var theme8    @SceneStorage("mcc.sidebar.selection") private var storedSelection = SidebarItem.overview.rawValue9    @SceneStorage("mcc.range") private var storedRange = API.TimeRange._24h.rawValue10    @State private var columns: NavigationSplitViewVisibility = .all11    @State private var search: SearchModel?12    @State private var restored = false13    @State private var sidebarSelection: SidebarItem?1415    private var visibleItems: [SidebarItem] {16        SidebarItem.allCases.filter { item in item.permission.map(app.session.can) ?? true }17    }1819    var body: some View {20        @Bindable var app = app21        NavigationSplitView(columnVisibility: $columns) {22            // Explicit button rows: `List(selection:)` does not select on click on macOS 27 (see SelectableRow).23            List {24                ForEach(SidebarItem.Group.allCases, id: \.self) { group in25                    Section(Localization.shared.string("nav.group." + group.rawValue)) {26                        ForEach(visibleItems.filter { $0.group == group }) { item in27                            SelectableRow(isSelected: app.selection == item, identifier: "sidebar-\(item.rawValue)") {28                                app.selection = item29                            } label: {30                                Label(item.title, systemImage: item.symbol).badge(badge(for: item))31                            }32                        }33                    }34                }35            }36            .listStyle(.sidebar)37            .navigationSplitViewColumnWidth(min: 200, ideal: Tokens.Size.sidebar, max: 300)38            .safeAreaInset(edge: .bottom) { AccountFooter() }39        } detail: {40            VStack(spacing: 0) {41                OfflineBanner()42                SectionContent(item: app.selection)43            }44            .frame(maxWidth: .infinity, maxHeight: .infinity)45            .background(theme.canvas)46        }47        .navigationTitle(app.selection.title)48        .toolbar { toolbar }49        .searchable(text: Binding(get: { search?.query ?? "" }, set: { search?.query = $0 }), placement: .toolbar, prompt: tr("search.prompt"))50        .searchSuggestions { searchSuggestions }51        .sheet(isPresented: $app.paletteVisible) { CommandPaletteView() }52        .sheet(item: app.actionIntentBinding(host: ActionHost.main)) { intent in ActionRequestSheet(intent: intent) }53        .onAppear {54            if search == nil { search = SearchModel(session: app.session) }55            guard !restored else { return }56            restored = true57            // State restoration: the last section and period of this window.58            if app.focus == nil, app.selection == .overview, let item = SidebarItem(rawValue: storedSelection), visibleItems.contains(item) { app.selection = item }59            if let r = API.TimeRange(rawValue: storedRange) { app.range = r }60        }61        .onChange(of: app.selection, initial: true) { _, new in62            storedSelection = new.rawValue63            if sidebarSelection != new { sidebarSelection = new }64        }65        .onChange(of: sidebarSelection) { _, new in66            if let new, new != app.selection { app.selection = new }67        }68        .onChange(of: app.range) { _, new in storedRange = new.rawValue }69        .task {70            await app.session.cluster.overview.loadIfNeeded()71            await app.session.nodes.list.loadIfNeeded()72            if app.session.can("alerts.read") { await app.session.alerts.alerts.loadIfNeeded() }73        }74    }7576    private func badge(for item: SidebarItem) -> Int {77        switch item {78        case .alerts: (app.session.alerts.alerts.value ?? []).filter { $0.state == .firing }.count79        default: 080        }81    }8283    @ToolbarContentBuilder84    private var toolbar: some ToolbarContent {85        @Bindable var app = app86        ToolbarItem(placement: .navigation) {87            GlobalStateIndicator()88        }89        ToolbarItem(placement: .principal) {90            Picker(tr("menu.period"), selection: $app.range) {91                ForEach(API.TimeRange.allCases, id: \.self) { Text($0.label).tag($0) }92            }93            .pickerStyle(.segmented)94            .help(tr("toolbar.period.help"))95            .accessibilityIdentifier("period-picker")96        }97        ToolbarItemGroup(placement: .primaryAction) {98            Button { app.paletteVisible = true } label: { Label(tr("menu.command_palette"), systemImage: "command") }99                .help(tr("menu.command_palette") + " (⌘K)")100            Button { app.session.reloadAll() } label: { Label(tr("menu.refresh"), systemImage: "arrow.clockwise") }101                .help(tr("menu.refresh") + " (⌘R)")102        }103    }104105    @ViewBuilder106    private var searchSuggestions: some View {107        if let search, !search.query.trimmingCharacters(in: .whitespaces).isEmpty {108            switch search.state {109            case .loading:110                Text(tr("search.searching")).foregroundStyle(.secondary)111            case .unavailable, .failed:112                Text(tr("search.unavailable")).foregroundStyle(.secondary)113            default:114                if search.results.isEmpty {115                    Text(tr("search.no_results")).foregroundStyle(.secondary)116                } else {117                    ForEach(search.results, id: \.id) { r in118                        Button {119                            app.open(r)120                            search.clear()121                        } label: {122                            SearchResultRow(result: r)123                        }124                    }125                }126            }127        }128    }129}130131struct SearchResultRow: View {132    let result: API.SearchResult133    var body: some View {134        Label {135            VStack(alignment: .leading, spacing: 1) {136                Text(result.title)137                Text([result.kind.label, result.subtitle, result.state].compactMap { $0 }.joined(separator: " · "))138                    .font(.caption).foregroundStyle(.secondary)139            }140        } icon: {141            Image(systemName: result.kind.symbol)142        }143        .accessibilityElement(children: .combine)144    }145}146147/// Routes the sidebar selection to its screen.148struct SectionContent: View {149    let item: SidebarItem150    var body: some View {151        switch item {152        case .overview: OverviewView()153        case .nodes: NodesView()154        case .services: ServicesView()155        case .models: ModelsView()156        case .jobs: JobsView()157        case .network: NetworkView()158        case .storage: StorageView()159        case .alerts: AlertsView()160        case .maintenance: MaintenanceView()161        case .activity: ActivityView()162        case .audit: AuditView()163        case .settings: SettingsView()164        }165    }166}167168/// Toolbar pill: nodes fresh / stale / offline, firing alerts, state of the live connection.169struct GlobalStateIndicator: View {170    @Environment(AppModel.self) private var app171    @Environment(\.mccTheme) private var theme172173    var body: some View {174        let s = ClusterGlance(session: app.session)175        HStack(spacing: Tokens.Space.s3) {176            StatusLabel(s.connectionLabel, tone: s.connectionTone)177            if let n = s.nodes {178                Divider().frame(height: 14)179                Text(tr("glance.nodes", n.fresh, n.total)).monospacedDigit()180            }181            if s.firing > 0 {182                Divider().frame(height: 14)183                StatusLabel(tr("glance.alerts", s.firing), tone: s.worstSeverity?.tone ?? .warning)184            }185        }186        .font(.callout)187        .padding(.horizontal, Tokens.Space.s3)188        .accessibilityElement(children: .ignore)189        .accessibilityLabel(tr("glance.title") + " : " + s.spoken)190        .accessibilityIdentifier("global-state")191        .help(s.spoken)192    }193}194195/// The few figures shown in the toolbar and in the menu bar extra, derived from what the server reported.196@MainActor197struct ClusterGlance {198    var nodes: API.NodeCounts?199    var firing = 0200    var firingBySeverity: [API.Severity: Int] = [:]201    var worstSeverity: API.Severity?202    var connectionLabel: String203    var connectionTone: StatusTone204    var lastUpdate: Date?205    var alertsKnown: Bool206207    init(session: AppSession) {208        nodes = session.cluster.overview.value?.nodes209        if nodes == nil, let list = session.nodes.list.value {210            let active = list.filter { $0.retiredAt == nil }211            nodes = API.NodeCounts(total: active.count, fresh: active.filter { $0.freshness == .fresh }.count,212                                   stale: active.filter { $0.freshness == .stale }.count,213                                   offline: active.filter { $0.freshness == .offline }.count,214                                   maintenance: active.filter(\.maintenance).count)215        }216        let alerts = session.alerts.alerts.value217        alertsKnown = alerts != nil218        for a in alerts ?? [] where a.state == .firing {219            firing += 1220            firingBySeverity[a.severity, default: 0] += 1221        }222        worstSeverity = firingBySeverity.keys.max { $0.rank < $1.rank }223        lastUpdate = [session.cluster.overview.receivedAt, session.nodes.list.receivedAt, session.lastEventAt].compactMap { $0 }.max()224        if session.isOffline {225            connectionLabel = tr("connection.offline"); connectionTone = .offline226        } else {227            switch session.streamState {228            case .connected: connectionLabel = tr("connection.live"); connectionTone = .ok229            case .connecting, .idle: connectionLabel = tr("connection.connecting"); connectionTone = .info230            case .reconnecting: connectionLabel = tr("connection.reconnecting"); connectionTone = .stale231            case .paused: connectionLabel = tr("connection.paused"); connectionTone = .neutral232            case .stopped: connectionLabel = tr("connection.stopped"); connectionTone = .offline233            }234        }235    }236237    var spoken: String {238        var parts = [connectionLabel]239        if let n = nodes { parts.append(tr("glance.nodes.spoken", n.fresh, n.stale, n.offline)) }240        parts.append(alertsKnown ? tr("glance.alerts", firing) : tr("glance.alerts.unknown"))241        if let t = lastUpdate { parts.append(tr("glance.updated", Format.time(t, seconds: true))) }242        return parts.joined(separator: ", ")243    }244}245246/// Who is signed in, at the bottom of the sidebar.247struct AccountFooter: View {248    @Environment(AppModel.self) private var app249    @Environment(\.mccTheme) private var theme250    var body: some View {251        if let user = app.session.user {252            HStack(spacing: Tokens.Space.s3) {253                Image(systemName: "person.crop.circle").font(.title3).foregroundStyle(theme.textSecondary).accessibilityHidden(true)254                VStack(alignment: .leading, spacing: 0) {255                    Text(user.displayName).font(.callout.weight(.medium)).foregroundStyle(theme.textPrimary).lineLimit(1)256                    Text(user.role.label).font(.caption).foregroundStyle(theme.textSecondary)257                }258                Spacer(minLength: 0)259            }260            .padding(Tokens.Space.s4)261            .accessibilityElement(children: .combine)262            .accessibilityLabel(tr("account.signed_in_as", user.displayName, user.role.label))263            .accessibilityIdentifier("account-footer")264        }265    }266}267
Files main
Menu

Theme