DomainDig/HistoryView.swift
436 lines · 20325 bytes
1import SwiftUI
2
3struct HistoryView: View {
4 @Environment(\.appDensity) private var appDensity
5 @Bindable var viewModel: DomainViewModel
6 @Environment(\.dismiss) private var dismiss
7 @State private var showClearAllConfirmation = false
8 @State private var showWorkflowAddSheet = false
9
10 private var domainSummaries: [(domain: String, latest: SnapshotSummary, count: Int)] {
11 viewModel.timelineDomains.compactMap { domain in
12 let entries = viewModel.timelineEntries(for: domain)
13 guard let latest = entries.first else { return nil }
14 return (domain, latest, entries.count)
15 }
16 }
17
18 var body: some View {
19 List {
20 if viewModel.filteredHistory.isEmpty {
21 EmptyStateCardView(
22 title: "No History Yet",
23 message: "History stores local snapshots of previous inspections so you can revisit and compare them later.",
24 suggestion: "Run a lookup to create your first saved snapshot.",
25 systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90",
26 showsCardBackground: false
27 )
28 .listRowBackground(Color(.appSurface))
29 } else {
30 Section("Domains") {
31 ForEach(domainSummaries, id: \.domain) { item in
32 NavigationLink {
33 TimelineView(viewModel: viewModel, domain: item.domain)
34 } label: {
35 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing + 1) {
36 HStack(alignment: .center, spacing: 8) {
37 Text(item.domain)
38 .font(appDensity.font(.callout))
39 .foregroundStyle(.primary)
40 Spacer()
41 Text("\(item.count) snapshots")
42 .font(appDensity.font(.caption2))
43 .foregroundStyle(Color(.appTextSecondary))
44 }
45
46 Text(item.latest.changeSummaryMessage ?? "No change summary")
47 .font(appDensity.font(.caption))
48 .foregroundStyle(Color(.appTextSecondary))
49 .lineLimit(2)
50
51 HStack(spacing: 8) {
52 AppStatusBadgeView(model: AppStatusFactory.availability(item.latest.availability))
53 if let severity = item.latest.severitySummary {
54 AppStatusBadgeView(
55 model: .init(
56 title: severity.title,
57 systemImage: "arrow.triangle.2.circlepath",
58 foregroundColor: severity == .high ? Color(.statusCritical) : Color(.statusWarning),
59 backgroundColor: (severity == .high ? AppStatusTone.critical : .warning).surface
60 )
61 )
62 }
63 }
64 }
65 }
66 .listRowBackground(Color(.appSurface))
67 }
68 }
69 }
70 }
71 .scrollContentBackground(.hidden)
72 .background(Color(.appBackground))
73 .navigationTitle("History")
74 .searchable(text: $viewModel.timelineDomainFilter, prompt: "Search domains")
75 .toolbar {
76 if !viewModel.history.isEmpty {
77 ToolbarItemGroup(placement: .topBarTrailing) {
78 Menu {
79 Picker("Date Range", selection: $viewModel.historyDateFilter) {
80 ForEach(HistoryDateFilter.allCases) { option in
81 Text(option.title).tag(option)
82 }
83 }
84
85 Picker("Change Filter", selection: $viewModel.historyChangeFilter) {
86 ForEach(ChangeFilterOption.allCases) { option in
87 Text(option.title).tag(option)
88 }
89 }
90
91 Picker("Sort", selection: $viewModel.historySortOption) {
92 ForEach(HistorySortOption.allCases) { option in
93 Text(option.title).tag(option)
94 }
95 }
96
97 Button("Clear All", role: .destructive) {
98 showClearAllConfirmation = true
99 }
100
101 if !viewModel.filteredHistory.isEmpty {
102 Button("Add to Workflow") {
103 showWorkflowAddSheet = true
104 }
105 }
106 } label: {
107 Image(systemName: "line.3.horizontal.decrease.circle")
108 }
109 .accessibilityLabel("Filter")
110
111 EditButton()
112 }
113 }
114 }
115 .alert("Clear history?", isPresented: $showClearAllConfirmation) {
116 Button("Clear All", role: .destructive) {
117 viewModel.clearHistory()
118 }
119 Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
120 } message: {
121 Text("This will delete all saved history entries. This cannot be undone.")
122 }
123 .sheet(isPresented: $showWorkflowAddSheet) {
124 WorkflowBulkAddSheet(
125 viewModel: viewModel,
126 title: "Add History Domains",
127 availableDomains: Array(Set(viewModel.filteredHistory.map(\.domain))).sorted()
128 )
129 }
130 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
131 dismiss()
132 }
133 }
134
135 private func deleteFilteredHistoryEntries(at offsets: IndexSet) {
136 let ids = offsets.map { viewModel.filteredHistory[$0].id }
137 viewModel.removeHistoryEntries(withIDs: ids)
138 }
139}
140
141struct HistoryDetailView: View {
142 @Environment(\.appDensity) private var appDensity
143 @Bindable var viewModel: DomainViewModel
144 let entry: HistoryEntry
145 @Environment(\.dismiss) private var dismiss
146 @State private var noteDraft = ""
147 @State private var isEditingNote = false
148 @State private var showRerunOptions = false
149
150 private let dateFormatter: DateFormatter = {
151 let formatter = DateFormatter()
152 formatter.dateStyle = .medium
153 formatter.timeStyle = .short
154 return formatter
155 }()
156
157 private var snapshot: LookupSnapshot {
158 entry.snapshot
159 }
160
161 private var report: DomainReport {
162 DomainReportBuilder().build(
163 from: entry,
164 previousSnapshot: viewModel.comparisonSnapshot(for: entry),
165 historyEntries: viewModel.historyEntries(for: entry.domain)
166 )
167 }
168
169 private var trackedDomain: TrackedDomain? {
170 viewModel.trackedDomains.first { $0.domain.caseInsensitiveCompare(entry.domain) == .orderedSame }
171 }
172
173 var body: some View {
174 ScrollView(.vertical) {
175 VStack(alignment: .leading, spacing: 0) {
176 snapshotBanner
177 SummaryView(fields: DomainViewModel.summaryFields(from: snapshot))
178 .padding(.top, 8)
179 RiskSummaryCardView(report: report)
180 .padding(.top, 8)
181 InsightsSummaryCardView(insights: report.insights)
182 .padding(.top, 8)
183 IntelligenceSectionView(
184 isCollapsed: .constant(false),
185 report: report,
186 showsPlaceholder: !FeatureAccessService.hasAccess(to: .intelligenceDetail)
187 )
188 .padding(.top, 8)
189 DomainSectionView(
190 isCollapsed: .constant(false),
191 rows: DomainViewModel.domainRows(from: snapshot),
192 suggestions: DomainViewModel.suggestionRows(from: snapshot),
193 showSuggestions: entry.availabilityResult?.status == .registered && !entry.suggestions.isEmpty,
194 availabilityLoading: false,
195 suggestionsLoading: false,
196 provenance: snapshot.provenanceBySection[.availability],
197 confidence: snapshot.availabilityConfidence,
198 snapshotNote: entry.note,
199 trackedDomain: trackedDomain,
200 workflows: viewModel.workflowsContaining(domain: entry.domain),
201 trackingLimitMessage: nil,
202 onTrack: {
203 _ = viewModel.trackDomain(domain: entry.domain, availabilityStatus: entry.availabilityResult?.status)
204 },
205 onTogglePinned: {
206 guard let trackedDomain else { return }
207 viewModel.togglePinned(for: trackedDomain)
208 },
209 onEditNote: nil,
210 onAddToWorkflow: nil,
211 onOpenWorkflow: nil,
212 onRunWorkflow: nil
213 )
214 .padding(.top, appDensity.metrics.sectionSpacing)
215 OwnershipSectionView(
216 isCollapsed: .constant(false),
217 rows: DomainViewModel.ownershipRows(from: snapshot),
218 loading: false,
219 error: snapshot.ownershipError,
220 provenance: snapshot.provenanceBySection[.ownership],
221 confidence: snapshot.ownershipConfidence
222 )
223 .padding(.top, appDensity.metrics.sectionSpacing)
224 SubdomainsSectionView(
225 isCollapsed: .constant(false),
226 rows: DomainViewModel.subdomainRows(from: snapshot),
227 groups: report.subdomainGroups,
228 loading: false,
229 error: snapshot.subdomainsError,
230 provenance: snapshot.provenanceBySection[.subdomains],
231 confidence: snapshot.subdomainConfidence,
232 showsExtendedPlaceholder: !FeatureAccessService.hasAccess(to: .extendedSubdomains)
233 )
234 .padding(.top, appDensity.metrics.sectionSpacing)
235 if let comparisonSnapshot = viewModel.comparisonSnapshot(for: entry) {
236 if let changeSummary = entry.changeSummary {
237 DomainChangeSummaryView(summary: changeSummary)
238 .padding(.top, appDensity.metrics.sectionSpacing)
239 }
240 DomainDiffView(
241 title: "Compared With Previous Snapshot",
242 sections: DomainDiffService.diff(from: comparisonSnapshot, to: snapshot),
243 contextNote: DomainDiffService.comparisonContextNote(from: comparisonSnapshot, to: snapshot),
244 showsUnchanged: false,
245 highlightedSectionID: nil
246 )
247 .padding(.top, appDensity.metrics.sectionSpacing)
248 }
249 DNSSectionView(
250 isCollapsed: .constant(false),
251 dnssecLabel: DomainViewModel.dnssecLabel(from: snapshot),
252 patternSummary: report.dns.patternSummary,
253 sections: DomainViewModel.dnsRows(from: snapshot),
254 ptrMessage: DomainViewModel.ptrMessage(from: snapshot),
255 loading: false,
256 dnsProvenance: snapshot.provenanceBySection[.dns],
257 ptrProvenance: snapshot.provenanceBySection[.ptr],
258 sectionError: snapshot.dnsError
259 )
260 .padding(.top, appDensity.metrics.sectionSpacing)
261 WebSectionView(
262 isCollapsed: .constant(false),
263 certificateRows: DomainViewModel.webCertificateRows(from: snapshot),
264 sslInfo: snapshot.sslInfo,
265 tlsSummary: report.web,
266 sslLoading: false,
267 sslError: snapshot.sslError,
268 tlsProvenance: snapshot.provenanceBySection[.ssl],
269 responseRows: DomainViewModel.webResponseRows(from: snapshot),
270 headers: snapshot.httpHeaders,
271 headersLoading: false,
272 headersError: snapshot.httpHeadersError,
273 httpProvenance: snapshot.provenanceBySection[.httpHeaders],
274 redirects: DomainViewModel.redirectRows(from: snapshot),
275 redirectLoading: false,
276 redirectError: snapshot.redirectChainError,
277 redirectProvenance: snapshot.provenanceBySection[.redirectChain],
278 finalURL: snapshot.redirectChain.last?.url
279 )
280 .padding(.top, appDensity.metrics.sectionSpacing)
281 EmailSectionView(
282 isCollapsed: .constant(false),
283 rows: DomainViewModel.emailRows(from: snapshot),
284 assessment: report.email,
285 loading: false,
286 provenance: snapshot.provenanceBySection[.emailSecurity],
287 confidence: snapshot.emailSecurityConfidence,
288 error: snapshot.emailSecurityError
289 )
290 .padding(.top, appDensity.metrics.sectionSpacing)
291 NetworkSectionView(
292 isCollapsed: .constant(false),
293 reachabilityRows: DomainViewModel.reachabilityRows(from: snapshot),
294 reachabilityLoading: false,
295 reachabilityError: snapshot.reachabilityError,
296 reachabilityProvenance: snapshot.provenanceBySection[.reachability],
297 locationRows: DomainViewModel.locationRows(from: snapshot),
298 geolocation: snapshot.ipGeolocation,
299 geolocationLoading: false,
300 geolocationError: snapshot.ipGeolocationError,
301 geolocationProvenance: snapshot.provenanceBySection[.ipGeolocation],
302 geolocationConfidence: snapshot.geolocationConfidence,
303 standardPortRows: DomainViewModel.portRows(from: snapshot, kind: .standard),
304 customPortRows: DomainViewModel.portRows(from: snapshot, kind: .custom),
305 portScanLoading: false,
306 portScanError: snapshot.portScanError,
307 portScanProvenance: snapshot.provenanceBySection[.portScan],
308 customPortScanLoading: false,
309 customPortScanError: nil,
310 isCloudflareProxied: snapshot.httpHeaders.contains(where: { $0.name.lowercased() == "cf-ray" }),
311 customPortsExpanded: .constant(false),
312 customPortInput: .constant(""),
313 onScanCustomPorts: { /* Historical snapshot; re-scanning is not offered here. */ }
314 )
315 .padding(.top, appDensity.metrics.sectionSpacing)
316 }
317 .padding(.horizontal)
318 .padding(.bottom, 32)
319 }
320 .background(Color(.appBackground))
321 .navigationTitle(entry.domain)
322 .toolbar {
323 ToolbarItemGroup(placement: .topBarTrailing) {
324 Button("Note") {
325 noteDraft = entry.note ?? ""
326 isEditingNote = true
327 }
328 Button("Re-run") {
329 showRerunOptions = true
330 }
331 }
332 }
333 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
334 dismiss()
335 }
336 .confirmationDialog("Re-run lookup", isPresented: $showRerunOptions) {
337 Button("Run with Current Settings") {
338 viewModel.rerunLookup(from: entry, useSnapshotResolver: false)
339 }
340 Button("Run with Snapshot Resolver") {
341 viewModel.rerunLookup(from: entry, useSnapshotResolver: true)
342 }
343 Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
344 } message: {
345 Text(viewModel.resolverMismatchNote(for: entry) ?? "Choose how to reproduce this snapshot.")
346 }
347 .sheet(isPresented: $isEditingNote) {
348 NavigationStack {
349 Form {
350 Section("Audit Note") {
351 TextField("Optional note", text: $noteDraft, axis: .vertical)
352 .lineLimit(3...6)
353 }
354 }
355 .navigationTitle(entry.domain)
356 .toolbar {
357 ToolbarItem(placement: .cancellationAction) {
358 Button("Cancel") {
359 isEditingNote = false
360 }
361 }
362 ToolbarItem(placement: .confirmationAction) {
363 Button("Save") {
364 viewModel.updateHistoryNote(noteDraft, for: entry)
365 isEditingNote = false
366 }
367 }
368 }
369 }
370 }
371 }
372
373 private var snapshotBanner: some View {
374 VStack(alignment: .leading, spacing: 8) {
375 HStack(spacing: 8) {
376 Image(systemName: "archivebox")
377 .font(.caption)
378 Text("Snapshot from \(dateFormatter.string(from: entry.timestamp))")
379 .font(appDensity.font(.caption))
380 Spacer()
381 Text("Live re-run available")
382 .font(appDensity.font(.caption2))
383 .foregroundStyle(Color(.appTextSecondary))
384 }
385 if let mismatchNote = viewModel.resolverMismatchNote(for: entry) {
386 Text(mismatchNote)
387 .font(appDensity.font(.caption2))
388 .foregroundStyle(Color(.statusWarning))
389 }
390 if entry.isPartialSnapshot {
391 Text("Partial snapshot: \(entry.validationIssues.joined(separator: " | "))")
392 .font(appDensity.font(.caption2))
393 .foregroundStyle(Color(.statusWarning))
394 }
395 if let note = entry.note, !note.isEmpty {
396 Text(note)
397 .font(appDensity.font(.caption2))
398 .foregroundStyle(Color(.appTextSecondary))
399 }
400 }
401 .foregroundStyle(Color(.appTextSecondary))
402 .padding(8)
403 .frame(maxWidth: .infinity, alignment: .leading)
404 .background(Color(.appSurface))
405 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
406 .padding(.vertical, 12)
407 }
408}
409
410private struct HistoryGroup: Identifiable {
411 let title: String
412 let entries: [HistoryEntry]
413
414 var id: String { title }
415
416 static func groups(for entries: [HistoryEntry]) -> [HistoryGroup] {
417 let calendar = Calendar.current
418 let today = Date()
419 let yesterday = calendar.date(byAdding: .day, value: -1, to: today) ?? today
420
421 let grouped = Dictionary(grouping: entries) { entry -> String in
422 if calendar.isDate(entry.timestamp, inSameDayAs: today) {
423 return "Today"
424 }
425 if calendar.isDate(entry.timestamp, inSameDayAs: yesterday) {
426 return "Yesterday"
427 }
428 return "Older"
429 }
430
431 return ["Today", "Yesterday", "Older"].compactMap { title in
432 guard let entries = grouped[title], !entries.isEmpty else { return nil }
433 return HistoryGroup(title: title, entries: entries)
434 }
435 }
436}