36 lines
1.3 KiB
Swift
36 lines
1.3 KiB
Swift
import Foundation
|
|
import Observation
|
|
|
|
@MainActor @Observable final class MenuBarPreferences {
|
|
private static let key = "menuBar.metrics"
|
|
@ObservationIgnored private let defaults: UserDefaults
|
|
@ObservationIgnored var onDemandChange: ((Bool) -> Void)?
|
|
private(set) var selected: Set<MenuBarMetric>
|
|
|
|
var allSelected: Bool { selected.count == MenuBarMetric.allCases.count }
|
|
|
|
init(defaults: UserDefaults = .standard) {
|
|
self.defaults = defaults
|
|
selected = defaults.stringArray(forKey: Self.key).map { Set($0.compactMap(MenuBarMetric.init(rawValue:))) }
|
|
?? Set(MenuBarMetric.allCases)
|
|
}
|
|
|
|
func set(_ metric: MenuBarMetric, enabled: Bool) {
|
|
var next = selected
|
|
if enabled { next.insert(metric) } else { next.remove(metric) }
|
|
replaceSelection(with: next)
|
|
}
|
|
|
|
func setAllSelected(_ enabled: Bool) {
|
|
replaceSelection(with: enabled ? Set(MenuBarMetric.allCases) : [])
|
|
}
|
|
|
|
private func replaceSelection(with next: Set<MenuBarMetric>) {
|
|
guard selected != next else { return }
|
|
let wasEmpty = selected.isEmpty
|
|
selected = next
|
|
defaults.set(MenuBarMetric.allCases.filter(selected.contains).map(\.rawValue), forKey: Self.key)
|
|
if wasEmpty != selected.isEmpty { onDemandChange?(!selected.isEmpty) }
|
|
}
|
|
}
|