DomainDig/ResultPrimitives.swift
344 lines · 12528 bytes
1import SwiftUI
2
3// The shared presentation primitives every result view builds on — cards,
4// rows, section titles, trust metadata, colours — and the small formatting
5// extensions that go with them. Split out of ContentView.swift (A13).
6
7struct TrackedDomainDetailHeaderView: View {
8 let trackedDomain: TrackedDomain
9
10 var body: some View {
11 VStack(alignment: .leading, spacing: 4) {
12 if let note = trackedDomain.note?.nilIfEmpty {
13 LabeledValueRow(row: InfoRowViewData(label: "Tracking Note", value: note, tone: .secondary))
14 }
15 HStack(spacing: 8) {
16 if trackedDomain.isPinned {
17 Label("Pinned", systemImage: "pin.fill")
18 }
19 Text("Last refresh \(trackedDomain.updatedAt.formatted(date: .abbreviated, time: .shortened))")
20 }
21 .font(.system(.caption2, design: .monospaced))
22 .foregroundStyle(Color(.appTextSecondary))
23 }
24 }
25}
26
27struct SectionTitleView: View {
28 @Environment(\.appDensity) private var appDensity
29 let title: String
30
31 var body: some View {
32 Text(title)
33 .font(appDensity.font(.headline, design: .default, weight: .semibold))
34 .foregroundStyle(.primary)
35 .accessibilityAddTraits(.isHeader)
36 }
37}
38
39/// Whether a `CardView` draws its own surface, or whether whatever contains it
40/// already provides one.
41///
42/// Set to `false` by the screens that put cards in `List` rows, where the row's
43/// `.listRowBackground` is the surface and a card drawing its own would be a
44/// panel inside a panel. `CardView` sets it back to `true` for its content, so
45/// only the outermost card in a row gives up its chrome and a card nested
46/// inside one keeps it.
47private struct CardProvidesSurfaceKey: EnvironmentKey {
48 static let defaultValue = true
49}
50
51extension EnvironmentValues {
52 var cardProvidesSurface: Bool {
53 get { self[CardProvidesSurfaceKey.self] }
54 set { self[CardProvidesSurfaceKey.self] = newValue }
55 }
56}
57
58/// A card that wraps its content by default.
59///
60/// `allowsHorizontalScroll` used to default to `true`, so nine call sites put
61/// their content behind a horizontal gesture instead of letting it wrap — a
62/// WCAG 1.4.10 (Reflow) failure, and the mechanism behind clipped rows at large
63/// text sizes. It also forced VoiceOver and Switch Control users onto a nested
64/// scroll axis to reach data.
65///
66/// The default is now `false`. Where horizontal scrolling genuinely suits wide
67/// tabular content, it is still opt-in — but it is suppressed at accessibility
68/// text sizes, where wrapping always beats a hidden axis.
69struct CardView<Content: View>: View {
70 @Environment(\.appDensity) private var appDensity
71 @Environment(\.dynamicTypeSize) private var dynamicTypeSize
72 @Environment(\.cardProvidesSurface) private var providesSurface
73 let allowsHorizontalScroll: Bool
74 let content: Content
75
76 init(allowsHorizontalScroll: Bool = false, @ViewBuilder content: () -> Content) {
77 self.allowsHorizontalScroll = allowsHorizontalScroll
78 self.content = content()
79 }
80
81 var body: some View {
82 Group {
83 if allowsHorizontalScroll, !dynamicTypeSize.isAccessibilitySize {
84 ScrollView(.horizontal) {
85 cardContent
86 .scrollTargetLayout()
87 }
88 .scrollBounceBehavior(.basedOnSize, axes: .horizontal)
89 } else {
90 cardContent
91 .frame(maxWidth: .infinity, alignment: .leading)
92 }
93 }
94 .frame(maxWidth: .infinity, alignment: .leading)
95 .padding(providesSurface ? appDensity.metrics.cardPadding : 0)
96 .background(providesSurface ? Color(.appSurface) : Color.clear)
97 .clipShape(
98 RoundedRectangle(cornerRadius: providesSurface ? appDensity.metrics.cardCornerRadius : 0)
99 )
100 }
101
102 private var cardContent: some View {
103 VStack(alignment: .leading, spacing: appDensity.metrics.cardSpacing) {
104 content
105 }
106 // Only the outermost card in a row gives up its surface.
107 .environment(\.cardProvidesSurface, true)
108 }
109}
110
111struct LoadingCardView: View {
112 let text: String
113
114 var body: some View {
115 CardView {
116 ProgressView(text)
117 .appLoadingStyle()
118 .frame(maxWidth: .infinity, alignment: .center)
119 }
120 }
121}
122
123struct MessageCardView: View {
124 let text: String
125 let isError: Bool
126
127 var body: some View {
128 CardView {
129 MessageRowView(text: text, isError: isError)
130 }
131 }
132}
133
134struct MessageRowView: View {
135 @Environment(\.appDensity) private var appDensity
136 let text: String
137 let isError: Bool
138
139 var body: some View {
140 Label(text, systemImage: isError ? "exclamationmark.triangle.fill" : "info.circle")
141 .font(appDensity.font(.caption))
142 .foregroundStyle(isError ? Color(.statusCritical) : .secondary)
143 .lineLimit(nil)
144 .fixedSize(horizontal: false, vertical: true)
145 }
146}
147
148struct SectionTrustMetadataView: View {
149 @Environment(\.appDensity) private var appDensity
150 let provenance: SectionProvenance?
151 let confidence: ConfidenceLevel?
152 let note: String?
153
154 init(provenance: SectionProvenance?, confidence: ConfidenceLevel?, note: String? = nil) {
155 self.provenance = provenance
156 self.confidence = confidence
157 self.note = note
158 }
159
160 var body: some View {
161 if provenance != nil || confidence != nil || note != nil {
162 VStack(alignment: .leading, spacing: 6) {
163 HStack(spacing: 8) {
164 if let confidence {
165 Text("Confidence \(confidence.title)")
166 .font(appDensity.font(.caption2))
167 .foregroundStyle(Color(.appTextSecondary))
168 }
169 if let provenance {
170 Text(provenance.provider ?? provenance.source)
171 .font(appDensity.font(.caption2))
172 .foregroundStyle(Color(.appTextSecondary))
173 Text(provenance.resultSource.label)
174 .font(appDensity.font(.caption2))
175 .foregroundStyle(Color(.appTextSecondary))
176 }
177 }
178 DisclosureGroup("Details") {
179 VStack(alignment: .leading, spacing: 4) {
180 if let provenance {
181 LabeledValueRow(row: .init(label: "Method", value: provenance.source, tone: .secondary))
182 if let provider = provenance.provider {
183 LabeledValueRow(row: .init(label: "Provider", value: provider, tone: .secondary))
184 }
185 if let resolver = provenance.resolver {
186 LabeledValueRow(row: .init(label: "Resolver", value: resolver, tone: .secondary))
187 }
188 LabeledValueRow(row: .init(label: "Collected", value: provenance.collectedAt.formatted(date: .abbreviated, time: .shortened), tone: .secondary))
189 LabeledValueRow(row: .init(label: "Mode", value: provenance.resultSource.label, tone: .secondary))
190 }
191 if let note {
192 LabeledValueRow(row: .init(label: "Note", value: note, tone: .secondary))
193 }
194 }
195 .padding(.top, 4)
196 }
197 .font(appDensity.font(.caption))
198 .tint(.secondary)
199 }
200 }
201 }
202}
203
204struct LabeledValueRow: View {
205 @Environment(\.appDensity) private var appDensity
206 @Environment(\.accessibilityDifferentiateWithoutColor) private var differentiateWithoutColor
207 let row: InfoRowViewData
208
209 var body: some View {
210 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
211 HStack(alignment: .top, spacing: 8) {
212 VStack(alignment: .leading, spacing: appDensity.metrics.rowSpacing - 1) {
213 Text(row.label)
214 .font(appDensity.font(.caption2))
215 .foregroundStyle(Color(.appTextSecondary))
216 HStack(alignment: .firstTextBaseline, spacing: 4) {
217 if differentiateWithoutColor, let symbol = toneSymbol {
218 Image(systemName: symbol)
219 .font(appDensity.font(.caption2))
220 .foregroundStyle(ResultColors.color(for: row.tone))
221 .accessibilityHidden(true)
222 }
223 valueText
224 }
225 }
226 .frame(maxWidth: .infinity, alignment: .leading)
227 .layoutPriority(1)
228 Spacer(minLength: 6)
229 if !row.value.isEmpty, row.value != "Unavailable" {
230 AppCopyButton(value: row.value, label: "Copy \(row.label)")
231 }
232 }
233 }
234 .frame(minHeight: appDensity.metrics.rowMinHeight, alignment: .topLeading)
235 }
236
237 /// A leading symbol for warning/failure tones, shown only under Differentiate
238 /// Without Color so tone is not conveyed by text colour alone. Hidden from
239 /// VoiceOver — the value text already carries the meaning.
240 private var toneSymbol: String? {
241 switch row.tone {
242 case .warning: return "exclamationmark.triangle.fill"
243 case .failure: return "xmark.octagon.fill"
244 default: return nil
245 }
246 }
247
248 @ViewBuilder
249 private var valueText: some View {
250 let base = Text(row.value)
251 .font(appDensity.font(.caption))
252 .foregroundStyle(ResultColors.color(for: row.tone))
253
254 switch row.speechStyle {
255 case .plain:
256 base
257 .lineLimit(nil)
258 .fixedSize(horizontal: false, vertical: true)
259 .textSelection(.enabled)
260 case .technical:
261 // Record values and identifiers: keep punctuation audible (SPF/DMARC
262 // separators are semantically load-bearing) and let VoiceOver use its
263 // code-reading heuristics.
264 base
265 .speechAlwaysIncludesPunctuation()
266 .accessibilityTextContentType(.sourceCode)
267 .lineLimit(nil)
268 .fixedSize(horizontal: false, vertical: true)
269 .textSelection(.enabled)
270 }
271 }
272}
273
274/// Maps a row's semantic tone onto the app palette.
275///
276/// See `Docs/ACCESSIBILITY.md` for the measured contrast ratios behind these
277/// colours. Never reach for a literal (`Color(.statusCritical)`, `Color(.statusWarning)`, …) — the system
278/// palette fails WCAG AA badly in light mode (systemYellow is 1.28:1 on white).
279enum ResultColors {
280 static func color(for tone: ResultTone) -> Color {
281 switch tone {
282 case .primary:
283 return .primary
284 case .secondary:
285 return .secondary
286 case .success:
287 return Color(.statusPositive)
288 case .warning:
289 return Color(.statusWarning)
290 case .failure:
291 return Color(.statusCritical)
292 }
293 }
294}
295
296extension DateFormatter {
297 static let certDate: DateFormatter = {
298 let formatter = DateFormatter()
299 formatter.dateStyle = .medium
300 formatter.timeStyle = .short
301 return formatter
302 }()
303}
304
305extension View {
306 func appLoadingStyle() -> some View {
307 font(.system(.caption, design: .monospaced))
308 }
309}
310
311
312extension ChangeImpactClassification {
313 var tone: AppStatusTone {
314 switch self {
315 case .informational: return .neutral
316 case .warning: return .warning
317 case .critical: return .critical
318 }
319 }
320}
321
322extension TLSGrade {
323 var tone: ResultTone {
324 switch self {
325 case .a: return .success
326 case .f: return .failure
327 default: return .warning
328 }
329 }
330}
331
332extension EmailSecurityGrade {
333 var tone: ResultTone {
334 switch self {
335 case .a: return .success
336 case .f: return .failure
337 default: return .warning
338 }
339 }
340}
341
342#Preview {
343 ContentView(viewModel: DomainViewModel())
344}