SPB Git

Repository Public

NetworkView.swift 13.9 KB 237 lines swift

1import MCCCore2import SwiftUI34struct NetworkView: View {5    enum Tab: String, CaseIterable, Identifiable { case topology, interfaces; var id: String { rawValue } }6    @Environment(AppModel.self) private var app7    @State private var tab: Tab = .topology89    var body: some View {10        Page(title: SidebarItem.network.title, subtitle: tr("network.subtitle"), scrolls: true) {11            SectionTabs(selection: $tab) { Localization.shared.string("network.tab." + $0.rawValue) }12        } content: {13            switch tab {14            case .topology: TopologyPane()15            case .interfaces:16                if app.session.can("nodes.read") { InterfacesPane() } else { UnavailableStateView(reason: .forbidden) }17            }18        }19    }20}2122struct TopologyPane: View {23    @Environment(AppModel.self) private var app24    @Environment(\.mccTheme) private var theme25    @State private var selectedNode: String?26    @State private var selectedLink: String?2728    var body: some View {29        let topology = app.session.infrastructure.topology30        ResourceView(topology) { t in31            if t.nodes.isEmpty {32                EmptyStateView(tr("network.topology.empty"), message: tr("network.topology.empty.message"), systemImage: "point.3.connected.trianglepath.dotted")33            } else {34                VStack(alignment: .leading, spacing: Tokens.Space.s4) {35                    Card(padding: Tokens.Space.s3) {36                        VStack(alignment: .leading, spacing: Tokens.Space.s3) {37                            diagram(t).frame(height: max(420, CGFloat(t.nodes.count) * 16))38                            legend39                            Text(tr("network.topology.generated", Format.time(t.generatedAt, seconds: true))).font(.caption).foregroundStyle(theme.textTertiary)40                        }41                    }42                    if let id = selectedNode, let n = t.nodes.first(where: { $0.id == id }) { nodeDetail(n, in: t) }43                    DetailSection(title: tr("network.links.title")) {44                        Text(tr("network.links.help")).font(.caption).foregroundStyle(theme.textTertiary)45                        linksTable(t)46                    }47                }48            }49        }50        .task { await topology.load() }51    }5253    private func label(_ id: String, _ t: API.NetworkTopology) -> String { t.nodes.first { $0.id == id }?.label ?? id }5455    private func diagram(_ t: API.NetworkTopology) -> some View {56        GeometryReader { geo in57            let pos = TopologyLayout.positions(nodes: t.nodes, in: geo.size)58            ZStack {59                Canvas { ctx, _ in60                    for link in t.links {61                        guard let a = pos[link.source], let b = pos[link.target] else { continue }62                        var path = Path(); path.move(to: a); path.addLine(to: b)63                        let selected = link.id == selectedLink || link.source == selectedNode || link.target == selectedNode64                        ctx.stroke(path, with: .color(TopologyLayout.tone(link.state).color(theme).opacity(selected ? 1 : 0.7)),65                                   style: StrokeStyle(lineWidth: selected ? 3 : (link.kind == .lan ? 1.6 : 1.3), lineCap: .round,66                                                      dash: TopologyLayout.dash(kind: link.kind, state: link.state)))67                        if link.state == .down {68                            // A cross at mid-link: "down" does not rely on the colour.69                            let m = CGPoint(x: (a.x + b.x) / 2, y: (a.y + b.y) / 2)70                            var x = Path()71                            x.move(to: CGPoint(x: m.x - 5, y: m.y - 5)); x.addLine(to: CGPoint(x: m.x + 5, y: m.y + 5))72                            x.move(to: CGPoint(x: m.x + 5, y: m.y - 5)); x.addLine(to: CGPoint(x: m.x - 5, y: m.y + 5))73                            ctx.stroke(x, with: .color(StatusTone.critical.color(theme)), lineWidth: 2)74                        }75                    }76                }77                .accessibilityHidden(true)78                ForEach(t.nodes, id: \.id) { n in79                    if let p = pos[n.id] { nodeMark(n).position(p) }80                }81            }82        }83        .accessibilityElement(children: .contain)84        .accessibilityLabel(tr("network.topology.title"))85        .accessibilityIdentifier("topology-diagram")86    }8788    private func nodeMark(_ n: API.TopologyNode) -> some View {89        let hub = TopologyLayout.isHub(n)90        let tone = n.freshness?.tone ?? .neutral91        let selected = selectedNode == n.id92        return Button {93            selectedNode = selected ? nil : n.id94            selectedLink = nil95        } label: {96            VStack(spacing: 2) {97                Image(systemName: n.kind == .lanGateway ? "wifi.router" : n.kind == .wgHub ? "lock.shield" : "desktopcomputer")98                    .font(hub ? .title2 : .body)99                    .foregroundStyle(hub ? theme.accent : tone.color(theme))100                    .frame(width: hub ? 44 : 30, height: hub ? 44 : 30)101                    .background(theme.raised, in: RoundedRectangle(cornerRadius: hub ? Tokens.Radius.md : Tokens.Radius.pill))102                    .overlay(RoundedRectangle(cornerRadius: hub ? Tokens.Radius.md : Tokens.Radius.pill)103                        .strokeBorder(selected ? theme.focusRing : theme.border, lineWidth: selected ? 2.5 : 1))104                Text(n.label).font(.caption).foregroundStyle(theme.textPrimary).lineLimit(1)105                    .padding(.horizontal, 3).background(theme.surface.opacity(0.85), in: RoundedRectangle(cornerRadius: 3))106            }107        }108        .buttonStyle(.plain)109        .help([n.label, kindLabel(n), n.freshness?.label, n.address].compactMap { $0 }.joined(separator: " · "))110        .accessibilityLabel("\(kindLabel(n)) \(n.label)")111        .accessibilityValue([n.freshness?.label, n.address].compactMap { $0 }.joined(separator: ", "))112        .accessibilityAddTraits(selected ? .isSelected : [])113    }114115    private func kindLabel(_ n: API.TopologyNode) -> String { Localization.shared.string("network.node_kind." + n.kind.rawValue) }116    private func kindLabel(_ k: API.TopologyLink.KindPayload) -> String { Localization.shared.string("network.link_kind." + k.rawValue) }117    private func stateLabel(_ s: API.TopologyLink.StatePayload) -> String { Localization.shared.string("network.link_state." + s.rawValue) }118119    private struct LegendItem: Identifiable {120        let id: Int121        let kind: API.TopologyLink.KindPayload122        let state: API.TopologyLink.StatePayload123    }124125    private var legend: some View {126        let items = [LegendItem(id: 0, kind: .lan, state: .up), LegendItem(id: 1, kind: .wireguard, state: .up),127                     LegendItem(id: 2, kind: .lan, state: .down), LegendItem(id: 3, kind: .lan, state: .unknown)]128        return HStack(spacing: Tokens.Space.s6) {129            ForEach(items) { item in130                HStack(spacing: Tokens.Space.s2) {131                    Path { p in p.move(to: CGPoint(x: 0, y: 5)); p.addLine(to: CGPoint(x: 30, y: 5)) }132                        .stroke(TopologyLayout.tone(item.state).color(theme), style: StrokeStyle(lineWidth: 2, dash: TopologyLayout.dash(kind: item.kind, state: item.state)))133                        .frame(width: 30, height: 10)134                    Text(item.state == .up ? kindLabel(item.kind) : stateLabel(item.state)).font(.caption).foregroundStyle(theme.textSecondary)135                }136            }137            Label(Localization.shared.string("network.node_kind.lan_gateway"), systemImage: "wifi.router").font(.caption).foregroundStyle(theme.textSecondary)138            Label(Localization.shared.string("network.node_kind.wg_hub"), systemImage: "lock.shield").font(.caption).foregroundStyle(theme.textSecondary)139        }140        .accessibilityElement(children: .combine)141        .accessibilityLabel(tr("network.legend"))142    }143144    private func nodeDetail(_ n: API.TopologyNode, in t: API.NetworkTopology) -> some View {145        DetailSection(title: n.label) {146            KeyValueRow(tr("network.detail.kind"), kindLabel(n))147            if let f = n.freshness { KeyValueRow(tr("freshness.title"), f.label) }148            if let a = n.address { KeyValueRow(tr("network.detail.address"), a, monospaced: true) }149            KeyValueRow(tr("network.detail.links"), Format.integer(t.links.filter { $0.source == n.id || $0.target == n.id }.count))150            if let id = n.nodeId { LinkButton(title: tr("network.detail.open_node")) { app.openNode(id) } }151        }152    }153154    private func linksTable(_ t: API.NetworkTopology) -> some View {155        Table(t.links.keyed(\.id), selection: Binding(get: { selectedLink }, set: { selectedLink = $0; if $0 != nil { selectedNode = nil } })) {156            TableColumn(tr("network.links.from")) { r in Text(label(r.value.source, t)) }157            TableColumn(tr("network.links.to")) { r in Text(label(r.value.target, t)) }158            TableColumn(tr("network.links.kind")) { r in Text(kindLabel(r.value.kind) + (r.value.interface.map { " · \($0)" } ?? "")) }159            TableColumn(tr("network.links.state")) { r in StatusLabel(stateLabel(r.value.state), tone: TopologyLayout.tone(r.value.state)) }160            TableColumn(tr("network.links.latency")) { r in161                Text(TopologyLayout.measure(r.value.latencyMs, availability: r.value.latencyAvailability) { Format.milliseconds($0) }).monospacedDigit()162            }163            TableColumn(tr("network.links.loss")) { r in164                Text(TopologyLayout.measure(r.value.lossPct, availability: r.value.lossAvailability) { Format.percent($0, fractionDigits: 1) }).monospacedDigit()165            }166            TableColumn(tr("freshness.title")) { r in FreshnessLabel(r.value.freshness, observedAt: r.value.observedAt) }167        }168        .frame(minHeight: min(520, CGFloat(t.links.count + 1) * 28 + 30))169        .accessibilityLabel(tr("network.links.title"))170        .accessibilityIdentifier("topology-links")171    }172}173174struct InterfacesPane: View {175    @Environment(AppModel.self) private var app176    @Environment(\.mccTheme) private var theme177    @State private var node = ""178    @State private var hideLoopback = true179180    var body: some View {181        let resource = app.session.infrastructure.interfaces182        ResourceView(resource) { all in183            let list = all.filter { (node.isEmpty || $0.nodeId == node) && (!hideLoopback || $0.kind != .loopback) }184            // The server omits MAC and IP addresses below nodes.private.read: the columns exist only if it sent some.185            let showsPrivate = all.contains { $0.mac != nil || !$0.ipv4.isEmpty || !$0.ipv6.isEmpty }186            VStack(alignment: .leading, spacing: Tokens.Space.s3) {187                HStack(spacing: Tokens.Space.s4) {188                    Picker(tr("network.interfaces.node"), selection: $node) {189                        Text(tr("network.interfaces.all_nodes")).tag("")190                        ForEach(Dictionary(grouping: all, by: \.nodeId).map { ($0.key, $0.value[0].nodeAlias) }.sorted { $0.1 < $1.1 }, id: \.0) { Text($0.1).tag($0.0) }191                    }192                    .fixedSize()193                    Toggle(tr("network.interfaces.hide_loopback"), isOn: $hideLoopback)194                    Spacer()195                    if !showsPrivate { Text(tr("network.interfaces.private_hidden")).font(.caption).foregroundStyle(theme.textTertiary) }196                }197                if list.isEmpty {198                    EmptyStateView(tr("network.interfaces.empty"), systemImage: "network")199                } else if showsPrivate {200                    Table(list.keyed { "\($0.nodeId)/\($0.name)" }) {201                        commonColumns202                        TableColumn(tr("network.interfaces.mac")) { r in OptionalValueText(r.value.mac).font(.callout.monospaced()) }203                        TableColumn(tr("network.interfaces.ipv4")) { r in Text(r.value.ipv4.joined(separator: ", ")).font(.callout.monospaced()).textSelection(.enabled) }204                        TableColumn(tr("network.interfaces.ipv6")) { r in Text(r.value.ipv6.joined(separator: ", ")).font(.callout.monospaced()).lineLimit(1).textSelection(.enabled) }205                    }206                    .frame(minHeight: 460)207                    .accessibilityLabel(tr("network.tab.interfaces"))208                } else {209                    Table(list.keyed { "\($0.nodeId)/\($0.name)" }) { commonColumns }210                        .frame(minHeight: 460)211                        .accessibilityLabel(tr("network.tab.interfaces"))212                }213            }214        }215        .task { await resource.load() }216    }217218    @TableColumnBuilder<AdminKeyed<API.NetworkInterface>, Never>219    private var commonColumns: some TableColumnContent<AdminKeyed<API.NetworkInterface>, Never> {220        TableColumn(tr("network.interfaces.node")) { r in Text(r.value.nodeAlias) }221        TableColumn(tr("network.interfaces.name")) { r in222            Text("\(r.value.name) · " + Localization.shared.string("network.if_kind." + r.value.kind.rawValue)).lineLimit(1)223        }224        TableColumn(tr("network.links.state")) { r in225            StatusLabel(r.value.up ? tr("network.link_state.up") : tr("network.link_state.down"), tone: r.value.up ? .ok : .offline)226        }227        TableColumn(tr("network.interfaces.speed")) { r in OptionalValueText(r.value.linkSpeedMbps.map { "\(Format.integer($0)) Mb/s" }) }228        TableColumn(tr("network.interfaces.rx")) { r in OptionalValueText(r.value.rxBytesPerS.map { Format.bytesPerSecond($0) }) }229        TableColumn(tr("network.interfaces.tx")) { r in OptionalValueText(r.value.txBytesPerS.map { Format.bytesPerSecond($0) }) }230        TableColumn(tr("network.interfaces.errors")) { r in231            OptionalValueText(r.value.rxErrorsPerS == nil && r.value.txErrorsPerS == nil ? nil232                              : "\(Format.number(r.value.rxErrorsPerS ?? 0, fractionDigits: 2)) / \(Format.number(r.value.txErrorsPerS ?? 0, fractionDigits: 2))")233        }234        TableColumn(tr("freshness.title")) { r in FreshnessLabel(r.value.freshness, observedAt: r.value.observedAt) }235    }236}237
Files main
Menu

Theme