DomainDig/WatchlistView.swift

36ea668d7fc9070770973b0bc329f4319bf43cab
domain-dig/DomainDig/WatchlistView.swift history · blame · raw

458 lines · 18077 bytes

  1import SwiftUI
  2
  3struct WatchlistView: View {
  4    @Environment(\.appDensity) private var appDensity
  5    @Bindable var viewModel: DomainViewModel
  6    @Environment(\.dismiss) private var dismiss
  7
  8    private var pinnedDomains: [TrackedDomain] {
  9        viewModel.filteredTrackedDomains.filter(\.isPinned)
 10    }
 11
 12    private var otherDomains: [TrackedDomain] {
 13        viewModel.filteredTrackedDomains.filter { !$0.isPinned }
 14    }
 15
 16    var body: some View {
 17        List {
 18            if viewModel.batchLookupSource == .watchlistRefresh, (!viewModel.batchResults.isEmpty || viewModel.batchLookupRunning) {
 19                Section("Refresh Progress") {
 20                    VStack(alignment: .leading, spacing: 8) {
 21                        ProgressView(value: Double(viewModel.batchCompletedCount), total: Double(max(viewModel.batchTotalCount, 1)))
 22                            .tint(.cyan)
 23                        HStack {
 24                            Text(viewModel.batchProgressLabel)
 25                                .font(appDensity.font(.caption))
 26                                .foregroundStyle(.secondary)
 27                            Spacer()
 28                            if viewModel.batchLookupRunning {
 29                                Button("Cancel") {
 30                                    viewModel.cancelBatchLookup()
 31                                }
 32                                .buttonStyle(.bordered)
 33                                .font(appDensity.font(.caption2))
 34                            }
 35                        }
 36
 37                        ForEach(viewModel.batchResults.prefix(5)) { result in
 38                            BatchResultRowView(result: result)
 39                        }
 40                    }
 41                    .padding(.vertical, 4)
 42                }
 43                .listRowBackground(Color(.systemGray6).opacity(0.5))
 44            }
 45
 46            if viewModel.filteredTrackedDomains.isEmpty {
 47                Section {
 48                    EmptyStateCardView(
 49                        title: "No Tracked Domains",
 50                        message: "Track important domains locally so you can refresh them quickly and see status changes at a glance.",
 51                        suggestion: "Run an inspection and use the Track action on a domain you care about.",
 52                        systemImage: "eye"
 53                    )
 54                }
 55                .listRowBackground(Color(.systemGray6).opacity(0.5))
 56            } else {
 57                if let limitMessage = PremiumAccessService.trackedDomainLimitMessage(currentCount: viewModel.trackedDomains.count) {
 58                    Section {
 59                        Text(limitMessage)
 60                            .font(appDensity.font(.caption))
 61                            .foregroundStyle(.secondary)
 62                    }
 63                    .listRowBackground(Color(.systemGray6).opacity(0.5))
 64                }
 65
 66                if !pinnedDomains.isEmpty {
 67                    trackedSection(title: "Pinned", domains: pinnedDomains)
 68                }
 69
 70                if !otherDomains.isEmpty {
 71                    trackedSection(title: pinnedDomains.isEmpty ? "Tracked Domains" : "Others", domains: otherDomains)
 72                }
 73            }
 74        }
 75        .animation(.easeInOut(duration: 0.2), value: viewModel.filteredTrackedDomains.map(\.id))
 76        .scrollContentBackground(.hidden)
 77        .background(Color.black)
 78        .navigationTitle("Watchlist")
 79        .searchable(text: $viewModel.watchlistSearchText, prompt: "Search tracked domains")
 80        .toolbar {
 81            if !viewModel.filteredTrackedDomains.isEmpty {
 82                ToolbarItemGroup(placement: .topBarTrailing) {
 83                    Menu {
 84                        Picker("Filter", selection: $viewModel.watchlistFilter) {
 85                            ForEach(WatchlistFilterOption.allCases) { option in
 86                                Text(option.title).tag(option)
 87                            }
 88                        }
 89
 90                        Picker("Sort", selection: $viewModel.watchlistSortOption) {
 91                            ForEach(WatchlistSortOption.allCases) { option in
 92                                Text(option.title).tag(option)
 93                            }
 94                        }
 95
 96                        Button(viewModel.batchLookupRunning ? "Check All Running" : "Check All") {
 97                            AppHaptics.refresh()
 98                            viewModel.refreshAllTrackedDomains()
 99                        }
100                        .disabled(viewModel.batchLookupRunning)
101
102                        Button("Export TXT") {
103                            shareTrackedDomains(format: .text)
104                        }
105
106                        Button("Export CSV") {
107                            shareTrackedDomains(format: .csv)
108                        }
109
110                        Button("Export JSON") {
111                            shareTrackedDomains(format: .json)
112                        }
113                    } label: {
114                        Image(systemName: "line.3.horizontal.decrease.circle")
115                    }
116
117                    EditButton()
118                }
119            }
120        }
121        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
122            dismiss()
123        }
124        .sheet(item: batchSummaryBinding) { summary in
125            BatchSweepSummaryView(viewModel: viewModel, summary: summary)
126        }
127        .preferredColorScheme(.dark)
128    }
129
130    @ViewBuilder
131    private func trackedSection(title: String, domains: [TrackedDomain]) -> some View {
132        Section(title) {
133            ForEach(domains) { trackedDomain in
134                trackedDomainRow(trackedDomain)
135            }
136        }
137    }
138
139    private func trackedDomainRow(_ trackedDomain: TrackedDomain) -> some View {
140        NavigationLink {
141            TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
142        } label: {
143            WatchlistRowView(
144                trackedDomain: trackedDomain,
145                isRefreshing: viewModel.refreshingTrackedDomainID == trackedDomain.id
146            )
147        }
148        .buttonStyle(.plain)
149        .swipeActions(edge: .leading, allowsFullSwipe: false) {
150            Button {
151                AppHaptics.refresh()
152                viewModel.refreshTrackedDomain(trackedDomain)
153            } label: {
154                Label("Refresh", systemImage: "arrow.clockwise")
155            }
156            .tint(.cyan)
157
158            Button {
159                viewModel.togglePinned(for: trackedDomain)
160            } label: {
161                Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
162            }
163            .tint(.yellow)
164        }
165        .swipeActions(edge: .trailing, allowsFullSwipe: false) {
166            Button {
167                AppHaptics.refresh()
168                viewModel.refreshTrackedDomain(trackedDomain)
169            } label: {
170                Label("Refresh", systemImage: "arrow.clockwise")
171            }
172            .tint(.cyan)
173
174            Button(role: .destructive) {
175                viewModel.deleteTrackedDomain(trackedDomain)
176            } label: {
177                Label("Delete", systemImage: "trash")
178            }
179        }
180        .contextMenu {
181            Button {
182                AppHaptics.refresh()
183                viewModel.refreshTrackedDomain(trackedDomain)
184            } label: {
185                Label("Refresh", systemImage: "arrow.clockwise")
186            }
187
188            Button {
189                dismiss()
190                viewModel.rerunInspection(for: trackedDomain)
191            } label: {
192                Label("Open Inspection", systemImage: "magnifyingglass")
193            }
194
195            Button {
196                viewModel.togglePinned(for: trackedDomain)
197            } label: {
198                Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
199            }
200
201            Button(role: .destructive) {
202                viewModel.deleteTrackedDomain(trackedDomain)
203            } label: {
204                Label("Delete", systemImage: "trash")
205            }
206        }
207        .listRowBackground(Color(.systemGray6).opacity(0.5))
208    }
209
210    private var batchSummaryBinding: Binding<BatchSweepSummary?> {
211        Binding(
212            get: { viewModel.latestBatchSweepSummary },
213            set: { viewModel.latestBatchSweepSummary = $0 }
214        )
215    }
216
217    private func deleteFilteredTrackedDomains(at offsets: IndexSet) {
218        let domains = offsets.map { viewModel.filteredTrackedDomains[$0] }
219        domains.forEach(viewModel.deleteTrackedDomain)
220    }
221
222    private func shareTrackedDomains(format: DomainExportFormat) {
223        let formatter = DateFormatter()
224        formatter.dateFormat = "yyyyMMdd_HHmmss"
225        let timestamp = formatter.string(from: Date())
226        let filename = "\(timestamp)_domaindig_watchlist.\(format.fileExtension)"
227        let data: Data
228
229        switch format {
230        case .text:
231            data = Data(viewModel.exportTrackedDomainsText(domains: viewModel.filteredTrackedDomains).utf8)
232        case .csv:
233            data = Data(viewModel.exportTrackedDomainsCSV(domains: viewModel.filteredTrackedDomains).utf8)
234        case .json:
235            data = viewModel.exportTrackedDomainsJSONData(domains: viewModel.filteredTrackedDomains) ?? Data("[]".utf8)
236        }
237
238        ExportPresenter.share(filename: filename, data: data)
239    }
240}
241
242struct WatchlistRowView: View {
243    @Environment(\.appDensity) private var appDensity
244    let trackedDomain: TrackedDomain
245    let isRefreshing: Bool
246
247    var body: some View {
248        VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing + 1) {
249            HStack(alignment: .firstTextBaseline, spacing: 8) {
250                if trackedDomain.isPinned {
251                    Image(systemName: "pin.fill")
252                        .font(.caption2)
253                        .foregroundStyle(.yellow)
254                }
255                Text(trackedDomain.domain)
256                    .font(appDensity.font(.callout))
257                    .foregroundStyle(.primary)
258                    .lineLimit(2)
259                    .multilineTextAlignment(.leading)
260                Spacer(minLength: 8)
261                statusBadge
262            }
263
264            Text("Updated \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
265                .font(appDensity.font(.caption2))
266                .foregroundStyle(.secondary)
267
268            indicatorRow
269
270            if let note = trackedDomain.note?.trimmingCharacters(in: .whitespacesAndNewlines), !note.isEmpty {
271                Text(note)
272                    .font(appDensity.font(.caption))
273                    .foregroundStyle(.secondary)
274                    .lineLimit(2)
275            } else if let summary = trackedDomain.lastChangeSummary {
276                Text(summary.message)
277                    .font(appDensity.font(.caption))
278                    .foregroundStyle(.secondary)
279                    .lineLimit(2)
280            }
281        }
282        .frame(maxWidth: .infinity, alignment: .leading)
283        .padding(.vertical, 4)
284    }
285
286    private func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
287        switch status {
288        case .available:
289            return "Available"
290        case .registered:
291            return "Registered"
292        case .unknown, .none:
293            return "Unknown"
294        }
295    }
296
297    @ViewBuilder
298    private var statusBadge: some View {
299        if isRefreshing {
300            AppStatusBadgeView(model: .init(title: "Refreshing", systemImage: "arrow.clockwise", foregroundColor: .secondary, backgroundColor: Color(.systemGray5).opacity(0.6)))
301        } else {
302            AppStatusBadgeView(model: AppStatusFactory.availability(trackedDomain.lastKnownAvailability))
303        }
304    }
305
306    @ViewBuilder
307    private var indicatorRow: some View {
308        HStack(spacing: 8) {
309            AppStatusBadgeView(model: AppStatusFactory.change(trackedDomain.lastChangeSummary))
310
311            if trackedDomain.certificateWarningLevel != .none {
312                AppStatusBadgeView(model: certificateBadge)
313            }
314        }
315    }
316
317    private var certificateBadge: AppStatusBadgeModel {
318        let days = trackedDomain.certificateDaysRemaining.map { "\($0)d" } ?? "Soon"
319        switch trackedDomain.certificateWarningLevel {
320        case .critical:
321            return .init(title: "Invalid \(days)", systemImage: "xmark.octagon.fill", foregroundColor: .red, backgroundColor: .red.opacity(0.16))
322        case .warning:
323            return .init(title: "Expiring \(days)", systemImage: "exclamationmark.triangle.fill", foregroundColor: .yellow, backgroundColor: .yellow.opacity(0.16))
324        case .none:
325            return .init(title: "Valid", systemImage: "lock.fill", foregroundColor: .green, backgroundColor: .green.opacity(0.16))
326        }
327    }
328}
329
330struct TrackedDomainDetailView: View {
331    @Bindable var viewModel: DomainViewModel
332    let trackedDomain: TrackedDomain
333    @Environment(\.dismiss) private var dismiss
334
335    @State private var noteDraft = ""
336    @State private var isEditingNote = false
337
338    private var liveTrackedDomain: TrackedDomain {
339        viewModel.trackedDomains.first(where: { $0.id == trackedDomain.id }) ?? trackedDomain
340    }
341
342    private var latestSnapshots: [HistoryEntry] {
343        viewModel.recentSnapshots(for: liveTrackedDomain)
344    }
345
346    private var latestDiffSections: [DomainDiffSection] {
347        viewModel.diffSectionsForLatestSnapshots(of: liveTrackedDomain)
348    }
349
350    var body: some View {
351        List {
352            Section {
353                WatchlistRowView(
354                    trackedDomain: liveTrackedDomain,
355                    isRefreshing: viewModel.refreshingTrackedDomainID == liveTrackedDomain.id
356                )
357            }
358            .listRowBackground(Color(.systemGray6).opacity(0.5))
359
360            Section {
361                Button {
362                    viewModel.refreshTrackedDomain(liveTrackedDomain)
363                } label: {
364                    Label("Manual Refresh", systemImage: "arrow.clockwise")
365                }
366
367                Button {
368                    viewModel.rerunInspection(for: liveTrackedDomain)
369                } label: {
370                    Label("Re-run Inspection", systemImage: "magnifyingglass")
371                }
372
373                Button {
374                    viewModel.togglePinned(for: liveTrackedDomain)
375                } label: {
376                    Label(liveTrackedDomain.isPinned ? "Unpin Domain" : "Pin Domain", systemImage: liveTrackedDomain.isPinned ? "pin.slash" : "pin")
377                }
378
379                Button {
380                    noteDraft = liveTrackedDomain.note ?? ""
381                    isEditingNote = true
382                } label: {
383                    Label(liveTrackedDomain.note == nil ? "Add Note" : "Edit Note", systemImage: "note.text")
384                }
385            }
386            .listRowBackground(Color(.systemGray6).opacity(0.5))
387
388            if let summary = viewModel.latestChangeSummary(for: liveTrackedDomain) {
389                Section("Latest Change Summary") {
390                    DomainChangeSummaryView(summary: summary)
391                }
392                .listRowBackground(Color.clear)
393            }
394
395            if !latestDiffSections.isEmpty {
396                Section("Latest Diff") {
397                    DomainDiffView(title: "Latest Snapshot vs Previous", sections: latestDiffSections, showsUnchanged: false)
398                }
399                .listRowBackground(Color.clear)
400            }
401
402            Section("Recent Snapshots") {
403                if latestSnapshots.isEmpty {
404                    Text("No snapshots yet")
405                        .font(.system(.caption, design: .monospaced))
406                        .foregroundStyle(.secondary)
407                } else {
408                    ForEach(latestSnapshots) { entry in
409                        NavigationLink {
410                            HistoryDetailView(viewModel: viewModel, entry: entry)
411                        } label: {
412                            VStack(alignment: .leading, spacing: 4) {
413                                Text(entry.timestamp.formatted(date: .abbreviated, time: .shortened))
414                                    .font(.system(.caption, design: .monospaced))
415                                    .foregroundStyle(.primary)
416                                Text(entry.changeSummary?.hasChanges == true ? "Changed" : "Snapshot")
417                                    .font(.system(.caption2, design: .monospaced))
418                                    .foregroundStyle(.secondary)
419                            }
420                        }
421                    }
422                }
423            }
424            .listRowBackground(Color(.systemGray6).opacity(0.5))
425        }
426        .scrollContentBackground(.hidden)
427        .background(Color.black)
428        .navigationTitle(liveTrackedDomain.domain)
429        .preferredColorScheme(.dark)
430        .onChange(of: viewModel.rerunNavigationToken) { _, _ in
431            dismiss()
432        }
433        .sheet(isPresented: $isEditingNote) {
434            NavigationStack {
435                Form {
436                    Section("Tracking Note") {
437                        TextField("Optional note", text: $noteDraft, axis: .vertical)
438                            .lineLimit(3...6)
439                    }
440                }
441                .navigationTitle("Edit Note")
442                .toolbar {
443                    ToolbarItem(placement: .cancellationAction) {
444                        Button("Cancel") {
445                            isEditingNote = false
446                        }
447                    }
448                    ToolbarItem(placement: .confirmationAction) {
449                        Button("Save") {
450                            viewModel.updateNote(noteDraft, for: liveTrackedDomain)
451                            isEditingNote = false
452                        }
453                    }
454                }
455            }
456        }
457    }
458}