DomainDig/HistoryView.swift
418 lines · 18436 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 List {
175 Section {
176 snapshotBanner
177 }
178 Section {
179 SummaryView(fields: DomainViewModel.summaryFields(from: snapshot))
180 }
181 Section {
182 RiskSummaryCardView(report: report)
183 }
184 Section {
185 InsightsSummaryCardView(insights: report.insights)
186 }
187 Section {
188 IntelligenceSectionView(
189 isCollapsed: .constant(false),
190 report: report,
191 showsPlaceholder: !FeatureAccessService.hasAccess(to: .intelligenceDetail)
192 )
193 }
194 Section {
195 DomainSectionView(
196 isCollapsed: .constant(false),
197 rows: DomainViewModel.domainRows(from: snapshot),
198 suggestions: DomainViewModel.suggestionRows(from: snapshot),
199 showSuggestions: entry.availabilityResult?.status == .registered && !entry.suggestions.isEmpty,
200 availabilityLoading: false,
201 suggestionsLoading: false,
202 provenance: snapshot.provenanceBySection[.availability],
203 confidence: snapshot.availabilityConfidence,
204 snapshotNote: entry.note,
205 trackedDomain: trackedDomain,
206 workflows: viewModel.workflowsContaining(domain: entry.domain),
207 trackingLimitMessage: nil,
208 onTrack: {
209 _ = viewModel.trackDomain(domain: entry.domain, availabilityStatus: entry.availabilityResult?.status)
210 },
211 onTogglePinned: {
212 guard let trackedDomain else { return }
213 viewModel.togglePinned(for: trackedDomain)
214 },
215 onEditNote: nil,
216 onAddToWorkflow: nil,
217 onOpenWorkflow: nil,
218 onRunWorkflow: nil
219 )
220 }
221 Section {
222 OwnershipSectionView(
223 isCollapsed: .constant(false),
224 rows: DomainViewModel.ownershipRows(from: snapshot),
225 loading: false,
226 error: snapshot.ownershipError,
227 provenance: snapshot.provenanceBySection[.ownership],
228 confidence: snapshot.ownershipConfidence
229 )
230 }
231 Section {
232 SubdomainsSectionView(
233 isCollapsed: .constant(false),
234 rows: DomainViewModel.subdomainRows(from: snapshot),
235 groups: report.subdomainGroups,
236 loading: false,
237 error: snapshot.subdomainsError,
238 provenance: snapshot.provenanceBySection[.subdomains],
239 confidence: snapshot.subdomainConfidence,
240 showsExtendedPlaceholder: !FeatureAccessService.hasAccess(to: .extendedSubdomains)
241 )
242 }
243 if let comparisonSnapshot = viewModel.comparisonSnapshot(for: entry) {
244 if let changeSummary = entry.changeSummary {
245 Section {
246 DomainChangeSummaryView(summary: changeSummary)
247 }
248 }
249 Section {
250 DomainDiffView(
251 title: "Compared With Previous Snapshot",
252 sections: DomainDiffService.diff(from: comparisonSnapshot, to: snapshot),
253 contextNote: DomainDiffService.comparisonContextNote(from: comparisonSnapshot, to: snapshot),
254 showsUnchanged: false,
255 highlightedSectionID: nil
256 )
257 }
258 }
259 Section {
260 DNSSectionView(
261 isCollapsed: .constant(false),
262 dnssecLabel: DomainViewModel.dnssecLabel(from: snapshot),
263 patternSummary: report.dns.patternSummary,
264 sections: DomainViewModel.dnsRows(from: snapshot),
265 ptrMessage: DomainViewModel.ptrMessage(from: snapshot),
266 loading: false,
267 dnsProvenance: snapshot.provenanceBySection[.dns],
268 ptrProvenance: snapshot.provenanceBySection[.ptr],
269 sectionError: snapshot.dnsError
270 )
271 }
272 Section {
273 WebSectionView(
274 isCollapsed: .constant(false),
275 data: DomainViewModel.webSectionData(from: snapshot, report: report)
276 )
277 }
278 Section {
279 EmailSectionView(
280 isCollapsed: .constant(false),
281 rows: DomainViewModel.emailRows(from: snapshot),
282 assessment: report.email,
283 loading: false,
284 provenance: snapshot.provenanceBySection[.emailSecurity],
285 confidence: snapshot.emailSecurityConfidence,
286 error: snapshot.emailSecurityError
287 )
288 }
289 Section {
290 NetworkSectionView(
291 isCollapsed: .constant(false),
292 customPortsExpanded: .constant(false),
293 customPortInput: .constant(""),
294 data: DomainViewModel.networkSectionData(from: snapshot),
295 onScanCustomPorts: { /* Historical snapshot; re-scanning is not offered here. */ }
296 )
297 }
298 }
299 .listRowBackground(Color(.appSurface))
300 .environment(\.cardProvidesSurface, false)
301 .scrollContentBackground(.hidden)
302 .background(Color(.appBackground))
303 .navigationTitle(entry.domain)
304 .toolbar {
305 ToolbarItemGroup(placement: .topBarTrailing) {
306 Button("Note") {
307 noteDraft = entry.note ?? ""
308 isEditingNote = true
309 }
310 Button("Re-run") {
311 showRerunOptions = true
312 }
313 }
314 }
315 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
316 dismiss()
317 }
318 .confirmationDialog("Re-run lookup", isPresented: $showRerunOptions) {
319 Button("Run with Current Settings") {
320 viewModel.rerunLookup(from: entry, useSnapshotResolver: false)
321 }
322 Button("Run with Snapshot Resolver") {
323 viewModel.rerunLookup(from: entry, useSnapshotResolver: true)
324 }
325 Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
326 } message: {
327 Text(viewModel.resolverMismatchNote(for: entry) ?? "Choose how to reproduce this snapshot.")
328 }
329 .sheet(isPresented: $isEditingNote) {
330 NavigationStack {
331 Form {
332 Section("Audit Note") {
333 TextField("Optional note", text: $noteDraft, axis: .vertical)
334 .lineLimit(3...6)
335 }
336 }
337 .navigationTitle(entry.domain)
338 .toolbar {
339 ToolbarItem(placement: .cancellationAction) {
340 Button("Cancel") {
341 isEditingNote = false
342 }
343 }
344 ToolbarItem(placement: .confirmationAction) {
345 Button("Save") {
346 viewModel.updateHistoryNote(noteDraft, for: entry)
347 isEditingNote = false
348 }
349 }
350 }
351 }
352 }
353 }
354
355 private var snapshotBanner: some View {
356 VStack(alignment: .leading, spacing: 8) {
357 HStack(spacing: 8) {
358 Image(systemName: "archivebox")
359 .font(.caption)
360 Text("Snapshot from \(dateFormatter.string(from: entry.timestamp))")
361 .font(appDensity.font(.caption))
362 Spacer()
363 Text("Live re-run available")
364 .font(appDensity.font(.caption2))
365 .foregroundStyle(Color(.appTextSecondary))
366 }
367 if let mismatchNote = viewModel.resolverMismatchNote(for: entry) {
368 Text(mismatchNote)
369 .font(appDensity.font(.caption2))
370 .foregroundStyle(Color(.statusWarning))
371 }
372 if entry.isPartialSnapshot {
373 Text("Partial snapshot: \(entry.validationIssues.joined(separator: " | "))")
374 .font(appDensity.font(.caption2))
375 .foregroundStyle(Color(.statusWarning))
376 }
377 if let note = entry.note, !note.isEmpty {
378 Text(note)
379 .font(appDensity.font(.caption2))
380 .foregroundStyle(Color(.appTextSecondary))
381 }
382 }
383 .foregroundStyle(Color(.appTextSecondary))
384 .padding(8)
385 .frame(maxWidth: .infinity, alignment: .leading)
386 .background(Color(.appSurface))
387 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
388 .padding(.vertical, 12)
389 }
390}
391
392private struct HistoryGroup: Identifiable {
393 let title: String
394 let entries: [HistoryEntry]
395
396 var id: String { title }
397
398 static func groups(for entries: [HistoryEntry]) -> [HistoryGroup] {
399 let calendar = Calendar.current
400 let today = Date()
401 let yesterday = calendar.date(byAdding: .day, value: -1, to: today) ?? today
402
403 let grouped = Dictionary(grouping: entries) { entry -> String in
404 if calendar.isDate(entry.timestamp, inSameDayAs: today) {
405 return "Today"
406 }
407 if calendar.isDate(entry.timestamp, inSameDayAs: yesterday) {
408 return "Yesterday"
409 }
410 return "Older"
411 }
412
413 return ["Today", "Yesterday", "Older"].compactMap { title in
414 guard let entries = grouped[title], !entries.isEmpty else { return nil }
415 return HistoryGroup(title: title, entries: entries)
416 }
417 }
418}