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