DomainDig/HistoryView.swift
431 lines · 19992 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(.systemGray6).opacity(0.5))
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(.secondary)
44 }
45
46 Text(item.latest.changeSummaryMessage ?? "No change summary")
47 .font(appDensity.font(.caption))
48 .foregroundStyle(.secondary)
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 ? .red : .yellow,
59 backgroundColor: (severity == .high ? Color.red : .yellow).opacity(0.16)
60 )
61 )
62 }
63 }
64 }
65 }
66 .listRowBackground(Color(.systemGray6).opacity(0.5))
67 }
68 }
69 }
70 }
71 .scrollContentBackground(.hidden)
72 .background(Color.black)
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
110 EditButton()
111 }
112 }
113 }
114 .alert("Clear history?", isPresented: $showClearAllConfirmation) {
115 Button("Clear All", role: .destructive) {
116 viewModel.clearHistory()
117 }
118 Button("Cancel", role: .cancel) {}
119 } message: {
120 Text("This will delete all saved history entries. This cannot be undone.")
121 }
122 .sheet(isPresented: $showWorkflowAddSheet) {
123 WorkflowBulkAddSheet(
124 viewModel: viewModel,
125 title: "Add History Domains",
126 availableDomains: Array(Set(viewModel.filteredHistory.map(\.domain))).sorted()
127 )
128 }
129 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
130 dismiss()
131 }
132 .preferredColorScheme(.dark)
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(from: entry, previousSnapshot: viewModel.comparisonSnapshot(for: entry))
163 }
164
165 private var trackedDomain: TrackedDomain? {
166 viewModel.trackedDomains.first { $0.domain.caseInsensitiveCompare(entry.domain) == .orderedSame }
167 }
168
169 var body: some View {
170 ScrollView(.vertical) {
171 VStack(alignment: .leading, spacing: 0) {
172 snapshotBanner
173 SummaryView(fields: DomainViewModel.summaryFields(from: snapshot))
174 .padding(.top, 8)
175 RiskSummaryCardView(report: report)
176 .padding(.top, 8)
177 InsightsSummaryCardView(insights: report.insights)
178 .padding(.top, 8)
179 DomainSectionView(
180 isCollapsed: .constant(false),
181 rows: DomainViewModel.domainRows(from: snapshot),
182 suggestions: DomainViewModel.suggestionRows(from: snapshot),
183 showSuggestions: entry.availabilityResult?.status == .registered && !entry.suggestions.isEmpty,
184 availabilityLoading: false,
185 suggestionsLoading: false,
186 provenance: snapshot.provenanceBySection[.availability],
187 confidence: snapshot.availabilityConfidence,
188 snapshotNote: entry.note,
189 trackedDomain: trackedDomain,
190 workflows: viewModel.workflowsContaining(domain: entry.domain),
191 trackingLimitMessage: nil,
192 pricingLoading: false,
193 pricingError: snapshot.domainPricingError,
194 showsPricingPlaceholder: !DataAccessService.hasAccess(to: .domainPricing),
195 onTrack: {
196 _ = viewModel.trackDomain(domain: entry.domain, availabilityStatus: entry.availabilityResult?.status)
197 },
198 onTogglePinned: {
199 guard let trackedDomain else { return }
200 viewModel.togglePinned(for: trackedDomain)
201 },
202 onEditNote: nil,
203 onAddToWorkflow: nil,
204 onOpenWorkflow: nil,
205 onRunWorkflow: nil
206 )
207 .padding(.top, appDensity.metrics.sectionSpacing)
208 OwnershipSectionView(
209 isCollapsed: .constant(false),
210 rows: DomainViewModel.ownershipRows(from: snapshot),
211 loading: false,
212 error: snapshot.ownershipError,
213 provenance: snapshot.provenanceBySection[.ownership],
214 confidence: snapshot.ownershipConfidence,
215 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory)
216 )
217 .padding(.top, appDensity.metrics.sectionSpacing)
218 SubdomainsSectionView(
219 isCollapsed: .constant(false),
220 rows: DomainViewModel.subdomainRows(from: snapshot),
221 groups: report.subdomainGroups,
222 loading: false,
223 error: snapshot.subdomainsError,
224 provenance: snapshot.provenanceBySection[.subdomains],
225 confidence: snapshot.subdomainConfidence,
226 showsExtendedPlaceholder: !DataAccessService.hasAccess(to: .extendedSubdomains)
227 )
228 .padding(.top, appDensity.metrics.sectionSpacing)
229 if let comparisonSnapshot = viewModel.comparisonSnapshot(for: entry) {
230 if let changeSummary = entry.changeSummary {
231 DomainChangeSummaryView(summary: changeSummary)
232 .padding(.top, appDensity.metrics.sectionSpacing)
233 }
234 DomainDiffView(
235 title: "Compared With Previous Snapshot",
236 sections: DomainDiffService.diff(from: comparisonSnapshot, to: snapshot),
237 contextNote: DomainDiffService.comparisonContextNote(from: comparisonSnapshot, to: snapshot),
238 showsUnchanged: false,
239 highlightedSectionID: nil
240 )
241 .padding(.top, appDensity.metrics.sectionSpacing)
242 }
243 DNSSectionView(
244 isCollapsed: .constant(false),
245 dnssecLabel: DomainViewModel.dnssecLabel(from: snapshot),
246 patternSummary: report.dns.patternSummary,
247 sections: DomainViewModel.dnsRows(from: snapshot),
248 ptrMessage: DomainViewModel.ptrMessage(from: snapshot),
249 loading: false,
250 dnsProvenance: snapshot.provenanceBySection[.dns],
251 ptrProvenance: snapshot.provenanceBySection[.ptr],
252 sectionError: snapshot.dnsError
253 )
254 .padding(.top, appDensity.metrics.sectionSpacing)
255 WebSectionView(
256 isCollapsed: .constant(false),
257 certificateRows: DomainViewModel.webCertificateRows(from: snapshot),
258 sslInfo: snapshot.sslInfo,
259 tlsSummary: report.web,
260 sslLoading: false,
261 sslError: snapshot.sslError,
262 tlsProvenance: snapshot.provenanceBySection[.ssl],
263 responseRows: DomainViewModel.webResponseRows(from: snapshot),
264 headers: snapshot.httpHeaders,
265 headersLoading: false,
266 headersError: snapshot.httpHeadersError,
267 httpProvenance: snapshot.provenanceBySection[.httpHeaders],
268 redirects: DomainViewModel.redirectRows(from: snapshot),
269 redirectLoading: false,
270 redirectError: snapshot.redirectChainError,
271 redirectProvenance: snapshot.provenanceBySection[.redirectChain],
272 finalURL: snapshot.redirectChain.last?.url
273 )
274 .padding(.top, appDensity.metrics.sectionSpacing)
275 EmailSectionView(
276 isCollapsed: .constant(false),
277 rows: DomainViewModel.emailRows(from: snapshot),
278 assessment: report.email,
279 loading: false,
280 provenance: snapshot.provenanceBySection[.emailSecurity],
281 confidence: snapshot.emailSecurityConfidence,
282 error: snapshot.emailSecurityError
283 )
284 .padding(.top, appDensity.metrics.sectionSpacing)
285 NetworkSectionView(
286 isCollapsed: .constant(false),
287 reachabilityRows: DomainViewModel.reachabilityRows(from: snapshot),
288 reachabilityLoading: false,
289 reachabilityError: snapshot.reachabilityError,
290 reachabilityProvenance: snapshot.provenanceBySection[.reachability],
291 locationRows: DomainViewModel.locationRows(from: snapshot),
292 geolocation: snapshot.ipGeolocation,
293 geolocationLoading: false,
294 geolocationError: snapshot.ipGeolocationError,
295 geolocationProvenance: snapshot.provenanceBySection[.ipGeolocation],
296 geolocationConfidence: snapshot.geolocationConfidence,
297 standardPortRows: DomainViewModel.portRows(from: snapshot, kind: .standard),
298 customPortRows: DomainViewModel.portRows(from: snapshot, kind: .custom),
299 portScanLoading: false,
300 portScanError: snapshot.portScanError,
301 portScanProvenance: snapshot.provenanceBySection[.portScan],
302 customPortScanLoading: false,
303 customPortScanError: nil,
304 isCloudflareProxied: snapshot.httpHeaders.contains(where: { $0.name.lowercased() == "cf-ray" }),
305 customPortsExpanded: .constant(false),
306 customPortInput: .constant(""),
307 onScanCustomPorts: {}
308 )
309 .padding(.top, appDensity.metrics.sectionSpacing)
310 }
311 .padding(.horizontal)
312 .padding(.bottom, 32)
313 }
314 .background(Color.black)
315 .navigationTitle(entry.domain)
316 .toolbar {
317 ToolbarItemGroup(placement: .topBarTrailing) {
318 Button("Note") {
319 noteDraft = entry.note ?? ""
320 isEditingNote = true
321 }
322 Button("Re-run") {
323 showRerunOptions = true
324 }
325 }
326 }
327 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
328 dismiss()
329 }
330 .confirmationDialog("Re-run lookup", isPresented: $showRerunOptions) {
331 Button("Run with Current Settings") {
332 viewModel.rerunLookup(from: entry, useSnapshotResolver: false)
333 }
334 Button("Run with Snapshot Resolver") {
335 viewModel.rerunLookup(from: entry, useSnapshotResolver: true)
336 }
337 Button("Cancel", role: .cancel) {}
338 } message: {
339 Text(viewModel.resolverMismatchNote(for: entry) ?? "Choose how to reproduce this snapshot.")
340 }
341 .sheet(isPresented: $isEditingNote) {
342 NavigationStack {
343 Form {
344 Section("Audit Note") {
345 TextField("Optional note", text: $noteDraft, axis: .vertical)
346 .lineLimit(3...6)
347 }
348 }
349 .navigationTitle(entry.domain)
350 .toolbar {
351 ToolbarItem(placement: .cancellationAction) {
352 Button("Cancel") {
353 isEditingNote = false
354 }
355 }
356 ToolbarItem(placement: .confirmationAction) {
357 Button("Save") {
358 viewModel.updateHistoryNote(noteDraft, for: entry)
359 isEditingNote = false
360 }
361 }
362 }
363 }
364 }
365 .preferredColorScheme(.dark)
366 }
367
368 private var snapshotBanner: some View {
369 VStack(alignment: .leading, spacing: 8) {
370 HStack(spacing: 8) {
371 Image(systemName: "archivebox")
372 .font(.caption)
373 Text("Snapshot from \(dateFormatter.string(from: entry.timestamp))")
374 .font(appDensity.font(.caption))
375 Spacer()
376 Text("Live re-run available")
377 .font(appDensity.font(.caption2))
378 .foregroundStyle(.secondary)
379 }
380 if let mismatchNote = viewModel.resolverMismatchNote(for: entry) {
381 Text(mismatchNote)
382 .font(appDensity.font(.caption2))
383 .foregroundStyle(.orange)
384 }
385 if entry.isPartialSnapshot {
386 Text("Partial snapshot: \(entry.validationIssues.joined(separator: " | "))")
387 .font(appDensity.font(.caption2))
388 .foregroundStyle(.yellow)
389 }
390 if let note = entry.note, !note.isEmpty {
391 Text(note)
392 .font(appDensity.font(.caption2))
393 .foregroundStyle(.secondary)
394 }
395 }
396 .foregroundStyle(.secondary)
397 .padding(8)
398 .frame(maxWidth: .infinity, alignment: .leading)
399 .background(Color(.systemGray6).opacity(0.3))
400 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
401 .padding(.vertical, 12)
402 }
403}
404
405private struct HistoryGroup: Identifiable {
406 let title: String
407 let entries: [HistoryEntry]
408
409 var id: String { title }
410
411 static func groups(for entries: [HistoryEntry]) -> [HistoryGroup] {
412 let calendar = Calendar.current
413 let today = Date()
414 let yesterday = calendar.date(byAdding: .day, value: -1, to: today) ?? today
415
416 let grouped = Dictionary(grouping: entries) { entry -> String in
417 if calendar.isDate(entry.timestamp, inSameDayAs: today) {
418 return "Today"
419 }
420 if calendar.isDate(entry.timestamp, inSameDayAs: yesterday) {
421 return "Yesterday"
422 }
423 return "Older"
424 }
425
426 return ["Today", "Yesterday", "Older"].compactMap { title in
427 guard let entries = grouped[title], !entries.isEmpty else { return nil }
428 return HistoryGroup(title: title, entries: entries)
429 }
430 }
431}