36 lines
1.3 KiB
Swift
36 lines
1.3 KiB
Swift
import Foundation
|
|
import HelderCore
|
|
|
|
public protocol SessionStoring: Sendable {
|
|
func loadSession(root: String) -> SessionState?
|
|
func saveSession(_ session: SessionState, root: String)
|
|
func loadLayout() -> LayoutState
|
|
func saveLayout(_ layout: LayoutState)
|
|
}
|
|
|
|
/// Never throws: storage that cannot be read gives the defaults, one that cannot be written is skipped.
|
|
public struct SessionStore: SessionStoring, @unchecked Sendable {
|
|
private let defaults: UserDefaults
|
|
|
|
public init(defaults: UserDefaults = .standard) {
|
|
self.defaults = defaults
|
|
}
|
|
|
|
public func loadSession(root: String) -> SessionState? {
|
|
defaults.data(forKey: SessionState.key(root: root)).flatMap { try? JSONDecoder().decode(SessionState.self, from: $0) }
|
|
}
|
|
|
|
public func saveSession(_ session: SessionState, root: String) {
|
|
if let data = try? JSONEncoder().encode(session) { defaults.set(data, forKey: SessionState.key(root: root)) }
|
|
}
|
|
|
|
public func loadLayout() -> LayoutState {
|
|
guard defaults.object(forKey: LayoutState.key) != nil else { return LayoutState() }
|
|
return LayoutState(agentFraction: defaults.double(forKey: LayoutState.key))
|
|
}
|
|
|
|
public func saveLayout(_ layout: LayoutState) {
|
|
defaults.set(layout.agentFraction, forKey: LayoutState.key)
|
|
}
|
|
}
|