DomainDig/DashboardView.swift

464 lines · 20720 bytes

  1import SwiftUI
  2
  3struct DashboardView: View {
  4    @Environment(\.appDensity) private var appDensity
  5    @Environment(\.accessibilityDifferentiateWithoutColor) private var differentiateWithoutColor
  6    @Bindable var viewModel: DomainViewModel
  7    @State private var collapsedGroups = Set<String>()
  8
  9    private let summaryColumns = [
 10        GridItem(.flexible(), spacing: 10),
 11        GridItem(.flexible(), spacing: 10)
 12    ]
 13
 14    var body: some View {
 15        // Once per body evaluation. Each of these reads used to rebuild the
 16        // whole dashboard, and there were more than twenty of them (A4).
 17        let dashboard = viewModel.portfolioDashboardData
 18        let visible = dashboard.filtered(
 19            by: viewModel.dashboardFilter,
 20            searchText: viewModel.dashboardSearchText
 21        )
 22
 23        List {
 24            if viewModel.trackedDomains.isEmpty {
 25                Section {
 26                    EmptyStateCardView(
 27                        title: "No Portfolio Yet",
 28                        message: "Track domains to get portfolio health, recent changes, expiry visibility, and an attention queue in one place.",
 29                        suggestion: "Inspect a domain and use the Track action, or add one directly from the watchlist.",
 30                        systemImage: "square.stack.3d.up.fill",
 31                        showsCardBackground: false
 32                    )
 33                }
 34                .listRowBackground(Color(.appSurface))
 35            } else {
 36                Section {
 37                    LazyVGrid(columns: summaryColumns, spacing: 10) {
 38                        summaryCard(title: "Total Domains", value: dashboard.snapshot.totalDomains, filter: .all, tint: Color(.statusInfo))
 39                        summaryCard(title: "Healthy", value: dashboard.snapshot.healthyCount, filter: .healthy, tint: Color(.statusPositive))
 40                        summaryCard(title: "Warning", value: dashboard.snapshot.warningCount, filter: .warning, tint: Color(.statusWarning))
 41                        summaryCard(title: "Critical", value: dashboard.snapshot.criticalCount, filter: .critical, tint: Color(.statusCritical))
 42                        summaryCard(title: "Changes (24h)", value: dashboard.snapshot.changedLast24h, filter: .changed, tint: Color(.statusWarning))
 43                        summaryCard(title: "Unreachable", value: dashboard.snapshot.unreachableCount, filter: .unreachable, tint: Color(.statusCritical))
 44                    }
 45                    .padding(.vertical, 4)
 46                }
 47                .listRowBackground(Color(.appSurface))
 48
 49                Section("Quick Filters") {
 50                    ScrollView(.horizontal, showsIndicators: false) {
 51                        HStack(spacing: 8) {
 52                            ForEach(PortfolioFilterOption.allCases) { filter in
 53                                Button {
 54                                    viewModel.dashboardFilter = filter
 55                                } label: {
 56                                    let isSelected = viewModel.dashboardFilter == filter
 57                                    HStack(spacing: 4) {
 58                                        // Selection is a fill-colour change; under
 59                                        // Differentiate Without Color add a
 60                                        // checkmark + border so it does not depend
 61                                        // on hue alone.
 62                                        if isSelected, differentiateWithoutColor {
 63                                            Image(systemName: "checkmark")
 64                                                .font(.caption2.weight(.bold))
 65                                        }
 66                                        Text(filter.title)
 67                                            .font(appDensity.font(.caption, weight: .semibold))
 68                                    }
 69                                    .foregroundStyle(isSelected ? Color(.appOnAccent) : Color.primary)
 70                                    .padding(.horizontal, 12)
 71                                    .padding(.vertical, 8)
 72                                    .background(isSelected ? Color(.statusInfo) : Color(.appSurfaceElevated))
 73                                    .overlay(
 74                                        Capsule().strokeBorder(
 75                                            Color.primary,
 76                                            lineWidth: isSelected && differentiateWithoutColor ? 1.5 : 0
 77                                        )
 78                                    )
 79                                    .clipShape(Capsule())
 80                                }
 81                                .buttonStyle(.plain)
 82                                .accessibilityAddTraits(viewModel.dashboardFilter == filter ? .isSelected : [])
 83                            }
 84                        }
 85                        .padding(.vertical, 4)
 86                    }
 87                }
 88                .listRowBackground(Color(.appSurface))
 89
 90                Section("Recent Activity") {
 91                    if visible.recentActivity.isEmpty {
 92                        dashboardEmptyRow("No recent portfolio changes")
 93                    } else {
 94                        ForEach(visible.recentActivity.prefix(8)) { item in
 95                            trackedDomainLink(item.trackedDomainID) {
 96                                PortfolioActivityRow(item: item)
 97                            }
 98                        }
 99                    }
100                }
101                .listRowBackground(Color(.appSurface))
102
103                Section("Attention Required") {
104                    if visible.attentionRequired.isEmpty {
105                        dashboardEmptyRow("Nothing urgent right now")
106                    } else {
107                        ForEach(visible.attentionRequired.prefix(8)) { item in
108                            trackedDomainLink(item.trackedDomainID) {
109                                PortfolioAttentionRow(item: item)
110                            }
111                        }
112                    }
113                }
114                .listRowBackground(Color(.appSurface))
115
116                Section("Expiring Soon") {
117                    if visible.expiringSoon.isEmpty {
118                        dashboardEmptyRow("No certificates expiring within 30 days")
119                    } else {
120                        ForEach(visible.expiringSoon.prefix(8)) { state in
121                            NavigationLink {
122                                TrackedDomainDetailView(viewModel: viewModel, trackedDomain: state.trackedDomain)
123                            } label: {
124                                PortfolioExpiryRow(state: state)
125                            }
126                            .buttonStyle(.plain)
127                        }
128                    }
129                }
130                .listRowBackground(Color(.appSurface))
131
132                Section("Portfolio List") {
133                    if visible.groups.isEmpty {
134                        dashboardEmptyRow("No domains match the current filter")
135                    } else {
136                        ForEach(visible.groups) { group in
137                            DisclosureGroup(
138                                isExpanded: disclosureBinding(for: group.apexDomain),
139                                content: {
140                                    ForEach(group.domains) { state in
141                                        NavigationLink {
142                                            TrackedDomainDetailView(viewModel: viewModel, trackedDomain: state.trackedDomain)
143                                        } label: {
144                                            WatchlistRowView(
145                                                trackedDomain: state.trackedDomain,
146                                                isRefreshing: viewModel.refreshingTrackedDomainID == state.trackedDomain.id
147                                            )
148                                        }
149                                        .buttonStyle(.plain)
150                                    }
151                                },
152                                label: {
153                                    HStack {
154                                        VStack(alignment: .leading, spacing: 4) {
155                                            Text(group.apexDomain)
156                                                .font(appDensity.font(.headline, design: .default, weight: .semibold))
157                                            Text("\(group.domains.count) domain\(group.domains.count == 1 ? "" : "s")")
158                                                .font(appDensity.font(.caption))
159                                                .foregroundStyle(Color(.appTextSecondary))
160                                        }
161                                        Spacer()
162                                        groupBadge(for: group.domains)
163                                    }
164                                    .padding(.vertical, 4)
165                                }
166                            )
167                        }
168                    }
169                }
170                .listRowBackground(Color(.appSurface))
171            }
172        }
173        .scrollContentBackground(.hidden)
174        .background(Color(.appBackground))
175        .navigationTitle("Dashboard")
176        .searchable(text: $viewModel.dashboardSearchText, prompt: "Search portfolio")
177        .toolbar {
178            if !viewModel.trackedDomains.isEmpty {
179                ToolbarItem(placement: .topBarTrailing) {
180                    Button {
181                        AppHaptics.refresh()
182                        viewModel.refreshAllTrackedDomains()
183                    } label: {
184                        Image(systemName: "arrow.clockwise")
185                    }
186                    .accessibilityLabel("Refresh all tracked domains")
187                    .disabled(viewModel.batchLookupRunning)
188                }
189            }
190
191            // The dashboard reads the portfolio; the watchlist edits it.
192            ToolbarItem(placement: .topBarTrailing) {
193                NavigationLink {
194                    WatchlistView(viewModel: viewModel)
195                } label: {
196                    Label("Watchlist", systemImage: "list.bullet")
197                }
198                .accessibilityLabel("Watchlist")
199            }
200        }
201    }
202
203    private func disclosureBinding(for apexDomain: String) -> Binding<Bool> {
204        Binding(
205            get: { !collapsedGroups.contains(apexDomain) },
206            set: { isExpanded in
207                if isExpanded {
208                    collapsedGroups.remove(apexDomain)
209                } else {
210                    collapsedGroups.insert(apexDomain)
211                }
212            }
213        )
214    }
215
216    private func summaryCard(title: String, value: Int, filter: PortfolioFilterOption, tint: Color) -> some View {
217        Button {
218            viewModel.dashboardFilter = filter
219        } label: {
220            VStack(alignment: .leading, spacing: 8) {
221                Text(title)
222                    .font(appDensity.font(.caption, design: .default, weight: .semibold))
223                    .foregroundStyle(Color(.appTextSecondary))
224                Text("\(value)")
225                    // Was a fixed 28pt, which ignored Dynamic Type entirely.
226                    .font(.system(.title, design: .rounded, weight: .bold))
227                    .foregroundStyle(.primary)
228                HStack(spacing: 5) {
229                    // A symbol under Differentiate Without Color (where a bare
230                    // colour dot conveys nothing), a plain dot otherwise.
231                    if differentiateWithoutColor {
232                        Image(systemName: symbol(for: filter))
233                            .font(.caption2)
234                            .foregroundStyle(tint)
235                    } else {
236                        Circle()
237                            .fill(tint)
238                            .frame(width: 8, height: 8)
239                    }
240                    Text(filter.title)
241                        .font(appDensity.font(.caption2, design: .default, weight: .semibold))
242                        .foregroundStyle(tint)
243                }
244            }
245            .frame(maxWidth: .infinity, alignment: .leading)
246            .padding(appDensity.metrics.cardPadding)
247            .background(cardBackground(for: filter))
248            .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
249        }
250        .buttonStyle(.plain)
251    }
252
253    private func symbol(for filter: PortfolioFilterOption) -> String {
254        switch filter {
255        case .all: return "square.grid.2x2.fill"
256        case .healthy: return "checkmark.circle.fill"
257        case .warning: return "exclamationmark.triangle.fill"
258        case .critical: return "exclamationmark.octagon.fill"
259        case .changed: return "arrow.triangle.2.circlepath"
260        case .expiring: return "clock.badge.exclamationmark.fill"
261        case .unreachable: return "wifi.slash"
262        }
263    }
264
265    private func cardBackground(for filter: PortfolioFilterOption) -> some ShapeStyle {
266        if viewModel.dashboardFilter == filter {
267            // Uses the authored info surface rather than a translucent wash of
268            // the accent. `statusInfo` at 28% over a light background renders
269            // lavender, not blue — an artefact of carrying a dark-only opacity
270            // trick into light mode.
271            return AnyShapeStyle(
272                LinearGradient(
273                    colors: [Color(.statusInfoSurface), Color(.appSurface)],
274                    startPoint: .topLeading,
275                    endPoint: .bottomTrailing
276                )
277            )
278        }
279        return AnyShapeStyle(Color(.appSurfaceElevated))
280    }
281
282    /// `label`, opening the tracked domain's detail; nothing for a domain no longer tracked.
283    @ViewBuilder
284    private func trackedDomainLink<Label: View>(_ id: UUID, @ViewBuilder label: () -> Label) -> some View {
285        if let trackedDomain = viewModel.trackedDomain(withID: id) {
286            NavigationLink {
287                TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
288            } label: {
289                label()
290            }
291            .buttonStyle(.plain)
292        }
293    }
294
295    private func dashboardEmptyRow(_ message: String) -> some View {
296        Text(message)
297            .font(appDensity.font(.caption))
298            .foregroundStyle(Color(.appTextSecondary))
299            .padding(.vertical, 4)
300    }
301
302    private func groupBadge(for states: [PortfolioDomainStatus]) -> some View {
303        let criticalCount = states.filter { $0.health == .critical }.count
304        let warningCount = states.filter { $0.health == .warning }.count
305        let title: String
306        let tone: AppStatusTone
307        let systemImage: String
308
309        if criticalCount > 0 {
310            title = "\(criticalCount) critical"
311            tone = .critical
312            systemImage = "exclamationmark.octagon.fill"
313        } else if warningCount > 0 {
314            title = "\(warningCount) warning"
315            tone = .warning
316            systemImage = "exclamationmark.triangle.fill"
317        } else {
318            title = "Healthy"
319            tone = .positive
320            systemImage = "checkmark.circle.fill"
321        }
322
323        return AppStatusBadgeView(
324            model: .init(
325                title: title,
326                systemImage: systemImage,
327                foregroundColor: tone.foreground,
328                backgroundColor: tone.surface
329            )
330        )
331    }
332}
333
334private struct PortfolioActivityRow: View {
335    @Environment(\.appDensity) private var appDensity
336    let item: PortfolioActivityItem
337
338    var body: some View {
339        HStack(alignment: .top, spacing: 10) {
340            Image(systemName: item.systemImage)
341                .font(.caption.weight(.semibold))
342                .foregroundStyle(iconColor)
343                .frame(width: 22, height: 22)
344                .background(iconColor.opacity(0.14))
345                .clipShape(RoundedRectangle(cornerRadius: 7))
346
347            VStack(alignment: .leading, spacing: 4) {
348                Text(item.message)
349                    .font(appDensity.font(.callout, design: .default))
350                    .foregroundStyle(.primary)
351                HStack(spacing: 8) {
352                    Text(item.domain)
353                    Text(relativeTimestamp(item.timestamp))
354                }
355                .font(appDensity.font(.caption2))
356                .foregroundStyle(Color(.appTextSecondary))
357            }
358        }
359        .padding(.vertical, 4)
360    }
361
362    private var iconColor: Color {
363        switch item.health {
364        case .healthy:
365            return Color(.statusInfo)
366        case .warning:
367            return Color(.statusWarning)
368        case .critical:
369            return Color(.statusCritical)
370        }
371    }
372}
373
374private struct PortfolioAttentionRow: View {
375    @Environment(\.appDensity) private var appDensity
376    let item: PortfolioAttentionItem
377
378    var body: some View {
379        HStack(alignment: .top, spacing: 10) {
380            AppStatusBadgeView(model: badgeModel)
381
382            VStack(alignment: .leading, spacing: 4) {
383                Text(item.domain)
384                    .font(appDensity.font(.callout))
385                    .foregroundStyle(.primary)
386                Text(item.reason)
387                    .font(appDensity.font(.caption, design: .default))
388                    .foregroundStyle(Color(.appTextSecondary))
389                Text(relativeTimestamp(item.timestamp))
390                    .font(appDensity.font(.caption2))
391                    .foregroundStyle(Color(.appTextSecondary))
392            }
393        }
394        .padding(.vertical, 4)
395    }
396
397    private var badgeModel: AppStatusBadgeModel {
398        switch item.health {
399        case .healthy:
400            return .init(title: "Healthy", systemImage: "checkmark.circle.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositiveSurface))
401        case .warning:
402            return .init(title: "Warning", systemImage: "exclamationmark.triangle.fill", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarningSurface))
403        case .critical:
404            return .init(title: "Critical", systemImage: "exclamationmark.octagon.fill", foregroundColor: Color(.statusCritical), backgroundColor: Color(.statusCriticalSurface))
405        }
406    }
407}
408
409private struct PortfolioExpiryRow: View {
410    @Environment(\.appDensity) private var appDensity
411    let state: PortfolioDomainStatus
412
413    var body: some View {
414        // Wide while it fits; stacked at accessibility sizes so the badge does
415        // not letter-wrap beside a long domain.
416        ViewThatFits(in: .horizontal) {
417            HStack {
418                expiryText
419                Spacer()
420                AppStatusBadgeView(model: badgeModel)
421            }
422            VStack(alignment: .leading, spacing: 6) {
423                expiryText
424                AppStatusBadgeView(model: badgeModel)
425            }
426        }
427        .padding(.vertical, 4)
428    }
429
430    private var expiryText: some View {
431        VStack(alignment: .leading, spacing: 4) {
432            Text(state.trackedDomain.domain)
433                .font(appDensity.font(.callout))
434                .foregroundStyle(.primary)
435            Text(expirySubtitle)
436                .font(appDensity.font(.caption))
437                .foregroundStyle(Color(.appTextSecondary))
438        }
439    }
440
441    private var expirySubtitle: String {
442        if let days = state.certificateDaysRemaining {
443            return "Expires in \(days) day\(days == 1 ? "" : "s")"
444        }
445        return "Certificate needs review"
446    }
447
448    private var badgeModel: AppStatusBadgeModel {
449        switch state.certificateExpiryState {
450        case .none:
451            return .init(title: "Healthy", systemImage: "lock.fill", foregroundColor: Color(.statusPositive), backgroundColor: Color(.statusPositiveSurface))
452        case .warning:
453            return .init(title: "Warning", systemImage: "exclamationmark.triangle.fill", foregroundColor: Color(.statusWarning), backgroundColor: Color(.statusWarningSurface))
454        case .critical:
455            return .init(title: "Critical", systemImage: "xmark.octagon.fill", foregroundColor: Color(.statusCritical), backgroundColor: Color(.statusCriticalSurface))
456        }
457    }
458}
459
460private func relativeTimestamp(_ date: Date) -> String {
461    let formatter = RelativeDateTimeFormatter()
462    formatter.unitsStyle = .short
463    return formatter.localizedString(for: date, relativeTo: Date())
464}