krz/hutch
an ios client for sourcehut
clone: git clone https://gitbay.org/krz/hutch.git
v3.6.0: Shared/ContributionWidgetContext.swift · raw
1import Foundation
2#if canImport(WidgetKit)
3import WidgetKit
4#endif
5
6enum ContributionGraphWidgetConfiguration {
7 static let kind = "ContributionGraphWidget"
8}
9
10enum ContributionWidgetContextStore {
11 private static let actorKey = "contributionWidget.actor"
12 private static let enabledKey = "contributionWidget.enabled"
13
14 static func loadActor(
15 accountID: String? = ActiveAccountContextStore.load(),
16 defaults: UserDefaults? = sharedDefaults()
17 ) -> String? {
18 defaults?.string(forKey: scopedActorKey(for: accountID))
19 }
20
21 static func isEnabled(defaults: UserDefaults? = sharedDefaults()) -> Bool {
22 defaults?.object(forKey: enabledKey) == nil ? true : defaults?.bool(forKey: enabledKey) ?? true
23 }
24
25 static func setEnabled(_ enabled: Bool, defaults: UserDefaults? = sharedDefaults()) {
26 defaults?.set(enabled, forKey: enabledKey)
27 reloadWidgetTimelines()
28 }
29
30 static func saveActor(
31 _ actor: String,
32 accountID: String? = ActiveAccountContextStore.load(),
33 defaults: UserDefaults? = sharedDefaults()
34 ) {
35 defaults?.set(actor, forKey: scopedActorKey(for: accountID))
36 reloadWidgetTimelines()
37 }
38
39 static func clear(
40 accountID: String? = ActiveAccountContextStore.load(),
41 defaults: UserDefaults? = sharedDefaults()
42 ) {
43 defaults?.removeObject(forKey: scopedActorKey(for: accountID))
44 reloadWidgetTimelines()
45 }
46
47 private static func sharedDefaults() -> UserDefaults? {
48 UserDefaults(suiteName: HutchAppGroup.identifier)
49 }
50
51 private static func scopedActorKey(for accountID: String?) -> String {
52 guard let accountID, !accountID.isEmpty else { return actorKey }
53 return "\(actorKey).\(accountID)"
54 }
55
56 private static func reloadWidgetTimelines() {
57 #if canImport(WidgetKit)
58 WidgetCenter.shared.reloadTimelines(ofKind: ContributionGraphWidgetConfiguration.kind)
59 #endif
60 }
61}