DomainDig/DashboardView.swift

2ad5d8160338d289a65d6a4d1c214a02bf916f1f
domain-dig/DomainDig/DashboardView.swift history · blame · raw

467 lines · 20600 bytes

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