DomainDig/ContentView.swift

1f58092dcb67cded75a850db364f3b46d86181f3
domain-dig/DomainDig/ContentView.swift history · blame · raw

1377 lines · 55754 bytes

   1import MapKit
   2import SwiftUI
   3
   4enum LookupInputMode: String, CaseIterable, Identifiable {
   5    case single
   6    case bulk
   7
   8    var id: String { rawValue }
   9}
  10
  11struct ContentView: View {
  12    @State private var viewModel = DomainViewModel()
  13    @State private var navigationPath = NavigationPath()
  14    @FocusState private var domainFieldFocused: Bool
  15    @State private var customPortInput = ""
  16    @State private var customPortsExpanded = false
  17    @State private var trackingNoteDraft = ""
  18    @State private var editingTrackedDomain: TrackedDomain?
  19    @State private var showTrackLimitAlert = false
  20    @State private var inputMode: LookupInputMode = .single
  21
  22    var body: some View {
  23        NavigationStack(path: $navigationPath) {
  24            ScrollView(.vertical) {
  25                VStack(spacing: 0) {
  26                    inputSection
  27                    if !viewModel.batchResults.isEmpty || viewModel.batchLookupRunning {
  28                        batchSection
  29                            .padding(.top, 8)
  30                    }
  31                    if viewModel.hasRun {
  32                        actionButtons
  33                        SummaryView(fields: viewModel.summaryFields)
  34                            .padding(.top, 8)
  35                        if let changeSummary = viewModel.currentChangeSummary {
  36                            DomainChangeSummaryView(summary: changeSummary)
  37                                .padding(.top, 12)
  38                        }
  39                        DomainSectionView(
  40                            rows: viewModel.domainRows,
  41                            suggestions: viewModel.suggestionRows,
  42                            showSuggestions: viewModel.availabilityResult?.status == .registered || viewModel.suggestionsLoading,
  43                            availabilityLoading: viewModel.availabilityLoading,
  44                            suggestionsLoading: viewModel.suggestionsLoading,
  45                            trackedDomain: viewModel.currentTrackedDomain,
  46                            trackingLimitMessage: viewModel.trackingLimitMessage,
  47                            onTrack: {
  48                                if !viewModel.trackCurrentDomain() {
  49                                    showTrackLimitAlert = true
  50                                }
  51                            },
  52                            onTogglePinned: {
  53                                guard let trackedDomain = viewModel.currentTrackedDomain else { return }
  54                                viewModel.togglePinned(for: trackedDomain)
  55                            },
  56                            onEditNote: {
  57                                guard let trackedDomain = viewModel.currentTrackedDomain else { return }
  58                                trackingNoteDraft = trackedDomain.note ?? ""
  59                                editingTrackedDomain = trackedDomain
  60                            }
  61                        )
  62                            .padding(.top, 16)
  63                        if !viewModel.currentDiffSections.isEmpty {
  64                            DomainDiffView(
  65                                title: "Latest Changes",
  66                                sections: viewModel.currentDiffSections,
  67                                showsUnchanged: false
  68                            )
  69                            .padding(.top, 16)
  70                        }
  71                        DNSSectionView(
  72                            dnssecLabel: viewModel.dnssecLabel,
  73                            sections: viewModel.dnsRows,
  74                            ptrMessage: viewModel.ptrMessage,
  75                            loading: viewModel.dnsLoading || viewModel.ptrLoading,
  76                            sectionError: viewModel.dnsError
  77                        )
  78                        .padding(.top, 16)
  79                        WebSectionView(
  80                            certificateRows: viewModel.webCertificateRows,
  81                            sslInfo: viewModel.sslInfo,
  82                            sslLoading: viewModel.sslLoading || viewModel.hstsLoading,
  83                            sslError: viewModel.sslError,
  84                            responseRows: viewModel.webResponseRows,
  85                            headers: viewModel.httpHeaders,
  86                            headersLoading: viewModel.httpHeadersLoading,
  87                            headersError: viewModel.httpHeadersError,
  88                            redirects: viewModel.redirectRows,
  89                            redirectLoading: viewModel.redirectChainLoading,
  90                            redirectError: viewModel.redirectChainError,
  91                            finalURL: viewModel.currentSnapshot.redirectChain.last?.url
  92                        )
  93                        .padding(.top, 16)
  94                        EmailSectionView(
  95                            rows: viewModel.emailRows,
  96                            loading: viewModel.emailSecurityLoading,
  97                            error: viewModel.emailSecurityError
  98                        )
  99                        .padding(.top, 16)
 100                        NetworkSectionView(
 101                            reachabilityRows: viewModel.reachabilityRows,
 102                            reachabilityLoading: viewModel.reachabilityLoading,
 103                            reachabilityError: viewModel.reachabilityError,
 104                            locationRows: viewModel.locationRows,
 105                            geolocation: viewModel.ipGeolocation,
 106                            geolocationLoading: viewModel.ipGeolocationLoading,
 107                            geolocationError: viewModel.ipGeolocationError,
 108                            standardPortRows: viewModel.standardPortRows,
 109                            customPortRows: viewModel.customPortRows,
 110                            portScanLoading: viewModel.portScanLoading,
 111                            portScanError: viewModel.portScanError,
 112                            customPortScanLoading: viewModel.customPortScanLoading,
 113                            customPortScanError: viewModel.customPortScanError,
 114                            isCloudflareProxied: viewModel.isCloudflareProxied,
 115                            customPortsExpanded: $customPortsExpanded,
 116                            customPortInput: $customPortInput,
 117                            onScanCustomPorts: runCustomPortScan
 118                        )
 119                        .padding(.top, 16)
 120                    } else if !viewModel.recentSearches.isEmpty {
 121                        recentSearchesSection
 122                    }
 123                }
 124                .padding(.horizontal)
 125                .padding(.bottom, 32)
 126            }
 127            .background(Color.black)
 128            .navigationTitle("DomainDig")
 129            .toolbarColorScheme(.dark, for: .navigationBar)
 130            .preferredColorScheme(.dark)
 131            .toolbar {
 132                ToolbarItemGroup(placement: .topBarTrailing) {
 133                    if viewModel.hasRun {
 134                        Button {
 135                            viewModel.reset()
 136                        } label: {
 137                            Image(systemName: "xmark.circle")
 138                                .foregroundStyle(.secondary)
 139                        }
 140                    }
 141                    NavigationLink {
 142                        WatchlistView(viewModel: viewModel)
 143                    } label: {
 144                        Image(systemName: "eye")
 145                            .foregroundStyle(.secondary)
 146                    }
 147                    Menu {
 148                        NavigationLink {
 149                            HistoryView(viewModel: viewModel)
 150                        } label: {
 151                            Label("History", systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90")
 152                        }
 153
 154                        NavigationLink {
 155                            SavedDomainsView(viewModel: viewModel)
 156                        } label: {
 157                            Label("Saved Domains", systemImage: "bookmark")
 158                        }
 159
 160                        NavigationLink {
 161                            SettingsView()
 162                        } label: {
 163                            Label("Settings", systemImage: "gearshape")
 164                        }
 165                    } label: {
 166                        Image(systemName: "ellipsis.circle")
 167                            .foregroundStyle(.secondary)
 168                    }
 169                }
 170            }
 171        }
 172        .onAppear {
 173            domainFieldFocused = true
 174        }
 175        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
 176            navigationPath = NavigationPath()
 177            domainFieldFocused = false
 178        }
 179        .alert("Tracking limit reached", isPresented: $showTrackLimitAlert) {
 180            Button("OK", role: .cancel) {}
 181        } message: {
 182            Text("Free version supports up to 3 tracked domains. More tracked domains will be available in a future Pro upgrade.")
 183        }
 184        .sheet(item: $editingTrackedDomain) { trackedDomain in
 185            NavigationStack {
 186                Form {
 187                    Section("Tracking Note") {
 188                        TextField("Optional note", text: $trackingNoteDraft, axis: .vertical)
 189                            .lineLimit(3...6)
 190                            .textInputAutocapitalization(.never)
 191                            .autocorrectionDisabled()
 192                    }
 193                }
 194                .navigationTitle(trackedDomain.domain)
 195                .toolbar {
 196                    ToolbarItem(placement: .cancellationAction) {
 197                        Button("Cancel") {
 198                            editingTrackedDomain = nil
 199                        }
 200                    }
 201                    ToolbarItem(placement: .confirmationAction) {
 202                        Button("Save") {
 203                            viewModel.updateNote(trackingNoteDraft, for: trackedDomain)
 204                            editingTrackedDomain = nil
 205                        }
 206                    }
 207                }
 208            }
 209        }
 210    }
 211
 212    private var inputSection: some View {
 213        VStack(spacing: 12) {
 214            Picker("Mode", selection: $inputMode) {
 215                Text("Single").tag(LookupInputMode.single)
 216                Text("Bulk").tag(LookupInputMode.bulk)
 217            }
 218            .pickerStyle(.segmented)
 219
 220            if inputMode == .single {
 221                TextField("e.g. cleberg.net", text: $viewModel.domain)
 222                    .font(.system(.title3, design: .monospaced))
 223                    .textInputAutocapitalization(.never)
 224                    .autocorrectionDisabled()
 225                    .keyboardType(.URL)
 226                    .padding(12)
 227                    .background(Color(.systemGray6))
 228                    .cornerRadius(8)
 229                    .focused($domainFieldFocused)
 230                    .onSubmit { viewModel.run() }
 231
 232                Button {
 233                    domainFieldFocused = false
 234                    viewModel.run()
 235                } label: {
 236                    Text("Run")
 237                        .font(.headline)
 238                        .frame(maxWidth: .infinity)
 239                        .padding(.vertical, 12)
 240                }
 241                .buttonStyle(.borderedProminent)
 242                .disabled(viewModel.trimmedDomain.isEmpty)
 243            } else {
 244                VStack(alignment: .leading, spacing: 8) {
 245                    Text("Paste domains separated by new lines or commas.")
 246                        .font(.system(.caption, design: .monospaced))
 247                        .foregroundStyle(.secondary)
 248
 249                    TextField(
 250                        "example.com\napple.com, openai.com",
 251                        text: $viewModel.bulkInput,
 252                        axis: .vertical
 253                    )
 254                    .font(.system(.body, design: .monospaced))
 255                    .textInputAutocapitalization(.never)
 256                    .autocorrectionDisabled()
 257                    .keyboardType(.URL)
 258                    .lineLimit(4...10)
 259                    .padding(12)
 260                    .background(Color(.systemGray6))
 261                    .cornerRadius(8)
 262
 263                    Button {
 264                        domainFieldFocused = false
 265                        viewModel.runBulkLookup()
 266                    } label: {
 267                        Text(viewModel.batchLookupRunning ? "Running Batch…" : "Run Batch")
 268                            .font(.headline)
 269                            .frame(maxWidth: .infinity)
 270                            .padding(.vertical, 12)
 271                    }
 272                    .buttonStyle(.borderedProminent)
 273                    .disabled(viewModel.bulkInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.batchLookupRunning)
 274                }
 275            }
 276        }
 277        .padding(.vertical, 16)
 278    }
 279
 280    private var actionButtons: some View {
 281        HStack {
 282            Spacer()
 283            if viewModel.resultsLoaded {
 284                Button {
 285                    viewModel.toggleSavedDomain()
 286                } label: {
 287                    Image(systemName: viewModel.isCurrentDomainSaved ? "bookmark.fill" : "bookmark")
 288                        .font(.system(.body))
 289                        .foregroundStyle(viewModel.isCurrentDomainSaved ? .yellow : .secondary)
 290                }
 291                Menu {
 292                    Button("Export TXT") {
 293                        shareSingleResults(asCSV: false)
 294                    }
 295                    Button("Export CSV") {
 296                        shareSingleResults(asCSV: true)
 297                    }
 298                } label: {
 299                    Image(systemName: "square.and.arrow.up")
 300                        .font(.system(.body))
 301                        .foregroundStyle(.secondary)
 302                }
 303            }
 304        }
 305    }
 306
 307    private var batchSection: some View {
 308        VStack(alignment: .leading, spacing: 12) {
 309            HStack {
 310                Spacer()
 311                if viewModel.batchLookupRunning {
 312                    Button("Cancel") {
 313                        viewModel.cancelBatchLookup()
 314                    }
 315                    .buttonStyle(.bordered)
 316                    .font(.system(.caption, design: .monospaced))
 317                }
 318                if !viewModel.currentBatchResultEntries.isEmpty {
 319                    Menu {
 320                        Button("Export Batch TXT") {
 321                            shareBatchResults(asCSV: false)
 322                        }
 323                        Button("Export Batch CSV") {
 324                            shareBatchResults(asCSV: true)
 325                        }
 326                    } label: {
 327                        Label("Export", systemImage: "square.and.arrow.up")
 328                            .font(.system(.caption, design: .monospaced))
 329                    }
 330                    .buttonStyle(.bordered)
 331                }
 332            }
 333
 334            BatchResultsView(
 335                viewModel: viewModel,
 336                title: viewModel.batchLookupSource == .watchlistRefresh ? "Tracked Domain Refresh" : "Batch Results"
 337            )
 338        }
 339    }
 340
 341    private var recentSearchesSection: some View {
 342        VStack(alignment: .leading, spacing: 8) {
 343            HStack {
 344                Text("RECENT")
 345                    .font(.system(.caption2, design: .monospaced))
 346                    .foregroundStyle(.secondary)
 347                Spacer()
 348                Button("Clear") {
 349                    viewModel.clearRecentSearches()
 350                }
 351                .font(.system(.caption2, design: .monospaced))
 352                .foregroundStyle(.secondary)
 353            }
 354
 355            ForEach(viewModel.recentSearches, id: \.self) { domain in
 356                Button {
 357                    viewModel.domain = domain
 358                    domainFieldFocused = false
 359                    viewModel.run()
 360                } label: {
 361                    Text(domain)
 362                        .font(.system(.callout, design: .monospaced))
 363                        .foregroundStyle(.primary)
 364                        .frame(maxWidth: .infinity, alignment: .leading)
 365                        .padding(.vertical, 6)
 366                        .padding(.horizontal, 10)
 367                        .background(Color(.systemGray6).opacity(0.5))
 368                        .cornerRadius(6)
 369                }
 370            }
 371        }
 372        .padding(.top, 8)
 373    }
 374
 375    private func runCustomPortScan() {
 376        let ports = parsedCustomPorts(from: customPortInput)
 377        Task {
 378            await viewModel.runCustomPortScan(ports: ports)
 379        }
 380    }
 381
 382    private func parsedCustomPorts(from input: String) -> [UInt16] {
 383        let parts = input.split(separator: ",", omittingEmptySubsequences: true)
 384        var seen = Set<UInt16>()
 385        var ports: [UInt16] = []
 386
 387        for part in parts {
 388            let trimmed = part.trimmingCharacters(in: .whitespacesAndNewlines)
 389            guard let value = UInt16(trimmed), seen.insert(value).inserted else {
 390                continue
 391            }
 392            ports.append(value)
 393            if ports.count == 20 {
 394                break
 395            }
 396        }
 397
 398        return ports
 399    }
 400
 401    private func shareSingleResults(asCSV: Bool) {
 402        let (filename, contents) = exportPayload(
 403            prefix: "domaindig_single",
 404            text: viewModel.exportText(),
 405            csv: viewModel.exportCSV(),
 406            asCSV: asCSV
 407        )
 408        ExportPresenter.share(filename: filename, contents: contents)
 409    }
 410
 411    private func shareBatchResults(asCSV: Bool) {
 412        let (filename, contents) = exportPayload(
 413            prefix: "domaindig_batch",
 414            text: viewModel.exportBatchText(),
 415            csv: viewModel.exportBatchCSV(),
 416            asCSV: asCSV
 417        )
 418        ExportPresenter.share(filename: filename, contents: contents)
 419    }
 420
 421    private func exportPayload(prefix: String, text: String, csv: String, asCSV: Bool) -> (String, String) {
 422        let formatter = DateFormatter()
 423        formatter.dateFormat = "yyyyMMdd_HHmmss"
 424        let timestamp = formatter.string(from: Date())
 425        let fileExtension = asCSV ? "csv" : "txt"
 426        let filename = "\(timestamp)_\(prefix).\(fileExtension)"
 427        return (filename, asCSV ? csv : text)
 428    }
 429}
 430
 431struct SummaryView: View {
 432    let fields: [SummaryFieldViewData]
 433
 434    var body: some View {
 435        VStack(alignment: .leading, spacing: 12) {
 436            SectionTitleView(title: "Summary")
 437            LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) {
 438                ForEach(fields) { field in
 439                    VStack(alignment: .leading, spacing: 4) {
 440                        Text(field.label)
 441                            .font(.system(.caption2, design: .monospaced))
 442                            .foregroundStyle(.secondary)
 443                        Text(field.value)
 444                            .font(.system(.caption, design: .monospaced))
 445                            .foregroundStyle(ResultColors.color(for: field.tone))
 446                            .lineLimit(2)
 447                            .textSelection(.enabled)
 448                    }
 449                    .frame(maxWidth: .infinity, alignment: .leading)
 450                    .padding(10)
 451                    .background(Color(.systemGray6).opacity(0.5))
 452                    .cornerRadius(6)
 453                }
 454            }
 455        }
 456    }
 457}
 458
 459struct DomainChangeSummaryView: View {
 460    let summary: DomainChangeSummary
 461
 462    var body: some View {
 463        CardView(allowsHorizontalScroll: false) {
 464            HStack {
 465                Label(summary.hasChanges ? "Changed" : "Stable", systemImage: summary.hasChanges ? "arrow.triangle.2.circlepath" : "checkmark.circle")
 466                    .font(.system(.caption, design: .monospaced))
 467                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .green)
 468                Spacer()
 469                Text(summary.severity.title.uppercased())
 470                    .font(.system(.caption2, design: .monospaced))
 471                    .foregroundStyle(summary.hasChanges ? severityColor(summary.severity) : .secondary)
 472                    .padding(.horizontal, 8)
 473                    .padding(.vertical, 4)
 474                    .background((summary.hasChanges ? severityColor(summary.severity) : .secondary).opacity(0.16))
 475                    .clipShape(Capsule())
 476                Text(summary.generatedAt, style: .time)
 477                    .font(.system(.caption2, design: .monospaced))
 478                    .foregroundStyle(.secondary)
 479            }
 480
 481            Text(summary.message)
 482                .font(.system(.caption, design: .monospaced))
 483                .foregroundStyle(.primary)
 484        }
 485    }
 486
 487    private func severityColor(_ severity: ChangeSeverity) -> Color {
 488        switch severity {
 489        case .low:
 490            return .secondary
 491        case .medium:
 492            return .yellow
 493        case .high:
 494            return .red
 495        }
 496    }
 497}
 498
 499struct DomainDiffView: View {
 500    let title: String
 501    let sections: [DomainDiffSection]
 502    let showsUnchanged: Bool
 503
 504    @State private var collapsedSections = Set<UUID>()
 505    @State private var showsLowSeverity = false
 506
 507    private var filteredSections: [DomainDiffSection] {
 508        sections
 509            .map { section in
 510                let items = section.items.filter { item in
 511                    if !showsUnchanged, !item.hasChanges {
 512                        return false
 513                    }
 514                    if showsLowSeverity {
 515                        return true
 516                    }
 517                    return item.severity >= .medium || (showsUnchanged && item.changeType == .unchanged)
 518                }
 519                return DomainDiffSection(title: section.title, items: items)
 520            }
 521            .filter { !$0.items.isEmpty }
 522    }
 523
 524    private var hasLowSeverityChanges: Bool {
 525        sections.flatMap(\.items).contains { $0.hasChanges && $0.severity == .low }
 526    }
 527
 528    var body: some View {
 529        VStack(alignment: .leading, spacing: 12) {
 530            HStack {
 531                SectionTitleView(title: title)
 532                Spacer()
 533                if hasLowSeverityChanges {
 534                    Button(showsLowSeverity ? "Hide Low" : "Show Low") {
 535                        showsLowSeverity.toggle()
 536                    }
 537                    .buttonStyle(.bordered)
 538                    .font(.system(.caption, design: .monospaced))
 539                }
 540            }
 541            if filteredSections.isEmpty {
 542                MessageCardView(text: "No comparison data available", isError: false)
 543            } else {
 544                ForEach(filteredSections) { section in
 545                    CardView(allowsHorizontalScroll: false) {
 546                        DisclosureGroup(isExpanded: binding(for: section)) {
 547                            let visibleItems = showsUnchanged ? section.items : section.items.filter(\.hasChanges)
 548
 549                            ForEach(visibleItems) { item in
 550                                VStack(alignment: .leading, spacing: 6) {
 551                                    HStack {
 552                                        Text(item.label)
 553                                            .font(.system(.caption, design: .monospaced))
 554                                            .foregroundStyle(.secondary)
 555                                        Spacer()
 556                                        Text("\(item.severity.title) • \(changeLabel(for: item.changeType))")
 557                                            .font(.system(.caption2, design: .monospaced))
 558                                            .foregroundStyle(changeColor(for: item))
 559                                            .padding(.horizontal, 8)
 560                                            .padding(.vertical, 4)
 561                                            .background(changeColor(for: item).opacity(0.16))
 562                                            .clipShape(Capsule())
 563                                    }
 564
 565                                    if let oldValue = item.oldValue {
 566                                        VStack(alignment: .leading, spacing: 2) {
 567                                            Text("Old")
 568                                                .font(.system(.caption2, design: .monospaced))
 569                                                .foregroundStyle(.secondary)
 570                                            Text(oldValue)
 571                                                .font(.system(.caption2, design: .monospaced))
 572                                                .foregroundStyle(.secondary)
 573                                                .textSelection(.enabled)
 574                                        }
 575                                    }
 576
 577                                    if let newValue = item.newValue {
 578                                        VStack(alignment: .leading, spacing: 2) {
 579                                            Text("New")
 580                                                .font(.system(.caption2, design: .monospaced))
 581                                                .foregroundStyle(.secondary)
 582                                            Text(newValue)
 583                                                .font(.system(.caption, design: .monospaced))
 584                                                .foregroundStyle(item.hasChanges ? .primary : .secondary)
 585                                                .textSelection(.enabled)
 586                                        }
 587                                    }
 588                                }
 589                                .padding(10)
 590                                .background(item.hasChanges ? changeColor(for: item).opacity(0.08) : Color(.systemGray6).opacity(0.25))
 591                                .cornerRadius(8)
 592                            }
 593                        } label: {
 594                            HStack {
 595                                Text(section.title)
 596                                    .font(.system(.subheadline, design: .monospaced))
 597                                    .fontWeight(.semibold)
 598                                    .foregroundStyle(sectionColor(section))
 599                                Spacer()
 600                                Text(section.severity.title)
 601                                    .font(.system(.caption2, design: .monospaced))
 602                                    .foregroundStyle(sectionColor(section))
 603                            }
 604                        }
 605                    }
 606                }
 607            }
 608        }
 609    }
 610
 611    private func changeLabel(for changeType: DiffChangeType) -> String {
 612        switch changeType {
 613        case .added:
 614            return "Added"
 615        case .removed:
 616            return "Removed"
 617        case .changed:
 618            return "Changed"
 619        case .unchanged:
 620            return "Unchanged"
 621        }
 622    }
 623
 624    private func changeColor(for item: DomainDiffItem) -> Color {
 625        if item.changeType == .unchanged {
 626            return .secondary
 627        }
 628
 629        switch item.severity {
 630        case .low:
 631            return .blue
 632        case .medium:
 633            return .yellow
 634        case .high:
 635            return .red
 636        }
 637    }
 638
 639    private func sectionColor(_ section: DomainDiffSection) -> Color {
 640        switch section.severity {
 641        case .low:
 642            return .blue
 643        case .medium:
 644            return .yellow
 645        case .high:
 646            return .red
 647        }
 648    }
 649
 650    private func binding(for section: DomainDiffSection) -> Binding<Bool> {
 651        Binding(
 652            get: { !collapsedSections.contains(section.id) },
 653            set: { isExpanded in
 654                if isExpanded {
 655                    collapsedSections.remove(section.id)
 656                } else {
 657                    collapsedSections.insert(section.id)
 658                }
 659            }
 660        )
 661    }
 662}
 663
 664struct TrackedDomainDetailHeaderView: View {
 665    let trackedDomain: TrackedDomain
 666
 667    var body: some View {
 668        VStack(alignment: .leading, spacing: 4) {
 669            if let note = trackedDomain.note?.nilIfEmpty {
 670                LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
 671            }
 672            HStack(spacing: 8) {
 673                if trackedDomain.isPinned {
 674                    Label("Pinned", systemImage: "pin.fill")
 675                }
 676                Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
 677            }
 678            .font(.system(.caption2, design: .monospaced))
 679            .foregroundStyle(.secondary)
 680        }
 681    }
 682}
 683
 684struct DomainSectionView: View {
 685    let rows: [InfoRowViewData]
 686    let suggestions: [DomainSuggestionViewData]
 687    let showSuggestions: Bool
 688    let availabilityLoading: Bool
 689    let suggestionsLoading: Bool
 690    let trackedDomain: TrackedDomain?
 691    let trackingLimitMessage: String?
 692    let onTrack: () -> Void
 693    let onTogglePinned: () -> Void
 694    let onEditNote: (() -> Void)?
 695
 696    var body: some View {
 697        VStack(alignment: .leading, spacing: 12) {
 698            HStack {
 699                SectionTitleView(title: "Domain")
 700                Spacer()
 701                if let trackedDomain {
 702                    HStack(spacing: 8) {
 703                        Text("Tracked")
 704                            .font(.system(.caption, design: .monospaced))
 705                            .foregroundStyle(.green)
 706                        Button {
 707                            onTogglePinned()
 708                        } label: {
 709                            Image(systemName: trackedDomain.isPinned ? "pin.fill" : "pin")
 710                        }
 711                        .buttonStyle(.bordered)
 712                        .font(.system(.caption, design: .monospaced))
 713                        if let onEditNote {
 714                            Button("Note") {
 715                                onEditNote()
 716                            }
 717                            .buttonStyle(.bordered)
 718                            .font(.system(.caption, design: .monospaced))
 719                        }
 720                    }
 721                } else {
 722                    Button("Track") {
 723                        onTrack()
 724                    }
 725                    .buttonStyle(.bordered)
 726                    .font(.system(.caption, design: .monospaced))
 727                }
 728            }
 729            CardView(allowsHorizontalScroll: false) {
 730                ForEach(rows) { row in
 731                    LabeledValueRow(row: row)
 732                }
 733                if let trackedDomain {
 734                    TrackedDomainDetailHeaderView(trackedDomain: trackedDomain)
 735                        .padding(.top, 4)
 736                } else if let trackingLimitMessage {
 737                    MessageRowView(text: trackingLimitMessage, isError: false)
 738                        .padding(.top, 4)
 739                }
 740                if availabilityLoading {
 741                    ProgressView("Checking availability…")
 742                        .appLoadingStyle()
 743                        .padding(.top, 4)
 744                }
 745                if showSuggestions {
 746                    Text("Suggestions")
 747                        .font(.system(.caption, design: .monospaced))
 748                        .foregroundStyle(.secondary)
 749                        .padding(.top, 4)
 750                    if suggestionsLoading {
 751                        ProgressView("Checking alternatives…")
 752                            .appLoadingStyle()
 753                    } else if suggestions.isEmpty {
 754                        MessageRowView(text: "No suggestions", isError: false)
 755                    } else {
 756                        ForEach(suggestions) { suggestion in
 757                            HStack {
 758                                Text(suggestion.domain)
 759                                    .font(.system(.caption, design: .monospaced))
 760                                    .foregroundStyle(.primary)
 761                                    .textSelection(.enabled)
 762                                Spacer()
 763                                Text(suggestion.status)
 764                                    .font(.system(.caption2, design: .monospaced))
 765                                    .foregroundStyle(ResultColors.color(for: suggestion.tone))
 766                            }
 767                        }
 768                    }
 769                }
 770            }
 771        }
 772    }
 773}
 774
 775struct DNSSectionView: View {
 776    let dnssecLabel: String?
 777    let sections: [DNSRecordSectionViewData]
 778    let ptrMessage: SectionMessageViewData?
 779    let loading: Bool
 780    let sectionError: String?
 781
 782    var body: some View {
 783        VStack(alignment: .leading, spacing: 12) {
 784            HStack(alignment: .top, spacing: 8) {
 785                SectionTitleView(title: "DNS")
 786                Spacer()
 787                if let dnssecLabel {
 788                    Text(dnssecLabel)
 789                        .font(.system(.caption2, design: .monospaced))
 790                        .foregroundStyle(.secondary)
 791                        .multilineTextAlignment(.trailing)
 792                }
 793            }
 794
 795            if loading {
 796                LoadingCardView(text: "Querying DNS…")
 797            } else if let sectionError, sections.isEmpty {
 798                MessageCardView(text: sectionError, isError: true)
 799            } else {
 800                ForEach(sections) { section in
 801                    CardView {
 802                        Text(section.title)
 803                            .font(.system(.subheadline, design: .monospaced))
 804                            .fontWeight(.semibold)
 805                            .foregroundStyle(.cyan)
 806
 807                        if let message = section.message {
 808                            MessageRowView(text: message.text, isError: message.isError)
 809                        }
 810
 811                        ForEach(section.rows) { row in
 812                            LabeledValueRow(row: row)
 813                        }
 814
 815                        if let wildcardTitle = section.wildcardTitle {
 816                            Text(wildcardTitle)
 817                                .font(.system(.caption, design: .monospaced))
 818                                .foregroundStyle(.secondary)
 819                                .padding(.top, 4)
 820                            ForEach(section.wildcardRows) { row in
 821                                LabeledValueRow(row: row)
 822                            }
 823                        }
 824                    }
 825                }
 826
 827                if let ptrMessage {
 828                    CardView {
 829                        Text("PTR")
 830                            .font(.system(.subheadline, design: .monospaced))
 831                            .fontWeight(.semibold)
 832                            .foregroundStyle(.cyan)
 833                        MessageRowView(text: ptrMessage.text, isError: ptrMessage.isError)
 834                    }
 835                }
 836            }
 837        }
 838    }
 839}
 840
 841struct WebSectionView: View {
 842    let certificateRows: [InfoRowViewData]
 843    let sslInfo: SSLCertificateInfo?
 844    let sslLoading: Bool
 845    let sslError: String?
 846    let responseRows: [InfoRowViewData]
 847    let headers: [HTTPHeader]
 848    let headersLoading: Bool
 849    let headersError: String?
 850    let redirects: [RedirectHopViewData]
 851    let redirectLoading: Bool
 852    let redirectError: String?
 853    let finalURL: String?
 854
 855    var body: some View {
 856        VStack(alignment: .leading, spacing: 12) {
 857            SectionTitleView(title: "Web")
 858
 859            CardView {
 860                Text("TLS")
 861                    .font(.system(.subheadline, design: .monospaced))
 862                    .fontWeight(.semibold)
 863                    .foregroundStyle(.cyan)
 864                if sslLoading {
 865                    ProgressView("Checking certificate…")
 866                        .appLoadingStyle()
 867                } else if let sslError {
 868                    MessageRowView(text: sslError, isError: true)
 869                } else {
 870                    ForEach(certificateRows) { row in
 871                        LabeledValueRow(row: row)
 872                    }
 873                    if let sslInfo, !sslInfo.subjectAltNames.isEmpty {
 874                        Text("SANs")
 875                            .font(.system(.caption2, design: .monospaced))
 876                            .foregroundStyle(.secondary)
 877                        ForEach(sslInfo.subjectAltNames, id: \.self) { san in
 878                            Text(san)
 879                                .font(.system(.caption, design: .monospaced))
 880                                .textSelection(.enabled)
 881                        }
 882                    }
 883                }
 884            }
 885
 886            CardView {
 887                Text("Headers")
 888                    .font(.system(.subheadline, design: .monospaced))
 889                    .fontWeight(.semibold)
 890                    .foregroundStyle(.cyan)
 891                if headersLoading {
 892                    ProgressView("Fetching headers…")
 893                        .appLoadingStyle()
 894                } else if let headersError {
 895                    MessageRowView(text: headersError, isError: true)
 896                } else {
 897                    ForEach(responseRows) { row in
 898                        LabeledValueRow(row: row)
 899                    }
 900                    if headers.isEmpty {
 901                        MessageRowView(text: "No HTTP headers returned", isError: false)
 902                    } else {
 903                        ForEach(headers) { header in
 904                            HStack(alignment: .top, spacing: 4) {
 905                                Text(header.name + ":")
 906                                    .font(.system(.caption, design: .monospaced))
 907                                    .foregroundStyle(header.isSecurityHeader ? .yellow : .cyan)
 908                                Text(header.value)
 909                                    .font(.system(.caption, design: .monospaced))
 910                                    .foregroundStyle(.primary)
 911                                    .textSelection(.enabled)
 912                            }
 913                        }
 914                    }
 915                }
 916            }
 917
 918            CardView {
 919                Text("Redirects")
 920                    .font(.system(.subheadline, design: .monospaced))
 921                    .fontWeight(.semibold)
 922                    .foregroundStyle(.cyan)
 923                if redirectLoading {
 924                    ProgressView("Tracing redirects…")
 925                        .appLoadingStyle()
 926                } else if let redirectError {
 927                    MessageRowView(text: redirectError, isError: true)
 928                } else if redirects.isEmpty {
 929                    MessageRowView(text: "No redirect data available", isError: false)
 930                } else {
 931                    if let finalURL {
 932                        LabeledValueRow(row: InfoRowViewData(label: "Final URL", value: finalURL, tone: .secondary))
 933                    }
 934                    ForEach(redirects) { redirect in
 935                        HStack(alignment: .top, spacing: 6) {
 936                            Text(redirect.stepLabel)
 937                                .font(.system(.caption, design: .monospaced))
 938                                .foregroundStyle(.secondary)
 939                                .frame(width: 16, alignment: .trailing)
 940                            Text(redirect.statusCode)
 941                                .font(.system(.caption, design: .monospaced))
 942                                .foregroundStyle(.cyan)
 943                                .frame(width: 36, alignment: .leading)
 944                            Text(redirect.url)
 945                                .font(.system(.caption, design: .monospaced))
 946                                .textSelection(.enabled)
 947                            if redirect.isFinal {
 948                                Text("(final)")
 949                                    .font(.system(.caption2, design: .monospaced))
 950                                    .foregroundStyle(.secondary)
 951                            }
 952                        }
 953                    }
 954                }
 955            }
 956        }
 957    }
 958}
 959
 960struct EmailSectionView: View {
 961    let rows: [EmailRowViewData]
 962    let loading: Bool
 963    let error: String?
 964
 965    var body: some View {
 966        VStack(alignment: .leading, spacing: 12) {
 967            SectionTitleView(title: "Email")
 968            CardView {
 969                if loading {
 970                    ProgressView("Checking email records…")
 971                        .appLoadingStyle()
 972                } else if let error {
 973                    MessageRowView(text: error, isError: true)
 974                } else if rows.isEmpty {
 975                    MessageRowView(text: "No email security records found", isError: false)
 976                } else {
 977                    ForEach(rows) { row in
 978                        VStack(alignment: .leading, spacing: 4) {
 979                            HStack(spacing: 8) {
 980                                Text(row.label)
 981                                    .font(.system(.caption, design: .monospaced))
 982                                    .foregroundStyle(.cyan)
 983                                    .frame(width: 76, alignment: .leading)
 984                                Text(row.status)
 985                                    .font(.system(.caption, design: .monospaced))
 986                                    .foregroundStyle(ResultColors.color(for: row.statusTone))
 987                            }
 988                            Text(row.detail)
 989                                .font(.system(.caption2, design: .monospaced))
 990                                .foregroundStyle(.primary)
 991                                .textSelection(.enabled)
 992                            if let auxiliaryDetail = row.auxiliaryDetail {
 993                                Text(auxiliaryDetail)
 994                                    .font(.system(.caption2, design: .monospaced))
 995                                    .foregroundStyle(.secondary)
 996                            }
 997                        }
 998                    }
 999                }
1000            }
1001        }
1002    }
1003}
1004
1005struct NetworkSectionView: View {
1006    let reachabilityRows: [ReachabilityRowViewData]
1007    let reachabilityLoading: Bool
1008    let reachabilityError: String?
1009    let locationRows: [InfoRowViewData]
1010    let geolocation: IPGeolocation?
1011    let geolocationLoading: Bool
1012    let geolocationError: String?
1013    let standardPortRows: [PortScanRowViewData]
1014    let customPortRows: [PortScanRowViewData]
1015    let portScanLoading: Bool
1016    let portScanError: String?
1017    let customPortScanLoading: Bool
1018    let customPortScanError: String?
1019    let isCloudflareProxied: Bool
1020    @Binding var customPortsExpanded: Bool
1021    @Binding var customPortInput: String
1022    let onScanCustomPorts: () -> Void
1023
1024    var body: some View {
1025        VStack(alignment: .leading, spacing: 12) {
1026            SectionTitleView(title: "Network")
1027
1028            CardView {
1029                Text("Reachability")
1030                    .font(.system(.subheadline, design: .monospaced))
1031                    .fontWeight(.semibold)
1032                    .foregroundStyle(.cyan)
1033                if reachabilityLoading {
1034                    ProgressView("Checking ports…")
1035                        .appLoadingStyle()
1036                } else if let reachabilityError {
1037                    MessageRowView(text: reachabilityError, isError: true)
1038                } else {
1039                    ForEach(reachabilityRows) { row in
1040                        HStack {
1041                            Text(row.portLabel)
1042                                .font(.system(.caption, design: .monospaced))
1043                            Spacer()
1044                            Text(row.latencyLabel)
1045                                .font(.system(.caption2, design: .monospaced))
1046                                .foregroundStyle(.secondary)
1047                            Text(row.statusLabel)
1048                                .font(.system(.caption, design: .monospaced))
1049                                .foregroundStyle(ResultColors.color(for: row.statusTone))
1050                        }
1051                    }
1052                }
1053            }
1054
1055            CardView(allowsHorizontalScroll: false) {
1056                Text("Location")
1057                    .font(.system(.subheadline, design: .monospaced))
1058                    .fontWeight(.semibold)
1059                    .foregroundStyle(.cyan)
1060                if geolocationLoading {
1061                    ProgressView("Looking up location…")
1062                        .appLoadingStyle()
1063                } else if let geolocationError, geolocation == nil {
1064                    MessageRowView(text: geolocationError, isError: geolocationError != "No A record available")
1065                } else if let geolocation {
1066                    ForEach(locationRows) { row in
1067                        LabeledValueRow(row: row)
1068                    }
1069                    if let latitude = geolocation.latitude, let longitude = geolocation.longitude {
1070                        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
1071                        Map(initialPosition: .region(MKCoordinateRegion(
1072                            center: coordinate,
1073                            span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)
1074                        ))) {
1075                            Marker(geolocation.ip, coordinate: coordinate)
1076                        }
1077                        .mapStyle(.standard)
1078                        .frame(maxWidth: .infinity)
1079                        .frame(height: 180)
1080                        .cornerRadius(8)
1081                    }
1082                } else {
1083                    MessageRowView(text: "No location data available", isError: false)
1084                }
1085            }
1086
1087            CardView(allowsHorizontalScroll: false) {
1088                Text("Port Scan")
1089                    .font(.system(.subheadline, design: .monospaced))
1090                    .fontWeight(.semibold)
1091                    .foregroundStyle(.cyan)
1092
1093                if isCloudflareProxied {
1094                    Text("Domain is behind Cloudflare's proxy. Results reflect the edge, not the origin.")
1095                        .font(.system(.caption2, design: .monospaced))
1096                        .foregroundStyle(.orange)
1097                        .fixedSize(horizontal: false, vertical: true)
1098                }
1099
1100                if portScanLoading {
1101                    ProgressView("Scanning ports…")
1102                        .appLoadingStyle()
1103                } else if let portScanError, standardPortRows.isEmpty {
1104                    MessageRowView(text: portScanError, isError: true)
1105                } else {
1106                    Text("Standard Ports")
1107                        .font(.system(.caption, design: .monospaced))
1108                        .foregroundStyle(.secondary)
1109                    PortRowsView(rows: standardPortRows)
1110                }
1111
1112                DisclosureGroup("Custom Ports", isExpanded: $customPortsExpanded) {
1113                    VStack(alignment: .leading, spacing: 10) {
1114                        TextField("8888, 9000, 27017", text: $customPortInput)
1115                            .font(.system(.caption, design: .monospaced))
1116                            .textInputAutocapitalization(.never)
1117                            .autocorrectionDisabled()
1118                            .keyboardType(.numberPad)
1119                            .padding(10)
1120                            .background(Color(.systemGray6).opacity(0.5))
1121                            .cornerRadius(6)
1122
1123                        Button("Scan") {
1124                            onScanCustomPorts()
1125                        }
1126                        .buttonStyle(.borderedProminent)
1127                        .disabled(customPortScanLoading)
1128
1129                        if customPortScanLoading {
1130                            ProgressView("Scanning custom ports…")
1131                                .appLoadingStyle()
1132                        } else if let customPortScanError {
1133                            MessageRowView(text: customPortScanError, isError: true)
1134                        } else {
1135                            PortRowsView(rows: customPortRows)
1136                        }
1137                    }
1138                    .padding(.top, 8)
1139                }
1140                .font(.system(.caption, design: .monospaced))
1141                .tint(.secondary)
1142            }
1143        }
1144    }
1145}
1146
1147struct PortRowsView: View {
1148    let rows: [PortScanRowViewData]
1149
1150    var body: some View {
1151        if rows.isEmpty {
1152            MessageRowView(text: "No results", isError: false)
1153        } else {
1154            ForEach(rows) { row in
1155                VStack(alignment: .leading, spacing: 2) {
1156                    HStack {
1157                        Text(row.portLabel)
1158                            .font(.system(.caption, design: .monospaced))
1159                            .frame(width: 52, alignment: .leading)
1160                        Text(row.service)
1161                            .font(.system(.caption, design: .monospaced))
1162                            .foregroundStyle(.primary)
1163                        Spacer()
1164                        if let durationLabel = row.durationLabel {
1165                            Text(durationLabel)
1166                                .font(.system(.caption2, design: .monospaced))
1167                                .foregroundStyle(.secondary)
1168                        }
1169                        Text(row.statusLabel)
1170                            .font(.system(.caption2, design: .monospaced))
1171                            .foregroundStyle(ResultColors.color(for: row.statusTone))
1172                    }
1173                    if let banner = row.banner {
1174                        Text(banner)
1175                            .font(.system(.caption2, design: .monospaced))
1176                            .foregroundStyle(.secondary)
1177                            .padding(.leading, 8)
1178                    }
1179                }
1180            }
1181        }
1182    }
1183}
1184
1185struct SectionTitleView: View {
1186    let title: String
1187
1188    var body: some View {
1189        Text(title)
1190            .font(.system(.headline))
1191            .foregroundStyle(.white)
1192    }
1193}
1194
1195struct CardView<Content: View>: View {
1196    let allowsHorizontalScroll: Bool
1197    let content: Content
1198
1199    init(allowsHorizontalScroll: Bool = true, @ViewBuilder content: () -> Content) {
1200        self.allowsHorizontalScroll = allowsHorizontalScroll
1201        self.content = content()
1202    }
1203
1204    var body: some View {
1205        Group {
1206            if allowsHorizontalScroll {
1207                ScrollView(.horizontal) {
1208                    cardContent
1209                        .scrollTargetLayout()
1210                }
1211                .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
1212            } else {
1213                cardContent
1214                    .frame(maxWidth: .infinity, alignment: .leading)
1215            }
1216        }
1217        .frame(maxWidth: .infinity, alignment: .leading)
1218        .padding(10)
1219        .background(Color(.systemGray6).opacity(0.5))
1220        .cornerRadius(6)
1221    }
1222
1223    private var cardContent: some View {
1224        VStack(alignment: .leading, spacing: 6) {
1225            content
1226        }
1227    }
1228}
1229
1230struct LoadingCardView: View {
1231    let text: String
1232
1233    var body: some View {
1234        CardView {
1235            ProgressView(text)
1236                .appLoadingStyle()
1237                .frame(maxWidth: .infinity, alignment: .center)
1238        }
1239    }
1240}
1241
1242struct MessageCardView: View {
1243    let text: String
1244    let isError: Bool
1245
1246    var body: some View {
1247        CardView {
1248            MessageRowView(text: text, isError: isError)
1249        }
1250    }
1251}
1252
1253struct MessageRowView: View {
1254    let text: String
1255    let isError: Bool
1256
1257    var body: some View {
1258        Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
1259            .font(.system(.caption, design: .monospaced))
1260            .foregroundStyle(isError ? .red : .secondary)
1261    }
1262}
1263
1264struct LabeledValueRow: View {
1265    let row: InfoRowViewData
1266
1267    var body: some View {
1268        VStack(alignment: .leading, spacing: 2) {
1269            Text(row.label)
1270                .font(.system(.caption2, design: .monospaced))
1271                .foregroundStyle(.secondary)
1272            Text(row.value)
1273                .font(.system(.caption, design: .monospaced))
1274                .foregroundStyle(ResultColors.color(for: row.tone))
1275                .textSelection(.enabled)
1276        }
1277    }
1278}
1279
1280enum ResultColors {
1281    static func color(for tone: ResultTone) -> Color {
1282        switch tone {
1283        case .primary:
1284            return .primary
1285        case .secondary:
1286            return .secondary
1287        case .success:
1288            return .green
1289        case .warning:
1290            return .yellow
1291        case .failure:
1292            return .red
1293        }
1294    }
1295}
1296
1297extension DateFormatter {
1298    static let certDate: DateFormatter = {
1299        let formatter = DateFormatter()
1300        formatter.dateStyle = .medium
1301        formatter.timeStyle = .short
1302        return formatter
1303    }()
1304}
1305
1306private extension View {
1307    func appLoadingStyle() -> some View {
1308        font(.system(.caption, design: .monospaced))
1309    }
1310}
1311
1312private extension String {
1313    var nilIfEmpty: String? {
1314        isEmpty ? nil : self
1315    }
1316}
1317
1318private struct SettingsView: View {
1319    @AppStorage(DNSResolverOption.userDefaultsKey)
1320    private var storedResolverURL = DNSResolverOption.defaultURLString
1321
1322    @State private var resolverOption: DNSResolverOption = .cloudflare
1323    @State private var customResolverURL = DNSResolverOption.defaultURLString
1324
1325    private var customResolverError: String? {
1326        guard resolverOption == .custom else {
1327            return nil
1328        }
1329        return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
1330    }
1331
1332    var body: some View {
1333        Form {
1334            Section {
1335                Picker("Resolver", selection: $resolverOption) {
1336                    ForEach(DNSResolverOption.allCases) { option in
1337                        Text(option.title).tag(option)
1338                    }
1339                }
1340
1341                if resolverOption == .custom {
1342                    TextField("https://resolver.example/dns-query", text: $customResolverURL)
1343                        .textInputAutocapitalization(.never)
1344                        .autocorrectionDisabled()
1345                        .keyboardType(.URL)
1346
1347                    if let customResolverError {
1348                        Text(customResolverError)
1349                            .font(.caption)
1350                            .foregroundStyle(.red)
1351                    }
1352                }
1353            }
1354        }
1355        .navigationTitle("Settings")
1356        .onAppear {
1357            let currentResolverURL = storedResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
1358            resolverOption = DNSResolverOption.option(for: currentResolverURL)
1359            customResolverURL = resolverOption == .custom ? currentResolverURL : DNSResolverOption.defaultURLString
1360        }
1361        .onChange(of: resolverOption) { _, newValue in
1362            guard let presetURL = newValue.urlString else {
1363                storedResolverURL = customResolverURL.trimmingCharacters(in: .whitespacesAndNewlines)
1364                return
1365            }
1366            storedResolverURL = presetURL
1367        }
1368        .onChange(of: customResolverURL) { _, newValue in
1369            guard resolverOption == .custom else { return }
1370            storedResolverURL = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
1371        }
1372    }
1373}
1374
1375#Preview {
1376    ContentView()
1377}