55 lines
1.5 KiB
Swift
55 lines
1.5 KiB
Swift
import SwiftUI
|
|
|
|
// Enum to represent the three theme options
|
|
enum Theme: String, CaseIterable {
|
|
case system = "System"
|
|
case light = "Light"
|
|
case oledDark = "Oled"
|
|
// case dark = "Dark" // TODO
|
|
|
|
var colorScheme: ColorScheme? {
|
|
switch self {
|
|
case .system:
|
|
return nil
|
|
case .light:
|
|
return .light
|
|
case .oledDark:
|
|
return .dark
|
|
}
|
|
}
|
|
}
|
|
|
|
// Observable class to manage the theme state
|
|
class ThemeManager: ObservableObject {
|
|
@AppStorage("selectedTheme") private var selectedThemeValue: String = Theme.system.rawValue
|
|
|
|
@Published var theme: Theme
|
|
|
|
init() {
|
|
// Read directly from UserDefaults to avoid using self before initialization is complete.
|
|
let storedThemeValue = UserDefaults.standard.string(forKey: "selectedTheme") ?? ""
|
|
self.theme = Theme(rawValue: storedThemeValue) ?? .system
|
|
}
|
|
|
|
func setTheme(_ theme: Theme) {
|
|
self.theme = theme
|
|
selectedThemeValue = theme.rawValue
|
|
}
|
|
|
|
// This will be called from the button
|
|
func toggleTheme(from currentSystemScheme: ColorScheme) {
|
|
let newTheme: Theme
|
|
|
|
switch theme {
|
|
case .system:
|
|
// If system is active, toggle to the opposite of the current system theme
|
|
newTheme = currentSystemScheme == .dark ? .light : .oledDark
|
|
case .light:
|
|
newTheme = .oledDark
|
|
case .oledDark:
|
|
newTheme = .light
|
|
}
|
|
setTheme(newTheme)
|
|
}
|
|
}
|