DomainDig/DomainDigUI.swift
579 lines · 21091 bytes
1import SwiftUI
2
3#if canImport(UIKit)
4import UIKit
5#elseif canImport(AppKit)
6import AppKit
7#endif
8
9/// User-selected appearance, applied once at the `WindowGroup`.
10///
11/// Deliberately applied in exactly one place. The app previously carried 16
12/// separate `.preferredColorScheme(.dark)` calls scattered across view bodies,
13/// which is how it became impossible to reach light mode at all — re-applying
14/// per view is what let the lock spread unnoticed.
15enum AppAppearance: String, CaseIterable, Identifiable {
16 case system
17 case light
18 case dark
19
20 static let userDefaultsKey = "appAppearance"
21
22 var id: String { rawValue }
23
24 var title: String {
25 switch self {
26 case .system:
27 return "System"
28 case .light:
29 return "Light"
30 case .dark:
31 return "Dark"
32 }
33 }
34
35 /// `nil` hands control back to the system setting.
36 var colorScheme: ColorScheme? {
37 switch self {
38 case .system:
39 return nil
40 case .light:
41 return .light
42 case .dark:
43 return .dark
44 }
45 }
46}
47
48enum AppDensity: String, CaseIterable, Identifiable {
49 case compact
50 case comfortable
51
52 static let userDefaultsKey = "appDensity"
53
54 var id: String { rawValue }
55
56 var title: String {
57 switch self {
58 case .compact:
59 return "Compact"
60 case .comfortable:
61 return "Comfortable"
62 }
63 }
64
65 var metrics: AppDensityMetrics {
66 switch self {
67 case .compact:
68 return AppDensityMetrics(
69 sectionSpacing: 14,
70 cardSpacing: 6,
71 cardPadding: 10,
72 rowSpacing: 4,
73 rowMinHeight: 30,
74 controlVerticalPadding: 10,
75 // Was 42, which put every control using it under the 44pt
76 // minimum in compact density — section headers, Run, Run Batch.
77 controlMinHeight: AppLayout.minimumTapTarget,
78 cardCornerRadius: 10
79 )
80 case .comfortable:
81 return AppDensityMetrics(
82 sectionSpacing: 18,
83 cardSpacing: 10,
84 cardPadding: 14,
85 rowSpacing: 7,
86 rowMinHeight: 38,
87 controlVerticalPadding: 14,
88 controlMinHeight: 48,
89 cardCornerRadius: 14
90 )
91 }
92 }
93
94 func font(_ textStyle: Font.TextStyle, design: Font.Design = .monospaced, weight: Font.Weight? = nil) -> Font {
95 var font = Font.system(textStyle, design: design)
96 if let weight {
97 font = font.weight(weight)
98 }
99 return font
100 }
101}
102
103/// Layout constants that are not density-dependent.
104enum AppLayout {
105 /// The HIG minimum for an interactive control, and WCAG 2.5.8's floor.
106 /// Controls scale up from here with Dynamic Type; none may sit below it.
107 static let minimumTapTarget: CGFloat = 44
108}
109
110struct AppDensityMetrics: Equatable {
111 let sectionSpacing: CGFloat
112 let cardSpacing: CGFloat
113 let cardPadding: CGFloat
114 let rowSpacing: CGFloat
115 let rowMinHeight: CGFloat
116 let controlVerticalPadding: CGFloat
117 let controlMinHeight: CGFloat
118 let cardCornerRadius: CGFloat
119}
120
121private struct AppDensityKey: EnvironmentKey {
122 static let defaultValue: AppDensity = .compact
123}
124
125extension EnvironmentValues {
126 var appDensity: AppDensity {
127 get { self[AppDensityKey.self] }
128 set { self[AppDensityKey.self] = newValue }
129 }
130}
131
132/// A status colour pairing: the foreground and the surface it sits on.
133///
134/// These travel together because they cannot be derived from one another. The
135/// badge fill used to be `foreground.opacity(0.16)`, which forced every
136/// foreground dark enough to stay legible against its own wash — that is how the
137/// light palette ended up olive-and-mud rather than amber-and-green. Decoupling
138/// them lets the foregrounds stay fully saturated.
139///
140/// See `Docs/ACCESSIBILITY.md` for the measured ratios.
141enum AppStatusTone {
142 case positive
143 case warning
144 case critical
145 case info
146 case neutral
147
148 var foreground: ThemeToken {
149 switch self {
150 case .positive:
151 return .positive
152 case .warning:
153 return .warning
154 case .critical:
155 return .critical
156 case .info:
157 return .info
158 case .neutral:
159 return .neutral
160 }
161 }
162
163 var surface: ThemeToken {
164 switch self {
165 case .positive:
166 return .positiveSurface
167 case .warning:
168 return .warningSurface
169 case .critical:
170 return .criticalSurface
171 case .info:
172 return .infoSurface
173 case .neutral:
174 return .neutralSurface
175 }
176 }
177}
178
179/// A badge's appearance, named rather than resolved.
180///
181/// The colours are `ThemeToken`s because every one of these is built outside a
182/// view body — `AppStatusFactory` and the per-row helpers are plain functions —
183/// so they cannot read the environment. `AppStatusBadgeView` resolves them when
184/// it draws.
185struct AppStatusBadgeModel: Equatable {
186 let title: String
187 let systemImage: String?
188 let foreground: ThemeToken
189 let background: ThemeToken
190}
191
192enum AppStatusFactory {
193 static func availability(_ status: DomainAvailabilityStatus?) -> AppStatusBadgeModel {
194 switch status {
195 case .available:
196 return .init(title: "Available", systemImage: "checkmark.circle.fill", foreground: .positive, background: .positiveSurface)
197 case .registered:
198 return .init(title: "Registered", systemImage: "circle.fill", foreground: .warning, background: .warningSurface)
199 case .unknown, .none:
200 return .init(title: "Unknown", systemImage: "questionmark.circle", foreground: .textSecondary, background: .surfaceElevated)
201 }
202 }
203
204 static func tls(sslInfo: SSLCertificateInfo?, error: String?) -> AppStatusBadgeModel {
205 if error != nil || sslInfo == nil {
206 return .init(title: "Invalid", systemImage: "xmark.octagon.fill", foreground: .critical, background: .criticalSurface)
207 }
208 if let sslInfo, sslInfo.daysUntilExpiry <= 14 {
209 return .init(title: "Expiring", systemImage: "exclamationmark.triangle.fill", foreground: .warning, background: .warningSurface)
210 }
211 return .init(title: "Valid", systemImage: "lock.fill", foreground: .positive, background: .positiveSurface)
212 }
213
214 static func email(_ result: EmailSecurityResult?, error: String?) -> AppStatusBadgeModel {
215 guard error == nil, let result else {
216 return .init(title: "Missing", systemImage: "minus.circle", foreground: .textSecondary, background: .surfaceElevated)
217 }
218
219 let foundCount = [result.spf.found, result.dmarc.found, result.dkim.found].filter { $0 }.count
220 switch foundCount {
221 case 3:
222 return .init(title: "Secure", systemImage: "checkmark.shield.fill", foreground: .positive, background: .positiveSurface)
223 case 1, 2:
224 return .init(title: "Partial", systemImage: "shield.lefthalf.filled", foreground: .warning, background: .warningSurface)
225 default:
226 return .init(title: "Missing", systemImage: "minus.circle", foreground: .textSecondary, background: .surfaceElevated)
227 }
228 }
229
230 static func change(_ summary: DomainChangeSummary?) -> AppStatusBadgeModel {
231 guard let summary else {
232 return .init(title: "Unchanged", systemImage: "circle", foreground: .textSecondary, background: .surfaceElevated)
233 }
234 if summary.hasChanges {
235 return .init(title: "Changed", systemImage: "arrow.triangle.2.circlepath", foreground: .info, background: .infoSurface)
236 }
237 return .init(title: "Unchanged", systemImage: "checkmark.circle", foreground: .textSecondary, background: .surfaceElevated)
238 }
239}
240
241struct AppStatusBadgeView: View {
242 @Environment(\.appDensity) private var appDensity
243 @Environment(\.theme) private var theme
244
245 let model: AppStatusBadgeModel
246
247 var body: some View {
248 HStack(spacing: 6) {
249 if let systemImage = model.systemImage {
250 Image(systemName: systemImage)
251 .font(.caption2)
252 }
253 Text(model.title)
254 }
255 // Never compress. Squeezed beside a long domain at accessibility sizes,
256 // the capsule otherwise wraps one character per line into a
257 // screen-height pill. Taking natural width instead forces the row's
258 // ViewThatFits onto its stacked layout, which is the intended fallback.
259 .fixedSize()
260 .font(appDensity.font(.caption, weight: .semibold))
261 .foregroundStyle(theme[model.foreground])
262 .padding(.horizontal, 9)
263 .padding(.vertical, 5)
264 .background(theme[model.background])
265 .clipShape(Capsule())
266 // Read as one word ("Critical"), not "icon, Critical". The symbol
267 // duplicates the title for VoiceOver.
268 .accessibilityElement(children: .ignore)
269 .accessibilityLabel(model.title)
270 }
271}
272
273struct AppCopyButton: View {
274 @Environment(\.appDensity) private var appDensity
275 @Environment(\.accessibilityReduceMotion) private var reduceMotion
276 @State private var didCopy = false
277
278 /// Grows with Dynamic Type. The `max(_, minimumTapTarget)` floor matters
279 /// because `@ScaledMetric` also scales *down* below the default text size,
280 /// which would push this back under the 44pt minimum.
281 @ScaledMetric(relativeTo: .caption) private var size: CGFloat = AppLayout.minimumTapTarget
282
283 let value: String
284 let label: String
285
286 var body: some View {
287 Button {
288 AppClipboard.copy(value)
289 AppHaptics.copy()
290 withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.18)) {
291 didCopy = true
292 }
293 Task {
294 try? await Task.sleep(nanoseconds: 900_000_000)
295 await MainActor.run {
296 withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.18)) {
297 didCopy = false
298 }
299 }
300 }
301 } label: {
302 Image(systemName: didCopy ? "checkmark" : "doc.on.doc")
303 .font(appDensity.font(.caption))
304 .foregroundStyle(didCopy ? ThemeToken.positive : ThemeToken.textSecondary)
305 .frame(width: max(size, AppLayout.minimumTapTarget), height: max(size, AppLayout.minimumTapTarget))
306 .background(ThemeToken.surfaceElevated)
307 .clipShape(RoundedRectangle(cornerRadius: 8))
308 }
309 .buttonStyle(.plain)
310 .accessibilityLabel(didCopy ? "\(label) copied" : label)
311 }
312}
313
314enum AppClipboard {
315 static func copy(_ value: String) {
316 #if canImport(UIKit)
317 UIPasteboard.general.string = value
318 #elseif canImport(AppKit)
319 NSPasteboard.general.clearContents()
320 NSPasteboard.general.setString(value, forType: .string)
321 #endif
322 }
323}
324
325enum AppAccessibility {
326 /// Speaks a status update through VoiceOver without moving focus. Used at
327 /// lookup and sweep completion so a blind user hears the result land instead
328 /// of having to hunt for whether anything changed.
329 static func announce(_ message: String) {
330 #if canImport(UIKit)
331 var announcement = AttributedString(message)
332 announcement.accessibilitySpeechAnnouncementPriority = .high
333 AccessibilityNotification.Announcement(announcement).post()
334 #endif
335 }
336}
337
338enum AppHaptics {
339 static func copy() {
340 #if canImport(UIKit)
341 let generator = UINotificationFeedbackGenerator()
342 generator.notificationOccurred(.success)
343 #endif
344 }
345
346 static func refresh() {
347 #if canImport(UIKit)
348 let generator = UIImpactFeedbackGenerator(style: .light)
349 generator.impactOccurred()
350 #endif
351 }
352
353 static func track() {
354 #if canImport(UIKit)
355 let generator = UIImpactFeedbackGenerator(style: .soft)
356 generator.impactOccurred()
357 #endif
358 }
359}
360
361struct EmptyStateCardView: View {
362 @Environment(\.appDensity) private var appDensity
363
364 let title: String
365 let message: String
366 let suggestion: String
367 let systemImage: String
368 let showsCardBackground: Bool
369
370 init(
371 title: String,
372 message: String,
373 suggestion: String,
374 systemImage: String,
375 showsCardBackground: Bool = true
376 ) {
377 self.title = title
378 self.message = message
379 self.suggestion = suggestion
380 self.systemImage = systemImage
381 self.showsCardBackground = showsCardBackground
382 }
383
384 var body: some View {
385 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
386 // `Text(message)` already carried `fixedSize`; the title and
387 // suggestion did not, which is why the audit reported the *title*
388 // clipped on every empty state while the body beneath it wrapped.
389 // Deliberately an HStack rather than `Label`. `Label` constrains its
390 // own title text and `.fixedSize` applied to the Label does not
391 // reach the Text inside, so every empty-state heading reported as
392 // clipped. Splitting it lets the modifier land on the Text itself.
393 // Verified: doing this alone cleared the finding on all four empty
394 // states; changing the font design did not.
395 HStack(alignment: .firstTextBaseline, spacing: 8) {
396 // Decorative. `Label` used to fold the icon into the title's
397 // element; splitting them exposed it as its own, announcing the
398 // raw SF Symbol name ("checklist.unchecked") to VoiceOver.
399 Image(systemName: systemImage)
400 .accessibilityHidden(true)
401 Text(title)
402 .fixedSize(horizontal: false, vertical: true)
403 .multilineTextAlignment(.leading)
404 }
405 .font(appDensity.font(.headline, weight: .semibold))
406 .foregroundStyle(.primary)
407
408 Text(message)
409 .font(appDensity.font(.body))
410 .foregroundStyle(ThemeToken.textSecondary)
411 .fixedSize(horizontal: false, vertical: true)
412
413 Text(suggestion)
414 .font(appDensity.font(.caption))
415 .foregroundStyle(ThemeToken.info)
416 .fixedSize(horizontal: false, vertical: true)
417 }
418 .frame(maxWidth: .infinity, alignment: .leading)
419 .padding(appDensity.metrics.cardPadding)
420 .background(showsCardBackground ? AnyShapeStyle(ThemeToken.surface) : AnyShapeStyle(.clear))
421 .clipShape(RoundedRectangle(cornerRadius: appDensity.metrics.cardCornerRadius))
422 }
423}
424
425/// A collapsible result section.
426///
427/// Its body is a `Group`, not a stack: inside a `List` that makes the header
428/// and each piece of content their own row, so the row backgrounds draw one
429/// grouped panel per section and the separators keep the cards inside it
430/// apart. Every caller puts it in a `List` for that reason — a stack would lay
431/// the children out itself and lose both.
432struct CollapsibleSectionView<HeaderTrailing: View, Content: View>: View {
433 @Environment(\.appDensity) private var appDensity
434 @Environment(\.accessibilityReduceMotion) private var reduceMotion
435
436 let title: String
437 @Binding var isCollapsed: Bool
438 let subtitle: String?
439 @ViewBuilder let trailing: () -> HeaderTrailing
440 @ViewBuilder let content: () -> Content
441
442 init(
443 title: String,
444 isCollapsed: Binding<Bool>,
445 subtitle: String? = nil,
446 @ViewBuilder trailing: @escaping () -> HeaderTrailing = { EmptyView() },
447 @ViewBuilder content: @escaping () -> Content
448 ) {
449 self.title = title
450 self._isCollapsed = isCollapsed
451 self.subtitle = subtitle
452 self.trailing = trailing
453 self.content = content
454 }
455
456 var body: some View {
457 Group {
458 Button {
459 withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.2)) {
460 isCollapsed.toggle()
461 }
462 } label: {
463 // One line while the title, trailing controls, and chevron
464 // genuinely fit; otherwise the trailing controls drop below the
465 // title. Without this, a squeezed trailing button letter-wraps
466 // vertically ("N o t e" as a screen-tall capsule) at larger
467 // Dynamic Type sizes — same pathology as the row badges.
468 ViewThatFits(in: .horizontal) {
469 HStack(alignment: .center, spacing: 10) {
470 titleBlock
471 Spacer(minLength: 8)
472 trailing()
473 chevron
474 }
475 VStack(alignment: .leading, spacing: 8) {
476 HStack(alignment: .center, spacing: 10) {
477 titleBlock
478 Spacer(minLength: 8)
479 chevron
480 }
481 trailing()
482 }
483 }
484 .contentShape(Rectangle())
485 .frame(minHeight: appDensity.metrics.controlMinHeight, alignment: .center)
486 }
487 .buttonStyle(.plain)
488 // A header that is also the expand/collapse control. The chevron is
489 // decorative; state and hint carry it to VoiceOver instead. No
490 // `children: .combine` here — `trailing()` may hold its own controls
491 // (Track, Pin), and combining would swallow them into the header.
492 .accessibilityAddTraits(.isHeader)
493 .accessibilityValue(isCollapsed ? "Collapsed" : "Expanded")
494 .accessibilityHint(isCollapsed ? "Expands the section" : "Collapses the section")
495
496 if !isCollapsed {
497 content()
498 .transition(.opacity.combined(with: .move(edge: .top)))
499 }
500 }
501 }
502
503 private var titleBlock: some View {
504 VStack(alignment: .leading, spacing: 3) {
505 Text(title)
506 .font(appDensity.font(.headline, weight: .semibold))
507 .foregroundStyle(.primary)
508 .fixedSize(horizontal: false, vertical: true)
509 .multilineTextAlignment(.leading)
510 if let subtitle {
511 Text(subtitle)
512 .font(appDensity.font(.caption))
513 .foregroundStyle(ThemeToken.textSecondary)
514 .fixedSize(horizontal: false, vertical: true)
515 }
516 }
517 }
518
519 private var chevron: some View {
520 Image(systemName: isCollapsed ? "chevron.down" : "chevron.up")
521 .font(.caption.weight(.semibold))
522 .foregroundStyle(ThemeToken.textSecondary)
523 .accessibilityHidden(true)
524 }
525}
526
527/// A horizontally scrolling row of read-only tag chips, e.g. for a tracked
528/// domain's detail view.
529struct TagChipRowView: View {
530 let tags: [String]
531
532 var body: some View {
533 ScrollView(.horizontal, showsIndicators: false) {
534 HStack(spacing: 8) {
535 ForEach(tags, id: \.self) { tag in
536 Text(tag)
537 .font(.caption)
538 .padding(.horizontal, 10)
539 .padding(.vertical, 5)
540 .background(ThemeToken.surfaceElevated, in: Capsule())
541 }
542 }
543 }
544 }
545}
546
547/// A horizontally scrolling row of selectable tag chips used to filter a list,
548/// with an "All" chip to clear the selection.
549struct TagFilterChipRowView: View {
550 let tags: [String]
551 @Binding var selection: String?
552
553 var body: some View {
554 ScrollView(.horizontal, showsIndicators: false) {
555 HStack(spacing: 8) {
556 filterChip(title: "All", isSelected: selection == nil) {
557 selection = nil
558 }
559 ForEach(tags, id: \.self) { tag in
560 filterChip(title: tag, isSelected: selection == tag) {
561 selection = (selection == tag) ? nil : tag
562 }
563 }
564 }
565 }
566 }
567
568 private func filterChip(title: String, isSelected: Bool, action: @escaping () -> Void) -> some View {
569 Button(action: action) {
570 Text(title)
571 .font(.caption)
572 .padding(.horizontal, 10)
573 .padding(.vertical, 5)
574 .background(isSelected ? ThemeToken.infoSurface : ThemeToken.surfaceElevated, in: Capsule())
575 .foregroundStyle(isSelected ? AnyShapeStyle(ThemeToken.info) : AnyShapeStyle(.primary))
576 }
577 .buttonStyle(.plain)
578 }
579}