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