SnoozeStateModel.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import Observation
  2. import SwiftUI
  3. extension Snooze {
  4. @Observable final class StateModel: BaseStateModel<Provider> {
  5. @ObservationIgnored @Persisted(key: "UserNotificationsManager.snoozeUntilDate") var snoozeUntilDate: Date = .distantPast
  6. @ObservationIgnored @Injected() var glucoseStorage: GlucoseStorage!
  7. @ObservationIgnored @Injected() var notificationsManager: UserNotificationsManager!
  8. @ObservationIgnored @Injected() var broadcaster: Broadcaster!
  9. var alarm: GlucoseAlarm?
  10. override func subscribe() {
  11. alarm = glucoseStorage.alarm
  12. broadcaster.register(SnoozeObserver.self, observer: self)
  13. }
  14. func unsubscribe() {
  15. broadcaster.unregister(SnoozeObserver.self, observer: self)
  16. }
  17. // Add validation helper inside the class
  18. private func validateSnoozeDuration(_ duration: TimeInterval) -> Bool {
  19. // Only allow durations matching our defined actions
  20. NotificationResponseAction.allCases
  21. .map(\.duration)
  22. .contains(duration)
  23. }
  24. @MainActor func applySnooze(_ duration: TimeInterval) async {
  25. // Allow any duration chosen in the Snooze UI, while keeping validation for quick actions elsewhere.
  26. snoozeUntilDate = duration > 0 ? Date().addingTimeInterval(duration) : .distantPast
  27. alarm = glucoseStorage.alarm
  28. await notificationsManager.applySnooze(for: duration)
  29. }
  30. }
  31. }
  32. extension Snooze.StateModel: SnoozeObserver {
  33. func snoozeDidChange(_ untilDate: Date) {
  34. snoozeUntilDate = untilDate
  35. alarm = glucoseStorage.alarm
  36. }
  37. }