DomainDig/WatchlistView.swift
479 lines · 19107 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 @State private var showRerunOptions = false
338
339 private var liveTrackedDomain: TrackedDomain {
340 viewModel.trackedDomains.first(where: { $0.id == trackedDomain.id }) ?? trackedDomain
341 }
342
343 private var latestSnapshots: [HistoryEntry] {
344 viewModel.recentSnapshots(for: liveTrackedDomain)
345 }
346
347 private var latestDiffSections: [DomainDiffSection] {
348 viewModel.diffSectionsForLatestSnapshots(of: liveTrackedDomain)
349 }
350
351 var body: some View {
352 List {
353 Section {
354 WatchlistRowView(
355 trackedDomain: liveTrackedDomain,
356 isRefreshing: viewModel.refreshingTrackedDomainID == liveTrackedDomain.id
357 )
358 }
359 .listRowBackground(Color(.systemGray6).opacity(0.5))
360
361 Section {
362 Button {
363 viewModel.refreshTrackedDomain(liveTrackedDomain)
364 } label: {
365 Label("Manual Refresh", systemImage: "arrow.clockwise")
366 }
367
368 Button {
369 showRerunOptions = true
370 } label: {
371 Label("Re-run Inspection", systemImage: "magnifyingglass")
372 }
373
374 Button {
375 viewModel.togglePinned(for: liveTrackedDomain)
376 } label: {
377 Label(liveTrackedDomain.isPinned ? "Unpin Domain" : "Pin Domain", systemImage: liveTrackedDomain.isPinned ? "pin.slash" : "pin")
378 }
379
380 Button {
381 noteDraft = liveTrackedDomain.note ?? ""
382 isEditingNote = true
383 } label: {
384 Label(liveTrackedDomain.note == nil ? "Add Note" : "Edit Note", systemImage: "note.text")
385 }
386 }
387 .listRowBackground(Color(.systemGray6).opacity(0.5))
388
389 if let summary = viewModel.latestChangeSummary(for: liveTrackedDomain) {
390 Section("Latest Change Summary") {
391 DomainChangeSummaryView(summary: summary)
392 }
393 .listRowBackground(Color.clear)
394 }
395
396 if !latestDiffSections.isEmpty {
397 Section("Latest Diff") {
398 DomainDiffView(
399 title: "Latest Snapshot vs Previous",
400 sections: latestDiffSections,
401 contextNote: latestSnapshots.count >= 2
402 ? DomainDiffService.comparisonContextNote(from: latestSnapshots[1].snapshot, to: latestSnapshots[0].snapshot)
403 : nil,
404 showsUnchanged: false
405 )
406 }
407 .listRowBackground(Color.clear)
408 }
409
410 Section("Recent Snapshots") {
411 if latestSnapshots.isEmpty {
412 Text("No snapshots yet")
413 .font(.system(.caption, design: .monospaced))
414 .foregroundStyle(.secondary)
415 } else {
416 ForEach(latestSnapshots) { entry in
417 NavigationLink {
418 HistoryDetailView(viewModel: viewModel, entry: entry)
419 } label: {
420 VStack(alignment: .leading, spacing: 4) {
421 Text(entry.timestamp.formatted(date: .abbreviated, time: .shortened))
422 .font(.system(.caption, design: .monospaced))
423 .foregroundStyle(.primary)
424 Text(entry.changeSummary?.hasChanges == true ? "Changed" : "Snapshot")
425 .font(.system(.caption2, design: .monospaced))
426 .foregroundStyle(.secondary)
427 }
428 }
429 }
430 }
431 }
432 .listRowBackground(Color(.systemGray6).opacity(0.5))
433 }
434 .scrollContentBackground(.hidden)
435 .background(Color.black)
436 .navigationTitle(liveTrackedDomain.domain)
437 .preferredColorScheme(.dark)
438 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
439 dismiss()
440 }
441 .confirmationDialog("Re-run inspection", isPresented: $showRerunOptions) {
442 Button("Run with Current Settings") {
443 viewModel.rerunInspection(for: liveTrackedDomain, useSnapshotResolver: false)
444 }
445 if latestSnapshots.first != nil {
446 Button("Run with Snapshot Resolver") {
447 viewModel.rerunInspection(for: liveTrackedDomain, useSnapshotResolver: true)
448 }
449 }
450 Button("Cancel", role: .cancel) {}
451 } message: {
452 Text(viewModel.resolverMismatchNote(for: liveTrackedDomain) ?? "Choose how to reproduce the most recent snapshot.")
453 }
454 .sheet(isPresented: $isEditingNote) {
455 NavigationStack {
456 Form {
457 Section("Tracking Note") {
458 TextField("Optional note", text: $noteDraft, axis: .vertical)
459 .lineLimit(3...6)
460 }
461 }
462 .navigationTitle("Edit Note")
463 .toolbar {
464 ToolbarItem(placement: .cancellationAction) {
465 Button("Cancel") {
466 isEditingNote = false
467 }
468 }
469 ToolbarItem(placement: .confirmationAction) {
470 Button("Save") {
471 viewModel.updateNote(noteDraft, for: liveTrackedDomain)
472 isEditingNote = false
473 }
474 }
475 }
476 }
477 }
478 }
479}