DomainDig/WatchlistView.swift
826 lines · 34192 bytes
1import SwiftUI
2
3struct WatchlistView: View {
4 @Environment(\.appDensity) private var appDensity
5 @Environment(\.accessibilityReduceMotion) private var reduceMotion
6 @Bindable var viewModel: DomainViewModel
7 @Environment(\.dismiss) private var dismiss
8 @State private var showWorkflowAddSheet = false
9 @State private var showAddDomainSheet = false
10 @State private var newTrackedDomain = ""
11 @State private var addDomainError: String?
12 @FocusState private var isAddDomainFieldFocused: Bool
13 @State private var showSavedViewsSheet = false
14 @State private var showSaveViewPrompt = false
15 @State private var newSavedViewName = ""
16
17 private var pinnedDomains: [TrackedDomain] {
18 viewModel.filteredTrackedDomains.filter(\.isPinned)
19 }
20
21 private var otherDomains: [TrackedDomain] {
22 viewModel.filteredTrackedDomains.filter { !$0.isPinned }
23 }
24
25 var body: some View {
26
27 List {
28 if !viewModel.allWatchlistTags.isEmpty {
29 Section {
30 TagFilterChipRowView(tags: viewModel.allWatchlistTags, selection: $viewModel.watchlistTagFilter)
31 }
32 .listRowBackground(Color.clear)
33 .listRowInsets(EdgeInsets())
34 }
35
36 if viewModel.batchLookupSource == .watchlistRefresh, (!viewModel.batchResults.isEmpty || viewModel.batchLookupRunning) {
37 Section("Refresh Progress") {
38 VStack(alignment: .leading, spacing: 8) {
39 ProgressView(value: Double(viewModel.batchCompletedCount), total: Double(max(viewModel.batchTotalCount, 1)))
40 .tint(ThemeToken.info)
41 HStack {
42 Text(viewModel.batchProgressLabel)
43 .font(appDensity.font(.caption))
44 .foregroundStyle(ThemeToken.textSecondary)
45 Spacer()
46 if viewModel.batchLookupRunning {
47 Button("Cancel") {
48 viewModel.cancelBatchLookup()
49 }
50 .buttonStyle(.bordered)
51 .font(appDensity.font(.caption2))
52 }
53 }
54
55 ForEach(viewModel.batchResults.prefix(5)) { result in
56 BatchResultRowView(result: result)
57 }
58 }
59 .padding(.vertical, 4)
60 }
61 .themedListRowBackground(.surface)
62 }
63
64 if viewModel.filteredTrackedDomains.isEmpty {
65 Section {
66 EmptyStateCardView(
67 title: "No Tracked Domains",
68 message: "Track important domains locally so you can refresh them quickly and see status changes at a glance.",
69 suggestion: "Run an inspection and use the Track action on a domain you care about.",
70 systemImage: "eye",
71 showsCardBackground: false
72 )
73 }
74 .themedListRowBackground(.surface)
75 } else {
76 if let limitMessage = FeatureAccessService.trackedDomainLimitMessage(currentCount: viewModel.trackedDomains.count) {
77 Section {
78 Text(limitMessage)
79 .font(appDensity.font(.caption))
80 .foregroundStyle(ThemeToken.textSecondary)
81 }
82 .themedListRowBackground(.surface)
83 }
84
85 if !pinnedDomains.isEmpty {
86 trackedSection(title: "Pinned", domains: pinnedDomains)
87 }
88
89 if !otherDomains.isEmpty {
90 trackedSection(title: pinnedDomains.isEmpty ? "Tracked Domains" : "Others", domains: otherDomains)
91 }
92 }
93 }
94 .animation(reduceMotion ? nil : .easeInOut(duration: 0.2), value: viewModel.filteredTrackedDomains.map(\.id))
95 .scrollContentBackground(.hidden)
96 .background(ThemeToken.background)
97 .navigationTitle("Watchlist")
98 .searchable(text: $viewModel.watchlistSearchText, prompt: "Search tracked domains")
99 .toolbar {
100 ToolbarItemGroup(placement: .topBarTrailing) {
101 Button {
102 addDomainError = nil
103 newTrackedDomain = ""
104 showAddDomainSheet = true
105 } label: {
106 Image(systemName: "plus")
107 }
108 .accessibilityLabel("Add domain")
109
110 if !viewModel.filteredTrackedDomains.isEmpty {
111 Menu {
112 Picker("Filter", selection: $viewModel.watchlistFilter) {
113 ForEach(WatchlistFilterOption.allCases) { option in
114 Text(option.title).tag(option)
115 }
116 }
117
118 Picker("Sort", selection: $viewModel.watchlistSortOption) {
119 ForEach(WatchlistSortOption.allCases) { option in
120 Text(option.title).tag(option)
121 }
122 }
123
124 Button("Save Current View…") {
125 newSavedViewName = ""
126 showSaveViewPrompt = true
127 }
128
129 if !viewModel.watchlistSavedViews.isEmpty {
130 Button("Saved Views") {
131 showSavedViewsSheet = true
132 }
133 }
134
135 Button(viewModel.batchLookupRunning ? "Check All Running" : "Check All") {
136 AppHaptics.refresh()
137 viewModel.refreshAllTrackedDomains()
138 }
139 .disabled(viewModel.batchLookupRunning)
140
141 Button("Add to Workflow") {
142 showWorkflowAddSheet = true
143 }
144
145 if viewModel.trackedDomains.count >= 2 {
146 NavigationLink("Compare Domains") {
147 DomainCompareView(viewModel: viewModel)
148 }
149 }
150
151 ExportFormatButtons(share: shareTrackedDomains)
152 } label: {
153 Image(systemName: "line.3.horizontal.decrease.circle")
154 }
155 .accessibilityLabel("Filter and sort")
156
157 EditButton()
158 }
159 }
160 }
161 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
162 dismiss()
163 }
164 .sheet(item: batchSummaryBinding) { summary in
165 BatchSweepSummaryView(viewModel: viewModel, summary: summary)
166 }
167 .sheet(isPresented: $showAddDomainSheet) {
168 NavigationStack {
169 Form {
170 Section("Domain") {
171 TextField("example.com", text: $newTrackedDomain)
172 .textInputAutocapitalization(.never)
173 .autocorrectionDisabled()
174 .keyboardType(.URL)
175 .textContentType(.URL)
176 .focused($isAddDomainFieldFocused)
177 .onSubmit(addTrackedDomain)
178 }
179
180 Section {
181 Text("Adds the domain directly to your watchlist so monitoring can run without a prior inspection.")
182 .font(appDensity.font(.caption))
183 .foregroundStyle(ThemeToken.textSecondary)
184 }
185
186 if let addDomainError {
187 Section {
188 Text(addDomainError)
189 .font(appDensity.font(.caption))
190 .foregroundStyle(ThemeToken.critical)
191 }
192 }
193 }
194 .navigationTitle("Add Domain")
195 .toolbar {
196 ToolbarItem(placement: .cancellationAction) {
197 Button("Cancel") {
198 showAddDomainSheet = false
199 }
200 }
201
202 ToolbarItem(placement: .confirmationAction) {
203 Button("Add", action: addTrackedDomain)
204 }
205 }
206 .onAppear {
207 DispatchQueue.main.async {
208 isAddDomainFieldFocused = true
209 }
210 }
211 }
212 }
213 .sheet(isPresented: $showWorkflowAddSheet) {
214 WorkflowBulkAddSheet(
215 viewModel: viewModel,
216 title: "Add Watchlist Domains",
217 availableDomains: viewModel.filteredTrackedDomains.map(\.domain)
218 )
219 }
220 .alert("Save Current View", isPresented: $showSaveViewPrompt) {
221 TextField("View name", text: $newSavedViewName)
222 Button("Save") {
223 viewModel.saveCurrentWatchlistView(name: newSavedViewName)
224 }
225 Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
226 } message: {
227 Text("Saves the current tag, filter, and sort as a reusable preset.")
228 }
229 .sheet(isPresented: $showSavedViewsSheet) {
230 NavigationStack {
231 List {
232 ForEach(viewModel.watchlistSavedViews) { view in
233 Button {
234 viewModel.applyWatchlistSavedView(view)
235 showSavedViewsSheet = false
236 } label: {
237 VStack(alignment: .leading, spacing: 2) {
238 Text(view.name)
239 .foregroundStyle(.primary)
240 Text([view.tag, view.filter.title, view.sort.title].compactMap { $0 }.joined(separator: " • "))
241 .font(.caption)
242 .foregroundStyle(ThemeToken.textSecondary)
243 }
244 }
245 }
246 .onDelete { offsets in
247 viewModel.deleteWatchlistSavedViews(at: offsets)
248 }
249 }
250 .navigationTitle("Saved Views")
251 .toolbar {
252 ToolbarItem(placement: .cancellationAction) {
253 Button("Done") {
254 showSavedViewsSheet = false
255 }
256 }
257 ToolbarItem(placement: .topBarTrailing) {
258 EditButton()
259 }
260 }
261 }
262 }
263 }
264
265 @ViewBuilder
266 private func trackedSection(title: String, domains: [TrackedDomain]) -> some View {
267 Section(title) {
268 ForEach(domains) { trackedDomain in
269 trackedDomainRow(trackedDomain)
270 }
271 }
272 }
273
274 private func trackedDomainRow(_ trackedDomain: TrackedDomain) -> some View {
275 NavigationLink {
276 TrackedDomainDetailView(viewModel: viewModel, trackedDomain: trackedDomain)
277 } label: {
278 WatchlistRowView(
279 trackedDomain: trackedDomain,
280 isRefreshing: viewModel.refreshingTrackedDomainID == trackedDomain.id
281 )
282 }
283 .buttonStyle(.plain)
284 .swipeActions(edge: .leading, allowsFullSwipe: false) {
285 refreshButton(trackedDomain)
286 .tint(ThemeToken.info)
287 pinButton(trackedDomain)
288 .tint(ThemeToken.warning)
289 }
290 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
291 refreshButton(trackedDomain)
292 .tint(ThemeToken.info)
293 deleteButton(trackedDomain)
294 }
295 .contextMenu {
296 rowMenu(trackedDomain)
297 }
298 .themedListRowBackground(.surface)
299 }
300
301 @ViewBuilder
302 private func rowMenu(_ trackedDomain: TrackedDomain) -> some View {
303 refreshButton(trackedDomain)
304
305 Button {
306 dismiss()
307 viewModel.rerunInspection(for: trackedDomain)
308 } label: {
309 Label("Open Inspection", systemImage: "magnifyingglass")
310 }
311
312 pinButton(trackedDomain)
313 .disabled(!viewModel.canEdit(trackedDomain))
314
315 Button {
316 // The system sharing UI manages participants and permissions.
317 } label: {
318 Label(trackedDomain.collaboration?.isShared == true ? "Shared" : "Private", systemImage: "person.2")
319 }
320 .disabled(true)
321
322 deleteButton(trackedDomain)
323 }
324
325 private func refreshButton(_ trackedDomain: TrackedDomain) -> some View {
326 Button {
327 AppHaptics.refresh()
328 viewModel.refreshTrackedDomain(trackedDomain)
329 } label: {
330 Label("Refresh", systemImage: "arrow.clockwise")
331 }
332 }
333
334 private func pinButton(_ trackedDomain: TrackedDomain) -> some View {
335 Button {
336 viewModel.togglePinned(for: trackedDomain)
337 } label: {
338 Label(trackedDomain.isPinned ? "Unpin" : "Pin", systemImage: trackedDomain.isPinned ? "pin.slash" : "pin")
339 }
340 }
341
342 @ViewBuilder
343 private func deleteButton(_ trackedDomain: TrackedDomain) -> some View {
344 if viewModel.canDelete(trackedDomain) {
345 Button(role: .destructive) {
346 viewModel.deleteTrackedDomain(trackedDomain)
347 } label: {
348 Label("Delete", systemImage: "trash")
349 }
350 }
351 }
352
353 private var batchSummaryBinding: Binding<BatchSweepSummary?> {
354 Binding(
355 get: { viewModel.latestBatchSweepSummary },
356 set: { viewModel.latestBatchSweepSummary = $0 }
357 )
358 }
359
360 private func deleteFilteredTrackedDomains(at offsets: IndexSet) {
361 let domains = offsets.map { viewModel.filteredTrackedDomains[$0] }
362 domains.forEach(viewModel.deleteTrackedDomain)
363 }
364
365 private func shareTrackedDomains(format: DomainExportFormat) {
366 let formatter = DateFormatter()
367 formatter.dateFormat = "yyyyMMdd_HHmmss"
368 let timestamp = formatter.string(from: Date())
369 let filename = "\(timestamp)_domaindig_watchlist.\(format.fileExtension)"
370 guard let data = viewModel.exportTrackedDomainsData(domains: viewModel.filteredTrackedDomains, format: format) else {
371 return
372 }
373
374 ExportPresenter.share(filename: filename, data: data)
375 }
376
377 private func addTrackedDomain() {
378 let draft = newTrackedDomain.trimmingCharacters(in: .whitespacesAndNewlines)
379 guard !draft.isEmpty else {
380 addDomainError = "Enter a domain to add."
381 return
382 }
383
384 if viewModel.trackDomain(domain: draft, availabilityStatus: nil) {
385 AppHaptics.track()
386 isAddDomainFieldFocused = false
387 addDomainError = nil
388 newTrackedDomain = ""
389 showAddDomainSheet = false
390 } else if viewModel.upgradePrompt == nil {
391 addDomainError = "Enter a valid domain like example.com."
392 }
393 }
394}
395
396struct WatchlistRowView: View {
397 @Environment(\.appDensity) private var appDensity
398 let trackedDomain: TrackedDomain
399 let isRefreshing: Bool
400
401 var body: some View {
402 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing + 1) {
403 // Side-by-side while it fits; at accessibility sizes the badge drops
404 // below the domain instead of squeezing it into "hea lt…" while the
405 // badge letter-wraps down the screen. ViewThatFits picks the wide
406 // layout whenever it genuinely fits, so default sizes keep density.
407 ViewThatFits(in: .horizontal) {
408 HStack(alignment: .firstTextBaseline, spacing: 8) {
409 domainTitle
410 Spacer(minLength: 8)
411 statusBadge
412 }
413 VStack(alignment: .leading, spacing: 6) {
414 domainTitle
415 statusBadge
416 }
417 }
418
419 Text("Updated \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
420 .font(appDensity.font(.caption2))
421 .foregroundStyle(ThemeToken.textSecondary)
422
423 if let collaboration = trackedDomain.collaboration, collaboration.isShared {
424 Text("\(collaboration.ownership.title) • \(collaboration.permission.title)")
425 .font(appDensity.font(.caption2))
426 .foregroundStyle(ThemeToken.textSecondary)
427 }
428
429 ViewThatFits(in: .horizontal) {
430 HStack(spacing: 8) { monitoringMetadata }
431 VStack(alignment: .leading, spacing: 2) { monitoringMetadata }
432 }
433 .font(appDensity.font(.caption2))
434 .foregroundStyle(ThemeToken.textSecondary)
435
436 indicatorRow
437
438 if let note = trackedDomain.note?.trimmingCharacters(in: .whitespacesAndNewlines), !note.isEmpty {
439 Text(note)
440 .font(appDensity.font(.caption))
441 .foregroundStyle(ThemeToken.textSecondary)
442 .lineLimit(2)
443 } else if let summary = trackedDomain.lastChangeSummary {
444 Text(summary.message)
445 .font(appDensity.font(.caption))
446 .foregroundStyle(ThemeToken.textSecondary)
447 .lineLimit(2)
448 }
449 }
450 .frame(maxWidth: .infinity, alignment: .leading)
451 .padding(.vertical, 4)
452 .modifier(WatchlistRowAccessibility(trackedDomain: trackedDomain, isRefreshing: isRefreshing))
453 }
454
455 @ViewBuilder
456 private var monitoringMetadata: some View {
457 Text(trackedDomain.monitoringEnabled ? "Monitoring on" : "Monitoring off")
458 if let lastMonitoredAt = trackedDomain.lastMonitoredAt {
459 Text("Checked \(lastMonitoredAt.formatted(date: .omitted, time: .shortened))")
460 }
461 if let lastAlertAt = trackedDomain.lastAlertAt {
462 Text("Alert \(lastAlertAt.formatted(date: .omitted, time: .shortened))")
463 }
464 }
465
466 private var domainTitle: some View {
467 HStack(alignment: .firstTextBaseline, spacing: 8) {
468 if trackedDomain.isPinned {
469 Image(systemName: "pin.fill")
470 .font(.caption2)
471 .foregroundStyle(ThemeToken.warning)
472 }
473 Text(trackedDomain.domain)
474 .font(appDensity.font(.callout))
475 .foregroundStyle(.primary)
476 .lineLimit(3)
477 .multilineTextAlignment(.leading)
478 .fixedSize(horizontal: false, vertical: true)
479 }
480 }
481
482 private func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
483 switch status {
484 case .available:
485 return "Available"
486 case .registered:
487 return "Registered"
488 case .unknown, .none:
489 return "Unknown"
490 }
491 }
492
493 @ViewBuilder
494 private var statusBadge: some View {
495 if isRefreshing {
496 AppStatusBadgeView(model: .init(title: "Refreshing", systemImage: "arrow.clockwise", foreground: .textSecondary, background: .surfaceElevated))
497 } else {
498 AppStatusBadgeView(model: AppStatusFactory.availability(trackedDomain.lastKnownAvailability))
499 }
500 }
501
502 @ViewBuilder
503 private var indicatorRow: some View {
504 HStack(spacing: 8) {
505 if trackedDomain.collaboration?.isShared == true {
506 AppStatusBadgeView(
507 model: .init(
508 title: "Shared",
509 systemImage: "person.2.fill",
510 foreground: .info,
511 background: .infoSurface
512 )
513 )
514 }
515
516 AppStatusBadgeView(model: AppStatusFactory.change(trackedDomain.lastChangeSummary))
517
518 if trackedDomain.certificateWarningLevel != .none {
519 AppStatusBadgeView(model: certificateBadge)
520 }
521 }
522 }
523
524 private var certificateBadge: AppStatusBadgeModel {
525 let days = trackedDomain.certificateDaysRemaining.map { "\($0)d" } ?? "Soon"
526 switch trackedDomain.certificateWarningLevel {
527 case .critical:
528 return .init(title: "Invalid \(days)", systemImage: "xmark.octagon.fill", foreground: .critical, background: .criticalSurface)
529 case .warning:
530 return .init(title: "Expiring \(days)", systemImage: "exclamationmark.triangle.fill", foreground: .warning, background: .warningSurface)
531 case .none:
532 return .init(title: "Valid", systemImage: "lock.fill", foreground: .positive, background: .positiveSurface)
533 }
534 }
535}
536
537/// Row-level VoiceOver treatment for a tracked domain: domain as label,
538/// availability as value, the rest on the More Content rotor. Same rationale as
539/// the batch row — up to nine text elements would be one unnavigable utterance.
540private struct WatchlistRowAccessibility: ViewModifier {
541 let trackedDomain: TrackedDomain
542 let isRefreshing: Bool
543
544 func body(content: Content) -> some View {
545 content
546 .accessibilityElement(children: .ignore)
547 .accessibilityLabel(trackedDomain.domain)
548 .accessibilityValue(isRefreshing ? "Refreshing" : AppStatusFactory.availability(trackedDomain.lastKnownAvailability).title)
549 .accessibilityCustomContent("Certificate", certificateContent, importance: .high)
550 .accessibilityCustomContent("Monitoring", trackedDomain.monitoringEnabled ? "on" : "off")
551 .accessibilityCustomContent("Updated", trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))
552 .accessibilityCustomContent("Pinned", trackedDomain.isPinned ? "yes" : "no")
553 }
554
555 private var certificateContent: String {
556 let days = trackedDomain.certificateDaysRemaining.map { "\($0) days" } ?? "unknown"
557 switch trackedDomain.certificateWarningLevel {
558 case .critical: return "invalid, \(days)"
559 case .warning: return "expiring, \(days)"
560 case .none: return "valid"
561 }
562 }
563}
564
565struct TrackedDomainDetailView: View {
566 @Bindable var viewModel: DomainViewModel
567 let trackedDomain: TrackedDomain
568 @Environment(\.dismiss) private var dismiss
569
570 @State private var noteDraft = ""
571 @State private var isEditingNote = false
572 @State private var tagsDraft = ""
573 @State private var isEditingTags = false
574 @State private var showRerunOptions = false
575 @State private var shareEntity: ShareableEntity?
576 @State private var showingAuditTimeline = false
577 @State private var auditStartInFlight = false
578
579 private var liveTrackedDomain: TrackedDomain {
580 viewModel.trackedDomains.first(where: { $0.id == trackedDomain.id }) ?? trackedDomain
581 }
582
583 private var latestSnapshots: [HistoryEntry] {
584 viewModel.recentSnapshots(for: liveTrackedDomain)
585 }
586
587 private var latestDiffSections: [DomainDiffSection] {
588 viewModel.diffSectionsForLatestSnapshots(of: liveTrackedDomain)
589 }
590
591 var body: some View {
592 List {
593 Section {
594 WatchlistRowView(
595 trackedDomain: liveTrackedDomain,
596 isRefreshing: viewModel.refreshingTrackedDomainID == liveTrackedDomain.id
597 )
598 }
599 .themedListRowBackground(.surface)
600
601 Section {
602 Button {
603 viewModel.refreshTrackedDomain(liveTrackedDomain)
604 } label: {
605 Label("Manual Refresh", systemImage: "arrow.clockwise")
606 }
607
608 Button {
609 showRerunOptions = true
610 } label: {
611 Label("Re-run Inspection", systemImage: "magnifyingglass")
612 }
613
614 Button {
615 Task {
616 auditStartInFlight = true
617 if await viewModel.startAudit(for: liveTrackedDomain.domain) != nil {
618 showingAuditTimeline = true
619 }
620 auditStartInFlight = false
621 }
622 } label: {
623 Label(auditStartInFlight ? "Starting Audit…" : "Start Audit", systemImage: "checklist")
624 }
625 .disabled(auditStartInFlight)
626
627 if !viewModel.audits(for: liveTrackedDomain.domain).isEmpty {
628 Button {
629 showingAuditTimeline = true
630 } label: {
631 Label("View Audits", systemImage: "clock.badge.checkmark")
632 }
633 }
634
635 Button {
636 viewModel.togglePinned(for: liveTrackedDomain)
637 } label: {
638 Label(liveTrackedDomain.isPinned ? "Unpin Domain" : "Pin Domain", systemImage: liveTrackedDomain.isPinned ? "pin.slash" : "pin")
639 }
640 .disabled(!viewModel.canEdit(liveTrackedDomain))
641
642 Button {
643 viewModel.toggleMonitoring(for: liveTrackedDomain)
644 } label: {
645 Label(
646 liveTrackedDomain.monitoringEnabled ? "Disable Monitoring" : "Enable Monitoring",
647 systemImage: liveTrackedDomain.monitoringEnabled ? "bell.slash" : "bell"
648 )
649 }
650 .disabled(!viewModel.canEdit(liveTrackedDomain))
651
652 Button {
653 noteDraft = liveTrackedDomain.note ?? ""
654 isEditingNote = true
655 } label: {
656 Label(liveTrackedDomain.note == nil ? "Add Note" : "Edit Note", systemImage: "note.text")
657 }
658 .disabled(!viewModel.canEdit(liveTrackedDomain))
659
660 Button {
661 tagsDraft = liveTrackedDomain.tags.joined(separator: ", ")
662 isEditingTags = true
663 } label: {
664 Label(liveTrackedDomain.tags.isEmpty ? "Add Tags" : "Edit Tags", systemImage: "tag")
665 }
666 .disabled(!viewModel.canEdit(liveTrackedDomain))
667
668 Button {
669 // Managing a share the user already has stays available on
670 // any tier; only creating a new one needs Pro+.
671 guard liveTrackedDomain.collaboration?.isShared == true
672 || FeatureAccessService.hasAccess(to: .sharedPortfolios) else {
673 viewModel.upgradePrompt = FeatureAccessService.upgradePrompt(for: .sharedPortfolios)
674 return
675 }
676 shareEntity = .trackedDomain(liveTrackedDomain.domain)
677 } label: {
678 Label(liveTrackedDomain.collaboration?.isShared == true ? "Manage Share" : "Share Domain", systemImage: "person.2")
679 }
680 }
681 .themedListRowBackground(.surface)
682
683 if !liveTrackedDomain.tags.isEmpty {
684 Section("Tags") {
685 TagChipRowView(tags: liveTrackedDomain.tags)
686 }
687 .themedListRowBackground(.surface)
688 }
689
690 Section("Monitoring Status") {
691 LabeledContent("State", value: viewModel.monitoringStatusLabel(for: liveTrackedDomain))
692 LabeledContent("Current Interval", value: viewModel.monitoringIntervalLabel(for: liveTrackedDomain))
693 LabeledContent(
694 "Last Change",
695 value: liveTrackedDomain.monitoringState.lastChangeDate?.formatted(date: .abbreviated, time: .shortened) ?? "None"
696 )
697 if !liveTrackedDomain.pendingMonitoringAlerts.isEmpty {
698 LabeledContent("Queued Alerts", value: "\(liveTrackedDomain.pendingMonitoringAlerts.count)")
699 }
700 }
701 .themedListRowBackground(.surface)
702
703 if let summary = viewModel.latestChangeSummary(for: liveTrackedDomain) {
704 Section("Latest Change Summary") {
705 DomainChangeSummaryView(summary: summary)
706 }
707 .listRowBackground(Color.clear)
708 }
709
710 if !latestDiffSections.isEmpty {
711 Section("Latest Diff") {
712 DomainDiffView(
713 title: "Latest Snapshot vs Previous",
714 sections: latestDiffSections,
715 contextNote: latestSnapshots.count >= 2
716 ? DomainDiffService.comparisonContextNote(from: latestSnapshots[1].snapshot, to: latestSnapshots[0].snapshot)
717 : nil,
718 showsUnchanged: false,
719 highlightedSectionID: nil
720 )
721 }
722 .listRowBackground(Color.clear)
723 }
724
725 Section("Recent Snapshots") {
726 if latestSnapshots.isEmpty {
727 Text("No snapshots yet")
728 .font(.system(.caption, design: .monospaced))
729 .foregroundStyle(ThemeToken.textSecondary)
730 } else {
731 ForEach(latestSnapshots) { entry in
732 NavigationLink {
733 HistoryDetailView(viewModel: viewModel, entry: entry)
734 } label: {
735 VStack(alignment: .leading, spacing: 4) {
736 Text(entry.timestamp.formatted(date: .abbreviated, time: .shortened))
737 .font(.system(.caption, design: .monospaced))
738 .foregroundStyle(.primary)
739 Text(entry.changeSummary?.hasChanges == true ? "Changed" : "Snapshot")
740 .font(.system(.caption2, design: .monospaced))
741 .foregroundStyle(ThemeToken.textSecondary)
742 }
743 }
744 }
745 }
746 }
747 .themedListRowBackground(.surface)
748 }
749 .scrollContentBackground(.hidden)
750 .background(ThemeToken.background)
751 .navigationTitle(liveTrackedDomain.domain)
752 .onChange(of: viewModel.rerunNavigationToken) { _, _ in
753 dismiss()
754 }
755 .confirmationDialog("Re-run inspection", isPresented: $showRerunOptions) {
756 Button("Run with Current Settings") {
757 viewModel.rerunInspection(for: liveTrackedDomain, useSnapshotResolver: false)
758 }
759 if latestSnapshots.first != nil {
760 Button("Run with Snapshot Resolver") {
761 viewModel.rerunInspection(for: liveTrackedDomain, useSnapshotResolver: true)
762 }
763 }
764 Button("Cancel", role: .cancel) { /* Dismiss only; SwiftUI closes the alert. */ }
765 } message: {
766 Text(viewModel.resolverMismatchNote(for: liveTrackedDomain) ?? "Choose how to reproduce the most recent snapshot.")
767 }
768 .sheet(isPresented: $isEditingNote) {
769 NavigationStack {
770 Form {
771 Section("Tracking Note") {
772 TextField("Optional note", text: $noteDraft, axis: .vertical)
773 .lineLimit(3...6)
774 }
775 }
776 .navigationTitle("Edit Note")
777 .toolbar {
778 ToolbarItem(placement: .cancellationAction) {
779 Button("Cancel") {
780 isEditingNote = false
781 }
782 }
783 ToolbarItem(placement: .confirmationAction) {
784 Button("Save") {
785 viewModel.updateNote(noteDraft, for: liveTrackedDomain)
786 isEditingNote = false
787 }
788 }
789 }
790 }
791 }
792 .sheet(isPresented: $isEditingTags) {
793 NavigationStack {
794 Form {
795 Section("Tags") {
796 TextField("comma, separated, tags", text: $tagsDraft)
797 .textInputAutocapitalization(.never)
798 }
799 }
800 .navigationTitle("Edit Tags")
801 .toolbar {
802 ToolbarItem(placement: .cancellationAction) {
803 Button("Cancel") {
804 isEditingTags = false
805 }
806 }
807 ToolbarItem(placement: .confirmationAction) {
808 Button("Save") {
809 let tags = tagsDraft.components(separatedBy: ",")
810 viewModel.updateTags(tags, for: liveTrackedDomain)
811 isEditingTags = false
812 }
813 }
814 }
815 }
816 }
817 .sheet(item: $shareEntity) { entity in
818 CloudSharingSheet(entity: entity, title: liveTrackedDomain.domain)
819 }
820 .sheet(isPresented: $showingAuditTimeline) {
821 NavigationStack {
822 AuditDomainTimelineView(viewModel: viewModel, domain: liveTrackedDomain.domain)
823 }
824 }
825 }
826}