Files
SonarDesk/SonarDesk/Views/Dashboard/DashboardView.swift
T
2026-10-01 10:48:59 +01:00

181 lines
13 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SwiftUI
import Charts
struct DashboardView: View {
@EnvironmentObject var app: AppState
@EnvironmentObject var reportStore: ReportStore
let onNavigate: (Destination) -> Void
@State private var projectPage = 1
@State private var pageSize = 10
@State private var failedOnly = false
@State private var search = ""
@State private var showingCreateProject = false
private func total(_ key: String) -> Int { app.projects.reduce(0) { $0 + (Int($1.measures[key] ?? "0") ?? 0) } }
private var failed: Int { app.projects.filter { $0.qualityGate != "OK" }.count }
private var filtered: [ProjectSnapshot] {
app.projects.filter { p in
(!failedOnly || p.qualityGate != "OK") && (search.isEmpty || app.projectDisplayName(for: p.project).localizedCaseInsensitiveContains(search) || p.project.key.localizedCaseInsensitiveContains(search))
}
}
private var pageCount: Int { max(1, Int(ceil(Double(filtered.count) / Double(pageSize)))) }
private var pageRows: [ProjectSnapshot] {
let p = min(max(projectPage, 1), pageCount), start = (p - 1) * pageSize
guard start < filtered.count else { return [] }
return Array(filtered[start..<min(start + pageSize, filtered.count)])
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 22) {
header
LazyVGrid(columns: [GridItem(.adaptive(minimum: 210), spacing: 14)], spacing: 14) {
MetricCard(title: "Projects", value: "\(app.projects.count)", systemImage: "shippingbox.fill", tint: .blue, subtitle: "Monitored projects") { onNavigate(.metric(.projects)) }
MetricCard(title: "Failed Gates", value: "\(failed)", systemImage: failed == 0 ? "checkmark.seal.fill" : "xmark.seal.fill", tint: failed == 0 ? .green : .red, subtitle: failed == 0 ? "All projects passing" : "Needs attention") { failedOnly = true; projectPage = 1 }
MetricCard(title: "Bugs", value: total("bugs").formatted(), systemImage: "ladybug.fill", tint: .red, subtitle: "Open reliability issues") { onNavigate(.issuesFiltered(.bugs)) }
MetricCard(title: "Vulnerabilities", value: total("vulnerabilities").formatted(), systemImage: "lock.trianglebadge.exclamationmark.fill", tint: .orange, subtitle: "Open security issues") { onNavigate(.issuesFiltered(.vulnerabilities)) }
MetricCard(title: "Code Smells", value: total("code_smells").formatted(), systemImage: "exclamationmark.bubble.fill", tint: .yellow, subtitle: "Maintainability issues") { onNavigate(.issuesFiltered(.codeSmells)) }
MetricCard(title: "Security Hotspots", value: total("security_hotspots").formatted(), systemImage: "shield.lefthalf.filled.badge.checkmark", tint: .purple, subtitle: "Security review points") { onNavigate(.metric(.securityHotspots)) }
}
analyticsPanel
projectPanel
}.padding(26)
}
.background(Color(nsColor: .windowBackgroundColor))
.sheet(isPresented: $showingCreateProject) { CreateProjectView().environmentObject(app) }
.onChange(of: pageSize) { _, _ in projectPage = 1 }
.onChange(of: search) { _, _ in projectPage = 1 }
}
private var header: some View {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 5) {
Text("Dashboard").font(.system(size: 32, weight: .bold))
Text("Overview of your SonarQube instance").foregroundStyle(.secondary)
}
Spacer()
Button { do { try reportStore.makeReport(projects: app.projects, server: app.selectedServer) } catch { reportStore.errorMessage = error.localizedDescription } } label: { Label("Save Report", systemImage: "doc.badge.plus") }.buttonStyle(.borderedProminent).disabled(app.projects.isEmpty)
if let date = app.lastRefresh { Text("Updated \(date, style: .relative) ago").font(.caption).foregroundStyle(.secondary).padding(.top, 7) }
}
}
private struct ChartMetric: Identifiable { let id = UUID(); let name: String; let value: Int; let color: Color }
private var issueMetrics: [ChartMetric] {
[ChartMetric(name: "Bugs", value: total("bugs"), color: SonarTheme.danger),
ChartMetric(name: "Vulnerabilities", value: total("vulnerabilities"), color: SonarTheme.warning),
ChartMetric(name: "Code Smells", value: total("code_smells"), color: SonarTheme.smell),
ChartMetric(name: "Hotspots", value: total("security_hotspots"), color: SonarTheme.purple)]
}
private var analyticsPanel: some View {
VStack(alignment: .leading, spacing: 14) {
HStack { VStack(alignment:.leading,spacing:2){ Text("Analytics").font(.title3.bold()); Text("Issue distribution and project health").font(.caption).foregroundStyle(.secondary) }; Spacer() }
HStack(alignment:.top,spacing:14) {
SonarPanel { VStack(alignment:.leading,spacing:10) {
Text("Issues by type").font(.headline)
Chart(issueMetrics) { item in
BarMark(x:.value("Type",item.name), y:.value("Issues",item.value)).foregroundStyle(item.color).cornerRadius(4)
}.chartYAxis { AxisMarks(position:.leading) }.frame(height:220)
}.padding(16) }.frame(maxWidth:.infinity)
SonarPanel { VStack(alignment:.leading,spacing:10) {
Text("Project issue load").font(.headline)
Chart(app.projects.prefix(8)) { item in
BarMark(x:.value("Project",app.projectDisplayName(for: item.project)), y:.value("Issues", (Int(item.measures["bugs"] ?? "0") ?? 0) + (Int(item.measures["vulnerabilities"] ?? "0") ?? 0) + (Int(item.measures["code_smells"] ?? "0") ?? 0)))
.foregroundStyle(SonarTheme.accent.gradient).cornerRadius(4)
}.chartXAxis { AxisMarks { value in AxisValueLabel { if let text=value.as(String.self){Text(text).lineLimit(1).font(.caption2)} } } }.frame(height:220)
}.padding(16) }.frame(maxWidth:.infinity)
}
HStack(alignment:.top,spacing:14) {
SonarPanel { VStack(alignment:.leading,spacing:10) {
Text("Quality gates").font(.headline)
Chart([("Passing", max(0,app.projects.count-failed)),("Failed",failed)], id:\.0) { row in
SectorMark(angle:.value("Projects",row.1), innerRadius:.ratio(0.62), angularInset:2).foregroundStyle(row.0 == "Passing" ? SonarTheme.success : SonarTheme.danger)
}.frame(height:180)
}.padding(16) }.frame(maxWidth:.infinity)
SonarPanel { VStack(alignment:.leading,spacing:10) {
Text("Coverage by project").font(.headline)
Chart(app.projects.prefix(8)) { item in
BarMark(x:.value("Project",app.projectDisplayName(for: item.project)), y:.value("Coverage",Double(item.measures["coverage"] ?? "0") ?? 0)).foregroundStyle(SonarTheme.success.gradient).cornerRadius(4)
}.chartYScale(domain:0...100).chartYAxis { AxisMarks(position:.leading) { v in AxisGridLine(); AxisValueLabel { if let n=v.as(Double.self){Text("\(Int(n))%")}} } }.frame(height:180)
}.padding(16) }.frame(maxWidth:.infinity)
}
if reportStore.reports.count >= 2 {
SonarPanel { VStack(alignment:.leading,spacing:10) {
Text("Issue trend from saved reports").font(.headline)
Chart(reportStore.reports.sorted { $0.createdAt < $1.createdAt }.suffix(20)) { report in
LineMark(x:.value("Date",report.createdAt), y:.value("Bugs",report.bugs)).foregroundStyle(by:.value("Metric","Bugs"))
LineMark(x:.value("Date",report.createdAt), y:.value("Vulnerabilities",report.vulnerabilities)).foregroundStyle(by:.value("Metric","Vulnerabilities"))
LineMark(x:.value("Date",report.createdAt), y:.value("Code Smells",report.codeSmells)).foregroundStyle(by:.value("Metric","Code Smells"))
}.frame(height:220)
}.padding(16) }
}
}
}
private var projectPanel: some View {
SonarPanel {
VStack(spacing: 0) {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(failedOnly ? "Projects — Failed Quality Gates" : "Projects").font(.title3.bold())
Text("Your SonarQube projects in your preferred order").font(.caption).foregroundStyle(.secondary)
}
Spacer()
if failedOnly { Button("Show All") { failedOnly = false; projectPage = 1 }.buttonStyle(.bordered) }
Button { showingCreateProject = true } label: { Label("New Project", systemImage: "plus") }.buttonStyle(.borderedProminent)
TextField("Search projects…", text: $search).textFieldStyle(.roundedBorder).frame(width: 210)
Picker("Rows", selection: $pageSize) { Text("10 per page").tag(10); Text("25 per page").tag(25); Text("50 per page").tag(50) }.labelsHidden().frame(width: 120)
}.padding(16)
Divider()
HStack {
Text("PROJECT").frame(maxWidth: .infinity, alignment: .leading)
Text("BUGS").frame(width: 65, alignment: .trailing)
Text("VULNS").frame(width: 65, alignment: .trailing)
Text("SMELLS").frame(width: 80, alignment: .trailing)
Text("COVERAGE").frame(width: 80, alignment: .trailing)
Text("QUALITY GATE").frame(width: 110, alignment: .trailing)
Color.clear.frame(width: 18)
}.font(.caption2.bold()).foregroundStyle(.tertiary).padding(.horizontal, 16).padding(.vertical, 9)
Divider()
ForEach(Array(pageRows.enumerated()), id: \.element.id) { index, item in
Button { onNavigate(.project(item.project.key)) } label: {
HStack {
HStack(spacing: 11) {
Image(systemName: "shippingbox.fill").foregroundStyle(.blue)
VStack(alignment: .leading, spacing: 1) { Text(app.projectDisplayName(for: item.project)).fontWeight(.semibold); Text(item.project.key).font(.caption).foregroundStyle(.secondary) }
}.frame(maxWidth: .infinity, alignment: .leading)
metricPill(item.measures["bugs"] ?? "0", .red, 65)
metricPill(item.measures["vulnerabilities"] ?? "0", .orange, 65)
metricPill(item.measures["code_smells"] ?? "0", .yellow, 80)
metricPill((item.measures["coverage"] ?? "0") + "%", .green, 80)
GateBadge(status: item.qualityGate).frame(width: 110, alignment: .trailing)
Image(systemName: "chevron.right").font(.caption).foregroundStyle(.tertiary).frame(width: 18)
}.padding(.horizontal, 16).padding(.vertical, 10).contentShape(Rectangle())
}.buttonStyle(.plain)
.draggable(item.project.key)
.dropDestination(for: String.self) { keys, _ in
guard let sourceKey = keys.first else { return false }
app.moveProject(sourceKey, before: item.project.key)
return true
}
if index < pageRows.count - 1 { Divider().padding(.leading, 16) }
}
if filtered.isEmpty { ContentUnavailableView("No projects", systemImage: "shippingbox", description: Text("No projects match the current view.")).padding(30) }
Divider()
HStack {
let start = filtered.isEmpty ? 0 : ((projectPage - 1) * pageSize + 1)
Text("Showing \(start)–\(min(projectPage * pageSize, filtered.count)) of \(filtered.count) projects").font(.caption).foregroundStyle(.secondary)
Spacer()
Button { projectPage -= 1 } label: { Image(systemName: "chevron.left") }.disabled(projectPage <= 1)
Text("\(projectPage) / \(pageCount)").font(.caption.monospacedDigit()).frame(minWidth: 48)
Button { projectPage += 1 } label: { Image(systemName: "chevron.right") }.disabled(projectPage >= pageCount)
}.padding(12)
}
}
}
private func metricPill(_ text: String, _ color: Color, _ width: CGFloat) -> some View {
Text(text).font(.caption.monospacedDigit().weight(.semibold)).foregroundStyle(color).padding(.horizontal, 7).padding(.vertical, 4)
.background(color.opacity(0.10), in: Capsule()).frame(width: width, alignment: .trailing)
}
}