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