DomainDig/ContentView.swift
3760 lines · 160228 bytes
1import MapKit
2import SwiftUI
3import UniformTypeIdentifiers
4
5enum LookupInputMode: String, CaseIterable, Identifiable {
6 case single
7 case bulk
8
9 var id: String { rawValue }
10}
11
12enum ResultSection: String, Hashable {
13 case domain
14 case intelligence
15 case ownership
16 case dns
17 case web
18 case email
19 case network
20 case subdomains
21}
22
23private enum LookupInputField: Hashable {
24 case singleDomain
25 case bulkDomains
26}
27
28private struct WorkflowNavigationTarget: Hashable {
29 let workflowID: UUID
30}
31
32struct ContentView: View {
33 @Environment(\.appDensity) private var appDensity
34 @Bindable var viewModel: DomainViewModel
35 @State private var purchaseService = PurchaseService.shared
36 @State private var navigationPath = NavigationPath()
37 @FocusState private var focusedInputField: LookupInputField?
38 @State private var customPortInput = ""
39 @State private var customPortsExpanded = false
40 @State private var trackingNoteDraft = ""
41 @State private var editingTrackedDomain: TrackedDomain?
42 @State private var inputMode: LookupInputMode = .single
43 @State private var collapsedSections: Set<ResultSection> = [.network]
44 @State private var showingCurrentDomainWorkflowSheet = false
45 @State private var showingBatchWorkflowSheet = false
46 @State private var showingTimeline = false
47 @State private var showingAuditTimeline = false
48 @State private var auditStartInFlight = false
49
50 var body: some View {
51 let _ = purchaseService.currentTier
52
53 NavigationStack(path: $navigationPath) {
54 ScrollView(.vertical) {
55 VStack(spacing: 0) {
56 inputSection
57 if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
58 batchSection
59 .padding(.top, appDensity.metrics.cardSpacing)
60 }
61 if viewModel.hasRun {
62 actionButtons
63 if !viewModel.resultsLoaded {
64 LookupProgressOverviewView(steps: viewModel.activeLoadingLabels)
65 .padding(.top, appDensity.metrics.cardSpacing)
66 } else if let statusMessage = resultStatusMessage {
67 LookupStatusBannerView(message: statusMessage, resultSource: viewModel.currentResultSource)
68 .padding(.top, appDensity.metrics.cardSpacing)
69 }
70 if viewModel.resultsLoaded {
71 SummaryView(fields: viewModel.summaryFields)
72 .padding(.top, appDensity.metrics.cardSpacing)
73 if let report = viewModel.currentReport {
74 RiskSummaryCardView(report: report)
75 .padding(.top, appDensity.metrics.cardSpacing)
76 InsightsSummaryCardView(insights: report.insights)
77 .padding(.top, appDensity.metrics.cardSpacing)
78 }
79 if let changeSummary = viewModel.currentChangeSummary {
80 DomainChangeSummaryView(summary: changeSummary)
81 .padding(.top, appDensity.metrics.cardSpacing)
82 }
83 }
84 if let report = viewModel.currentReport {
85 intelligenceSection(report: report)
86 .padding(.top, appDensity.metrics.sectionSpacing)
87 }
88 domainOverviewSection
89 .padding(.top, appDensity.metrics.sectionSpacing)
90 ownershipSection
91 .padding(.top, appDensity.metrics.sectionSpacing)
92 subdomainsSection
93 .padding(.top, appDensity.metrics.sectionSpacing)
94 if !viewModel.currentDiffSections.isEmpty {
95 DomainDiffView(
96 title: "Latest Changes",
97 sections: viewModel.currentDiffSections,
98 contextNote: viewModel.currentChangeSummary?.contextNote,
99 showsUnchanged: false,
100 highlightedSectionID: nil
101 )
102 .padding(.top, appDensity.metrics.sectionSpacing)
103 }
104 dnsSection
105 .padding(.top, appDensity.metrics.sectionSpacing)
106 WebSectionView(
107 isCollapsed: sectionCollapsedBinding(.web),
108 certificateRows: viewModel.webCertificateRows,
109 sslInfo: viewModel.sslInfo,
110 tlsSummary: viewModel.currentTLSSummary,
111 sslLoading: viewModel.sslLoading || viewModel.hstsLoading,
112 sslError: viewModel.sslError,
113 tlsProvenance: viewModel.currentSnapshot.provenanceBySection[.ssl],
114 responseRows: viewModel.webResponseRows,
115 headers: viewModel.httpHeaders,
116 headersLoading: viewModel.httpHeadersLoading,
117 headersError: viewModel.httpHeadersError,
118 httpProvenance: viewModel.currentSnapshot.provenanceBySection[.httpHeaders],
119 redirects: viewModel.redirectRows,
120 redirectLoading: viewModel.redirectChainLoading,
121 redirectError: viewModel.redirectChainError,
122 redirectProvenance: viewModel.currentSnapshot.provenanceBySection[.redirectChain],
123 finalURL: viewModel.currentSnapshot.redirectChain.last?.url
124 )
125 .padding(.top, appDensity.metrics.sectionSpacing)
126 EmailSectionView(
127 isCollapsed: sectionCollapsedBinding(.email),
128 rows: viewModel.emailRows,
129 assessment: viewModel.currentEmailAssessment,
130 loading: viewModel.emailSecurityLoading,
131 provenance: viewModel.currentSnapshot.provenanceBySection[.emailSecurity],
132 confidence: viewModel.currentSnapshot.emailSecurityConfidence,
133 error: viewModel.emailSecurityError
134 )
135 .padding(.top, appDensity.metrics.sectionSpacing)
136 NetworkSectionView(
137 isCollapsed: sectionCollapsedBinding(.network),
138 reachabilityRows: viewModel.reachabilityRows,
139 reachabilityLoading: viewModel.reachabilityLoading,
140 reachabilityError: viewModel.reachabilityError,
141 reachabilityProvenance: viewModel.currentSnapshot.provenanceBySection[.reachability],
142 locationRows: viewModel.locationRows,
143 geolocation: viewModel.ipGeolocation,
144 geolocationLoading: viewModel.ipGeolocationLoading,
145 geolocationError: viewModel.ipGeolocationError,
146 geolocationProvenance: viewModel.currentSnapshot.provenanceBySection[.ipGeolocation],
147 geolocationConfidence: viewModel.currentSnapshot.geolocationConfidence,
148 standardPortRows: viewModel.standardPortRows,
149 customPortRows: viewModel.customPortRows,
150 portScanLoading: viewModel.portScanLoading,
151 portScanError: viewModel.portScanError,
152 portScanProvenance: viewModel.currentSnapshot.provenanceBySection[.portScan],
153 customPortScanLoading: viewModel.customPortScanLoading,
154 customPortScanError: viewModel.customPortScanError,
155 isCloudflareProxied: viewModel.isCloudflareProxied,
156 customPortsExpanded: $customPortsExpanded,
157 customPortInput: $customPortInput,
158 onScanCustomPorts: runCustomPortScan
159 )
160 .padding(.top, appDensity.metrics.sectionSpacing)
161 } else if !viewModel.recentSearches.isEmpty {
162 recentSearchesSection
163 }
164 }
165 .padding(.horizontal)
166 .padding(.bottom, 32)
167 }
168 .background(
169 LinearGradient(
170 colors: [Color.black, Color(.systemGray6).opacity(0.12)],
171 startPoint: .top,
172 endPoint: .bottom
173 )
174 )
175 .navigationTitle("DomainDig")
176 .toolbarColorScheme(.dark, for: .navigationBar)
177 .preferredColorScheme(.dark)
178 .toolbar {
179 ToolbarItem(placement: .topBarTrailing) {
180 if viewModel.hasRun {
181 Button {
182 viewModel.reset()
183 } label: {
184 Image(systemName: "xmark.circle")
185 .foregroundStyle(.secondary)
186 }
187 }
188 }
189
190 ToolbarItemGroup(placement: .keyboard) {
191 Spacer()
192 Button("Dismiss Keyboard") {
193 focusedInputField = nil
194 }
195 }
196 }
197 .navigationDestination(for: WorkflowNavigationTarget.self) { target in
198 WorkflowDetailView(viewModel: viewModel, workflowID: target.workflowID)
199 }
200 }
201 .onAppear {
202 focusedInputField = .singleDomain
203 }
204 .task {
205 await viewModel.refreshUsageCredits()
206 }
207 .onChange(of: viewModel.searchedDomain) { _, _ in
208 collapsedSections = defaultCollapsedSections
209 }
210 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
211 navigationPath = NavigationPath()
212 focusedInputField = nil
213 }
214 .onChange(of: inputMode) { _, newValue in
215 viewModel.clearPresentedResults()
216 focusedInputField = newValue == .single ? .singleDomain : .bulkDomains
217 }
218 .onChange(of: viewModel.domain) { _, newValue in
219 guard inputMode == .single else { return }
220 let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
221 guard normalized != viewModel.searchedDomain else { return }
222 guard viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
223 viewModel.clearPresentedResults()
224 }
225 .onChange(of: viewModel.bulkInput) { _, newValue in
226 guard inputMode == .bulk else { return }
227 let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
228 guard !normalized.isEmpty || viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
229 viewModel.clearPresentedResults()
230 }
231 .sheet(item: $editingTrackedDomain) { trackedDomain in
232 NavigationStack {
233 Form {
234 Section("Tracking Note") {
235 TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
236 .lineLimit(3...6)
237 .textInputAutocapitalization(.never)
238 .autocorrectionDisabled()
239 }
240 }
241 .navigationTitle(trackedDomain.domain)
242 .toolbar {
243 ToolbarItem(placement: .cancellationAction) {
244 Button("Cancel") {
245 editingTrackedDomain = nil
246 }
247 }
248 ToolbarItem(placement: .confirmationAction) {
249 Button("Save") {
250 viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
251 editingTrackedDomain = nil
252 }
253 }
254 }
255 }
256 }
257 .sheet(isPresented: $showingCurrentDomainWorkflowSheet) {
258 WorkflowBulkAddSheet(
259 viewModel: viewModel,
260 title: "Add Domain to Workflow",
261 availableDomains: [viewModel.searchedDomain]
262 )
263 }
264 .sheet(isPresented: $showingBatchWorkflowSheet) {
265 WorkflowBulkAddSheet(
266 viewModel: viewModel,
267 title: "Add Batch Domains",
268 availableDomains: viewModel.batchResults.map(\.domain)
269 )
270 }
271 .sheet(item: manualBatchSummaryBinding) { summary in
272 BatchSweepSummaryView(viewModel: viewModel, summary: summary)
273 }
274 .sheet(isPresented: $showingTimeline) {
275 NavigationStack {
276 TimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
277 }
278 }
279 .sheet(isPresented: $showingAuditTimeline) {
280 NavigationStack {
281 AuditDomainTimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
282 }
283 }
284 }
285
286 private var manualBatchSummaryBinding: Binding<BatchSweepSummary?> {
287 Binding(
288 get: {
289 guard let summary = viewModel.latestBatchSweepSummary,
290 summary.source == .manual else {
291 return nil
292 }
293 return summary
294 },
295 set: { viewModel.latestBatchSweepSummary = $0 }
296 )
297 }
298
299 private var inputSection: some View {
300 VStack(spacing: appDensity.metrics.cardSpacing + 2) {
301 Picker("Mode", selection: $inputMode) {
302 Text("Single").tag(LookupInputMode.single)
303 Text("Bulk").tag(LookupInputMode.bulk)
304 }
305 .pickerStyle(.segmented)
306
307 if inputMode == .single {
308 TextField("e.g. cleberg.net", text: $viewModel.domain)
309 .font(appDensity.font(.title3, design: .monospaced))
310 .textInputAutocapitalization(.never)
311 .autocorrectionDisabled()
312 .keyboardType(.URL)
313 .padding(.horizontal, 12)
314 .padding(.vertical, appDensity.metrics.controlVerticalPadding)
315 .background(Color(.systemGray6))
316 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
317 .focused($focusedInputField, equals: .singleDomain)
318 .onSubmit {
319 focusedInputField = nil
320 viewModel.run()
321 }
322
323 Button {
324 focusedInputField = nil
325 viewModel.run()
326 } label: {
327 Text("Run")
328 .font(appDensity.font(.headline, design: .default, weight: .semibold))
329 .frame(maxWidth: .infinity)
330 .frame(minHeight: appDensity.metrics.controlMinHeight)
331 }
332 .buttonStyle(.borderedProminent)
333 .disabled(viewModel.trimmedDomain.isEmpty)
334 } else {
335 if FeatureAccessService.hasAccess(to: .batchOperations) {
336 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
337 Text("Paste domains separated by new lines or commas.")
338 .font(appDensity.font(.caption))
339 .foregroundStyle(.secondary)
340
341 if let batchAllowanceSummary = FeatureAccessService.batchAllowanceSummary() {
342 Text(batchAllowanceSummary)
343 .font(appDensity.font(.caption2))
344 .foregroundStyle(.secondary)
345 }
346
347 TextField(
348 "example.com\napple.com, openai.com",
349 text: $viewModel.bulkInput,
350 axis: .vertical
351 )
352 .font(appDensity.font(.body))
353 .textInputAutocapitalization(.never)
354 .autocorrectionDisabled()
355 .keyboardType(.URL)
356 .lineLimit(4...10)
357 .padding(.horizontal, 12)
358 .padding(.vertical, appDensity.metrics.controlVerticalPadding)
359 .background(Color(.systemGray6))
360 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
361 .focused($focusedInputField, equals: .bulkDomains)
362
363 Button {
364 focusedInputField = nil
365 viewModel.runBulkLookup()
366 } label: {
367 Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
368 .font(appDensity.font(.headline, design: .default, weight: .semibold))
369 .frame(maxWidth: .infinity)
370 .frame(minHeight: appDensity.metrics.controlMinHeight)
371 }
372 .buttonStyle(.borderedProminent)
373 .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
374 }
375 } else {
376 lockedFeatureCard(
377 title: "Batch Operations",
378 message: FeatureAccessService.upgradeMessage(for: .batchOperations)
379 )
380 }
381 }
382 }
383 .padding(.vertical, appDensity.metrics.sectionSpacing)
384 }
385
386 private var domainOverviewSection: some View {
387 let trackedDomain = viewModel.currentTrackedDomain
388 let workflows = viewModel.currentDomainWorkflows
389
390 return DomainSectionView(
391 isCollapsed: sectionCollapsedBinding(.domain),
392 rows: viewModel.domainRows,
393 suggestions: viewModel.suggestionRows,
394 showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
395 availabilityLoading: viewModel.availabilityLoading,
396 suggestionsLoading: viewModel.suggestionsLoading,
397 provenance: viewModel.currentSnapshot.provenanceBySection[.availability],
398 confidence: viewModel.currentSnapshot.availabilityConfidence,
399 snapshotNote: viewModel.currentSnapshot.note,
400 trackedDomain: trackedDomain,
401 workflows: workflows,
402 trackingLimitMessage: viewModel.trackingLimitMessage,
403 pricingLoading: viewModel.domainPricingLoading,
404 pricingError: viewModel.domainPricingError,
405 showsPricingPlaceholder: !DataAccessService.hasAccess(to: .domainPricing),
406 onTrack: {
407 _ = viewModel.trackCurrentDomain()
408 },
409 onTogglePinned: {
410 guard let trackedDomain else { return }
411 viewModel.togglePinned(for: trackedDomain)
412 },
413 onEditNote: {
414 guard let trackedDomain else { return }
415 trackingNoteDraft = trackedDomain.note ?? ""
416 editingTrackedDomain = trackedDomain
417 },
418 onAddToWorkflow: {
419 showingCurrentDomainWorkflowSheet = true
420 },
421 onOpenWorkflow: { workflow in
422 navigationPath.append(WorkflowNavigationTarget(workflowID: workflow.id))
423 },
424 onRunWorkflow: { workflow in
425 viewModel.rerunCurrentDomain(in: workflow)
426 }
427 )
428 }
429
430 private func intelligenceSection(report: DomainReport) -> some View {
431 IntelligenceSectionView(
432 isCollapsed: sectionCollapsedBinding(.intelligence),
433 report: report,
434 showsPlaceholder: FeatureAccessService.currentTier != .proPlus
435 )
436 }
437
438 private var ownershipSection: some View {
439 OwnershipSectionView(
440 isCollapsed: sectionCollapsedBinding(.ownership),
441 rows: viewModel.ownershipRows,
442 loading: viewModel.ownershipLoading,
443 error: viewModel.ownershipError,
444 provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
445 confidence: viewModel.currentSnapshot.ownershipConfidence,
446 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .ownershipHistory),
447 history: viewModel.ownershipHistory,
448 historyLoading: viewModel.ownershipHistoryLoading,
449 historyError: viewModel.ownershipHistoryError,
450 historyCreditStatus: viewModel.ownershipHistoryCreditStatus,
451 onLoadHistory: {
452 Task {
453 await viewModel.loadOwnershipHistory()
454 }
455 }
456 )
457 }
458
459 private var subdomainsSection: some View {
460 SubdomainsSectionView(
461 isCollapsed: sectionCollapsedBinding(.subdomains),
462 rows: viewModel.subdomainRows,
463 groups: viewModel.currentSubdomainGroups,
464 loading: viewModel.subdomainsLoading,
465 error: viewModel.subdomainsError,
466 provenance: viewModel.currentSnapshot.provenanceBySection[.subdomains],
467 confidence: viewModel.currentSnapshot.subdomainConfidence,
468 showsExtendedPlaceholder: !DataAccessService.hasAccess(to: .extendedSubdomains),
469 extendedCount: viewModel.extendedSubdomains.count,
470 extendedLoading: viewModel.extendedSubdomainsLoading,
471 extendedError: viewModel.extendedSubdomainsError,
472 extendedCreditStatus: viewModel.extendedSubdomainsCreditStatus,
473 onLoadExtended: {
474 Task {
475 await viewModel.loadExtendedSubdomains()
476 }
477 }
478 )
479 }
480
481 private var dnsSection: some View {
482 DNSSectionView(
483 isCollapsed: sectionCollapsedBinding(.dns),
484 dnssecLabel: viewModel.dnssecLabel,
485 patternSummary: viewModel.currentDNSPatterns,
486 sections: viewModel.dnsRows,
487 ptrMessage: viewModel.ptrMessage,
488 loading: viewModel.dnsLoading || viewModel.ptrLoading,
489 dnsProvenance: viewModel.currentSnapshot.provenanceBySection[.dns],
490 ptrProvenance: viewModel.currentSnapshot.provenanceBySection[.ptr],
491 sectionError: viewModel.dnsError,
492 history: viewModel.dnsHistory,
493 historyLoading: viewModel.dnsHistoryLoading,
494 historyError: viewModel.dnsHistoryError,
495 showsHistoryPlaceholder: !DataAccessService.hasAccess(to: .dnsHistory),
496 historyCreditStatus: viewModel.dnsHistoryCreditStatus,
497 onLoadHistory: {
498 Task {
499 await viewModel.loadDNSHistory()
500 }
501 }
502 )
503 }
504
505 private var actionButtons: some View {
506 HStack {
507 Spacer()
508 if viewModel.resultsLoaded {
509 Menu {
510 if !viewModel.isCurrentDomainTracked {
511 Button("Track this domain") {
512 _ = viewModel.trackCurrentDomain()
513 }
514 }
515 Button("Add to workflow") {
516 showingCurrentDomainWorkflowSheet = true
517 }
518 Button(auditStartInFlight ? "Starting audit…" : "Start audit") {
519 Task {
520 auditStartInFlight = true
521 if await viewModel.startAudit(for: viewModel.searchedDomain) != nil {
522 showingAuditTimeline = true
523 }
524 auditStartInFlight = false
525 }
526 }
527 .disabled(auditStartInFlight)
528 if !viewModel.audits(for: viewModel.searchedDomain).isEmpty {
529 Button("View audits") {
530 showingAuditTimeline = true
531 }
532 }
533 if !viewModel.historyEntries(for: viewModel.searchedDomain).isEmpty {
534 Button("Open timeline") {
535 showingTimeline = true
536 }
537 }
538 if FeatureAccessService.hasAccess(to: .advancedExports) {
539 Button("Copy report JSON") {
540 guard let json = viewModel.exportJSONString() else { return }
541 AppClipboard.copy(json)
542 AppHaptics.copy()
543 }
544 } else {
545 Button("Copy report JSON") {
546 viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .advancedExports)
547 }
548 }
549 Button("Export report") {
550 shareSingleResults(format: .text)
551 }
552 } label: {
553 Image(systemName: "bolt.circle")
554 .font(appDensity.font(.body, design: .default))
555 .foregroundStyle(.secondary)
556 }
557 Button {
558 viewModel.toggleSavedDomain()
559 } label: {
560 Image(systemName: viewModel.isCurrentDomainSaved ? "bookmark.fill" : "bookmark")
561 .font(appDensity.font(.body, design: .default))
562 .foregroundStyle(viewModel.isCurrentDomainSaved ? .yellow : .secondary)
563 }
564 Menu {
565 Button("Export TXT") {
566 shareSingleResults(format: .text)
567 }
568 if FeatureAccessService.hasAccess(to: .advancedExports) {
569 Button("Export CSV") {
570 shareSingleResults(format: .csv)
571 }
572 Button("Export JSON") {
573 shareSingleResults(format: .json)
574 }
575 Button("Export Markdown") {
576 shareSingleResults(format: .markdown)
577 }
578 Button("Export PDF") {
579 shareSingleResults(format: .pdf)
580 }
581 } else {
582 Button("CSV Export • Available in Pro") {}
583 .disabled(true)
584 Button("JSON Export • Available in Pro") {}
585 .disabled(true)
586 Button("Markdown Export • Available in Pro") {}
587 .disabled(true)
588 Button("PDF Export • Available in Pro") {}
589 .disabled(true)
590 }
591 } label: {
592 Image(systemName: "square.and.arrow.up")
593 .font(appDensity.font(.body, design: .default))
594 .foregroundStyle(.secondary)
595 }
596 }
597 }
598 }
599
600 private var batchSection: some View {
601 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
602 HStack {
603 Spacer()
604 if viewModel.batchLookupRunning {
605 Button("Cancel") {
606 viewModel.cancelBatchLookup()
607 }
608 .buttonStyle(.bordered)
609 .font(appDensity.font(.caption))
610 }
611 if !viewModel.currentBatchResultEntries.isEmpty {
612 Menu {
613 Button("Add to Workflow") {
614 showingBatchWorkflowSheet = true
615 }
616 Divider()
617 Button("Export Batch TXT") {
618 shareBatchResults(format: .text)
619 }
620 if FeatureAccessService.hasAccess(to: .advancedExports) {
621 Button("Export Batch CSV") {
622 shareBatchResults(format: .csv)
623 }
624 Button("Export Batch JSON") {
625 shareBatchResults(format: .json)
626 }
627 Button("Export Batch Markdown") {
628 shareBatchResults(format: .markdown)
629 }
630 Button("Export Batch PDF") {
631 shareBatchResults(format: .pdf)
632 }
633 } else {
634 Button("Batch CSV • Available in Pro") {}
635 .disabled(true)
636 Button("Batch JSON • Available in Pro") {}
637 .disabled(true)
638 Button("Batch Markdown • Available in Pro") {}
639 .disabled(true)
640 Button("Batch PDF • Available in Pro") {}
641 .disabled(true)
642 }
643 } label: {
644 Label("Export", systemImage: "square.and.arrow.up")
645 .font(appDensity.font(.caption))
646 }
647 .buttonStyle(.bordered)
648 }
649 }
650
651 BatchResultsView(
652 viewModel: viewModel,
653 title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
654 )
655 }
656 }
657
658 private var recentSearchesSection: some View {
659 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
660 HStack {
661 Text("RECENT")
662 .font(appDensity.font(.caption2))
663 .foregroundStyle(.secondary)
664 Spacer()
665 Button("Clear") {
666 viewModel.clearRecentSearches()
667 }
668 .font(appDensity.font(.caption2))
669 .foregroundStyle(.secondary)
670 }
671
672 ForEach(viewModel.recentSearches, id: \.self) { domain in
673 Button {
674 viewModel.domain = domain
675 focusedInputField = nil
676 viewModel.run()
677 } label: {
678 Text(domain)
679 .font(appDensity.font(.callout))
680 .foregroundStyle(.primary)
681 .frame(maxWidth: .infinity, alignment: .leading)
682 .padding(.vertical, 8)
683 .padding(.horizontal, 10)
684 .background(Color(.systemGray6).opacity(0.5))
685 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
686 }
687 }
688 }
689 .padding(.top, appDensity.metrics.cardSpacing)
690 }
691
692 private func runCustomPortScan() {
693 let ports = parsedCustomPorts(from: customPortInput)
694 Task {
695 await viewModel.runCustomPortScan(ports: ports)
696 }
697 }
698
699 private func lockedFeatureCard(title: String, message: String) -> some View {
700 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
701 Text(title)
702 .font(appDensity.font(.headline, design: .default, weight: .semibold))
703 Text(message)
704 .font(appDensity.font(.callout, design: .default))
705 .foregroundStyle(.secondary)
706 }
707 .frame(maxWidth: .infinity, alignment: .leading)
708 .padding(appDensity.metrics.cardPadding)
709 .background(Color(.systemGray6))
710 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
711 }
712
713 private func parsedCustomPorts(from input: String) -> [UInt16] {
714 let parts = input.split(separator: ",", omittingEmptySubsequences: true)
715 var seen = Set<UInt16>()
716 var ports: [UInt16] = []
717
718 for part in parts {
719 let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
720 guard let value = UInt16(trimmed), seen.insert(value).inserted else {
721 continue
722 }
723 ports.append(value)
724 if ports.count == 20 {
725 break
726 }
727 }
728
729 return ports
730 }
731
732 private func shareSingleResults(format: DomainExportFormat) {
733 guard let data = viewModel.exportSingleReportData(format: format) else { return }
734 ExportPresenter.share(filename: exportFilename(prefix: "domaindig_single", format: format), data: data)
735 }
736
737 private func shareBatchResults(format: DomainExportFormat) {
738 guard let data = viewModel.exportBatchReportData(format: format) else { return }
739 ExportPresenter.share(filename: exportFilename(prefix: "domaindig_batch", format: format), data: data)
740 }
741
742 private func exportFilename(prefix: String, format: DomainExportFormat) -> String {
743 let formatter = DateFormatter()
744 formatter.dateFormat = "yyyyMMdd_HHmmss"
745 let timestamp = formatter.string(from: Date())
746 return "\(timestamp)_\(prefix).\(format.fileExtension)"
747 }
748
749 private var defaultCollapsedSections: Set<ResultSection> {
750 []
751 }
752
753 private var currentPrimaryIP: String? {
754 viewModel.currentSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
755 }
756
757 private var resultStatusMessage: String? {
758 if let currentStatusMessage = viewModel.currentStatusMessage {
759 return currentStatusMessage
760 }
761
762 if viewModel.currentResultSource != .live {
763 return viewModel.currentResultSource.label
764 }
765
766 return nil
767 }
768
769 private func sectionCollapsedBinding(_ section: ResultSection) -> Binding<Bool> {
770 Binding(
771 get: { collapsedSections.contains(section) },
772 set: { isCollapsed in
773 if isCollapsed {
774 collapsedSections.insert(section)
775 } else {
776 collapsedSections.remove(section)
777 }
778 }
779 )
780 }
781}
782
783struct SummaryView: View {
784 @Environment(\.appDensity) private var appDensity
785 let fields: [SummaryFieldViewData]
786
787 var body: some View {
788 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
789 SectionTitleView(title: "Summary")
790 LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: appDensity.metrics.cardSpacing) {
791 ForEach(fields) { field in
792 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing) {
793 Text(field.label)
794 .font(appDensity.font(.caption2))
795 .foregroundStyle(.secondary)
796 Text(field.value)
797 .font(appDensity.font(.caption))
798 .foregroundStyle(ResultColors.color(for: field.tone))
799 .lineLimit(2)
800 .textSelection(.enabled)
801 }
802 .frame(minHeight: appDensity.metrics.rowMinHeight + 12, alignment: .topLeading)
803 .frame(maxWidth: .infinity, alignment: .leading)
804 .padding(appDensity.metrics.cardPadding)
805 .background(Color(.systemGray6).opacity(0.5))
806 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
807 }
808 }
809 }
810 }
811}
812
813struct RiskSummaryCardView: View {
814 @Environment(\.appDensity) private var appDensity
815 let report: DomainReport
816
817 private var topFactors: [RiskFactor] {
818 Array(report.riskAssessment.factors.prefix(3))
819 }
820
821 var body: some View {
822 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
823 SectionTitleView(title: "Risk")
824 CardView(allowsHorizontalScroll: false) {
825 HStack(alignment: .firstTextBaseline) {
826 VStack(alignment: .leading, spacing: 4) {
827 Text("\(report.riskAssessment.score)")
828 .font(appDensity.font(.largeTitle, weight: .bold))
829 .foregroundStyle(levelColor)
830 Text(report.riskAssessment.level.title)
831 .font(appDensity.font(.caption))
832 .foregroundStyle(levelColor)
833 }
834 Spacer()
835 Text("Deterministic")
836 .font(appDensity.font(.caption2))
837 .foregroundStyle(.secondary)
838 }
839
840 if topFactors.isEmpty {
841 Text("No major risk factors identified")
842 .font(appDensity.font(.caption))
843 .foregroundStyle(.secondary)
844 } else {
845 ForEach(Array(topFactors.enumerated()), id: \.offset) { _, factor in
846 HStack(alignment: .top, spacing: 8) {
847 Circle()
848 .fill(factorColor(factor.impact))
849 .frame(width: 8, height: 8)
850 .padding(.top, 5)
851 Text(factor.description)
852 .font(appDensity.font(.caption))
853 .foregroundStyle(.primary)
854 }
855 }
856 }
857 }
858 }
859 }
860
861 private var levelColor: Color {
862 switch report.riskAssessment.level {
863 case .low:
864 return .green
865 case .medium:
866 return .yellow
867 case .high:
868 return .red
869 }
870 }
871
872 private func factorColor(_ impact: RiskImpact) -> Color {
873 switch impact {
874 case .positive:
875 return .green
876 case .neutral:
877 return .secondary
878 case .negative:
879 return .red
880 }
881 }
882}
883
884struct InsightsSummaryCardView: View {
885 @Environment(\.appDensity) private var appDensity
886 let insights: [String]
887
888 var body: some View {
889 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
890 SectionTitleView(title: "Insights")
891 CardView(allowsHorizontalScroll: false) {
892 if insights.isEmpty {
893 Text("No deterministic insights triggered")
894 .font(appDensity.font(.caption))
895 .foregroundStyle(.secondary)
896 } else {
897 ForEach(Array(insights.enumerated()), id: \.offset) { _, insight in
898 HStack(alignment: .top, spacing: 8) {
899 Image(systemName: "chart.line.uptrend.xyaxis")
900 .font(appDensity.font(.caption2))
901 .foregroundStyle(.cyan)
902 .padding(.top, 2)
903 Text(insight)
904 .font(appDensity.font(.caption))
905 .foregroundStyle(.primary)
906 }
907 }
908 }
909 }
910 }
911 }
912}
913
914struct StickyLookupSummaryView: View {
915 @Environment(\.appDensity) private var appDensity
916
917 let domain: String
918 let availability: DomainAvailabilityStatus?
919 let primaryIP: String?
920 let sslInfo: SSLCertificateInfo?
921 let sslError: String?
922 let emailSecurity: EmailSecurityResult?
923 let emailError: String?
924 let changeSummary: DomainChangeSummary?
925
926 var body: some View {
927 CardView(allowsHorizontalScroll: false) {
928 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
929 HStack(alignment: .center, spacing: 10) {
930 Text(domain)
931 .font(appDensity.font(.headline, weight: .semibold))
932 .foregroundStyle(.primary)
933 .lineLimit(1)
934 Spacer(minLength: 6)
935 AppCopyButton(value: domain, label: "Copy domain")
936 }
937
938 ScrollView(.horizontal, showsIndicators: false) {
939 HStack(spacing: 8) {
940 AppStatusBadgeView(model: AppStatusFactory.availability(availability))
941 AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
942 AppStatusBadgeView(model: AppStatusFactory.email(emailSecurity, error: emailError))
943 AppStatusBadgeView(model: AppStatusFactory.change(changeSummary))
944 }
945 }
946
947 if let primaryIP {
948 HStack(spacing: 8) {
949 Label(primaryIP, systemImage: "network")
950 .font(appDensity.font(.caption))
951 .foregroundStyle(.secondary)
952 Spacer(minLength: 6)
953 AppCopyButton(value: primaryIP, label: "Copy IP")
954 }
955 }
956 }
957 }
958 .shadow(color: .black.opacity(0.12), radius: 14, y: 6)
959 }
960}
961
962struct LookupProgressOverviewView: View {
963 @Environment(\.appDensity) private var appDensity
964 let steps: [String]
965
966 var body: some View {
967 CardView(allowsHorizontalScroll: false) {
968 HStack(spacing: 8) {
969 ProgressView()
970 .controlSize(.small)
971 VStack(alignment: .leading, spacing: 4) {
972 Text("Running lookup…")
973 .font(appDensity.font(.caption))
974 .foregroundStyle(.primary)
975 Text(steps.isEmpty ? "Preparing requests" : steps.joined(separator: " • "))
976 .font(appDensity.font(.caption2))
977 .foregroundStyle(.secondary)
978 }
979 Spacer()
980 }
981 }
982 }
983}
984
985struct LookupStatusBannerView: View {
986 @Environment(\.appDensity) private var appDensity
987 let message: String
988 let resultSource: LookupResultSource
989
990 var body: some View {
991 HStack(spacing: 8) {
992 Image(systemName: iconName)
993 .font(.caption)
994 Text(message)
995 .font(appDensity.font(.caption))
996 Spacer()
997 }
998 .foregroundStyle(color)
999 .padding(appDensity.metrics.cardPadding - 2)
1000 .frame(maxWidth: .infinity, alignment: .leading)
1001 .background(color.opacity(0.12))
1002 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
1003 }
1004
1005 private var color: Color {
1006 switch resultSource {
1007 case .live:
1008 return .green
1009 case .cached:
1010 return .secondary
1011 case .mixed:
1012 return .yellow
1013 case .snapshot:
1014 return .orange
1015 }
1016 }
1017
1018 private var iconName: String {
1019 switch resultSource {
1020 case .live:
1021 return "bolt.horizontal"
1022 case .cached:
1023 return "clock.arrow.trianglehead.counterclockwise.rotate.90"
1024 case .mixed:
1025 return "arrow.triangle.branch"
1026 case .snapshot:
1027 return "archivebox"
1028 }
1029 }
1030}
1031
1032struct DomainChangeSummaryView: View {
1033 @Environment(\.appDensity) private var appDensity
1034 let summary: DomainChangeSummary
1035 @State private var showsDetails = false
1036
1037 var body: some View {
1038 CardView(allowsHorizontalScroll: false) {
1039 HStack {
1040 Label(summary.hasChanges ? "Changed" : "Stable", systemImage: summary.hasChanges ? "arrow.triangle.2.circlepath" : "checkmark.circle")
1041 .font(appDensity.font(.caption))
1042 .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .green)
1043 Spacer()
1044 Text(summary.severity.title.uppercased())
1045 .font(appDensity.font(.caption2))
1046 .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .secondary)
1047 .padding(.horizontal, 8)
1048 .padding(.vertical, 4)
1049 .background((summary.hasChanges ? severityColor(summary.severity) : .secondary).opacity(0.16))
1050 .clipShape(Capsule())
1051 Text(summary.impactClassification.title.uppercased())
1052 .font(appDensity.font(.caption2))
1053 .foregroundStyle(impactColor(summary.impactClassification))
1054 .padding(.horizontal, 8)
1055 .padding(.vertical, 4)
1056 .background(impactColor(summary.impactClassification).opacity(0.16))
1057 .clipShape(Capsule())
1058 Text(summary.generatedAt, style: .time)
1059 .font(appDensity.font(.caption2))
1060 .foregroundStyle(.secondary)
1061 }
1062
1063 VStack(alignment: .leading, spacing: 4) {
1064 Text("Inference")
1065 .font(appDensity.font(.caption2))
1066 .foregroundStyle(.secondary)
1067 Text(summary.message)
1068 .font(appDensity.font(.caption))
1069 .foregroundStyle(.primary)
1070 .lineLimit(2)
1071 }
1072
1073 if !summary.observedFacts.isEmpty || summary.contextNote != nil {
1074 DisclosureGroup(showsDetails ? "Hide Details" : "Show Details", isExpanded: $showsDetails) {
1075 VStack(alignment: .leading, spacing: 8) {
1076 if !summary.observedFacts.isEmpty {
1077 VStack(alignment: .leading, spacing: 4) {
1078 Text("Observed")
1079 .font(appDensity.font(.caption2))
1080 .foregroundStyle(.secondary)
1081 ForEach(Array(summary.observedFacts.enumerated()), id: \.offset) { _, fact in
1082 Text(fact)
1083 .font(appDensity.font(.caption))
1084 .foregroundStyle(.primary)
1085 }
1086 }
1087 }
1088
1089 if let riskScoreDelta = summary.riskScoreDelta {
1090 Text("Risk delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
1091 .font(appDensity.font(.caption2))
1092 .foregroundStyle(riskScoreDelta > 0 ? .orange : .secondary)
1093 }
1094
1095 if let contextNote = summary.contextNote {
1096 Text(contextNote)
1097 .font(appDensity.font(.caption2))
1098 .foregroundStyle(.orange)
1099 }
1100 }
1101 .padding(.top, 4)
1102 }
1103 .font(appDensity.font(.caption))
1104 .tint(.secondary)
1105 }
1106 }
1107 }
1108
1109 private func severityColor(_ severity: ChangeSeverity) -> Color {
1110 switch severity {
1111 case .low:
1112 return .secondary
1113 case .medium:
1114 return .yellow
1115 case .high:
1116 return .red
1117 }
1118 }
1119
1120 private func impactColor(_ impact: ChangeImpactClassification) -> Color {
1121 switch impact {
1122 case .informational:
1123 return .secondary
1124 case .warning:
1125 return .yellow
1126 case .critical:
1127 return .red
1128 }
1129 }
1130}
1131
1132struct DomainDiffView: View {
1133 let title: String
1134 let sections: [DomainDiffSection]
1135 let contextNote: String?
1136 let showsUnchanged: Bool
1137 let highlightedSectionID: String?
1138
1139 @State private var collapsedSections = Set<String>()
1140 @State private var showsLowSeverity = false
1141
1142 private var filteredSections: [DomainDiffSection] {
1143 sections
1144 .map { section in
1145 let items = section.items.filter { item in
1146 if !showsUnchanged, !item.hasChanges {
1147 return false
1148 }
1149 if showsLowSeverity {
1150 return true
1151 }
1152 return item.severity >= .medium || (showsUnchanged && item.changeType == .unchanged)
1153 }
1154 return DomainDiffSection(id: section.id, title: section.title, items: items)
1155 }
1156 .filter { !$0.items.isEmpty }
1157 }
1158
1159 private var hasLowSeverityChanges: Bool {
1160 sections.flatMap(\.items).contains { $0.hasChanges && $0.severity == .low }
1161 }
1162
1163 var body: some View {
1164 VStack(alignment: .leading, spacing: 12) {
1165 HStack {
1166 SectionTitleView(title: title)
1167 Spacer()
1168 if hasLowSeverityChanges {
1169 Button(showsLowSeverity ? "Hide Low" : "Show Low") {
1170 showsLowSeverity.toggle()
1171 }
1172 .buttonStyle(.bordered)
1173 .font(.system(.caption, design: .monospaced))
1174 }
1175 }
1176 if let contextNote {
1177 MessageCardView(text: contextNote, isError: false)
1178 }
1179 if filteredSections.isEmpty {
1180 MessageCardView(text: "No comparison data available", isError: false)
1181 } else {
1182 ForEach(filteredSections) { section in
1183 CardView(allowsHorizontalScroll: false) {
1184 DisclosureGroup(isExpanded: binding(for: section)) {
1185 let visibleItems = showsUnchanged ? section.items : section.items.filter(\.hasChanges)
1186
1187 ForEach(visibleItems) { item in
1188 VStack(alignment: .leading, spacing: 6) {
1189 HStack {
1190 Text(item.label)
1191 .font(.system(.caption, design: .monospaced))
1192 .foregroundStyle(.secondary)
1193 Spacer()
1194 Text("\(item.changeType.marker) \(item.severity.title) • \(changeLabel(for: item.changeType))")
1195 .font(.system(.caption2, design: .monospaced))
1196 .foregroundStyle(changeColor(for: item))
1197 .padding(.horizontal, 8)
1198 .padding(.vertical, 4)
1199 .background(changeColor(for: item).opacity(0.16))
1200 .clipShape(Capsule())
1201 }
1202
1203 if let oldValue = item.oldValue {
1204 VStack(alignment: .leading, spacing: 2) {
1205 Text("Old")
1206 .font(.system(.caption2, design: .monospaced))
1207 .foregroundStyle(.secondary)
1208 Text(oldValue)
1209 .font(.system(.caption2, design: .monospaced))
1210 .foregroundStyle(.secondary)
1211 .textSelection(.enabled)
1212 }
1213 }
1214
1215 if let newValue = item.newValue {
1216 VStack(alignment: .leading, spacing: 2) {
1217 Text("New")
1218 .font(.system(.caption2, design: .monospaced))
1219 .foregroundStyle(.secondary)
1220 Text(newValue)
1221 .font(.system(.caption, design: .monospaced))
1222 .foregroundStyle(item.hasChanges ? .primary : .secondary)
1223 .textSelection(.enabled)
1224 }
1225 }
1226 }
1227 .padding(10)
1228 .background(item.hasChanges ? changeColor(for: item).opacity(0.08) : Color(.systemGray6).opacity(0.25))
1229 .cornerRadius(8)
1230 }
1231 } label: {
1232 HStack {
1233 Text(section.title)
1234 .font(.system(.subheadline, design: .monospaced))
1235 .fontWeight(.semibold)
1236 .foregroundStyle(sectionColor(section))
1237 Spacer()
1238 Text(section.severity.title)
1239 .font(.system(.caption2, design: .monospaced))
1240 .foregroundStyle(sectionColor(section))
1241 }
1242 }
1243 }
1244 .id(section.id)
1245 .overlay {
1246 if highlightedSectionID == section.id {
1247 RoundedRectangle(cornerRadius: 12)
1248 .stroke(Color.cyan.opacity(0.55), lineWidth: 1)
1249 }
1250 }
1251 }
1252 }
1253 }
1254 .onAppear {
1255 collapsedSections = Set(sections.filter { !showsUnchanged && !$0.hasChanges }.map(\.id))
1256 }
1257 }
1258
1259 private func changeLabel(for changeType: DiffChangeType) -> String {
1260 switch changeType {
1261 case .added:
1262 return "Added"
1263 case .removed:
1264 return "Removed"
1265 case .changed:
1266 return "Changed"
1267 case .unchanged:
1268 return "Unchanged"
1269 }
1270 }
1271
1272 private func changeColor(for item: DomainDiffItem) -> Color {
1273 if item.changeType == .unchanged {
1274 return .secondary
1275 }
1276
1277 switch item.severity {
1278 case .low:
1279 return .blue
1280 case .medium:
1281 return .yellow
1282 case .high:
1283 return .red
1284 }
1285 }
1286
1287 private func sectionColor(_ section: DomainDiffSection) -> Color {
1288 switch section.severity {
1289 case .low:
1290 return .blue
1291 case .medium:
1292 return .yellow
1293 case .high:
1294 return .red
1295 }
1296 }
1297
1298 private func binding(for section: DomainDiffSection) -> Binding<Bool> {
1299 Binding(
1300 get: { !collapsedSections.contains(section.id) },
1301 set: { isExpanded in
1302 if isExpanded {
1303 collapsedSections.remove(section.id)
1304 } else {
1305 collapsedSections.insert(section.id)
1306 }
1307 }
1308 )
1309 }
1310}
1311
1312struct TrackedDomainDetailHeaderView: View {
1313 let trackedDomain: TrackedDomain
1314
1315 var body: some View {
1316 VStack(alignment: .leading, spacing: 4) {
1317 if let note = trackedDomain.note?.nilIfEmpty {
1318 LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
1319 }
1320 HStack(spacing: 8) {
1321 if trackedDomain.isPinned {
1322 Label("Pinned", systemImage: "pin.fill")
1323 }
1324 Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
1325 }
1326 .font(.system(.caption2, design: .monospaced))
1327 .foregroundStyle(.secondary)
1328 }
1329 }
1330}
1331
1332struct DomainSectionView: View {
1333 @Environment(\.appDensity) private var appDensity
1334 @Binding var isCollapsed: Bool
1335 let rows: [InfoRowViewData]
1336 let suggestions: [DomainSuggestionViewData]
1337 let showSuggestions: Bool
1338 let availabilityLoading: Bool
1339 let suggestionsLoading: Bool
1340 let provenance: SectionProvenance?
1341 let confidence: ConfidenceLevel?
1342 let snapshotNote: String?
1343 let trackedDomain: TrackedDomain?
1344 let workflows: [DomainWorkflow]
1345 let trackingLimitMessage: String?
1346 let pricingLoading: Bool
1347 let pricingError: String?
1348 let showsPricingPlaceholder: Bool
1349 let onTrack: () -> Void
1350 let onTogglePinned: () -> Void
1351 let onEditNote: (() -> Void)?
1352 let onAddToWorkflow: (() -> Void)?
1353 let onOpenWorkflow: ((DomainWorkflow) -> Void)?
1354 let onRunWorkflow: ((DomainWorkflow) -> Void)?
1355
1356 var body: some View {
1357 CollapsibleSectionView(title: "Domain", isCollapsed: $isCollapsed) {
1358 if let trackedDomain {
1359 HStack(spacing: 8) {
1360 AppStatusBadgeView(model: .init(title: "Tracked", systemImage: "eye.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16)))
1361 Button {
1362 onTogglePinned()
1363 } label: {
1364 Image(systemName: trackedDomain.isPinned ? "pin.fill" : "pin")
1365 }
1366 .buttonStyle(.bordered)
1367 .font(appDensity.font(.caption))
1368 if let onEditNote {
1369 Button("Note") {
1370 onEditNote()
1371 }
1372 .buttonStyle(.bordered)
1373 .font(appDensity.font(.caption))
1374 }
1375 }
1376 } else {
1377 Button("Track") {
1378 AppHaptics.track()
1379 onTrack()
1380 }
1381 .buttonStyle(.bordered)
1382 .font(appDensity.font(.caption))
1383 }
1384 } content: {
1385 CardView(allowsHorizontalScroll: false) {
1386 SectionTrustMetadataView(
1387 provenance: provenance,
1388 confidence: confidence,
1389 note: snapshotNote == nil ? nil : "Audit note present"
1390 )
1391 ForEach(rows) { row in
1392 LabeledValueRow(row: row)
1393 }
1394 if let trackedDomain {
1395 TrackedDomainDetailHeaderView(trackedDomain: trackedDomain)
1396 .padding(.top, 4)
1397 } else if let trackingLimitMessage {
1398 MessageRowView(text: trackingLimitMessage, isError: false)
1399 .padding(.top, 4)
1400 }
1401 if let onAddToWorkflow {
1402 Button {
1403 onAddToWorkflow()
1404 } label: {
1405 Label("Add to workflow", systemImage: "plus.rectangle.on.folder")
1406 .font(appDensity.font(.caption))
1407 }
1408 .buttonStyle(.bordered)
1409 .padding(.top, 4)
1410 }
1411 if !workflows.isEmpty {
1412 VStack(alignment: .leading, spacing: 8) {
1413 Text("Part of workflow")
1414 .font(appDensity.font(.caption))
1415 .foregroundStyle(.secondary)
1416
1417 ForEach(workflows) { workflow in
1418 HStack {
1419 Text(workflow.name)
1420 .font(appDensity.font(.caption))
1421 .foregroundStyle(.primary)
1422 Spacer()
1423 if let onOpenWorkflow {
1424 Button("Open") {
1425 onOpenWorkflow(workflow)
1426 }
1427 .buttonStyle(.bordered)
1428 .font(appDensity.font(.caption2))
1429 }
1430 if let onRunWorkflow {
1431 Button("Run") {
1432 onRunWorkflow(workflow)
1433 }
1434 .buttonStyle(.bordered)
1435 .font(appDensity.font(.caption2))
1436 }
1437 }
1438 }
1439 }
1440 .padding(.top, 4)
1441 }
1442 if availabilityLoading {
1443 ProgressView("Checking availability…")
1444 .appLoadingStyle()
1445 .padding(.top, 4)
1446 }
1447 if showSuggestions {
1448 Text("Suggestions")
1449 .font(appDensity.font(.caption))
1450 .foregroundStyle(.secondary)
1451 .padding(.top, 4)
1452 if suggestionsLoading {
1453 ProgressView("Checking alternatives…")
1454 .appLoadingStyle()
1455 } else if suggestions.isEmpty {
1456 MessageRowView(text: "No suggestions", isError: false)
1457 } else {
1458 ForEach(suggestions) { suggestion in
1459 HStack {
1460 Text(suggestion.domain)
1461 .font(appDensity.font(.caption))
1462 .foregroundStyle(.primary)
1463 .textSelection(.enabled)
1464 Spacer()
1465 AppStatusBadgeView(model: AppStatusFactory.availability(suggestion.availabilityStatus))
1466 }
1467 }
1468 }
1469 }
1470 if pricingLoading {
1471 ProgressView("Loading external pricing…")
1472 .appLoadingStyle()
1473 .padding(.top, 4)
1474 } else if let pricingError {
1475 MessageRowView(text: pricingError, isError: false)
1476 .padding(.top, 4)
1477 } else if showsPricingPlaceholder {
1478 MessageRowView(text: "Pricing signals available in Pro+", isError: false)
1479 .padding(.top, 4)
1480 }
1481 }
1482 }
1483 }
1484}
1485
1486struct OwnershipSectionView: View {
1487 @Environment(\.appDensity) private var appDensity
1488 @Binding var isCollapsed: Bool
1489 let rows: [InfoRowViewData]
1490 let loading: Bool
1491 let error: String?
1492 let provenance: SectionProvenance?
1493 let confidence: ConfidenceLevel?
1494 let showsHistoryPlaceholder: Bool
1495 let history: [DomainOwnershipHistoryEvent]
1496 let historyLoading: Bool
1497 let historyError: String?
1498 let historyCreditStatus: UsageCreditStatus?
1499 let onLoadHistory: (() -> Void)?
1500
1501 init(
1502 isCollapsed: Binding<Bool>,
1503 rows: [InfoRowViewData],
1504 loading: Bool,
1505 error: String?,
1506 provenance: SectionProvenance?,
1507 confidence: ConfidenceLevel?,
1508 showsHistoryPlaceholder: Bool,
1509 history: [DomainOwnershipHistoryEvent] = [],
1510 historyLoading: Bool = false,
1511 historyError: String? = nil,
1512 historyCreditStatus: UsageCreditStatus? = nil,
1513 onLoadHistory: (() -> Void)? = nil
1514 ) {
1515 _isCollapsed = isCollapsed
1516 self.rows = rows
1517 self.loading = loading
1518 self.error = error
1519 self.provenance = provenance
1520 self.confidence = confidence
1521 self.showsHistoryPlaceholder = showsHistoryPlaceholder
1522 self.history = history
1523 self.historyLoading = historyLoading
1524 self.historyError = historyError
1525 self.historyCreditStatus = historyCreditStatus
1526 self.onLoadHistory = onLoadHistory
1527 }
1528
1529 var body: some View {
1530 CollapsibleSectionView(title: "Ownership", isCollapsed: $isCollapsed) {
1531 CardView(allowsHorizontalScroll: false) {
1532 SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1533 if loading {
1534 ProgressView("Fetching RDAP ownership…")
1535 .appLoadingStyle()
1536 } else {
1537 ForEach(rows) { row in
1538 LabeledValueRow(row: row)
1539 }
1540 if let error, rows.allSatisfy({ $0.value == "Unavailable" }) {
1541 MessageRowView(text: error, isError: error != "Unavailable")
1542 .padding(.top, 4)
1543 }
1544 VStack(alignment: .leading, spacing: 8) {
1545 HStack {
1546 Text("History")
1547 .font(appDensity.font(.caption))
1548 .foregroundStyle(.secondary)
1549 Spacer()
1550 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
1551 Button("Load") {
1552 onLoadHistory()
1553 }
1554 .buttonStyle(.bordered)
1555 .font(appDensity.font(.caption2))
1556 }
1557 }
1558 if historyLoading {
1559 ProgressView("Loading history…")
1560 .appLoadingStyle()
1561 } else if !history.isEmpty {
1562 ForEach(history) { event in
1563 VStack(alignment: .leading, spacing: 3) {
1564 Text(event.date.formatted(date: .abbreviated, time: .omitted))
1565 .font(appDensity.font(.caption2))
1566 .foregroundStyle(.secondary)
1567 Text(event.summary)
1568 .font(appDensity.font(.caption))
1569 Text(event.source)
1570 .font(appDensity.font(.caption2))
1571 .foregroundStyle(.secondary)
1572 }
1573 }
1574 } else if let historyError {
1575 MessageRowView(text: historyError, isError: false)
1576 } else if showsHistoryPlaceholder {
1577 MessageRowView(text: "Ownership history available in Pro+", isError: false)
1578 }
1579 }
1580 }
1581 }
1582 }
1583 }
1584}
1585
1586struct IntelligenceSectionView: View {
1587 @Environment(\.appDensity) private var appDensity
1588 @Binding var isCollapsed: Bool
1589 let report: DomainReport
1590 let showsPlaceholder: Bool
1591
1592 var body: some View {
1593 CollapsibleSectionView(title: "Data+ Intelligence", isCollapsed: $isCollapsed) {
1594 CardView(allowsHorizontalScroll: false) {
1595 if showsPlaceholder {
1596 MessageRowView(text: "Richer intelligence history, hosting analysis, and risk signals are available in Pro+", isError: false)
1597 } else {
1598 if let provider = report.inferredProvider {
1599 intelligenceBlock(title: "Infrastructure") {
1600 LabeledValueRow(row: .init(label: "Provider", value: provider.name, tone: .primary))
1601 if !provider.evidence.isEmpty {
1602 MessageRowView(text: provider.evidence.joined(separator: " • "), isError: false)
1603 }
1604 if !report.priorProviders.isEmpty {
1605 LabeledValueRow(row: .init(label: "Prior", value: report.priorProviders.joined(separator: ", "), tone: .secondary))
1606 }
1607 }
1608 }
1609 if let classification = report.domainClassification {
1610 intelligenceBlock(title: "Classification") {
1611 LabeledValueRow(row: .init(label: "Purpose", value: classification.kind.title, tone: .primary))
1612 MessageRowView(text: classification.reasons.joined(separator: " • "), isError: false)
1613 }
1614 }
1615 intelligenceBlock(title: "Risk Signals") {
1616 if report.riskSignals.isEmpty {
1617 MessageRowView(text: "No material historical risk signals detected", isError: false)
1618 } else {
1619 ForEach(report.riskSignals.prefix(4)) { signal in
1620 VStack(alignment: .leading, spacing: 3) {
1621 Text(signal.title)
1622 .font(appDensity.font(.caption, weight: .semibold))
1623 Text(signal.detail)
1624 .font(appDensity.font(.caption2))
1625 .foregroundStyle(.secondary)
1626 }
1627 }
1628 }
1629 }
1630 intelligenceBlock(title: "Ownership History") {
1631 if report.ownershipTransitions.isEmpty {
1632 MessageRowView(text: "No ownership transitions observed locally", isError: false)
1633 } else {
1634 ForEach(report.ownershipTransitions.prefix(4)) { event in
1635 intelligenceEventRow(date: event.date, title: event.summary)
1636 }
1637 }
1638 }
1639 intelligenceBlock(title: "Hosting History") {
1640 if report.hostingTransitions.isEmpty {
1641 MessageRowView(text: "No hosting transitions observed locally", isError: false)
1642 } else {
1643 ForEach(report.hostingTransitions.prefix(4)) { event in
1644 intelligenceEventRow(date: event.date, title: event.summary)
1645 }
1646 }
1647 }
1648 intelligenceBlock(title: "Subdomain Intelligence") {
1649 if report.subdomainHistory.isEmpty {
1650 MessageRowView(text: "No subdomain history available", isError: false)
1651 } else {
1652 ForEach(report.subdomainHistory.prefix(5)) { item in
1653 VStack(alignment: .leading, spacing: 3) {
1654 HStack {
1655 Text(item.hostname)
1656 .font(appDensity.font(.caption))
1657 Spacer()
1658 if item.isEphemeral {
1659 Text("Ephemeral")
1660 .font(appDensity.font(.caption2))
1661 .foregroundStyle(.yellow)
1662 }
1663 }
1664 Text("First \(item.firstSeen.formatted(date: .abbreviated, time: .omitted)) • Last \(item.lastSeen.formatted(date: .abbreviated, time: .omitted)) • Seen \(item.recurrenceCount)x")
1665 .font(appDensity.font(.caption2))
1666 .foregroundStyle(.secondary)
1667 }
1668 }
1669 }
1670 }
1671 intelligenceBlock(title: "Timeline") {
1672 if report.intelligenceTimeline.isEmpty {
1673 MessageRowView(text: "No inferred intelligence events yet", isError: false)
1674 } else {
1675 ForEach(report.intelligenceTimeline.prefix(5)) { event in
1676 intelligenceEventRow(date: event.date, title: "\(event.title): \(event.detail)")
1677 }
1678 }
1679 }
1680 }
1681 }
1682 }
1683 }
1684
1685 @ViewBuilder
1686 private func intelligenceBlock<Content: View>(title: String, @ViewBuilder content: () -> Content) -> some View {
1687 VStack(alignment: .leading, spacing: 8) {
1688 Text(title)
1689 .font(appDensity.font(.subheadline, weight: .semibold))
1690 .foregroundStyle(.cyan)
1691 content()
1692 }
1693 }
1694
1695 private func intelligenceEventRow(date: Date, title: String) -> some View {
1696 VStack(alignment: .leading, spacing: 3) {
1697 Text(date.formatted(date: .abbreviated, time: .omitted))
1698 .font(appDensity.font(.caption2))
1699 .foregroundStyle(.secondary)
1700 Text(title)
1701 .font(appDensity.font(.caption))
1702 }
1703 }
1704}
1705
1706struct SubdomainsSectionView: View {
1707 @Environment(\.appDensity) private var appDensity
1708 @Binding var isCollapsed: Bool
1709 let rows: [SubdomainRowViewData]
1710 let groups: [SubdomainGroup]
1711 let loading: Bool
1712 let error: String?
1713 let provenance: SectionProvenance?
1714 let confidence: ConfidenceLevel?
1715 let showsExtendedPlaceholder: Bool
1716 let extendedCount: Int
1717 let extendedLoading: Bool
1718 let extendedError: String?
1719 let extendedCreditStatus: UsageCreditStatus?
1720 let onLoadExtended: (() -> Void)?
1721
1722 init(
1723 isCollapsed: Binding<Bool>,
1724 rows: [SubdomainRowViewData],
1725 groups: [SubdomainGroup],
1726 loading: Bool,
1727 error: String?,
1728 provenance: SectionProvenance?,
1729 confidence: ConfidenceLevel?,
1730 showsExtendedPlaceholder: Bool,
1731 extendedCount: Int = 0,
1732 extendedLoading: Bool = false,
1733 extendedError: String? = nil,
1734 extendedCreditStatus: UsageCreditStatus? = nil,
1735 onLoadExtended: (() -> Void)? = nil
1736 ) {
1737 _isCollapsed = isCollapsed
1738 self.rows = rows
1739 self.groups = groups
1740 self.loading = loading
1741 self.error = error
1742 self.provenance = provenance
1743 self.confidence = confidence
1744 self.showsExtendedPlaceholder = showsExtendedPlaceholder
1745 self.extendedCount = extendedCount
1746 self.extendedLoading = extendedLoading
1747 self.extendedError = extendedError
1748 self.extendedCreditStatus = extendedCreditStatus
1749 self.onLoadExtended = onLoadExtended
1750 }
1751
1752 var body: some View {
1753 CollapsibleSectionView(title: "Subdomains", isCollapsed: $isCollapsed, subtitle: "\(rows.count) found") {
1754 CardView(allowsHorizontalScroll: false) {
1755 SectionTrustMetadataView(provenance: provenance, confidence: confidence)
1756 if loading {
1757 ProgressView("Checking certificate transparency…")
1758 .appLoadingStyle()
1759 } else if rows.isEmpty {
1760 MessageRowView(text: error ?? "No passive subdomains found", isError: false)
1761 if showsExtendedPlaceholder {
1762 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
1763 .padding(.top, 4)
1764 }
1765 } else {
1766 if let onLoadExtended, extendedCount == 0, !extendedLoading, !showsExtendedPlaceholder {
1767 Button("Load extended results") {
1768 onLoadExtended()
1769 }
1770 .buttonStyle(.bordered)
1771 .font(appDensity.font(.caption2))
1772 }
1773 if !groups.isEmpty {
1774 Text("Groups")
1775 .font(appDensity.font(.caption2))
1776 .foregroundStyle(.secondary)
1777 ForEach(groups) { group in
1778 HStack {
1779 Text("\(group.label).*")
1780 .font(appDensity.font(.caption))
1781 .foregroundStyle(.cyan)
1782 Spacer()
1783 Text("\(group.subdomains.count)")
1784 .font(appDensity.font(.caption2))
1785 .foregroundStyle(.secondary)
1786 }
1787 }
1788 }
1789 ForEach(rows) { row in
1790 HStack(spacing: 8) {
1791 Text(row.hostname)
1792 .font(appDensity.font(.caption))
1793 .foregroundStyle(.primary)
1794 .textSelection(.enabled)
1795 Spacer()
1796 if row.isInteresting {
1797 Text("Interesting")
1798 .font(.system(.caption2, design: .monospaced))
1799 .foregroundStyle(.yellow)
1800 .padding(.horizontal, 8)
1801 .padding(.vertical, 4)
1802 .background(Color.yellow.opacity(0.14))
1803 .clipShape(Capsule())
1804 }
1805 }
1806 }
1807 if extendedLoading {
1808 ProgressView("Loading extended subdomains…")
1809 .appLoadingStyle()
1810 .padding(.top, 4)
1811 } else if extendedCount > 0 {
1812 MessageRowView(text: "\(extendedCount) extended results included", isError: false)
1813 .padding(.top, 4)
1814 } else if let extendedError {
1815 MessageRowView(text: extendedError, isError: false)
1816 .padding(.top, 4)
1817 } else if showsExtendedPlaceholder {
1818 MessageRowView(text: "Extended subdomain discovery available in Pro+", isError: false)
1819 .padding(.top, 4)
1820 }
1821 }
1822 }
1823 }
1824 }
1825}
1826
1827struct DNSSectionView: View {
1828 @Environment(\.appDensity) private var appDensity
1829 @Binding var isCollapsed: Bool
1830 let dnssecLabel: String?
1831 let patternSummary: DNSPatternSummary?
1832 let sections: [DNSRecordSectionViewData]
1833 let ptrMessage: SectionMessageViewData?
1834 let loading: Bool
1835 let dnsProvenance: SectionProvenance?
1836 let ptrProvenance: SectionProvenance?
1837 let sectionError: String?
1838 let history: [DNSHistoryEvent]
1839 let historyLoading: Bool
1840 let historyError: String?
1841 let showsHistoryPlaceholder: Bool
1842 let historyCreditStatus: UsageCreditStatus?
1843 let onLoadHistory: (() -> Void)?
1844
1845 init(
1846 isCollapsed: Binding<Bool>,
1847 dnssecLabel: String?,
1848 patternSummary: DNSPatternSummary?,
1849 sections: [DNSRecordSectionViewData],
1850 ptrMessage: SectionMessageViewData?,
1851 loading: Bool,
1852 dnsProvenance: SectionProvenance?,
1853 ptrProvenance: SectionProvenance?,
1854 sectionError: String?,
1855 history: [DNSHistoryEvent] = [],
1856 historyLoading: Bool = false,
1857 historyError: String? = nil,
1858 showsHistoryPlaceholder: Bool = false,
1859 historyCreditStatus: UsageCreditStatus? = nil,
1860 onLoadHistory: (() -> Void)? = nil
1861 ) {
1862 _isCollapsed = isCollapsed
1863 self.dnssecLabel = dnssecLabel
1864 self.patternSummary = patternSummary
1865 self.sections = sections
1866 self.ptrMessage = ptrMessage
1867 self.loading = loading
1868 self.dnsProvenance = dnsProvenance
1869 self.ptrProvenance = ptrProvenance
1870 self.sectionError = sectionError
1871 self.history = history
1872 self.historyLoading = historyLoading
1873 self.historyError = historyError
1874 self.showsHistoryPlaceholder = showsHistoryPlaceholder
1875 self.historyCreditStatus = historyCreditStatus
1876 self.onLoadHistory = onLoadHistory
1877 }
1878
1879 var body: some View {
1880 CollapsibleSectionView(title: "DNS", isCollapsed: $isCollapsed, subtitle: dnssecLabel) {
1881 if loading {
1882 LoadingCardView(text: "Querying DNS…")
1883 } else if let sectionError, sections.isEmpty {
1884 MessageCardView(text: sectionError, isError: true)
1885 } else {
1886 if dnsProvenance != nil {
1887 CardView(allowsHorizontalScroll: false) {
1888 SectionTrustMetadataView(provenance: dnsProvenance, confidence: nil)
1889 if let patternSummary {
1890 if !patternSummary.providers.isEmpty {
1891 MessageRowView(text: "Providers: \(patternSummary.providers.joined(separator: ", "))", isError: false)
1892 }
1893 if !patternSummary.patterns.isEmpty {
1894 ForEach(Array(patternSummary.patterns.enumerated()), id: \.offset) { _, pattern in
1895 MessageRowView(text: pattern, isError: false)
1896 }
1897 }
1898 }
1899 }
1900 }
1901 ForEach(sections) { section in
1902 CardView {
1903 Text(section.title)
1904 .font(.system(.subheadline, design: .monospaced))
1905 .fontWeight(.semibold)
1906 .foregroundStyle(.cyan)
1907
1908 if let message = section.message {
1909 MessageRowView(text: message.text, isError: message.isError)
1910 }
1911
1912 ForEach(section.rows) { row in
1913 LabeledValueRow(row: row)
1914 }
1915
1916 if let wildcardTitle = section.wildcardTitle {
1917 Text(wildcardTitle)
1918 .font(.system(.caption, design: .monospaced))
1919 .foregroundStyle(.secondary)
1920 .padding(.top, 4)
1921 ForEach(section.wildcardRows) { row in
1922 LabeledValueRow(row: row)
1923 }
1924 }
1925 }
1926 }
1927
1928 if let ptrMessage {
1929 CardView {
1930 Text("PTR")
1931 .font(.system(.subheadline, design: .monospaced))
1932 .fontWeight(.semibold)
1933 .foregroundStyle(.cyan)
1934 SectionTrustMetadataView(provenance: ptrProvenance, confidence: nil)
1935 MessageRowView(text: ptrMessage.text, isError: ptrMessage.isError)
1936 }
1937 }
1938
1939 CardView(allowsHorizontalScroll: false) {
1940 HStack {
1941 Text("History")
1942 .font(appDensity.font(.subheadline, weight: .semibold))
1943 .foregroundStyle(.cyan)
1944 Spacer()
1945 if let onLoadHistory, history.isEmpty, !historyLoading, !showsHistoryPlaceholder {
1946 Button("Load") {
1947 onLoadHistory()
1948 }
1949 .buttonStyle(.bordered)
1950 .font(appDensity.font(.caption2))
1951 }
1952 }
1953 if historyLoading {
1954 ProgressView("Loading DNS history…")
1955 .appLoadingStyle()
1956 } else if !history.isEmpty {
1957 ForEach(history) { event in
1958 VStack(alignment: .leading, spacing: 3) {
1959 Text(event.date.formatted(date: .abbreviated, time: .omitted))
1960 .font(appDensity.font(.caption2))
1961 .foregroundStyle(.secondary)
1962 Text(event.summary)
1963 .font(appDensity.font(.caption))
1964 if !event.aRecords.isEmpty {
1965 Text("A: \(event.aRecords.joined(separator: ", "))")
1966 .font(appDensity.font(.caption2))
1967 .foregroundStyle(.secondary)
1968 }
1969 if !event.nameservers.isEmpty {
1970 Text("NS: \(event.nameservers.joined(separator: ", "))")
1971 .font(appDensity.font(.caption2))
1972 .foregroundStyle(.secondary)
1973 }
1974 }
1975 }
1976 } else if let historyError {
1977 MessageRowView(text: historyError, isError: false)
1978 } else if showsHistoryPlaceholder {
1979 MessageRowView(text: "DNS history available in Pro+", isError: false)
1980 }
1981 }
1982 }
1983 }
1984 }
1985}
1986
1987struct WebSectionView: View {
1988 @Environment(\.appDensity) private var appDensity
1989 @Binding var isCollapsed: Bool
1990 let certificateRows: [InfoRowViewData]
1991 let sslInfo: SSLCertificateInfo?
1992 let tlsSummary: WebResultSummary?
1993 let sslLoading: Bool
1994 let sslError: String?
1995 let tlsProvenance: SectionProvenance?
1996 let responseRows: [InfoRowViewData]
1997 let headers: [HTTPHeader]
1998 let headersLoading: Bool
1999 let headersError: String?
2000 let httpProvenance: SectionProvenance?
2001 let redirects: [RedirectHopViewData]
2002 let redirectLoading: Bool
2003 let redirectError: String?
2004 let redirectProvenance: SectionProvenance?
2005 let finalURL: String?
2006
2007 var body: some View {
2008 CollapsibleSectionView(title: "Web", isCollapsed: $isCollapsed) {
2009 CardView {
2010 HStack {
2011 Text("TLS")
2012 .font(appDensity.font(.subheadline, weight: .semibold))
2013 .foregroundStyle(.cyan)
2014 Spacer()
2015 if !sslLoading {
2016 AppStatusBadgeView(model: AppStatusFactory.tls(sslInfo: sslInfo, error: sslError))
2017 }
2018 }
2019 SectionTrustMetadataView(provenance: tlsProvenance, confidence: nil)
2020 if !sslLoading, let tlsSummary {
2021 LabeledValueRow(row: InfoRowViewData(label: "TLS Grade", value: tlsSummary.tlsGrade.rawValue, tone: tlsSummary.tlsGrade == .a ? .success : (tlsSummary.tlsGrade == .f ? .failure : .warning)))
2022 ForEach(Array(tlsSummary.tlsHighlights.enumerated()), id: \.offset) { _, highlight in
2023 MessageRowView(text: highlight, isError: isTLSHighlightError(highlight))
2024 }
2025 }
2026 if sslLoading {
2027 ProgressView("Checking certificate…")
2028 .appLoadingStyle()
2029 } else if let sslError {
2030 MessageRowView(text: sslError, isError: true)
2031 } else {
2032 ForEach(certificateRows) { row in
2033 LabeledValueRow(row: row)
2034 }
2035 if let sslInfo, !sslInfo.subjectAltNames.isEmpty {
2036 Text("SANs")
2037 .font(appDensity.font(.caption2))
2038 .foregroundStyle(.secondary)
2039 ForEach(sslInfo.subjectAltNames, id: \.self) { san in
2040 HStack(alignment: .top, spacing: 8) {
2041 Text(san)
2042 .font(appDensity.font(.caption))
2043 .lineLimit(nil)
2044 .fixedSize(horizontal: false, vertical: true)
2045 .textSelection(.enabled)
2046 Spacer()
2047 AppCopyButton(value: san, label: "Copy certificate SAN")
2048 }
2049 }
2050 }
2051 }
2052 }
2053
2054 CardView {
2055 Text("Headers")
2056 .font(appDensity.font(.subheadline, weight: .semibold))
2057 .foregroundStyle(.cyan)
2058 SectionTrustMetadataView(provenance: httpProvenance, confidence: nil)
2059 if headersLoading {
2060 ProgressView("Fetching headers…")
2061 .appLoadingStyle()
2062 } else if let headersError {
2063 MessageRowView(text: headersError, isError: true)
2064 } else {
2065 ForEach(responseRows) { row in
2066 LabeledValueRow(row: row)
2067 }
2068 if headers.isEmpty {
2069 MessageRowView(text: "No HTTP headers returned", isError: false)
2070 } else {
2071 ForEach(headers) { header in
2072 HStack(alignment: .top, spacing: 4) {
2073 Text(header.name + ":")
2074 .font(appDensity.font(.caption))
2075 .foregroundStyle(header.isSecurityHeader ? .yellow : .cyan)
2076 Text(header.value)
2077 .font(appDensity.font(.caption))
2078 .foregroundStyle(.primary)
2079 .textSelection(.enabled)
2080 }
2081 }
2082 }
2083 }
2084 }
2085
2086 CardView {
2087 HStack {
2088 Text("Redirects")
2089 .font(appDensity.font(.subheadline, weight: .semibold))
2090 .foregroundStyle(.cyan)
2091 Spacer()
2092 if let finalURL {
2093 AppCopyButton(value: finalURL, label: "Copy redirect URL")
2094 }
2095 }
2096 SectionTrustMetadataView(provenance: redirectProvenance, confidence: nil)
2097 if redirectLoading {
2098 ProgressView("Tracing redirects…")
2099 .appLoadingStyle()
2100 } else if let redirectError {
2101 MessageRowView(text: redirectError, isError: true)
2102 } else if redirects.isEmpty {
2103 MessageRowView(text: "No redirect data available", isError: false)
2104 } else {
2105 if let finalURL {
2106 LabeledValueRow(row: InfoRowViewData(label: "Final URL", value: finalURL, tone: .secondary))
2107 }
2108 ForEach(redirects) { redirect in
2109 HStack(alignment: .top, spacing: 6) {
2110 Text(redirect.stepLabel)
2111 .font(appDensity.font(.caption))
2112 .foregroundStyle(.secondary)
2113 .frame(width: 16, alignment: .trailing)
2114 Text(redirect.statusCode)
2115 .font(appDensity.font(.caption))
2116 .foregroundStyle(.cyan)
2117 .frame(width: 36, alignment: .leading)
2118 Text(redirect.url)
2119 .font(appDensity.font(.caption))
2120 .textSelection(.enabled)
2121 AppCopyButton(value: redirect.url, label: "Copy redirect URL")
2122 if redirect.isFinal {
2123 Text("(final)")
2124 .font(appDensity.font(.caption2))
2125 .foregroundStyle(.secondary)
2126 }
2127 }
2128 }
2129 }
2130 }
2131 }
2132 }
2133
2134 private func isTLSHighlightError(_ highlight: String) -> Bool {
2135 let normalized = highlight.lowercased()
2136 if normalized.contains("no weak tls indicators were detected") {
2137 return false
2138 }
2139 return normalized.contains("expires")
2140 || normalized.contains("weak")
2141 || normalized.contains("tls 1.0")
2142 || normalized.contains("tls 1.1")
2143 }
2144}
2145
2146struct EmailSectionView: View {
2147 @Environment(\.appDensity) private var appDensity
2148 @Binding var isCollapsed: Bool
2149 let rows: [EmailRowViewData]
2150 let assessment: EmailSecuritySummary?
2151 let loading: Bool
2152 let provenance: SectionProvenance?
2153 let confidence: ConfidenceLevel?
2154 let error: String?
2155
2156 var body: some View {
2157 CollapsibleSectionView(title: "Email", isCollapsed: $isCollapsed) {
2158 CardView {
2159 SectionTrustMetadataView(provenance: provenance, confidence: confidence)
2160 HStack {
2161 Spacer()
2162 AppStatusBadgeView(model: AppStatusFactory.email(nil, error: error))
2163 .opacity(loading ? 0 : 1)
2164 }
2165 if let assessment, let grade = assessment.grade {
2166 LabeledValueRow(row: InfoRowViewData(label: "Grade", value: grade.rawValue, tone: grade == .a ? .success : (grade == .f ? .failure : .warning)))
2167 if !assessment.reasons.isEmpty {
2168 Text(assessment.reasons.joined(separator: " | "))
2169 .font(appDensity.font(.caption2))
2170 .foregroundStyle(.secondary)
2171 }
2172 }
2173 if loading {
2174 ProgressView("Checking email records…")
2175 .appLoadingStyle()
2176 } else if let error {
2177 MessageRowView(text: error, isError: true)
2178 } else if rows.isEmpty {
2179 MessageRowView(text: "No email security records found", isError: false)
2180 } else {
2181 ForEach(rows) { row in
2182 VStack(alignment: .leading, spacing: 4) {
2183 HStack(spacing: 8) {
2184 Text(row.label)
2185 .font(appDensity.font(.caption))
2186 .foregroundStyle(.cyan)
2187 .frame(width: 76, alignment: .leading)
2188 AppStatusBadgeView(model: emailRowBadge(row))
2189 }
2190 Text(row.detail)
2191 .font(appDensity.font(.caption2))
2192 .foregroundStyle(.primary)
2193 .textSelection(.enabled)
2194 if let auxiliaryDetail = row.auxiliaryDetail {
2195 Text(auxiliaryDetail)
2196 .font(appDensity.font(.caption2))
2197 .foregroundStyle(.secondary)
2198 }
2199 }
2200 }
2201 }
2202 }
2203 }
2204 }
2205
2206 private func emailRowBadge(_ row: EmailRowViewData) -> AppStatusBadgeModel {
2207 switch row.statusTone {
2208 case .success:
2209 return .init(title: row.status, systemImage: "checkmark.shield.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
2210 case .warning:
2211 return .init(title: row.status, systemImage: "shield.lefthalf.filled", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
2212 case .failure:
2213 return .init(title: row.status, systemImage: "minus.circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2214 case .primary, .secondary:
2215 return .init(title: row.status, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2216 }
2217 }
2218}
2219
2220struct NetworkSectionView: View {
2221 @Environment(\.appDensity) private var appDensity
2222 @Binding var isCollapsed: Bool
2223 let reachabilityRows: [ReachabilityRowViewData]
2224 let reachabilityLoading: Bool
2225 let reachabilityError: String?
2226 let reachabilityProvenance: SectionProvenance?
2227 let locationRows: [InfoRowViewData]
2228 let geolocation: IPGeolocation?
2229 let geolocationLoading: Bool
2230 let geolocationError: String?
2231 let geolocationProvenance: SectionProvenance?
2232 let geolocationConfidence: ConfidenceLevel?
2233 let standardPortRows: [PortScanRowViewData]
2234 let customPortRows: [PortScanRowViewData]
2235 let portScanLoading: Bool
2236 let portScanError: String?
2237 let portScanProvenance: SectionProvenance?
2238 let customPortScanLoading: Bool
2239 let customPortScanError: String?
2240 let isCloudflareProxied: Bool
2241 @Binding var customPortsExpanded: Bool
2242 @Binding var customPortInput: String
2243 let onScanCustomPorts: () -> Void
2244
2245 var body: some View {
2246 CollapsibleSectionView(title: "Network", isCollapsed: $isCollapsed) {
2247 CardView {
2248 Text("Reachability")
2249 .font(appDensity.font(.subheadline, weight: .semibold))
2250 .foregroundStyle(.cyan)
2251 SectionTrustMetadataView(provenance: reachabilityProvenance, confidence: nil)
2252 if reachabilityLoading {
2253 ProgressView("Checking ports…")
2254 .appLoadingStyle()
2255 } else if let reachabilityError {
2256 MessageRowView(text: reachabilityError, isError: true)
2257 } else {
2258 ForEach(reachabilityRows) { row in
2259 HStack {
2260 Text(row.portLabel)
2261 .font(appDensity.font(.caption))
2262 Spacer()
2263 Text(row.latencyLabel)
2264 .font(appDensity.font(.caption2))
2265 .foregroundStyle(.secondary)
2266 AppStatusBadgeView(model: reachabilityBadge(row))
2267 }
2268 }
2269 }
2270 }
2271
2272 CardView(allowsHorizontalScroll: false) {
2273 Text("Location")
2274 .font(appDensity.font(.subheadline, weight: .semibold))
2275 .foregroundStyle(.cyan)
2276 SectionTrustMetadataView(provenance: geolocationProvenance, confidence: geolocationConfidence)
2277 if geolocationLoading {
2278 ProgressView("Looking up location…")
2279 .appLoadingStyle()
2280 } else if let geolocationError, geolocation == nil {
2281 MessageRowView(text: geolocationError, isError: geolocationError != "No A record available")
2282 } else if let geolocation {
2283 ForEach(locationRows) { row in
2284 LabeledValueRow(row: row)
2285 }
2286 if let latitude = geolocation.latitude, let longitude = geolocation.longitude {
2287 let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
2288 Map(initialPosition: .region(MKCoordinateRegion(
2289 center: coordinate,
2290 span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
2291 ))) {
2292 Marker(geolocation.ip, coordinate: coordinate)
2293 }
2294 .mapStyle(.standard)
2295 .frame(maxWidth: .infinity)
2296 .frame(height: 180)
2297 .cornerRadius(8)
2298 }
2299 } else {
2300 MessageRowView(text: "No location data available", isError: false)
2301 }
2302 }
2303
2304 CardView(allowsHorizontalScroll: false) {
2305 Text("Port Scan")
2306 .font(appDensity.font(.subheadline, weight: .semibold))
2307 .foregroundStyle(.cyan)
2308 SectionTrustMetadataView(provenance: portScanProvenance, confidence: nil)
2309
2310 if isCloudflareProxied {
2311 Text("Domain is behind Cloudflare's proxy. Results reflect the edge, not the origin.")
2312 .font(appDensity.font(.caption2))
2313 .foregroundStyle(.orange)
2314 .fixedSize(horizontal: false, vertical: true)
2315 }
2316
2317 if portScanLoading {
2318 ProgressView("Scanning ports…")
2319 .appLoadingStyle()
2320 } else if let portScanError, standardPortRows.isEmpty {
2321 MessageRowView(text: portScanError, isError: true)
2322 } else {
2323 Text("Standard Ports")
2324 .font(.system(.caption, design: .monospaced))
2325 .foregroundStyle(.secondary)
2326 PortRowsView(rows: standardPortRows)
2327 }
2328
2329 DisclosureGroup("Custom Ports", isExpanded: $customPortsExpanded) {
2330 VStack(alignment: .leading, spacing: 10) {
2331 TextField("8888, 9000, 27017", text: $customPortInput)
2332 .font(appDensity.font(.caption))
2333 .textInputAutocapitalization(.never)
2334 .autocorrectionDisabled()
2335 .keyboardType(.numberPad)
2336 .padding(10)
2337 .background(Color(.systemGray6).opacity(0.5))
2338 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
2339
2340 Button("Scan") {
2341 AppHaptics.refresh()
2342 onScanCustomPorts()
2343 }
2344 .buttonStyle(.borderedProminent)
2345 .disabled(customPortScanLoading)
2346
2347 if customPortScanLoading {
2348 ProgressView("Scanning custom ports…")
2349 .appLoadingStyle()
2350 } else if let customPortScanError {
2351 MessageRowView(text: customPortScanError, isError: true)
2352 } else {
2353 PortRowsView(rows: customPortRows)
2354 }
2355 }
2356 .padding(.top, 8)
2357 }
2358 .font(.system(.caption, design: .monospaced))
2359 .tint(.secondary)
2360 }
2361 }
2362 }
2363
2364 private func reachabilityBadge(_ row: ReachabilityRowViewData) -> AppStatusBadgeModel {
2365 switch row.statusTone {
2366 case .success:
2367 return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
2368 case .warning:
2369 return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
2370 case .failure:
2371 return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: .red, backgroundColor: .red.opacity(0.16))
2372 case .primary, .secondary:
2373 return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2374 }
2375 }
2376}
2377
2378struct PortRowsView: View {
2379 @Environment(\.appDensity) private var appDensity
2380 let rows: [PortScanRowViewData]
2381
2382 var body: some View {
2383 if rows.isEmpty {
2384 MessageRowView(text: "No results", isError: false)
2385 } else {
2386 ForEach(rows) { row in
2387 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
2388 HStack {
2389 Text(row.portLabel)
2390 .font(appDensity.font(.caption))
2391 .frame(width: 52, alignment: .leading)
2392 Text(row.service)
2393 .font(appDensity.font(.caption))
2394 .foregroundStyle(.primary)
2395 Spacer()
2396 if let durationLabel = row.durationLabel {
2397 Text(durationLabel)
2398 .font(appDensity.font(.caption2))
2399 .foregroundStyle(.secondary)
2400 }
2401 AppStatusBadgeView(model: portBadge(row))
2402 }
2403 if let banner = row.banner {
2404 Text(banner)
2405 .font(appDensity.font(.caption2))
2406 .foregroundStyle(.secondary)
2407 .padding(.leading, 8)
2408 }
2409 }
2410 .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
2411 }
2412 }
2413 }
2414
2415 private func portBadge(_ row: PortScanRowViewData) -> AppStatusBadgeModel {
2416 switch row.statusTone {
2417 case .success:
2418 return .init(title: row.statusLabel, systemImage: "checkmark.circle.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
2419 case .warning:
2420 return .init(title: row.statusLabel, systemImage: "exclamationmark.triangle.fill", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
2421 case .failure:
2422 return .init(title: row.statusLabel, systemImage: "xmark.circle.fill", foregroundColor: .red, backgroundColor: .red.opacity(0.16))
2423 case .primary, .secondary:
2424 return .init(title: row.statusLabel, systemImage: "circle", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.55))
2425 }
2426 }
2427}
2428
2429struct SectionTitleView: View {
2430 @Environment(\.appDensity) private var appDensity
2431 let title: String
2432
2433 var body: some View {
2434 Text(title)
2435 .font(appDensity.font(.headline, design: .default, weight: .semibold))
2436 .foregroundStyle(.white)
2437 }
2438}
2439
2440struct CardView<Content: View>: View {
2441 @Environment(\.appDensity) private var appDensity
2442 let allowsHorizontalScroll: Bool
2443 let content: Content
2444
2445 init(allowsHorizontalScroll: Bool = true, @ViewBuilder content: () -> Content) {
2446 self.allowsHorizontalScroll = allowsHorizontalScroll
2447 self.content = content()
2448 }
2449
2450 var body: some View {
2451 Group {
2452 if allowsHorizontalScroll {
2453 ScrollView(.horizontal) {
2454 cardContent
2455 .scrollTargetLayout()
2456 }
2457 .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
2458 } else {
2459 cardContent
2460 .frame(maxWidth: .infinity, alignment: .leading)
2461 }
2462 }
2463 .frame(maxWidth: .infinity, alignment: .leading)
2464 .padding(appDensity.metrics.cardPadding)
2465 .background(Color(.systemGray6).opacity(0.5))
2466 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
2467 }
2468
2469 private var cardContent: some View {
2470 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
2471 content
2472 }
2473 }
2474}
2475
2476struct LoadingCardView: View {
2477 let text: String
2478
2479 var body: some View {
2480 CardView {
2481 ProgressView(text)
2482 .appLoadingStyle()
2483 .frame(maxWidth: .infinity, alignment: .center)
2484 }
2485 }
2486}
2487
2488struct MessageCardView: View {
2489 let text: String
2490 let isError: Bool
2491
2492 var body: some View {
2493 CardView {
2494 MessageRowView(text: text, isError: isError)
2495 }
2496 }
2497}
2498
2499struct MessageRowView: View {
2500 @Environment(\.appDensity) private var appDensity
2501 let text: String
2502 let isError: Bool
2503
2504 var body: some View {
2505 Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
2506 .font(appDensity.font(.caption))
2507 .foregroundStyle(isError ? .red : .secondary)
2508 .lineLimit(nil)
2509 .fixedSize(horizontal: false, vertical: true)
2510 }
2511}
2512
2513struct SectionTrustMetadataView: View {
2514 @Environment(\.appDensity) private var appDensity
2515 let provenance: SectionProvenance?
2516 let confidence: ConfidenceLevel?
2517 let note: String?
2518
2519 init(provenance: SectionProvenance?, confidence: ConfidenceLevel?, note: String? = nil) {
2520 self.provenance = provenance
2521 self.confidence = confidence
2522 self.note = note
2523 }
2524
2525 var body: some View {
2526 if provenance != nil || confidence != nil || note != nil {
2527 VStack(alignment: .leading, spacing: 6) {
2528 HStack(spacing: 8) {
2529 if let confidence {
2530 Text("Confidence \(confidence.title)")
2531 .font(appDensity.font(.caption2))
2532 .foregroundStyle(.secondary)
2533 }
2534 if let provenance {
2535 Text(provenance.provider ?? provenance.source)
2536 .font(appDensity.font(.caption2))
2537 .foregroundStyle(.secondary)
2538 Text(provenance.resultSource.label)
2539 .font(appDensity.font(.caption2))
2540 .foregroundStyle(.secondary)
2541 }
2542 }
2543 DisclosureGroup("Details") {
2544 VStack(alignment: .leading, spacing: 4) {
2545 if let provenance {
2546 LabeledValueRow(row: .init(label: "Method", value: provenance.source, tone: .secondary))
2547 if let provider = provenance.provider {
2548 LabeledValueRow(row: .init(label: "Provider", value: provider, tone: .secondary))
2549 }
2550 if let resolver = provenance.resolver {
2551 LabeledValueRow(row: .init(label: "Resolver", value: resolver, tone: .secondary))
2552 }
2553 LabeledValueRow(row: .init(label: "Collected", value: provenance.collectedAt.formatted(date: .abbreviated, time: .shortened), tone: .secondary))
2554 LabeledValueRow(row: .init(label: "Mode", value: provenance.resultSource.label, tone: .secondary))
2555 }
2556 if let note {
2557 LabeledValueRow(row: .init(label: "Note", value: note, tone: .secondary))
2558 }
2559 }
2560 .padding(.top, 4)
2561 }
2562 .font(appDensity.font(.caption))
2563 .tint(.secondary)
2564 }
2565 }
2566 }
2567}
2568
2569struct LabeledValueRow: View {
2570 @Environment(\.appDensity) private var appDensity
2571 let row: InfoRowViewData
2572
2573 var body: some View {
2574 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
2575 HStack(alignment: .top, spacing: 8) {
2576 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
2577 Text(row.label)
2578 .font(appDensity.font(.caption2))
2579 .foregroundStyle(.secondary)
2580 Text(row.value)
2581 .font(appDensity.font(.caption))
2582 .foregroundStyle(ResultColors.color(for: row.tone))
2583 .lineLimit(nil)
2584 .fixedSize(horizontal: false, vertical: true)
2585 .textSelection(.enabled)
2586 }
2587 .frame(maxWidth: .infinity, alignment: .leading)
2588 .layoutPriority(1)
2589 Spacer(minLength: 6)
2590 if !row.value.isEmpty, row.value != "Unavailable" {
2591 AppCopyButton(value: row.value, label: "Copy \(row.label)")
2592 }
2593 }
2594 }
2595 .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
2596 }
2597}
2598
2599enum ResultColors {
2600 static func color(for tone: ResultTone) -> Color {
2601 switch tone {
2602 case .primary:
2603 return .primary
2604 case .secondary:
2605 return .secondary
2606 case .success:
2607 return .green
2608 case .warning:
2609 return .yellow
2610 case .failure:
2611 return .red
2612 }
2613 }
2614}
2615
2616extension DateFormatter {
2617 static let certDate: DateFormatter = {
2618 let formatter = DateFormatter()
2619 formatter.dateStyle = .medium
2620 formatter.timeStyle = .short
2621 return formatter
2622 }()
2623}
2624
2625private extension View {
2626 func appLoadingStyle() -> some View {
2627 font(.system(.caption, design: .monospaced))
2628 }
2629}
2630
2631private extension String {
2632 var nilIfEmpty: String? {
2633 isEmpty ? nil : self
2634 }
2635}
2636
2637struct SettingsView: View {
2638 @Environment(\.appDensity) private var appDensity
2639 @Bindable var viewModel: DomainViewModel
2640 @State private var purchaseService = PurchaseService.shared
2641
2642 var body: some View {
2643 let _ = purchaseService.currentTier
2644
2645 List {
2646 Section("Tier") {
2647 LabeledContent("Status", value: purchaseService.currentTier.title)
2648
2649 if purchaseService.currentTier == .free {
2650 Button("Upgrade") {
2651 viewModel.isPaywallPresented = true
2652 }
2653 } else {
2654 Button("Manage Subscription") {
2655 Task {
2656 await purchaseService.manageSubscription()
2657 }
2658 }
2659 }
2660
2661 Button(purchaseService.isRestoring ? "Restoring…" : "Restore Purchases") {
2662 Task {
2663 await purchaseService.restorePurchases()
2664 }
2665 }
2666 .disabled(purchaseService.isRestoring || purchaseService.isPurchasing)
2667
2668 if let statusMessage = purchaseService.statusMessage {
2669 Text(statusMessage)
2670 .font(appDensity.font(.caption, design: .default))
2671 .foregroundStyle(.secondary)
2672 }
2673
2674 if let errorMessage = purchaseService.errorMessage {
2675 Text(errorMessage)
2676 .font(appDensity.font(.caption, design: .default))
2677 .foregroundStyle(.red)
2678 }
2679 }
2680
2681 Section("Preferences") {
2682 NavigationLink("Tracked Domains") {
2683 WatchlistView(viewModel: viewModel)
2684 }
2685
2686 NavigationLink("Workflows") {
2687 WorkflowsView(viewModel: viewModel)
2688 }
2689
2690 NavigationLink("Display") {
2691 DisplaySettingsView()
2692 }
2693
2694 NavigationLink("History & Network") {
2695 HistoryNetworkSettingsView(viewModel: viewModel)
2696 }
2697 }
2698
2699 Section("Services") {
2700 NavigationLink("Monitoring Activity") {
2701 MonitoringView(viewModel: viewModel)
2702 }
2703
2704 NavigationLink("Integrations") {
2705 IntegrationsSettingsView()
2706 }
2707
2708 NavigationLink("Local API") {
2709 LocalAPISettingsView()
2710 }
2711
2712 NavigationLink("iCloud Sync") {
2713 CloudSyncSettingsView()
2714 }
2715
2716 NavigationLink("Monitoring") {
2717 MonitoringSettingsView(viewModel: viewModel)
2718 }
2719
2720 NavigationLink("Scheduled Reports") {
2721 ScheduledReportsView()
2722 }
2723 }
2724
2725 Section("Data") {
2726 NavigationLink("Import & Export") {
2727 DataPortabilitySettingsView(viewModel: viewModel)
2728 }
2729
2730 NavigationLink("Data Management") {
2731 DataManagementSettingsView(viewModel: viewModel)
2732 }
2733 }
2734
2735 Section("About") {
2736 NavigationLink("App Info") {
2737 AboutSettingsView()
2738 }
2739 }
2740 }
2741 .navigationTitle("Settings")
2742 }
2743}
2744
2745private struct DisplaySettingsView: View {
2746 @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue
2747
2748 var body: some View {
2749 Form {
2750 Section("Display") {
2751 Picker("Density", selection: $storedDensity) {
2752 ForEach(AppDensity.allCases) { density in
2753 Text(density.title).tag(density.rawValue)
2754 }
2755 }
2756 }
2757 }
2758 .navigationTitle("Display")
2759 }
2760}
2761
2762private struct HistoryNetworkSettingsView: View {
2763 @Environment(\.appDensity) private var appDensity
2764 @Bindable var viewModel: DomainViewModel
2765 @AppStorage(DNSResolverOption.userDefaultsKey) private var storedResolverURL = DNSResolverOption.defaultURLString
2766 @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue
2767
2768 @State private var resolverOption: DNSResolverOption = .cloudflare
2769 @State private var customResolverURL = DNSResolverOption.defaultURLString
2770
2771 private var customResolverError: String? {
2772 guard resolverOption == .custom else { return nil }
2773 return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
2774 }
2775
2776 var body: some View {
2777 Form {
2778 Section("History") {
2779 Picker(
2780 "Auto-prune",
2781 selection: Binding(
2782 get: { viewModel.historyAutoPruneOption },
2783 set: { viewModel.setHistoryAutoPruneOption($0) }
2784 )
2785 ) {
2786 ForEach(HistoryAutoPruneOption.allCases) { option in
2787 Text(option.title).tag(option)
2788 }
2789 }
2790
2791 Text("History remains local-first. Auto-prune only trims older local snapshots on this device and defaults to unlimited.")
2792 .font(appDensity.font(.caption, design: .default))
2793 .foregroundStyle(.secondary)
2794 }
2795
2796 Section("Network") {
2797 Picker("Resolver", selection: $resolverOption) {
2798 ForEach(DNSResolverOption.allCases) { option in
2799 Text(option.title).tag(option)
2800 }
2801 }
2802
2803 if resolverOption == .custom {
2804 TextField("https://resolver.example/dns-query", text: $customResolverURL)
2805 .textInputAutocapitalization(.never)
2806 .autocorrectionDisabled()
2807 .keyboardType(.URL)
2808
2809 if let customResolverError {
2810 Text(customResolverError)
2811 .font(appDensity.font(.caption, design: .default))
2812 .foregroundStyle(.red)
2813 }
2814 }
2815 }
2816 }
2817 .navigationTitle("History & Network")
2818 .onAppear {
2819 let currentResolverURL = storedResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
2820 resolverOption = DNSResolverOption.option(for: currentResolverURL)
2821 customResolverURL = resolverOption == .custom ? currentResolverURL : DNSResolverOption.defaultURLString
2822 }
2823 .onChange(of: resolverOption) { _, newValue in
2824 guard let presetURL = newValue.urlString else {
2825 storedResolverURL = customResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
2826 viewModel.persistCurrentAppSettings(
2827 resolverURLString: storedResolverURL,
2828 appDensityRawValue: storedDensity
2829 )
2830 return
2831 }
2832 storedResolverURL = presetURL
2833 viewModel.persistCurrentAppSettings(
2834 resolverURLString: storedResolverURL,
2835 appDensityRawValue: storedDensity
2836 )
2837 }
2838 .onChange(of: customResolverURL) { _, newValue in
2839 guard resolverOption == .custom else { return }
2840 storedResolverURL = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
2841 viewModel.persistCurrentAppSettings(
2842 resolverURLString: storedResolverURL,
2843 appDensityRawValue: storedDensity
2844 )
2845 }
2846 .onChange(of: storedDensity) { _, newValue in
2847 viewModel.persistCurrentAppSettings(
2848 resolverURLString: storedResolverURL,
2849 appDensityRawValue: newValue
2850 )
2851 }
2852 }
2853}
2854
2855private struct CloudSyncSettingsView: View {
2856 @Environment(\.appDensity) private var appDensity
2857 @State private var cloudSyncService = CloudSyncService.shared
2858
2859 var body: some View {
2860 Form {
2861 Section("iCloud Sync") {
2862 Toggle(
2863 "Enable iCloud Sync",
2864 isOn: Binding(
2865 get: { cloudSyncService.isEnabled },
2866 set: { cloudSyncService.setSyncEnabled($0) }
2867 )
2868 )
2869
2870 LabeledContent("Status", value: cloudSyncService.status.title)
2871 LabeledContent(
2872 "Last Sync",
2873 value: cloudSyncService.lastSyncDate?.formatted(date: .abbreviated, time: .shortened) ?? "Not yet synced"
2874 )
2875
2876 Button(cloudSyncService.status == .syncing ? "Syncing…" : "Sync Now") {
2877 Task {
2878 await cloudSyncService.syncNow(trigger: .manual)
2879 }
2880 }
2881 .disabled(!cloudSyncService.isEnabled || cloudSyncService.status == .syncing)
2882
2883 Text("iCloud Sync stores DomainDig data in your private iCloud account. DomainDig does not operate a sync server. Disabling sync keeps local data on this device.")
2884 .font(appDensity.font(.caption, design: .default))
2885 .foregroundStyle(.secondary)
2886
2887 Text(cloudSyncService.detailMessage)
2888 .font(appDensity.font(.caption, design: .default))
2889 .foregroundStyle(.secondary)
2890
2891 if let lastErrorMessage = cloudSyncService.lastErrorMessage {
2892 Text(lastErrorMessage)
2893 .font(appDensity.font(.caption, design: .default))
2894 .foregroundStyle(.red)
2895 }
2896 }
2897 }
2898 .navigationTitle("iCloud Sync")
2899 .task {
2900 await cloudSyncService.refreshAvailability()
2901 }
2902 }
2903}
2904
2905private struct LocalAPISettingsView: View {
2906 @Environment(\.appDensity) private var appDensity
2907 @State private var localAPIService = LocalAPIService.shared
2908 @State private var portText = ""
2909
2910 var body: some View {
2911 Form {
2912 Section("Local API") {
2913 Toggle(
2914 "Enable Local API",
2915 isOn: Binding(
2916 get: { localAPIService.config.isEnabled },
2917 set: { localAPIService.setEnabled($0) }
2918 )
2919 )
2920
2921 TextField(
2922 "Port",
2923 text: Binding(
2924 get: { portText },
2925 set: { newValue in
2926 portText = newValue
2927 if let port = Int(newValue) {
2928 localAPIService.setPort(port)
2929 }
2930 }
2931 )
2932 )
2933 .keyboardType(.numberPad)
2934
2935 LabeledContent("Address", value: localAPIService.address)
2936 LabeledContent("Status", value: localAPIService.isRunning ? "Running" : (localAPIService.config.isEnabled ? "Stopped" : "Disabled"))
2937 LabeledContent("Token", value: localAPIService.maskedToken)
2938
2939 if let statusMessage = localAPIService.statusMessage {
2940 Text(statusMessage)
2941 .font(appDensity.font(.caption, design: .default))
2942 .foregroundStyle(.secondary)
2943 }
2944 }
2945
2946 Section("Authentication") {
2947 Button("Copy Token") {
2948 localAPIService.copyToken()
2949 }
2950
2951 Button("Rotate Token") {
2952 localAPIService.rotateToken()
2953 }
2954
2955 Text("Every request requires either `Authorization: Bearer <token>` or `X-API-Token`. DomainDig stores the token in Keychain and only binds the server to localhost.")
2956 .font(appDensity.font(.caption, design: .default))
2957 .foregroundStyle(.secondary)
2958 }
2959
2960 Section("Request Logging") {
2961 Toggle(
2962 "Log Requests",
2963 isOn: Binding(
2964 get: { localAPIService.config.requestLoggingEnabled },
2965 set: { localAPIService.setRequestLoggingEnabled($0) }
2966 )
2967 )
2968
2969 if localAPIService.requestLogs.isEmpty {
2970 Text("No local API requests logged yet.")
2971 .font(appDensity.font(.caption, design: .default))
2972 .foregroundStyle(.secondary)
2973 } else {
2974 ForEach(localAPIService.requestLogs.prefix(25)) { log in
2975 VStack(alignment: .leading, spacing: 4) {
2976 HStack {
2977 Text("\(log.method) \(log.path)")
2978 .font(appDensity.font(.callout, design: .monospaced))
2979 Spacer()
2980 Text("\(log.statusCode)")
2981 .font(appDensity.font(.caption, design: .default))
2982 .foregroundStyle(log.statusCode >= 400 ? .red : .secondary)
2983 }
2984
2985 Text(log.timestamp.formatted(date: .abbreviated, time: .standard))
2986 .font(appDensity.font(.caption2, design: .default))
2987 .foregroundStyle(.secondary)
2988
2989 Text("\(Int(log.duration * 1000)) ms")
2990 .font(appDensity.font(.caption2, design: .default))
2991 .foregroundStyle(.secondary)
2992 }
2993 }
2994 }
2995
2996 Button("Clear Logs", role: .destructive) {
2997 localAPIService.clearRequestLogs()
2998 }
2999 }
3000
3001 Section("Control") {
3002 Button("Restart Server") {
3003 localAPIService.setEnabled(false)
3004 localAPIService.setEnabled(true)
3005 }
3006 .disabled(!localAPIService.config.isEnabled)
3007
3008 Button("Stop Server") {
3009 localAPIService.stopServer()
3010 }
3011 .disabled(!localAPIService.isRunning)
3012 }
3013 }
3014 .navigationTitle("Local API")
3015 .onAppear {
3016 portText = String(localAPIService.config.port)
3017 localAPIService.refresh()
3018 }
3019 }
3020}
3021
3022private struct MonitoringSettingsView: View {
3023 @Environment(\.appDensity) private var appDensity
3024 @Bindable var viewModel: DomainViewModel
3025
3026 private var notificationAuthorizationLabel: String {
3027 switch viewModel.monitoringNotificationStatus {
3028 case .authorized, .provisional, .ephemeral:
3029 return "Allowed"
3030 case .denied:
3031 return "Denied"
3032 case .notDetermined:
3033 return "Not Requested"
3034 @unknown default:
3035 return "Unknown"
3036 }
3037 }
3038
3039 var body: some View {
3040 Form {
3041 Section("Monitoring") {
3042 Toggle(
3043 "Enable Background Monitoring",
3044 isOn: Binding(
3045 get: { viewModel.monitoringSettings.isEnabled },
3046 set: { viewModel.setMonitoringEnabled($0) }
3047 )
3048 )
3049
3050 Picker(
3051 "Base Interval",
3052 selection: Binding(
3053 get: { MonitoringBaseInterval.nearest(to: viewModel.monitoringSettings.baseInterval) },
3054 set: { viewModel.setMonitoringBaseInterval($0) }
3055 )
3056 ) {
3057 ForEach(MonitoringBaseInterval.allCases) { interval in
3058 Text(interval.title).tag(interval)
3059 }
3060 }
3061
3062 Toggle(
3063 "Adaptive Monitoring",
3064 isOn: Binding(
3065 get: { viewModel.monitoringSettings.adaptiveEnabled },
3066 set: { viewModel.setMonitoringAdaptiveEnabled($0) }
3067 )
3068 )
3069
3070 Picker(
3071 "Sensitivity",
3072 selection: Binding(
3073 get: { viewModel.monitoringSettings.sensitivity },
3074 set: { viewModel.setMonitoringSensitivity($0) }
3075 )
3076 ) {
3077 ForEach(MonitoringSensitivity.allCases) { sensitivity in
3078 Text(sensitivity.title).tag(sensitivity)
3079 }
3080 }
3081
3082 let quietHoursStart = viewModel.monitoringSettings.quietHours?.startHour ?? 22
3083 let quietHoursEnd = viewModel.monitoringSettings.quietHours?.endHour ?? 7
3084 Toggle(
3085 "Quiet Hours",
3086 isOn: Binding(
3087 get: { viewModel.monitoringSettings.quietHours != nil },
3088 set: { isEnabled in
3089 viewModel.setMonitoringQuietHours(
3090 startHour: quietHoursStart,
3091 endHour: quietHoursEnd,
3092 isEnabled: isEnabled
3093 )
3094 }
3095 )
3096 )
3097
3098 if viewModel.monitoringSettings.quietHours != nil {
3099 Picker(
3100 "Quiet Starts",
3101 selection: Binding(
3102 get: { quietHoursStart },
3103 set: { startHour in
3104 viewModel.setMonitoringQuietHours(
3105 startHour: startHour,
3106 endHour: quietHoursEnd,
3107 isEnabled: true
3108 )
3109 }
3110 )
3111 ) {
3112 ForEach(0..<24, id: \.self) { hour in
3113 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
3114 }
3115 }
3116
3117 Picker(
3118 "Quiet Ends",
3119 selection: Binding(
3120 get: { quietHoursEnd },
3121 set: { endHour in
3122 viewModel.setMonitoringQuietHours(
3123 startHour: quietHoursStart,
3124 endHour: endHour,
3125 isEnabled: true
3126 )
3127 }
3128 )
3129 ) {
3130 ForEach(0..<24, id: \.self) { hour in
3131 Text(Self.monitoringHourLabel(for: hour)).tag(hour)
3132 }
3133 }
3134 }
3135
3136 Picker(
3137 "Domains",
3138 selection: Binding(
3139 get: { viewModel.monitoringSettings.scope },
3140 set: { viewModel.setMonitoringScope($0) }
3141 )
3142 ) {
3143 ForEach(MonitoringScope.allCases) { scope in
3144 Text(scope.title).tag(scope)
3145 }
3146 }
3147
3148 if viewModel.monitoringSettings.scope == .selectedOnly {
3149 ForEach(viewModel.trackedDomains) { trackedDomain in
3150 Toggle(
3151 trackedDomain.domain,
3152 isOn: Binding(
3153 get: { viewModel.monitoringSettings.selectedDomainIDs.contains(trackedDomain.id) },
3154 set: { viewModel.setMonitoringSelection(for: trackedDomain, isSelected: $0) }
3155 )
3156 )
3157 }
3158 }
3159
3160 Toggle(
3161 "Local Alerts",
3162 isOn: Binding(
3163 get: { viewModel.monitoringSettings.alertsEnabled },
3164 set: { isEnabled in
3165 if isEnabled {
3166 Task {
3167 await viewModel.requestMonitoringNotificationAuthorization()
3168 }
3169 } else {
3170 viewModel.setMonitoringAlertsEnabled(false)
3171 }
3172 }
3173 )
3174 )
3175
3176 Picker(
3177 "Notify For",
3178 selection: Binding(
3179 get: { viewModel.monitoringSettings.alertFilter },
3180 set: { viewModel.setMonitoringAlertFilter($0) }
3181 )
3182 ) {
3183 ForEach(MonitoringAlertFilter.allCases) { filter in
3184 Text(filter.title).tag(filter)
3185 }
3186 }
3187
3188 LabeledContent("Background Refresh", value: DomainMonitoringScheduler.shared.backgroundRefreshStatusDescription())
3189 LabeledContent("Notification Access", value: notificationAuthorizationLabel)
3190
3191 if let monitoringStatusMessage = viewModel.monitoringStatusMessage {
3192 Text(monitoringStatusMessage)
3193 .font(appDensity.font(.caption, design: .default))
3194 .foregroundStyle(.secondary)
3195 }
3196
3197 if !FeatureAccessService.hasAccess(to: .automatedMonitoring) {
3198 Text("Background monitoring and alerts are available in Pro.")
3199 .font(appDensity.font(.caption, design: .default))
3200 .foregroundStyle(.secondary)
3201 }
3202 }
3203 }
3204 .navigationTitle("Monitoring")
3205 .onAppear {
3206 viewModel.refreshMonitoringState()
3207 Task {
3208 await viewModel.refreshMonitoringAuthorizationStatus()
3209 }
3210 }
3211 }
3212
3213 private static func monitoringHourLabel(for hour: Int) -> String {
3214 let formatter = DateFormatter()
3215 formatter.dateFormat = "h a"
3216 let components = DateComponents(calendar: .current, hour: hour)
3217 return components.date.map(formatter.string(from:)) ?? "\(hour):00"
3218 }
3219}
3220
3221private struct DataPortabilitySettingsView: View {
3222 private enum ImportTarget {
3223 case backup
3224 case trackedDomains
3225 case workflows
3226
3227 var expectedKind: DataPortabilityImportKind {
3228 switch self {
3229 case .backup:
3230 return .backup
3231 case .trackedDomains:
3232 return .trackedDomains
3233 case .workflows:
3234 return .workflows
3235 }
3236 }
3237
3238 var allowedContentTypes: [UTType] {
3239 switch self {
3240 case .backup:
3241 return [UTType.json]
3242 case .trackedDomains, .workflows:
3243 return [UTType.json, UTType.commaSeparatedText]
3244 }
3245 }
3246 }
3247
3248 @Environment(\.appDensity) private var appDensity
3249 @Bindable var viewModel: DomainViewModel
3250
3251 @State private var importMode: DataPortabilityImportMode = .merge
3252 @State private var activeImportTarget: ImportTarget?
3253 @State private var pendingImportTarget: ImportTarget?
3254 @State private var importDebugStatus: String?
3255 @State private var pendingImportPreview: DataImportPreview?
3256 @State private var pendingImportError: String?
3257 @State private var showReplaceImportConfirmation = false
3258
3259 var body: some View {
3260 Form {
3261 Section("Import & Export") {
3262 Picker("Import Mode", selection: $importMode) {
3263 ForEach(DataPortabilityImportMode.allCases) { mode in
3264 Text(mode.title).tag(mode)
3265 }
3266 }
3267
3268 Text(importMode.explanation)
3269 .font(appDensity.font(.caption, design: .default))
3270 .foregroundStyle(.secondary)
3271
3272 Button("Export Full Backup") {
3273 exportFullBackup()
3274 }
3275
3276 Button("Import Backup") {
3277 recordImportDebugStatus("Tapped Import Backup")
3278 pendingImportTarget = .backup
3279 activeImportTarget = .backup
3280 }
3281
3282 Menu("Export Tracked Domains") {
3283 Button("JSON") {
3284 exportPortableTrackedDomainsJSON()
3285 }
3286 Button("CSV") {
3287 exportPortableTrackedDomainsCSV()
3288 }
3289 }
3290
3291 Button("Import Tracked Domains") {
3292 recordImportDebugStatus("Tapped Import Tracked Domains")
3293 pendingImportTarget = .trackedDomains
3294 activeImportTarget = .trackedDomains
3295 }
3296
3297 Menu("Export Workflows") {
3298 Button("JSON") {
3299 exportPortableWorkflowsJSON()
3300 }
3301 Button("CSV") {
3302 exportPortableWorkflowsCSV()
3303 }
3304 }
3305
3306 Button("Import Workflows") {
3307 recordImportDebugStatus("Tapped Import Workflows")
3308 pendingImportTarget = .workflows
3309 activeImportTarget = .workflows
3310 }
3311
3312 Button("Export History") {
3313 exportPortableHistoryJSON()
3314 }
3315 }
3316
3317 Section("Local Data") {
3318 LabeledContent("Tracked Domains", value: "\(viewModel.dataLifecycleSummary.trackedDomains)")
3319 LabeledContent("History Snapshots", value: "\(viewModel.dataLifecycleSummary.historySnapshots)")
3320 LabeledContent("Audit Sessions", value: "\(viewModel.dataLifecycleSummary.auditSessions)")
3321 LabeledContent("Workflows", value: "\(viewModel.dataLifecycleSummary.workflows)")
3322 LabeledContent("Cached Items", value: "\(viewModel.dataLifecycleSummary.cachedItems)")
3323 LabeledContent("Monitoring Logs", value: "\(viewModel.dataLifecycleSummary.monitoringLogs)")
3324
3325 Text("Data stays on this device unless you export it. Backup files can include domain history, monitoring settings, and notes. Imported files are processed on-device.")
3326 .font(appDensity.font(.caption, design: .default))
3327 .foregroundStyle(.secondary)
3328
3329 if let portabilityStatusMessage = viewModel.portabilityStatusMessage {
3330 Text(portabilityStatusMessage)
3331 .font(appDensity.font(.caption, design: .default))
3332 .foregroundStyle(.secondary)
3333 }
3334 }
3335
3336 #if DEBUG
3337 if let importDebugStatus {
3338 Section("Import Debug") {
3339 Text(importDebugStatus)
3340 .font(appDensity.font(.caption, design: .default))
3341 .foregroundStyle(.secondary)
3342 .textSelection(.enabled)
3343 }
3344 }
3345 #endif
3346 }
3347 .navigationTitle("Import & Export")
3348 .alert("Replace local data?", isPresented: $showReplaceImportConfirmation) {
3349 Button("Replace", role: .destructive) {
3350 applyPendingImport()
3351 }
3352 Button("Cancel", role: .cancel) {}
3353 } message: {
3354 Text("Replace mode overwrites local data covered by the imported file and may remove items that are only on this device.")
3355 }
3356 .alert("Import Error", isPresented: Binding(
3357 get: { pendingImportError != nil },
3358 set: { if !$0 { pendingImportError = nil } }
3359 )) {
3360 Button("OK", role: .cancel) {}
3361 } message: {
3362 Text(pendingImportError ?? "The import could not be completed.")
3363 }
3364 .sheet(isPresented: Binding(
3365 get: { pendingImportPreview != nil },
3366 set: { if !$0 { pendingImportPreview = nil } }
3367 )) {
3368 if let pendingImportPreview {
3369 DataImportPreviewSheet(
3370 preview: pendingImportPreview,
3371 mode: importMode,
3372 onCancel: {
3373 self.pendingImportPreview = nil
3374 },
3375 onApply: {
3376 if importMode == .replace {
3377 showReplaceImportConfirmation = true
3378 } else {
3379 applyPendingImport()
3380 }
3381 }
3382 )
3383 }
3384 }
3385 .fileImporter(
3386 isPresented: Binding(
3387 get: { activeImportTarget != nil },
3388 set: { if !$0 { activeImportTarget = nil } }
3389 ),
3390 allowedContentTypes: activeImportTarget?.allowedContentTypes ?? [UTType.json],
3391 allowsMultipleSelection: false
3392 ) { result in
3393 guard let pendingImportTarget else {
3394 recordImportDebugStatus("fileImporter returned with no active target")
3395 return
3396 }
3397 recordImportDebugStatus("fileImporter returned for \(pendingImportTarget.expectedKind.rawValue)")
3398 handleImportResult(result, expectedKind: pendingImportTarget.expectedKind)
3399 self.pendingImportTarget = nil
3400 self.activeImportTarget = nil
3401 }
3402 .onAppear {
3403 viewModel.refreshDataLifecycleSummary()
3404 }
3405 }
3406
3407 private func exportFullBackup() {
3408 guard let data = viewModel.exportFullBackupData() else { return }
3409 ExportPresenter.share(filename: portabilityFilename(suffix: "backup", fileExtension: "json"), data: data)
3410 }
3411
3412 private func exportPortableTrackedDomainsJSON() {
3413 guard let data = viewModel.exportPortableTrackedDomainsJSONData() else { return }
3414 ExportPresenter.share(filename: portabilityFilename(suffix: "tracked_domains", fileExtension: "json"), data: data)
3415 }
3416
3417 private func exportPortableTrackedDomainsCSV() {
3418 ExportPresenter.share(
3419 filename: portabilityFilename(suffix: "tracked_domains", fileExtension: "csv"),
3420 contents: viewModel.exportPortableTrackedDomainsCSV()
3421 )
3422 }
3423
3424 private func exportPortableWorkflowsJSON() {
3425 guard let data = viewModel.exportPortableWorkflowsJSONData() else { return }
3426 ExportPresenter.share(filename: portabilityFilename(suffix: "workflows", fileExtension: "json"), data: data)
3427 }
3428
3429 private func exportPortableWorkflowsCSV() {
3430 ExportPresenter.share(
3431 filename: portabilityFilename(suffix: "workflows", fileExtension: "csv"),
3432 contents: viewModel.exportPortableWorkflowsCSV()
3433 )
3434 }
3435
3436 private func exportPortableHistoryJSON() {
3437 guard let data = viewModel.exportPortableHistoryJSONData() else { return }
3438 ExportPresenter.share(filename: portabilityFilename(suffix: "history", fileExtension: "json"), data: data)
3439 }
3440
3441 private func handleImportResult(
3442 _ result: Result<[URL], Error>,
3443 expectedKind: DataPortabilityImportKind
3444 ) {
3445 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult expectedKind=\(expectedKind.rawValue)")
3446 recordImportDebugStatus("handleImportResult started for \(expectedKind.rawValue)")
3447 do {
3448 let urls = try result.get()
3449 guard let url = urls.first else {
3450 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult noURLReturned")
3451 recordImportDebugStatus("No URL returned from picker")
3452 return
3453 }
3454 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult selectedURL=\(url.absoluteString)")
3455 recordImportDebugStatus("Selected \(url.lastPathComponent)")
3456 let shouldStopAccessing = url.startAccessingSecurityScopedResource()
3457 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult securityScopeGranted=\(shouldStopAccessing)")
3458 recordImportDebugStatus("Security scope granted: \(shouldStopAccessing)")
3459 defer {
3460 if shouldStopAccessing {
3461 url.stopAccessingSecurityScopedResource()
3462 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult securityScopeReleased")
3463 }
3464 }
3465
3466 let data = try Data(contentsOf: url)
3467 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult dataRead bytes=\(data.count) fileName=\(url.lastPathComponent)")
3468 recordImportDebugStatus("Read \(data.count) bytes from \(url.lastPathComponent)")
3469 let preview = try viewModel.prepareDataImport(
3470 data: data,
3471 fileName: url.lastPathComponent,
3472 mode: importMode
3473 )
3474 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult previewReady previewKind=\(preview.kind.rawValue) expectedKind=\(expectedKind.rawValue)")
3475 recordImportDebugStatus("Preview ready: \(preview.kind.rawValue)")
3476
3477 guard preview.kind == expectedKind else {
3478 let message = preview.kind == .backup
3479 ? "That file is a full backup. Use Import Backup."
3480 : "That file type does not match this import action."
3481 DomainDebugLog.error("DataPortabilitySettingsView.handleImportResult kindMismatch message=\(message)")
3482 recordImportDebugStatus("Kind mismatch: \(message)")
3483 presentImportError(message)
3484 return
3485 }
3486
3487 DomainDebugLog.debug("DataPortabilitySettingsView.handleImportResult presentingPreview kind=\(preview.kind.rawValue)")
3488 recordImportDebugStatus("Presenting preview for \(preview.kind.rawValue)")
3489 presentImportPreview(preview)
3490 } catch {
3491 DomainDebugLog.error("DataPortabilitySettingsView.handleImportResult failed error=\(error.localizedDescription)")
3492 recordImportDebugStatus("Import failed: \(error.localizedDescription)")
3493 presentImportError(error.localizedDescription)
3494 }
3495 }
3496
3497 private func applyPendingImport() {
3498 guard let pendingImportPreview else { return }
3499 do {
3500 _ = try viewModel.applyDataImport(pendingImportPreview, mode: importMode)
3501 self.pendingImportPreview = nil
3502 } catch {
3503 pendingImportError = error.localizedDescription
3504 }
3505 }
3506
3507 private func portabilityFilename(suffix: String, fileExtension: String) -> String {
3508 let formatter = DateFormatter()
3509 formatter.dateFormat = "yyyyMMdd_HHmmss"
3510 return "\(formatter.string(from: Date()))_domaindig_\(suffix).\(fileExtension)"
3511 }
3512
3513 private func presentImportPreview(_ preview: DataImportPreview) {
3514 Task { @MainActor in
3515 try? await Task.sleep(for: .milliseconds(300))
3516 DomainDebugLog.debug("DataPortabilitySettingsView.presentImportPreview kind=\(preview.kind.rawValue) fileName=\(preview.fileName)")
3517 recordImportDebugStatus("Preview presented for \(preview.fileName)")
3518 pendingImportPreview = preview
3519 }
3520 }
3521
3522 private func presentImportError(_ message: String) {
3523 Task { @MainActor in
3524 try? await Task.sleep(for: .milliseconds(300))
3525 DomainDebugLog.error("DataPortabilitySettingsView.presentImportError message=\(message)")
3526 recordImportDebugStatus("Error presented: \(message)")
3527 pendingImportError = message
3528 }
3529 }
3530
3531 private func recordImportDebugStatus(_ message: String) {
3532 #if DEBUG
3533 let status = "[Import Debug] \(message)"
3534 importDebugStatus = status
3535 print(status)
3536 #endif
3537 }
3538}
3539
3540private struct DataManagementSettingsView: View {
3541 @Bindable var viewModel: DomainViewModel
3542
3543 @State private var showClearHistoryConfirmation = false
3544 @State private var showClearCacheConfirmation = false
3545 @State private var showClearWorkflowsConfirmation = false
3546 @State private var showClearTrackedDomainsConfirmation = false
3547 @State private var showDeleteAllConfirmation = false
3548 @State private var deleteAllErrorMessage: String?
3549 @State private var deleteAllSuccessMessage: String?
3550 @State private var isDeletingAllData = false
3551
3552 var body: some View {
3553 Form {
3554 Section("Data") {
3555 Button("Clear History", role: .destructive) {
3556 showClearHistoryConfirmation = true
3557 }
3558
3559 Button("Clear Cache", role: .destructive) {
3560 showClearCacheConfirmation = true
3561 }
3562
3563 Button("Clear Workflows", role: .destructive) {
3564 showClearWorkflowsConfirmation = true
3565 }
3566
3567 Button("Clear Tracked Domains", role: .destructive) {
3568 showClearTrackedDomainsConfirmation = true
3569 }
3570 }
3571
3572 Section {
3573 Button(role: .destructive) {
3574 showDeleteAllConfirmation = true
3575 } label: {
3576 HStack {
3577 Text("Delete All Data")
3578 Spacer()
3579 if isDeletingAllData {
3580 ProgressView()
3581 .controlSize(.small)
3582 }
3583 }
3584 }
3585 .disabled(isDeletingAllData)
3586 } header: {
3587 Text("Danger Zone")
3588 } footer: {
3589 Text("Permanently removes all local DomainDig data from this device.")
3590 }
3591 }
3592 .disabled(isDeletingAllData)
3593 .navigationTitle("Data Management")
3594 .alert("Clear history?", isPresented: $showClearHistoryConfirmation) {
3595 Button("Clear", role: .destructive) {
3596 viewModel.clearHistory()
3597 }
3598 Button("Cancel", role: .cancel) {}
3599 } message: {
3600 Text("This removes saved lookup snapshots and clears monitoring run history on this device.")
3601 }
3602 .alert("Clear cache?", isPresented: $showClearCacheConfirmation) {
3603 Button("Clear", role: .destructive) {
3604 viewModel.clearLookupCache()
3605 }
3606 Button("Cancel", role: .cancel) {}
3607 } message: {
3608 Text("This clears the in-memory lookup cache and cancels any cached in-flight work.")
3609 }
3610 .alert("Clear workflows?", isPresented: $showClearWorkflowsConfirmation) {
3611 Button("Clear", role: .destructive) {
3612 viewModel.clearWorkflows()
3613 }
3614 Button("Cancel", role: .cancel) {}
3615 } message: {
3616 Text("This removes saved workflows only. History, tracked domains, and saved reports stay intact.")
3617 }
3618 .alert("Clear tracked domains?", isPresented: $showClearTrackedDomainsConfirmation) {
3619 Button("Clear", role: .destructive) {
3620 viewModel.clearTrackedDomains()
3621 }
3622 Button("Cancel", role: .cancel) {}
3623 } message: {
3624 Text("This removes the watchlist and clears monitoring run history. History and workflows stay intact.")
3625 }
3626 .alert("Delete All Data?", isPresented: $showDeleteAllConfirmation) {
3627 Button("Cancel", role: .cancel) {}
3628 Button("Delete All Data", role: .destructive) {
3629 deleteAllData()
3630 }
3631 } message: {
3632 Text("This will permanently remove all saved DomainDig data from this device. This includes tracked domains, monitoring history, snapshots, exports, cached reports, and local settings. This action cannot be undone.")
3633 }
3634 .alert("Delete Failed", isPresented: Binding(
3635 get: { deleteAllErrorMessage != nil },
3636 set: { if !$0 { deleteAllErrorMessage = nil } }
3637 )) {
3638 Button("OK", role: .cancel) {}
3639 } message: {
3640 Text(deleteAllErrorMessage ?? "The local data reset could not be completed.")
3641 }
3642 .safeAreaInset(edge: .bottom) {
3643 if let deleteAllSuccessMessage {
3644 Text(deleteAllSuccessMessage)
3645 .font(.footnote.weight(.medium))
3646 .foregroundStyle(.secondary)
3647 .padding(.horizontal, 14)
3648 .padding(.vertical, 10)
3649 .background(.thinMaterial, in: Capsule())
3650 .padding(.bottom, 8)
3651 .transition(.move(edge: .bottom).combined(with: .opacity))
3652 }
3653 }
3654 }
3655
3656 private func deleteAllData() {
3657 guard !isDeletingAllData else { return }
3658
3659 isDeletingAllData = true
3660 deleteAllErrorMessage = nil
3661 deleteAllSuccessMessage = nil
3662
3663 Task {
3664 do {
3665 try await DataResetService.wipeAllLocalData(viewModel: viewModel)
3666 deleteAllSuccessMessage = "All local data removed."
3667 try? await Task.sleep(for: .seconds(2))
3668 if deleteAllSuccessMessage == "All local data removed." {
3669 deleteAllSuccessMessage = nil
3670 }
3671 } catch {
3672 deleteAllErrorMessage = error.localizedDescription
3673 }
3674
3675 isDeletingAllData = false
3676 }
3677 }
3678}
3679
3680private struct AboutSettingsView: View {
3681 @State private var cloudSyncService = CloudSyncService.shared
3682
3683 private var appVersion: String {
3684 AppVersion.current
3685 }
3686
3687 var body: some View {
3688 Form {
3689 Section("About") {
3690 LabeledContent("Version", value: appVersion)
3691 LabeledContent("Storage", value: cloudSyncService.isEnabled ? "Local-first + iCloud" : "Local-only")
3692 LabeledContent("Backup Schema", value: "v\(DomainDigBackup.currentSchemaVersion)")
3693 }
3694 }
3695 .navigationTitle("App Info")
3696 .task {
3697 await cloudSyncService.refreshAvailability()
3698 }
3699 }
3700}
3701
3702private struct DataImportPreviewSheet: View {
3703 @Environment(\.dismiss) private var dismiss
3704
3705 let preview: DataImportPreview
3706 let mode: DataPortabilityImportMode
3707 let onCancel: () -> Void
3708 let onApply: () -> Void
3709
3710 var body: some View {
3711 NavigationStack {
3712 List {
3713 Section("Summary") {
3714 ForEach(preview.summaryLines, id: \.self) { line in
3715 Text(line)
3716 }
3717 }
3718
3719 Section("Projected Counts") {
3720 LabeledContent("Tracked Domains", value: "\(preview.projectedCounts.trackedDomains)")
3721 LabeledContent("History Snapshots", value: "\(preview.projectedCounts.historySnapshots)")
3722 LabeledContent("Audit Sessions", value: "\(preview.projectedCounts.auditSessions)")
3723 LabeledContent("Workflows", value: "\(preview.projectedCounts.workflows)")
3724 LabeledContent("Cached Items", value: "\(preview.projectedCounts.cachedItems)")
3725 LabeledContent("Monitoring Logs", value: "\(preview.projectedCounts.monitoringLogs)")
3726 }
3727
3728 if !preview.warnings.isEmpty {
3729 Section("Warnings") {
3730 ForEach(preview.warnings, id: \.self) { warning in
3731 Text(warning)
3732 .foregroundStyle(.secondary)
3733 }
3734 }
3735 }
3736 }
3737 .navigationTitle("Import Preview")
3738 .toolbar {
3739 ToolbarItem(placement: .cancellationAction) {
3740 Button("Cancel") {
3741 onCancel()
3742 dismiss()
3743 }
3744 }
3745 ToolbarItem(placement: .confirmationAction) {
3746 Button(mode == .replace ? "Replace" : "Import") {
3747 onApply()
3748 if mode == .merge {
3749 dismiss()
3750 }
3751 }
3752 }
3753 }
3754 }
3755 }
3756}
3757
3758#Preview {
3759 ContentView(viewModel: DomainViewModel())
3760}