DomainDig/ContentView.swift

695 lines · 29807 bytes

  1import MapKit
  2import SwiftUI
  3import UniformTypeIdentifiers
  4
  5enum LookupInputMode: String, CaseIterable, Identifiable {
  6    case single
  7    case bulk
  8
  9    var id: String { rawValue }
 10}
 11
 12enum ResultSection: String, Hashable {
 13    case domain
 14    case intelligence
 15    case ownership
 16    case dns
 17    case web
 18    case email
 19    case network
 20    case subdomains
 21}
 22
 23private enum LookupInputField: Hashable {
 24    case singleDomain
 25    case bulkDomains
 26}
 27
 28private struct WorkflowNavigationTarget: Hashable {
 29    let workflowID: UUID
 30}
 31
 32struct ContentView: View {
 33    @Environment(\.appDensity) private var appDensity
 34    @Bindable var viewModel: DomainViewModel
 35    @State private var 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    @State private var showingAuditTimeline = false
 47    @State private var auditStartInFlight = false
 48
 49    var body: some View {
 50        NavigationStack(path: $navigationPath) {
 51            List {
 52                Section { inputSection }
 53                if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
 54                    Section { batchSection }
 55                }
 56                if viewModel.hasRun {
 57                    Section { actionButtons }
 58                    if !viewModel.resultsLoaded {
 59                        Section { LookupProgressOverviewView(steps: viewModel.activeLoadingLabels) }
 60                    } else if let statusMessage = resultStatusMessage {
 61                        Section {
 62                            LookupStatusBannerView(message: statusMessage, resultSource: viewModel.currentResultSource)
 63                        }
 64                    }
 65                    if viewModel.resultsLoaded {
 66                        Section { SummaryView(fields: viewModel.summaryFields) }
 67                        if let report = viewModel.currentReport {
 68                            Section { RiskSummaryCardView(report: report) }
 69                            Section { InsightsSummaryCardView(insights: report.insights) }
 70                        }
 71                        if let changeSummary = viewModel.currentChangeSummary {
 72                            Section { DomainChangeSummaryView(summary: changeSummary) }
 73                        }
 74                    }
 75                    if let report = viewModel.currentReport {
 76                        Section { intelligenceSection(report: report) }
 77                    }
 78                    Section { domainOverviewSection }
 79                    Section { ownershipSection }
 80                    Section { subdomainsSection }
 81                    if !viewModel.currentDiffSections.isEmpty {
 82                        Section {
 83                            DomainDiffView(
 84                                title: "Latest Changes",
 85                                sections: viewModel.currentDiffSections,
 86                                contextNote: viewModel.currentChangeSummary?.contextNote,
 87                                showsUnchanged: false,
 88                                highlightedSectionID: nil
 89                            )
 90                        }
 91                    }
 92                    Section { dnsSection }
 93                    Section {
 94                        WebSectionView(
 95                            isCollapsed: sectionCollapsedBinding(.web),
 96                            data: viewModel.webSectionData
 97                        )
 98                    }
 99                    Section {
100                        EmailSectionView(
101                            isCollapsed: sectionCollapsedBinding(.email),
102                            rows: viewModel.emailRows,
103                            assessment: viewModel.currentEmailAssessment,
104                            loading: viewModel.emailSecurityLoading,
105                            provenance: viewModel.currentSnapshot.provenanceBySection[.emailSecurity],
106                            confidence: viewModel.currentSnapshot.emailSecurityConfidence,
107                            error: viewModel.emailSecurityError
108                        )
109                    }
110                    Section {
111                        NetworkSectionView(
112                            isCollapsed: sectionCollapsedBinding(.network),
113                            customPortsExpanded: $customPortsExpanded,
114                            customPortInput: $customPortInput,
115                            data: viewModel.networkSectionData,
116                            onScanCustomPorts: runCustomPortScan
117                        )
118                    }
119                } else if !viewModel.recentSearches.isEmpty {
120                    Section { recentSearchesSection }
121                }
122            }
123            .listRowBackground(Color(.appSurface))
124            .environment(\.cardProvidesSurface, false)
125            .scrollContentBackground(.hidden)
126            .background(Color(.appBackground))
127            .navigationTitle("DomainDig")
128            .toolbar {
129                ToolbarItem(placement: .topBarTrailing) {
130                    // While a lookup is in flight the same action is a cancel,
131                    // so it says so rather than leaving an unlabelled glyph to
132                    // stand for both.
133                    if viewModel.singleLookupRunning {
134                        Button("Cancel") {
135                            viewModel.reset()
136                        }
137                        .accessibilityLabel("Cancel lookup")
138                    } else if viewModel.hasRun {
139                        Button {
140                            viewModel.reset()
141                        } label: {
142                            Image(systemName: "xmark.circle")
143                                .foregroundStyle(Color(.appTextSecondary))
144                        }
145                        .accessibilityLabel("Clear results")
146                    }
147                }
148
149                ToolbarItem(placement: .topBarTrailing) {
150                    NavigationLink {
151                        WorkflowsView(viewModel: viewModel)
152                    } label: {
153                        Label("Workflows", systemImage: "square.stack.3d.up")
154                    }
155                    .accessibilityLabel("Workflows")
156                }
157            }
158            .navigationDestination(for: WorkflowNavigationTarget.self) { target in
159                WorkflowDetailView(viewModel: viewModel, workflowID: target.workflowID)
160            }
161        }
162        .task {
163        }
164        .onChange(of: viewModel.searchedDomain) { _, _ in
165            collapsedSections = defaultCollapsedSections
166        }
167        .onChange(of: viewModel.resultsLoaded) { wasLoaded, isLoaded in
168            // Single-lookup completion has no single view-model moment
169            // (`resultsLoaded` is derived from many loading flags), so the
170            // announcement is posted from the view where the transition is
171            // observable. The batch path announces from the view model directly.
172            guard !wasLoaded, isLoaded, viewModel.hasRun else { return }
173            let summary = AppStatusFactory.availability(viewModel.availabilityResult?.status).title
174            AppAccessibility.announce("Lookup complete for \(viewModel.searchedDomain). \(summary).")
175        }
176        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
177            navigationPath = NavigationPath()
178            focusedInputField = nil
179        }
180        .onChange(of: inputMode) { _, newValue in
181            viewModel.clearPresentedResults()
182            focusedInputField = newValue == .single ? .singleDomain : .bulkDomains
183        }
184        .onChange(of: viewModel.domain) { _, newValue in
185            viewModel.domainInputError = nil
186            guard inputMode == .single else { return }
187            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
188            guard normalized != viewModel.searchedDomain else { return }
189            guard viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
190            viewModel.clearPresentedResults()
191        }
192        .onChange(of: viewModel.bulkInput) { _, newValue in
193            guard inputMode == .bulk else { return }
194            let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
195            guard !normalized.isEmpty || viewModel.hasRun || !viewModel.batchResults.isEmpty else { return }
196            viewModel.clearPresentedResults()
197        }
198        .sheet(item: $editingTrackedDomain) { trackedDomain in
199            NavigationStack {
200                Form {
201                    Section("Tracking Note") {
202                        TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
203                            .lineLimit(3...6)
204                            .textInputAutocapitalization(.never)
205                            .autocorrectionDisabled()
206                    }
207                }
208                .navigationTitle(trackedDomain.domain)
209                .toolbar {
210                    ToolbarItem(placement: .cancellationAction) {
211                        Button("Cancel") {
212                            editingTrackedDomain = nil
213                        }
214                    }
215                    ToolbarItem(placement: .confirmationAction) {
216                        Button("Save") {
217                            viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
218                            editingTrackedDomain = nil
219                        }
220                    }
221                }
222            }
223        }
224        .sheet(isPresented: $showingCurrentDomainWorkflowSheet) {
225            WorkflowBulkAddSheet(
226                viewModel: viewModel,
227                title: "Add Domain to Workflow",
228                availableDomains: [viewModel.searchedDomain]
229            )
230        }
231        .sheet(isPresented: $showingBatchWorkflowSheet) {
232            WorkflowBulkAddSheet(
233                viewModel: viewModel,
234                title: "Add Batch Domains",
235                availableDomains: viewModel.batchResults.map(\.domain)
236            )
237        }
238        .sheet(item: manualBatchSummaryBinding) { summary in
239            BatchSweepSummaryView(viewModel: viewModel, summary: summary)
240        }
241        .sheet(isPresented: $showingTimeline) {
242            NavigationStack {
243                TimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
244            }
245        }
246        .sheet(isPresented: $showingAuditTimeline) {
247            NavigationStack {
248                AuditDomainTimelineView(viewModel: viewModel, domain: viewModel.searchedDomain)
249            }
250        }
251    }
252
253    private var manualBatchSummaryBinding: Binding<BatchSweepSummary?> {
254        Binding(
255            get: {
256                guard let summary = viewModel.latestBatchSweepSummary,
257                      summary.source == .manual else {
258                    return nil
259                }
260                return summary
261            },
262            set: { viewModel.latestBatchSweepSummary = $0 }
263        )
264    }
265
266    private var inputSection: some View {
267        VStack(spacing: appDensity.metrics.cardSpacing + 2) {
268            Picker("Mode", selection: $inputMode) {
269                Text("Single").tag(LookupInputMode.single)
270                Text("Bulk").tag(LookupInputMode.bulk)
271            }
272            .pickerStyle(.segmented)
273
274            if inputMode == .single {
275                TextField("e.g. cleberg.net", text: $viewModel.domain)
276                    .font(appDensity.font(.title3, design: .monospaced))
277                    .textInputAutocapitalization(.never)
278                    .autocorrectionDisabled()
279                    .keyboardType(.URL)
280                    .padding(.horizontal, 12)
281                    .padding(.vertical, appDensity.metrics.controlVerticalPadding)
282                    .background(Color(.appSurfaceElevated))
283                    .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
284                    .focused($focusedInputField, equals: .singleDomain)
285                    .onSubmit {
286                        focusedInputField = nil
287                        viewModel.run()
288                    }
289
290                if let domainInputError = viewModel.domainInputError {
291                    Text(domainInputError)
292                        .font(appDensity.font(.caption))
293                        .foregroundStyle(Color(.statusCritical))
294                        .frame(maxWidth: .infinity, alignment: .leading)
295                }
296
297                Button {
298                    focusedInputField = nil
299                    viewModel.run()
300                } label: {
301                    Text("Run")
302                        .font(appDensity.font(.headline, design: .default, weight: .semibold))
303                        .frame(maxWidth: .infinity)
304                        .frame(minHeight: appDensity.metrics.controlMinHeight)
305                }
306                .buttonStyle(.borderedProminent)
307                .tint(Color(.accentFill))
308                .disabled(viewModel.trimmedDomain.isEmpty)
309            } else {
310                if FeatureAccessService.hasAccess(to: .batchOperations) {
311                    VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
312                        Text("Paste domains separated by new lines or commas.")
313                            .font(appDensity.font(.caption))
314                            .foregroundStyle(Color(.appTextSecondary))
315
316                        if let batchAllowanceSummary = FeatureAccessService.batchAllowanceSummary() {
317                            Text(batchAllowanceSummary)
318                                .font(appDensity.font(.caption2))
319                                .foregroundStyle(Color(.appTextSecondary))
320                        }
321
322                        TextField(
323                            "example.com\napple.com, openai.com",
324                            text: $viewModel.bulkInput,
325                            axis: .vertical
326                        )
327                        .font(appDensity.font(.body))
328                        .textInputAutocapitalization(.never)
329                        .autocorrectionDisabled()
330                        .keyboardType(.URL)
331                        .lineLimit(4...10)
332                        .padding(.horizontal, 12)
333                        .padding(.vertical, appDensity.metrics.controlVerticalPadding)
334                        .background(Color(.appSurfaceElevated))
335                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
336                        .focused($focusedInputField, equals: .bulkDomains)
337
338                        Button {
339                            focusedInputField = nil
340                            viewModel.runBulkLookup()
341                        } label: {
342                            Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
343                                .font(appDensity.font(.headline, design: .default, weight: .semibold))
344                                .frame(maxWidth: .infinity)
345                                .frame(minHeight: appDensity.metrics.controlMinHeight)
346                        }
347                        .buttonStyle(.borderedProminent)
348                        .tint(Color(.accentFill))
349                        .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
350                    }
351                } else {
352                    lockedFeatureCard(
353                        title: "Batch Operations",
354                        message: FeatureAccessService.upgradeMessage(for: .batchOperations)
355                    )
356                }
357            }
358        }
359        .padding(.vertical, appDensity.metrics.sectionSpacing)
360    }
361
362    private var domainOverviewSection: some View {
363        let trackedDomain = viewModel.currentTrackedDomain
364        let workflows = viewModel.currentDomainWorkflows
365
366        return DomainSectionView(
367            isCollapsed: sectionCollapsedBinding(.domain),
368            rows: viewModel.domainRows,
369            suggestions: viewModel.suggestionRows,
370            showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
371            availabilityLoading: viewModel.availabilityLoading,
372            suggestionsLoading: viewModel.suggestionsLoading,
373            provenance: viewModel.currentSnapshot.provenanceBySection[.availability],
374            confidence: viewModel.currentSnapshot.availabilityConfidence,
375            snapshotNote: viewModel.currentSnapshot.note,
376            trackedDomain: trackedDomain,
377            workflows: workflows,
378            trackingLimitMessage: viewModel.trackingLimitMessage,
379
380            onTrack: {
381                _ = viewModel.trackCurrentDomain()
382            },
383            onTogglePinned: {
384                guard let trackedDomain else { return }
385                viewModel.togglePinned(for: trackedDomain)
386            },
387            onEditNote: {
388                guard let trackedDomain else { return }
389                trackingNoteDraft = trackedDomain.note ?? ""
390                editingTrackedDomain = trackedDomain
391            },
392            onAddToWorkflow: {
393                showingCurrentDomainWorkflowSheet = true
394            },
395            onOpenWorkflow: { workflow in
396                navigationPath.append(WorkflowNavigationTarget(workflowID: workflow.id))
397            },
398            onRunWorkflow: { workflow in
399                viewModel.rerunCurrentDomain(in: workflow)
400            }
401        )
402    }
403
404    private func intelligenceSection(report: DomainReport) -> some View {
405        IntelligenceSectionView(
406            isCollapsed: sectionCollapsedBinding(.intelligence),
407            report: report,
408            showsPlaceholder: !FeatureAccessService.hasAccess(to: .intelligenceDetail)
409        )
410    }
411
412    private var ownershipSection: some View {
413        OwnershipSectionView(
414            isCollapsed: sectionCollapsedBinding(.ownership),
415            rows: viewModel.ownershipRows,
416            loading: viewModel.ownershipLoading,
417            error: viewModel.ownershipError,
418            provenance: viewModel.currentSnapshot.provenanceBySection[.ownership],
419            confidence: viewModel.currentSnapshot.ownershipConfidence,
420            history: viewModel.ownershipHistory,
421            historyLoading: viewModel.ownershipHistoryLoading,
422            historyError: viewModel.ownershipHistoryError,
423            onLoadHistory: {
424                Task {
425                    await viewModel.loadOwnershipHistory()
426                }
427            }
428        )
429    }
430
431    private var subdomainsSection: some View {
432        SubdomainsSectionView(
433            isCollapsed: sectionCollapsedBinding(.subdomains),
434            rows: viewModel.subdomainRows,
435            groups: viewModel.currentSubdomainGroups,
436            loading: viewModel.subdomainsLoading,
437            error: viewModel.subdomainsError,
438            provenance: viewModel.currentSnapshot.provenanceBySection[.subdomains],
439            confidence: viewModel.currentSnapshot.subdomainConfidence,
440            showsExtendedPlaceholder: !FeatureAccessService.hasAccess(to: .extendedSubdomains),
441            extendedCount: viewModel.extendedSubdomains.count,
442            extendedLoading: viewModel.extendedSubdomainsLoading,
443            extendedError: viewModel.extendedSubdomainsError,
444            onLoadExtended: {
445                Task {
446                    await viewModel.loadExtendedSubdomains()
447                }
448            }
449        )
450    }
451
452    private var dnsSection: some View {
453        DNSSectionView(
454            isCollapsed: sectionCollapsedBinding(.dns),
455            dnssecLabel: viewModel.dnssecLabel,
456            patternSummary: viewModel.currentDNSPatterns,
457            sections: viewModel.dnsRows,
458            ptrMessage: viewModel.ptrMessage,
459            loading: viewModel.dnsLoading || viewModel.ptrLoading,
460            dnsProvenance: viewModel.currentSnapshot.provenanceBySection[.dns],
461            ptrProvenance: viewModel.currentSnapshot.provenanceBySection[.ptr],
462            sectionError: viewModel.dnsError,
463            history: viewModel.dnsHistory,
464            historyLoading: viewModel.dnsHistoryLoading,
465            historyError: viewModel.dnsHistoryError,
466            onLoadHistory: {
467                Task {
468                    await viewModel.loadDNSHistory()
469                }
470            }
471        )
472    }
473
474    private var actionButtons: some View {
475        HStack {
476            Spacer()
477            if viewModel.resultsLoaded {
478                Menu {
479                    if !viewModel.isCurrentDomainTracked {
480                        Button("Track this domain") {
481                            _ = viewModel.trackCurrentDomain()
482                        }
483                    }
484                    Button("Add to workflow") {
485                        showingCurrentDomainWorkflowSheet = true
486                    }
487                    Button(auditStartInFlight ? "Starting audit…" : "Start audit") {
488                        Task {
489                            auditStartInFlight = true
490                            if await viewModel.startAudit(for: viewModel.searchedDomain) != nil {
491                                showingAuditTimeline = true
492                            }
493                            auditStartInFlight = false
494                        }
495                    }
496                    .disabled(auditStartInFlight)
497                    if !viewModel.audits(for: viewModel.searchedDomain).isEmpty {
498                        Button("View audits") {
499                            showingAuditTimeline = true
500                        }
501                    }
502                    if !viewModel.historyEntries(for: viewModel.searchedDomain).isEmpty {
503                        Button("Open timeline") {
504                            showingTimeline = true
505                        }
506                    }
507                    if FeatureAccessService.hasAccess(to: .advancedExports) {
508                        Button("Copy report JSON") {
509                            guard let json = viewModel.exportJSONString() else { return }
510                            AppClipboard.copy(json)
511                            AppHaptics.copy()
512                        }
513                    } else {
514                        Button("Copy report JSON") {
515                            viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .advancedExports)
516                        }
517                    }
518                    Button("Export report") {
519                        shareSingleResults(format: .text)
520                    }
521                } label: {
522                    Image(systemName: "bolt.circle")
523                        .font(appDensity.font(.body, design: .default))
524                        .foregroundStyle(Color(.appTextSecondary))
525                }
526                .accessibilityLabel("Actions")
527                Menu {
528                    ExportFormatButtons(share: shareSingleResults)
529                } label: {
530                    Image(systemName: "square.and.arrow.up")
531                        .font(appDensity.font(.body, design: .default))
532                        .foregroundStyle(Color(.appTextSecondary))
533                }
534                .accessibilityLabel("Export")
535            }
536        }
537    }
538
539    private var batchSection: some View {
540        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
541            HStack {
542                Spacer()
543                if viewModel.batchLookupRunning {
544                    Button("Cancel") {
545                        viewModel.cancelBatchLookup()
546                    }
547                    .buttonStyle(.bordered)
548                    .font(appDensity.font(.caption))
549                }
550                if !viewModel.currentBatchResultEntries.isEmpty {
551                    Menu {
552                        Button("Add to Workflow") {
553                            showingBatchWorkflowSheet = true
554                        }
555                        Divider()
556                        ExportFormatButtons(share: shareBatchResults, batch: true)
557                    } label: {
558                        Label("Export", systemImage: "square.and.arrow.up")
559                            .font(appDensity.font(.caption))
560                    }
561                    .buttonStyle(.bordered)
562                }
563            }
564
565            BatchResultsView(
566                viewModel: viewModel,
567                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
568            )
569        }
570    }
571
572    private var recentSearchesSection: some View {
573        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
574            HStack {
575                Text("RECENT")
576                    .font(appDensity.font(.caption2))
577                    .foregroundStyle(Color(.appTextSecondary))
578                Spacer()
579                Button("Clear") {
580                    viewModel.clearRecentSearches()
581                }
582                .font(appDensity.font(.caption2))
583                .foregroundStyle(Color(.appTextSecondary))
584            }
585
586            ForEach(viewModel.recentSearches, id: \.self) { domain in
587                Button {
588                    viewModel.domain = domain
589                    focusedInputField = nil
590                    viewModel.run()
591                } label: {
592                    Text(domain)
593                        .font(appDensity.font(.callout))
594                        .foregroundStyle(.primary)
595                        .frame(maxWidth: .infinity, alignment: .leading)
596                        .padding(.vertical, 8)
597                        .padding(.horizontal, 10)
598                        .background(Color(.appSurface))
599                        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
600                }
601            }
602        }
603        .padding(.top, appDensity.metrics.cardSpacing)
604    }
605
606    private func runCustomPortScan() {
607        let ports = parsedCustomPorts(from: customPortInput)
608        Task {
609            await viewModel.runCustomPortScan(ports: ports)
610        }
611    }
612
613    private func lockedFeatureCard(title: String, message: String) -> some View {
614        VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
615            Text(title)
616                .font(appDensity.font(.headline, design: .default, weight: .semibold))
617            Text(message)
618                .font(appDensity.font(.callout, design: .default))
619                .foregroundStyle(Color(.appTextSecondary))
620        }
621        .frame(maxWidth: .infinity, alignment: .leading)
622        .padding(appDensity.metrics.cardPadding)
623        .background(Color(.appSurfaceElevated))
624        .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
625    }
626
627    private func parsedCustomPorts(from input: String) -> [UInt16] {
628        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
629        var seen = Set<UInt16>()
630        var ports: [UInt16] = []
631
632        for part in parts {
633            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
634            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
635                continue
636            }
637            ports.append(value)
638            if ports.count == 20 {
639                break
640            }
641        }
642
643        return ports
644    }
645
646    private func shareSingleResults(format: DomainExportFormat) {
647        guard let data = viewModel.exportSingleReportData(format: format) else { return }
648        ExportPresenter.share(filename: exportFilename(prefix: "domaindig_single", format: format), data: data)
649    }
650
651    private func shareBatchResults(format: DomainExportFormat) {
652        guard let data = viewModel.exportBatchReportData(format: format) else { return }
653        ExportPresenter.share(filename: exportFilename(prefix: "domaindig_batch", format: format), data: data)
654    }
655
656    private func exportFilename(prefix: String, format: DomainExportFormat) -> String {
657        let formatter = DateFormatter()
658        formatter.dateFormat = "yyyyMMdd_HHmmss"
659        let timestamp = formatter.string(from: Date())
660        return "\(timestamp)_\(prefix).\(format.fileExtension)"
661    }
662
663    private var defaultCollapsedSections: Set<ResultSection> {
664        []
665    }
666
667    private var currentPrimaryIP: String? {
668        viewModel.currentSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
669    }
670
671    private var resultStatusMessage: String? {
672        if let currentStatusMessage = viewModel.currentStatusMessage {
673            return currentStatusMessage
674        }
675
676        if viewModel.currentResultSource != .live {
677            return viewModel.currentResultSource.label
678        }
679
680        return nil
681    }
682
683    private func sectionCollapsedBinding(_ section: ResultSection) -> Binding<Bool> {
684        Binding(
685            get: { collapsedSections.contains(section) },
686            set: { isCollapsed in
687                if isCollapsed {
688                    collapsedSections.insert(section)
689                } else {
690                    collapsedSections.remove(section)
691                }
692            }
693        )
694    }
695}