DomainDig/DashboardView.swift

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