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