DomainDig/HistoryView.swift

9384a668bf36f23f71e25d05b490d1040d308845
domain-dig/DomainDig/HistoryView.swift history · blame · raw

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