SPB Git

Repository Public

StorageView.swift 13.3 KB 248 lines swift

1import MCCCore2import SwiftUI34struct StorageView: View {5    enum Tab: String, CaseIterable, Identifiable { case volumes, nas, backups; var id: String { rawValue } }6    @Environment(AppModel.self) private var app7    @State private var tab: Tab = .volumes89    var body: some View {10        Page(title: SidebarItem.storage.title, subtitle: tr("storage.subtitle"), scrolls: true) {11            SectionTabs(selection: $tab) { Localization.shared.string("storage.tab." + $0.rawValue) }12        } content: {13            switch tab {14            case .volumes:15                if app.session.can("nodes.read") { VolumesPane() } else { UnavailableStateView(reason: .forbidden) }16            case .nas: NasPane()17            case .backups: BackupsPane()18            }19        }20    }21}2223struct VolumesPane: View {24    @Environment(AppModel.self) private var app25    @Environment(\.mccTheme) private var theme26    @State private var node = ""27    @State private var kind: API.VolumeKind?28    @State private var minUsed = 0.02930    var body: some View {31        let resource = app.session.infrastructure.volumes32        ResourceView(resource) { all in33            let present = all.filter { $0.goneAt == nil }34            let list = StorageLogic.filter(present, nodeID: node.isEmpty ? nil : node, kind: kind, minUsedPct: minUsed)35                .sorted { ($0.nodeAlias, $0.mount) < ($1.nodeAlias, $1.mount) }36            VStack(alignment: .leading, spacing: Tokens.Space.s3) {37                HStack(spacing: Tokens.Space.s4) {38                    Picker(tr("storage.volumes.node"), selection: $node) {39                        Text(tr("storage.volumes.all_nodes")).tag("")40                        ForEach(Dictionary(grouping: present, by: \.nodeId).map { ($0.key, $0.value[0].nodeAlias) }.sorted { $0.1 < $1.1 }, id: \.0) { Text($0.1).tag($0.0) }41                    }42                    .fixedSize()43                    Picker(tr("storage.volumes.kind"), selection: $kind) {44                        Text(tr("storage.volumes.all_kinds")).tag(API.VolumeKind?.none)45                        ForEach(API.VolumeKind.allCases, id: \.self) { Text($0.label).tag(API.VolumeKind?.some($0)) }46                    }47                    .fixedSize()48                    Slider(value: $minUsed, in: 0...95, step: 5) { Text(tr("storage.volumes.min_used", Format.percent(minUsed))) }49                        .frame(maxWidth: 320)50                        .accessibilityValue(Format.percent(minUsed))51                    Spacer()52                    Text(tr("storage.volumes.count", list.count, present.count)).font(.caption).foregroundStyle(theme.textTertiary)53                }54                if list.isEmpty {55                    EmptyStateView(tr("storage.volumes.empty"), systemImage: "internaldrive")56                } else {57                    Table(list.keyed(\.id)) {58                        TableColumn(tr("storage.volumes.node")) { r in Text(r.value.nodeAlias) }59                        TableColumn(tr("storage.volumes.mount")) { r in60                            VStack(alignment: .leading, spacing: 0) {61                                Text(r.value.mount).font(.callout.monospaced()).lineLimit(1)62                                if let d = r.value.device { Text(d).font(.caption.monospaced()).foregroundStyle(theme.textTertiary).lineLimit(1) }63                            }64                        }65                        TableColumn(tr("storage.volumes.kind")) { r in Text(r.value.kind.label + (r.value.fs.map { " · \($0)" } ?? "")) }66                        TableColumn(tr("storage.volumes.usage")) { r in67                            UsageMeter(label: usageLabel(r.value), ratio: StorageLogic.usedRatio(used: r.value.usedBytes, total: r.value.totalBytes))68                        }69                        .width(min: 220, ideal: 280)70                        TableColumn(tr("storage.volumes.smart")) { r in71                            if let s = r.value.smartStatus, !s.isEmpty {72                                StatusLabel(s, tone: s.lowercased().contains("verified") || s.lowercased() == "ok" || s.lowercased() == "passed" ? .ok : .warning)73                            } else {74                                OptionalValueText(nil)75                            }76                        }77                        TableColumn(tr("storage.volumes.remote")) { r in OptionalValueText(r.value.remote) }78                        TableColumn(tr("freshness.title")) { r in FreshnessLabel(r.value.freshness, observedAt: r.value.observedAt) }79                    }80                    .frame(minHeight: 480)81                    .accessibilityLabel(tr("storage.tab.volumes"))82                    .accessibilityIdentifier("volumes-table")83                }84            }85        }86        .task { await resource.load() }87    }8889    private func usageLabel(_ v: API.Volume) -> String {90        switch (v.usedBytes, v.totalBytes) {91        case let (u?, t?): tr("storage.used_of", Format.bytes(u), Format.bytes(t))92        case let (nil, t?): tr("storage.total_only", Format.bytes(t))93        default: tr("metric.not_measured")94        }95    }96}9798struct NasPane: View {99    @Environment(AppModel.self) private var app100    @Environment(\.mccTheme) private var theme101    @State private var creating = false102    @State private var deleting: API.NasTarget?103104    var body: some View {105        let resource = app.session.infrastructure.nas106        VStack(alignment: .leading, spacing: Tokens.Space.s3) {107            if app.session.can("settings.manage") {108                Button { creating = true } label: { Label(tr("storage.nas.add"), systemImage: "plus") }.mutation(app, permission: "settings.manage")109            }110            ResourceView(resource) { list in111                if list.isEmpty {112                    EmptyStateView(tr("storage.nas.empty"), message: tr("storage.nas.empty.message"), systemImage: "externaldrive.connected.to.line.below")113                } else {114                    Table(list.keyed(\.id)) {115                        TableColumn(tr("storage.nas.name")) { r in116                            VStack(alignment: .leading, spacing: 0) {117                                Text(r.value.name)118                                if !r.value.note.isEmpty { Text(r.value.note).font(.caption).foregroundStyle(theme.textSecondary).lineLimit(1) }119                            }120                        }121                        TableColumn(tr("storage.nas.share")) { r in122                            Text("\(r.value._protocol.rawValue)://\(r.value.host ?? "…")/\(r.value.share)").font(.callout.monospaced()).lineLimit(1)123                        }124                        TableColumn(tr("storage.nas.state")) { r in125                            VStack(alignment: .leading, spacing: 0) {126                                StatusLabel(Localization.shared.string("storage.nas.state." + r.value.state.rawValue),127                                            tone: r.value.state == .online ? .ok : r.value.state == .offline ? .critical : .neutral)128                                if let at = r.value.stateAt { Text(Format.relative(at)).font(.caption).foregroundStyle(theme.textTertiary) }129                            }130                        }131                        TableColumn(tr("storage.nas.latency")) { r in OptionalValueText(r.value.latencyMs.map { Format.milliseconds($0) }) }132                        TableColumn(tr("storage.nas.mounted_on")) { r in Text(Format.integer(r.value.mountedOn)).monospacedDigit() }133                        TableColumn(tr("storage.volumes.usage")) { r in134                            UsageMeter(label: capacity(r.value), ratio: StorageLogic.usedRatio(used: r.value.usedBytes, total: r.value.totalBytes))135                        }136                        .width(min: 200, ideal: 260)137                        TableColumn("") { r in138                            if app.session.can("settings.manage") {139                                Button(tr("action.delete"), role: .destructive) { deleting = r.value }.mutation(app, permission: "settings.manage")140                            }141                        }142                    }143                    .frame(minHeight: 320)144                    .accessibilityLabel(tr("storage.tab.nas"))145                }146            }147        }148        .task { await resource.load() }149        .sheet(isPresented: $creating) { NasCreateSheet() }150        .confirmationDialog(tr("storage.nas.delete.title"), isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), presenting: deleting) { n in151            Button(tr("action.delete"), role: .destructive) { Task { await app.perform { try await app.session.infrastructure.deleteNas(id: n.id) } } }152            Button(tr("action.cancel"), role: .cancel) {}153        } message: { n in Text(tr("storage.nas.delete.message", n.name)) }154    }155156    private func capacity(_ n: API.NasTarget) -> String {157        switch (n.usedBytes, n.totalBytes) {158        case let (u?, t?): tr("storage.used_of", Format.bytes(u), Format.bytes(t))159        case let (nil, t?): tr("storage.total_only", Format.bytes(t))160        default: tr("metric.not_measured")161        }162    }163}164165struct NasCreateSheet: View {166    @Environment(AppModel.self) private var app167    @Environment(\.dismiss) private var dismiss168    @State private var name = ""169    @State private var host = ""170    @State private var share = ""171    @State private var proto: API.CreateNasTargetRequest._ProtocolPayload = .smb172    @State private var note = ""173    @State private var failure: APIError?174    @State private var working = false175176    var body: some View {177        VStack(alignment: .leading, spacing: Tokens.Space.s4) {178            Text(tr("storage.nas.add")).font(.title3.weight(.semibold))179            Form {180                TextField(tr("storage.nas.name"), text: $name)181                TextField(tr("storage.nas.host"), text: $host)182                TextField(tr("storage.nas.share_name"), text: $share)183                Picker(tr("storage.nas.protocol"), selection: $proto) {184                    ForEach(API.CreateNasTargetRequest._ProtocolPayload.allCases, id: \.self) { Text($0.rawValue.uppercased()).tag($0) }185                }186                .pickerStyle(.segmented)187                TextField(tr("storage.nas.note"), text: $note)188            }189            .formStyle(.grouped)190            if let failure { InlineErrorView(failure) }191            HStack {192                Spacer()193                Button(tr("action.cancel")) { dismiss() }.keyboardShortcut(.cancelAction)194                Button(tr("action.add")) {195                    let t = { (s: String) in s.trimmingCharacters(in: .whitespaces) }196                    let request = API.CreateNasTargetRequest(name: t(name), host: t(host), share: t(share).isEmpty ? nil : t(share), _protocol: proto, note: t(note).isEmpty ? nil : t(note))197                    Task {198                        working = true; failure = nil199                        defer { working = false }200                        do { _ = try await app.session.infrastructure.createNas(request); dismiss() } catch {201                            let e = APIError.from(error)202                            if !e.isPasskeyCancelled { failure = e }203                        }204                    }205                }206                .keyboardShortcut(.defaultAction)207                .disabled(working || name.trimmingCharacters(in: .whitespaces).isEmpty || host.trimmingCharacters(in: .whitespaces).isEmpty)208                .mutation(app, permission: "settings.manage")209            }210        }211        .padding(Tokens.Space.s6).frame(width: 460)212    }213}214215struct BackupsPane: View {216    @Environment(AppModel.self) private var app217    @Environment(\.mccTheme) private var theme218219    var body: some View {220        let resource = app.session.infrastructure.backups221        ResourceView(resource) { list in222            if list.isEmpty {223                EmptyStateView(tr("storage.backups.empty"), message: tr("storage.backups.empty.message"), systemImage: "clock.arrow.2.circlepath")224            } else {225                Table(list.keyed(\.id)) {226                    TableColumn(tr("storage.backups.name")) { r in227                        VStack(alignment: .leading, spacing: 0) {228                            Text(r.value.name)229                            Text([r.value.kind, r.value.nodeAlias].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(theme.textSecondary)230                        }231                    }232                    TableColumn(tr("storage.backups.status")) { r in233                        StatusLabel(Localization.shared.string("storage.backups.status." + r.value.lastStatus.rawValue),234                                    tone: r.value.lastStatus == .ok ? .ok : r.value.lastStatus == .failed ? .critical : .neutral)235                    }236                    TableColumn(tr("storage.backups.last_run")) { r in OptionalValueText(r.value.lastRunAt.map { Format.dateTime($0) }) }237                    TableColumn(tr("storage.backups.last_success")) { r in OptionalValueText(r.value.lastSuccessAt.map { Format.relative($0) }) }238                    TableColumn(tr("storage.backups.size")) { r in OptionalValueText(r.value.sizeBytes.map { Format.bytes($0) }) }239                    TableColumn(tr("storage.backups.detail")) { r in Text(r.value.detail).lineLimit(2).help(r.value.detail) }240                }241                .frame(minHeight: 360)242                .accessibilityLabel(tr("storage.tab.backups"))243            }244        }245        .task { await resource.load() }246    }247}248
Files main
Menu

Theme