Jotley / app · jotley.ai / Shared / Styling / SharedThemeColors.swift
| 1 | import Combine |
| 2 | import SwiftUI |
| 3 | |
| 4 | // Environment key for theme refresh |
| 5 | struct ThemeRefreshKey: EnvironmentKey { |
| 6 | static let defaultValue = UUID() |
| 7 | } |
| 8 | |
| 9 | extension EnvironmentValues { |
| 10 | var themeRefresh: UUID { |
| 11 | get { self[ThemeRefreshKey.self] } |
| 12 | set { self[ThemeRefreshKey.self] = newValue } |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | extension ThemeColor { |
| 17 | var color: Color { |
| 18 | color(in: Color.shouldUseDarkTheme() ? .dark : .light) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | // Appearance mode enum for light/dark/system theme selection |
| 23 | enum AppearanceMode: String, CaseIterable, Codable { |
| 24 | case light = "Light" |
| 25 | case dark = "Dark" |
| 26 | case system = "System" |
| 27 | |
| 28 | var displayName: String { |
| 29 | return self.rawValue |
| 30 | } |
| 31 | |
| 32 | var colorScheme: ColorScheme? { |
| 33 | switch self { |
| 34 | case .light: |
| 35 | return .light |
| 36 | case .dark: |
| 37 | return .dark |
| 38 | case .system: |
| 39 | return nil // nil means follow system |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | // Notification posted when theme changes |
| 45 | extension Notification.Name { |
| 46 | static let themeDidChange = Notification.Name("themeDidChange") |
| 47 | } |
| 48 | |
| 49 | // Theme manager for handling theme color and appearance mode selection |
| 50 | class ThemeManager: ObservableObject { |
| 51 | static let shared = ThemeManager() |
| 52 | |
| 53 | @AppStorage("selectedThemeColor") private var storedThemeColor: String = ThemeColor.purple.rawValue |
| 54 | @AppStorage("selectedAppearanceMode") private var storedAppearanceMode: String = AppearanceMode.system.rawValue |
| 55 | |
| 56 | @Published var currentThemeColor: ThemeColor { |
| 57 | didSet { |
| 58 | if storedThemeColor != currentThemeColor.rawValue { |
| 59 | storedThemeColor = currentThemeColor.rawValue |
| 60 | } |
| 61 | Color.invalidateDarkThemeCache() |
| 62 | objectWillChange.send() |
| 63 | NotificationCenter.default.post(name: .themeDidChange, object: nil) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | @Published var currentAppearanceMode: AppearanceMode { |
| 68 | didSet { |
| 69 | if storedAppearanceMode != currentAppearanceMode.rawValue { |
| 70 | storedAppearanceMode = currentAppearanceMode.rawValue |
| 71 | } |
| 72 | // Force all color values to be re-evaluated |
| 73 | Color.invalidateDarkThemeCache() |
| 74 | objectWillChange.send() |
| 75 | NotificationCenter.default.post(name: .themeDidChange, object: nil) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | var effectiveColorScheme: ColorScheme? { |
| 80 | currentAppearanceMode.colorScheme |
| 81 | } |
| 82 | |
| 83 | private init() { |
| 84 | // Initialize theme color with stored value or default |
| 85 | let storedThemeColorValue = UserDefaults.standard.string(forKey: "selectedThemeColor") ?? ThemeColor.purple.rawValue |
| 86 | self.currentThemeColor = ThemeColor(rawValue: storedThemeColorValue) ?? .purple |
| 87 | |
| 88 | // Initialize appearance mode with stored value or default |
| 89 | let storedAppearanceModeValue = UserDefaults.standard.string(forKey: "selectedAppearanceMode") ?? AppearanceMode.system.rawValue |
| 90 | self.currentAppearanceMode = AppearanceMode(rawValue: storedAppearanceModeValue) ?? .system |
| 91 | } |
| 92 | |
| 93 | func setThemeColor(_ color: ThemeColor) { |
| 94 | currentThemeColor = color |
| 95 | } |
| 96 | |
| 97 | func setAppearanceMode(_ mode: AppearanceMode) { |
| 98 | currentAppearanceMode = mode |
| 99 | } |
| 100 | |
| 101 | /// Called by app delegates when system appearance changes |
| 102 | func notifySystemAppearanceChanged() { |
| 103 | guard currentAppearanceMode == .system else { |
| 104 | print("🎨 System appearance changed but app is using manual mode (\(currentAppearanceMode.rawValue))") |
| 105 | return |
| 106 | } |
| 107 | print("🎨 System appearance changed, notifying observers") |
| 108 | Color.invalidateDarkThemeCache() |
| 109 | objectWillChange.send() |
| 110 | NotificationCenter.default.post(name: .themeDidChange, object: nil) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | extension Color { |
| 115 | // Dark theme colors (based on common dark themes like Obsidian) |
| 116 | static let themeDarkBackground = Color(red: 0.12, green: 0.12, blue: 0.12) // Approx #1F1F1F |
| 117 | static let themeDarkContentBackground = Color(red: 0.15, green: 0.15, blue: 0.15) // Approx #262626 |
| 118 | static let themeDarkTextPrimary = Color(red: 0.85, green: 0.85, blue: 0.85) // Approx #D9D9D9 |
| 119 | static let themeDarkTextSecondary = Color(red: 0.6, green: 0.6, blue: 0.6) // Approx #999999 |
| 120 | static let themeDarkAccent = Color(red: 0.4, green: 0.4, blue: 0.45) // A slightly bluish gray for accents/borders |
| 121 | |
| 122 | // Light theme colors |
| 123 | static let themeLightBackground = Color(red: 0.98, green: 0.98, blue: 0.98) // Approx #FAFAFA |
| 124 | static let themeLightContentBackground = Color(red: 0.96, green: 0.96, blue: 0.96) // Approx #F5F5F5 |
| 125 | static let themeLightTextPrimary = Color(red: 0.1, green: 0.1, blue: 0.1) // Approx #1A1A1A |
| 126 | static let themeLightTextSecondary = Color(red: 0.4, green: 0.4, blue: 0.4) // Approx #666666 |
| 127 | static let themeLightAccent = Color(red: 0.88, green: 0.88, blue: 0.88) // Approx #E0E0E0 |
| 128 | |
| 129 | // Dynamic theme colors - adapt based on selected appearance mode |
| 130 | static var themeBackground: Color { |
| 131 | let isDark = shouldUseDarkTheme() |
| 132 | return isDark ? themeDarkBackground : themeLightBackground |
| 133 | } |
| 134 | |
| 135 | static var themeContentBackground: Color { |
| 136 | let isDark = shouldUseDarkTheme() |
| 137 | return isDark ? themeDarkContentBackground : themeLightContentBackground |
| 138 | } |
| 139 | |
| 140 | static var themeTextPrimary: Color { |
| 141 | let isDark = shouldUseDarkTheme() |
| 142 | return isDark ? themeDarkTextPrimary : themeLightTextPrimary |
| 143 | } |
| 144 | |
| 145 | static var themeTextSecondary: Color { |
| 146 | let isDark = shouldUseDarkTheme() |
| 147 | return isDark ? themeDarkTextSecondary : themeLightTextSecondary |
| 148 | } |
| 149 | |
| 150 | static var themeAccent: Color { |
| 151 | let isDark = shouldUseDarkTheme() |
| 152 | return isDark ? themeDarkAccent : themeLightAccent |
| 153 | } |
| 154 | |
| 155 | static var themeSelectionBackground: Color { |
| 156 | shouldUseDarkTheme() ? Color(white: 0.20) : Color(white: 0.91) |
| 157 | } |
| 158 | |
| 159 | // Cache for shouldUseDarkTheme()'s appearance computation. SwiftUI body |
| 160 | // re-evaluations hit each theme color getter constantly (the playback |
| 161 | // waveform resolves them on every 10 Hz progress tick; the live recording |
| 162 | // waveform on every frame), so the resolution must never do real work in |
| 163 | // steady state. |
| 164 | // |
| 165 | // Invalidation is EVENT-DRIVEN, not TTL-based: ThemeManager bumps the |
| 166 | // generation whenever the theme/appearance changes (manual mode switches |
| 167 | // and the system-appearance hooks in SceneDelegate / JotleyAppDelegate, |
| 168 | // which call notifySystemAppearanceChanged on trait changes). A previous |
| 169 | // version used a 1 s TTL — that recomputed mid-frame exactly once per |
| 170 | // second, which is precisely the rhythm of the reported 1 Hz waveform |
| 171 | // hitch. The long TTL below is only a safety net for any appearance-change |
| 172 | // path that misses the delegate hooks. |
| 173 | private nonisolated(unsafe) static var cachedDarkTheme: (mode: AppearanceMode, generation: UInt64, isDark: Bool, expiresAt: TimeInterval)? |
| 174 | private nonisolated(unsafe) static var darkThemeCacheGeneration: UInt64 = 0 |
| 175 | private static let darkThemeCacheLock = NSLock() |
| 176 | private static let darkThemeCacheTTL: TimeInterval = 300.0 |
| 177 | |
| 178 | /// Called by ThemeManager whenever the theme color, appearance mode, or |
| 179 | /// system appearance changes. The next theme color resolution recomputes. |
| 180 | static func invalidateDarkThemeCache() { |
| 181 | darkThemeCacheLock.lock() |
| 182 | darkThemeCacheGeneration &+= 1 |
| 183 | darkThemeCacheLock.unlock() |
| 184 | } |
| 185 | |
| 186 | // Helper function to determine if dark theme should be used |
| 187 | static func shouldUseDarkTheme() -> Bool { |
| 188 | let appearanceMode = ThemeManager.shared.currentAppearanceMode |
| 189 | let now = ProcessInfo.processInfo.systemUptime |
| 190 | darkThemeCacheLock.lock() |
| 191 | let generation = darkThemeCacheGeneration |
| 192 | if let cached = cachedDarkTheme, |
| 193 | cached.mode == appearanceMode, |
| 194 | cached.generation == generation, |
| 195 | cached.expiresAt > now { |
| 196 | darkThemeCacheLock.unlock() |
| 197 | return cached.isDark |
| 198 | } |
| 199 | darkThemeCacheLock.unlock() |
| 200 | |
| 201 | let result = computeShouldUseDarkTheme(appearanceMode: appearanceMode) |
| 202 | darkThemeCacheLock.lock() |
| 203 | cachedDarkTheme = (appearanceMode, generation, result, now + darkThemeCacheTTL) |
| 204 | darkThemeCacheLock.unlock() |
| 205 | return result |
| 206 | } |
| 207 | |
| 208 | private static func computeShouldUseDarkTheme(appearanceMode: AppearanceMode) -> Bool { |
| 209 | switch appearanceMode { |
| 210 | case .light: |
| 211 | return false |
| 212 | case .dark: |
| 213 | return true |
| 214 | case .system: |
| 215 | // Check system appearance |
| 216 | #if os(macOS) |
| 217 | if #available(macOS 10.14, *) { |
| 218 | return NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua |
| 219 | } |
| 220 | return true |
| 221 | #else |
| 222 | // SwiftUI reports the active view's appearance. There is no single |
| 223 | // main screen on a two-display iPhone, and polling scenes here also |
| 224 | // stalls frequent waveform updates. |
| 225 | darkThemeCacheLock.lock() |
| 226 | let isDark = observedSystemIsDark |
| 227 | darkThemeCacheLock.unlock() |
| 228 | return isDark |
| 229 | #endif |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | private static var observedSystemIsDark = false |
| 234 | static func recordSystemColorScheme(_ scheme: ColorScheme) { |
| 235 | darkThemeCacheLock.lock() |
| 236 | observedSystemIsDark = scheme == .dark |
| 237 | cachedDarkTheme = nil |
| 238 | darkThemeCacheGeneration &+= 1 |
| 239 | darkThemeCacheLock.unlock() |
| 240 | } |
| 241 | |
| 242 | // Dynamic theme primary accent color |
| 243 | static var themePrimaryAccent: Color { |
| 244 | ThemeManager.shared.currentThemeColor.color |
| 245 | } |
| 246 | |
| 247 | /// Contrast for labels drawn directly on a solid accent fill. |
| 248 | static var themeTextOnAccent: Color { |
| 249 | ThemeManager.shared.currentThemeColor.textOnAccent(in: shouldUseDarkTheme() ? .dark : .light) |
| 250 | } |
| 251 | |
| 252 | /// Neutral foreground for action text in either appearance. |
| 253 | static var themeActionText: Color { |
| 254 | .primary |
| 255 | } |
| 256 | |
| 257 | // iOS specific colors that adapt to light/dark mode |
| 258 | } |
| 259 | |
| 260 | // View modifier to ensure theme changes are observed |
| 261 | struct ThemeObserver: ViewModifier { |
| 262 | @ObservedObject private var themeManager = ThemeManager.shared |
| 263 | @State private var refreshToken = UUID() |
| 264 | @Environment(\.colorScheme) private var colorScheme |
| 265 | |
| 266 | func body(content: Content) -> some View { |
| 267 | content |
| 268 | // Trigger view recomputation without resetting identity so presented sheets stay mounted. |
| 269 | .environment(\.themeRefresh, refreshToken) |
| 270 | .onReceive(NotificationCenter.default.publisher(for: .themeDidChange)) { _ in |
| 271 | refreshToken = UUID() |
| 272 | } |
| 273 | .onChange(of: colorScheme, initial: true) { _, scheme in |
| 274 | Color.recordSystemColorScheme(scheme) |
| 275 | // System appearance can change without a manual preference change. |
| 276 | themeManager.notifySystemAppearanceChanged() |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | extension View { |
| 282 | func jotleyNoteSelection(_ selected: Bool, unselectedBackground: Color) -> some View { |
| 283 | let outline = RoundedRectangle(cornerRadius: 8) |
| 284 | return background(selected ? Color.themeSelectionBackground : unselectedBackground, in: outline) |
| 285 | .overlay(alignment: .leading) { |
| 286 | if selected { |
| 287 | Capsule().fill(Color.themePrimaryAccent) |
| 288 | .frame(width: 3, height: 20) |
| 289 | .padding(.leading, 3) |
| 290 | .allowsHitTesting(false) |
| 291 | .accessibilityHidden(true) |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | func observeThemeChanges() -> some View { |
| 297 | modifier(ThemeObserver()) |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | extension View { |
| 302 | /// Use the same label and glass surface for Done and Cancel across platforms. |
| 303 | func jotleyDismissButtonStyle(expandsHorizontally: Bool = false, inToolbar: Bool = false) -> some View { |
| 304 | font(.subheadline.weight(.semibold)) |
| 305 | .buttonStyle(JotleyGlassButtonStyle(diameter: inToolbar ? 32 : nil, floatsOverContent: true)) |
| 306 | .fixedSize(horizontal: !expandsHorizontally, vertical: false) |
| 307 | .frame(minHeight: inToolbar ? 44 : nil) |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | struct JotleyNoteFooterTextStyle: ViewModifier { |
| 312 | @Environment(\.isEnabled) private var isEnabled |
| 313 | |
| 314 | func body(content: Content) -> some View { |
| 315 | content.foregroundStyle(Color.primary.opacity(isEnabled ? 1 : 0.55)) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | extension View { |
| 320 | func noteMetadataPill(font: Font = .system(size: 11, weight: .medium), minHeight: CGFloat = 22) -> some View { |
| 321 | self |
| 322 | .font(font) |
| 323 | .padding(.horizontal, 8) |
| 324 | .frame(minHeight: minHeight) |
| 325 | .background { Capsule().strokeBorder(Color.gray.opacity(0.5), lineWidth: 1) } |
| 326 | .contentShape(Capsule()) |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | /// Keep action text neutral while the symbol follows the current theme. |
| 331 | struct JotleyAccentIconLabel: View { |
| 332 | @ObservedObject private var theme = ThemeManager.shared |
| 333 | @Environment(\.colorScheme) private var colorScheme |
| 334 | let title: LocalizedStringKey |
| 335 | let systemImage: String |
| 336 | |
| 337 | var body: some View { |
| 338 | Label { |
| 339 | Text(title).foregroundStyle(Color.primary) |
| 340 | } icon: { |
| 341 | Image(systemName: systemImage) |
| 342 | .foregroundStyle(theme.currentThemeColor.color(in: colorScheme)) |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | struct JotleyNoteTagStyle: ViewModifier { |
| 348 | @ObservedObject private var theme = ThemeManager.shared |
| 349 | @Environment(\.colorScheme) private var colorScheme |
| 350 | var horizontalPadding: CGFloat = 10 |
| 351 | var verticalPadding: CGFloat = 6 |
| 352 | |
| 353 | func body(content: Content) -> some View { |
| 354 | let accent = theme.currentThemeColor.color(in: colorScheme) |
| 355 | return content |
| 356 | .foregroundStyle(Color.primary) |
| 357 | .padding(.horizontal, horizontalPadding) |
| 358 | .padding(.vertical, verticalPadding) |
| 359 | .overlay { |
| 360 | Capsule().strokeBorder(accent, lineWidth: 1) |
| 361 | .allowsHitTesting(false) |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | #if os(iOS) |
| 367 | /// Match compact action icons to the selected accent. |
| 368 | struct MobileActionLabel: View { |
| 369 | let title: LocalizedStringKey |
| 370 | let systemImage: String |
| 371 | |
| 372 | init(_ title: LocalizedStringKey, systemImage: String) { |
| 373 | self.title = title |
| 374 | self.systemImage = systemImage |
| 375 | } |
| 376 | |
| 377 | var body: some View { |
| 378 | JotleyAccentIconLabel(title: title, systemImage: systemImage) |
| 379 | } |
| 380 | } |
| 381 | #endif |
| 382 | |
| 383 | |
| 384 | /// Neutral editing surface with a visible boundary and an accent focus ring. |
| 385 | struct JotleyEditorField: ViewModifier { |
| 386 | @Environment(\.colorScheme) private var colorScheme |
| 387 | @ObservedObject private var theme = ThemeManager.shared |
| 388 | var isFocused = false |
| 389 | |
| 390 | func body(content: Content) -> some View { |
| 391 | let outline = RoundedRectangle(cornerRadius: 10) |
| 392 | let scheme = theme.effectiveColorScheme ?? colorScheme |
| 393 | let accent = theme.currentThemeColor.color(in: scheme) |
| 394 | content |
| 395 | .foregroundStyle(Color.themeTextPrimary) |
| 396 | .tint(accent) |
| 397 | .background(scheme == .dark ? Color.themeDarkContentBackground : .white, in: outline) |
| 398 | .overlay { |
| 399 | outline.strokeBorder(isFocused ? accent : Color.themeTextSecondary.opacity(0.34), |
| 400 | lineWidth: isFocused ? 2 : 1) |
| 401 | .allowsHitTesting(false) |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | /// Use an app-colored outline instead of the platform's fixed focus-ring color. |
| 407 | struct JotleyFormInputStyle: ViewModifier { |
| 408 | @FocusState private var focused: Bool |
| 409 | @ObservedObject private var themeManager = ThemeManager.shared |
| 410 | func body(content: Content) -> some View { |
| 411 | content.textFieldStyle(.plain) |
| 412 | .foregroundStyle(Color.themeTextPrimary) |
| 413 | .tint(themeManager.currentThemeColor.color) |
| 414 | .accentColor(themeManager.currentThemeColor.color) |
| 415 | .padding(8) |
| 416 | .background(Color.themeBackground, in: RoundedRectangle(cornerRadius: 8)) |
| 417 | .overlay { |
| 418 | RoundedRectangle(cornerRadius: 8) |
| 419 | .strokeBorder(focused ? themeManager.currentThemeColor.color : Color.themeTextSecondary.opacity(0.25), lineWidth: focused ? 2 : 1) |
| 420 | .allowsHitTesting(false) |
| 421 | } |
| 422 | .focused($focused) |
| 423 | } |
| 424 | } |