DomainDig/Theme.swift

206 lines · 7743 bytes

  1import SwiftUI
  2
  3/// One of the app's semantic colours, named rather than resolved.
  4///
  5/// A token instead of a `Color` so a colour chosen outside a view body — a
  6/// status badge's model, for one — can say which colour it means and leave the
  7/// resolving to the view that draws it. That is what lets the whole palette sit
  8/// in the environment rather than only the parts used inside `body`.
  9///
 10/// The case names drop the `app`/`status` prefixes that the colorsets carry so
 11/// they do not collide with the style accessors below, which keep the prefixed
 12/// spelling the call sites already used. The raw value is the colorset's name.
 13nonisolated enum ThemeToken: String, CaseIterable, Sendable {
 14    case background = "AppBackground"
 15    case surface = "AppSurface"
 16    case surfaceElevated = "AppSurfaceElevated"
 17    case textSecondary = "AppTextSecondary"
 18    case separator = "AppSeparator"
 19    case onAccent = "AppOnAccent"
 20    case accent = "AccentFill"
 21    case positive = "StatusPositive"
 22    case positiveSurface = "StatusPositiveSurface"
 23    case warning = "StatusWarning"
 24    case warningSurface = "StatusWarningSurface"
 25    case critical = "StatusCritical"
 26    case criticalSurface = "StatusCriticalSurface"
 27    case info = "StatusInfo"
 28    case infoSurface = "StatusInfoSurface"
 29    case neutral = "StatusNeutral"
 30    case neutralSurface = "StatusNeutralSurface"
 31
 32    /// The palette in `Shared/Colors.xcassets`, which stays the single
 33    /// definition of every default colour.
 34    ///
 35    /// `Docs/ACCESSIBILITY.txt` names that palette as the guard against
 36    /// contrast regressions, and reading the defaults from it here is what
 37    /// keeps the guard: a theme overrides individual tokens, it does not
 38    /// replace the set.
 39    ///
 40    /// Looked up by name rather than through the generated `ColorResource`
 41    /// symbols, which are MainActor-isolated and so cannot be read from
 42    /// `ShapeStyle.resolve(in:)`. `ThemeTests` asserts that every token still
 43    /// has a colorset and that no colorset is left without a token.
 44    var assetColor: Color {
 45        Color(rawValue, bundle: .main)
 46    }
 47}
 48
 49/// A token is itself a style, so it can be handed straight to `foregroundStyle`,
 50/// `background`, `tint` or `fill` and resolve against the environment's theme
 51/// when the view draws.
 52///
 53/// This is what keeps the refactor from adding an `@Environment(\.theme)`
 54/// property to every view in the app: in a style position the token needs no
 55/// one to resolve it. Only a colour used as a plain value — a list row's
 56/// background, which takes a view rather than a style — needs the environment
 57/// read explicitly.
 58nonisolated extension ThemeToken: ShapeStyle {
 59    func resolve(in environment: EnvironmentValues) -> some ShapeStyle {
 60        environment.theme[self]
 61    }
 62}
 63
 64/// The colours a screen draws with.
 65///
 66/// Carried in the environment so an accent choice reaches every view without
 67/// threading a parameter. The default resolves every token from the asset
 68/// catalog, so an app with no theme chosen renders exactly as it did before
 69/// this existed.
 70nonisolated struct Theme: Equatable, Sendable {
 71    /// What this theme changes about the palette. Empty for the default.
 72    private let overrides: [ThemeToken: Color]
 73
 74    init(overrides: [ThemeToken: Color] = [:]) {
 75        self.overrides = overrides
 76    }
 77
 78    static let `default` = Theme()
 79
 80    subscript(token: ThemeToken) -> Color {
 81        overrides[token] ?? token.assetColor
 82    }
 83
 84    /// For the few places that need a `Color` rather than a style, such as a
 85    /// list row's background.
 86    var appBackground: Color { self[.background] }
 87    var appSurface: Color { self[.surface] }
 88    var appSurfaceElevated: Color { self[.surfaceElevated] }
 89    var appTextSecondary: Color { self[.textSecondary] }
 90    var accentFill: Color { self[.accent] }
 91}
 92
 93/// An accent a user can pick.
 94///
 95/// Only the accent tokens are overridden. The status colours keep their palette
 96/// values deliberately: "critical" means one thing, and letting an accent
 97/// recolour it would undo the contrast work phases 1–5 of #21 did and leave the
 98/// palette no longer answerable for its own contrast.
 99nonisolated enum AccentTheme: String, Codable, CaseIterable, Identifiable, Sendable {
100    case `default`
101    case graphite
102    case forest
103    case plum
104
105    static let userDefaultsKey = "appAccentTheme"
106
107    var id: String { rawValue }
108
109    var title: String {
110        switch self {
111        case .default: return "Default"
112        case .graphite: return "Graphite"
113        case .forest: return "Forest"
114        case .plum: return "Plum"
115        }
116    }
117
118    var theme: Theme {
119        guard let fill = accentFill else { return .default }
120        return Theme(overrides: [.accent: fill, .onAccent: .white])
121    }
122
123    private var accentFill: Color? {
124        switch self {
125        case .default:
126            return nil
127        case .graphite:
128            return Color(red: 0.26, green: 0.28, blue: 0.31)
129        case .forest:
130            return Color(red: 0.13, green: 0.40, blue: 0.27)
131        case .plum:
132            return Color(red: 0.42, green: 0.20, blue: 0.44)
133        }
134    }
135}
136
137extension AccentTheme {
138    /// The alternate app icon for this accent, or `nil` for the primary one.
139    ///
140    /// The names match the asset catalog's icon sets, which
141    /// `ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES` lists.
142    var alternateIconName: String? {
143        switch self {
144        case .default: return nil
145        case .graphite: return "AppIconGraphite"
146        case .forest: return "AppIconForest"
147        case .plum: return "AppIconPlum"
148        }
149    }
150}
151
152/// Keeps the home-screen icon on whichever accent is in force.
153///
154/// The icon follows the accent rather than being a second picker: iOS shows its
155/// own "You have changed the icon" alert on every change and there is no public
156/// way to suppress it, so two pickers would mean two alerts for what a user
157/// thinks of as one choice.
158@MainActor
159enum AppIconController {
160    /// Idempotent, so it is safe to call on launch as well as on change —
161    /// which is what reverts the icon when a lapsed tier drops the accent back
162    /// to default.
163    static func apply(_ accent: AccentTheme) {
164        guard UIApplication.shared.supportsAlternateIcons else { return }
165
166        let desired = accent.alternateIconName
167        guard UIApplication.shared.alternateIconName != desired else { return }
168
169        UIApplication.shared.setAlternateIconName(desired) { error in
170            guard let error else { return }
171            DomainDebugLog.error("AppIcon.setFailed name=\(desired ?? "primary") error=\(error.localizedDescription)")
172        }
173    }
174}
175
176nonisolated private struct ThemeKey: EnvironmentKey {
177    static let defaultValue = Theme.default
178}
179
180extension EnvironmentValues {
181    /// Nonisolated so `ShapeStyle.resolve(in:)`, which is itself nonisolated,
182    /// can read it.
183    nonisolated var theme: Theme {
184        get { self[ThemeKey.self] }
185        set { self[ThemeKey.self] = newValue }
186    }
187}
188
189/// `listRowBackground` takes a view rather than a style, so a token cannot be
190/// handed to it directly — it has to be resolved first, which needs the
191/// environment. This is the one place in the app that reads the theme to get a
192/// `Color` rather than passing a token as a style.
193private struct ThemedListRowBackground: ViewModifier {
194    @Environment(\.theme) private var theme
195    let token: ThemeToken
196
197    func body(content: Content) -> some View {
198        content.listRowBackground(theme[token])
199    }
200}
201
202extension View {
203    func themedListRowBackground(_ token: ThemeToken) -> some View {
204        modifier(ThemedListRowBackground(token: token))
205    }
206}