DomainDigTests/PaletteContrastTests.swift

170 lines · 7293 bytes

  1import XCTest
  2@testable import DomainDig
  3
  4/// The measured ratios in `Docs/ACCESSIBILITY.txt` were prose, while
  5/// `AccessibilityAuditHarness` names the centralised palette as "the actual
  6/// guard against contrast regressions" — the reason `.contrast` is allowed to
  7/// stay report-only in the audit. Nothing checked the palette, so the guard was
  8/// a claim. This is the check.
  9///
 10/// Read from the colorsets rather than resolved `UIColor`s, for the reason
 11/// `ThemeTests` gives: the catalog is compiled into the app bundle, and the
 12/// source tree is the palette's definition.
 13final class PaletteContrastTests: XCTestCase {
 14
 15    /// WCAG AA for body text.
 16    private let minimumRatio = 4.5
 17
 18    /// Each status foreground and the surfaces it is drawn on: the page, a
 19    /// card, and its own badge fill — `AppStatusBadgeView` draws
 20    /// `theme[foreground]` over `theme[background]`, paired by `AppStatusTone`.
 21    private let pairings: [(foreground: String, badge: String)] = [
 22        ("StatusInfo", "StatusInfoSurface"),
 23        ("StatusPositive", "StatusPositiveSurface"),
 24        ("StatusWarning", "StatusWarningSurface"),
 25        ("StatusCritical", "StatusCriticalSurface"),
 26        ("StatusNeutral", "StatusNeutralSurface")
 27    ]
 28
 29    func testEveryStatusForegroundClearsAAOnEverySurfaceItIsDrawnOn() throws {
 30        for appearance in Appearance.allCases {
 31            let background = try components("AppBackground", appearance)
 32            let surface = try components("AppSurface", appearance)
 33
 34            for pairing in pairings {
 35                let foreground = try components(pairing.foreground, appearance)
 36                let badge = try components(pairing.badge, appearance)
 37
 38                for (name, against) in [("page", background), ("card", surface), ("badge", badge)] {
 39                    let ratio = contrastRatio(foreground, against)
 40                    XCTAssertGreaterThanOrEqual(
 41                        ratio,
 42                        minimumRatio,
 43                        "\(pairing.foreground) on its \(name) in \(appearance) is \(rounded(ratio)):1"
 44                    )
 45                }
 46            }
 47        }
 48    }
 49
 50    /// `AppTextSecondary` exists because iOS's own `secondaryLabel` is 3.29:1
 51    /// on a light card. A regression here would reintroduce that across the
 52    /// body text it replaced.
 53    func testSecondaryTextClearsAAOnThePageAndOnACard() throws {
 54        for appearance in Appearance.allCases {
 55            let secondary = try components("AppTextSecondary", appearance)
 56
 57            for name in ["AppBackground", "AppSurface", "AppSurfaceElevated"] {
 58                let ratio = try contrastRatio(secondary, components(name, appearance))
 59                XCTAssertGreaterThanOrEqual(
 60                    ratio,
 61                    minimumRatio,
 62                    "AppTextSecondary on \(name) in \(appearance) is \(rounded(ratio)):1"
 63                )
 64            }
 65        }
 66    }
 67
 68    /// `AppOnAccent` is drawn over `StatusInfo`, by the selected Dashboard
 69    /// filter chip — the only site that uses it. It is deliberately white in
 70    /// light and black in dark, because `StatusInfo` goes from `#0000FF` to
 71    /// `#4DA3FF` and the readable foreground flips with it.
 72    ///
 73    /// Not asserted against `AccentFill`, which nothing pairs it with:
 74    /// `accentFill` is passed to `.tint`, where iOS picks its own label colour.
 75    /// Were anything to start drawing that pair, note that black on the dark
 76    /// `AccentFill` (`#0040DD`) measures 2.78:1 and would need white instead.
 77    func testTextOnTheSelectedChipClearsAA() throws {
 78        for appearance in Appearance.allCases {
 79            let ratio = try contrastRatio(
 80                components("AppOnAccent", appearance),
 81                components("StatusInfo", appearance)
 82            )
 83            XCTAssertGreaterThanOrEqual(
 84                ratio,
 85                minimumRatio,
 86                "AppOnAccent on StatusInfo in \(appearance) is \(rounded(ratio)):1"
 87            )
 88        }
 89    }
 90
 91    // MARK: Colorsets
 92
 93    private enum Appearance: String, CaseIterable {
 94        case light
 95        case dark
 96    }
 97
 98    private struct RGB {
 99        let red: Double
100        let green: Double
101        let blue: Double
102    }
103
104    /// The sRGB components a colorset defines for one appearance.
105    ///
106    /// The light entry is the one with no `appearances` key; the dark entry
107    /// carries `luminosity: dark`. High-contrast variants are skipped: they
108    /// only ever push further in the same direction, so the base values are the
109    /// worst case.
110    private func components(_ name: String, _ appearance: Appearance) throws -> RGB {
111        let url = URL(fileURLWithPath: #filePath)
112            .deletingLastPathComponent()
113            .deletingLastPathComponent()
114            .appendingPathComponent("Shared/Colors.xcassets/\(name).colorset/Contents.json")
115        let data = try Data(contentsOf: url)
116        let parsed = try JSONSerialization.jsonObject(with: data) as? [String: Any]
117        let colors = parsed?["colors"] as? [[String: Any]] ?? []
118
119        let entry = colors.first { entry in
120            let appearances = entry["appearances"] as? [[String: Any]] ?? []
121            if appearances.contains(where: { ($0["appearance"] as? String) == "contrast" }) {
122                return false
123            }
124            let isDark = appearances.contains { $0["appearance"] as? String == "luminosity" && $0["value"] as? String == "dark" }
125            return appearance == .dark ? isDark : appearances.isEmpty
126        }
127
128        let raw = try XCTUnwrap(
129            (entry?["color"] as? [String: Any])?["components"] as? [String: String],
130            "\(name) has no \(appearance) components"
131        )
132        return RGB(
133            red: try channel(raw["red"], in: name),
134            green: try channel(raw["green"], in: name),
135            blue: try channel(raw["blue"], in: name)
136        )
137    }
138
139    /// Xcode writes these as `0xAD`, but a catalog edited by hand can hold a
140    /// decimal or a float, so all three are accepted and anything else fails
141    /// loudly rather than silently measuring black.
142    private func channel(_ raw: String?, in name: String) throws -> Double {
143        let value = try XCTUnwrap(raw, "\(name) is missing a channel")
144        if value.hasPrefix("0x") {
145            return Double(try XCTUnwrap(UInt8(value.dropFirst(2), radix: 16), "\(name): bad hex '\(value)'")) / 255
146        }
147        let number = try XCTUnwrap(Double(value), "\(name): bad component '\(value)'")
148        return number > 1 ? number / 255 : number
149    }
150
151    // MARK: WCAG
152
153    private func contrastRatio(_ lhs: RGB, _ rhs: RGB) -> Double {
154        let a = relativeLuminance(lhs)
155        let b = relativeLuminance(rhs)
156        return (max(a, b) + 0.05) / (min(a, b) + 0.05)
157    }
158
159    /// WCAG 2.1 relative luminance.
160    private func relativeLuminance(_ rgb: RGB) -> Double {
161        func linear(_ channel: Double) -> Double {
162            channel <= 0.03928 ? channel / 12.92 : pow((channel + 0.055) / 1.055, 2.4)
163        }
164        return 0.2126 * linear(rgb.red) + 0.7152 * linear(rgb.green) + 0.0722 * linear(rgb.blue)
165    }
166
167    private func rounded(_ value: Double) -> String {
168        String(format: "%.2f", value)
169    }
170}