Sources/OrgApp/TimerModel.swift

44 lines · 1897 bytes

 1import Foundation
 2import Observation
 3import OrgCore
 4@preconcurrency import UserNotifications
 5
 6/// The app's org-timer, which commands get in `EditingOptions.timer` and change through
 7/// `Effect.timer`. A countdown ends with a notification and `onDone`.
 8@MainActor @Observable
 9public final class TimerModel {
10    public static let shared = TimerModel()
11
12    public private(set) var timer: OrgTimer?
13    /// The countdown's message when it ends, for the echo area.
14    @ObservationIgnored public var onDone: ((String) -> Void)?
15    @ObservationIgnored private var countdown: Task<Void, Never>?
16    static let notification = "sh.krz.orgstar.org-timer"
17
18    public init() {}
19
20    public func set(_ new: OrgTimer?) {
21        timer = new
22        countdown?.cancel()
23        countdown = nil
24        let center = UNUserNotificationCenter.current()
25        center.removePendingNotificationRequests(withIdentifiers: [Self.notification])
26        guard let new, new.isCountdown, new.paused == nil else { return }
27        let left = max(0, new.start.timeIntervalSinceNow)
28        countdown = Task { [weak self] in
29            try? await Task.sleep(for: .seconds(left))
30            guard !Task.isCancelled, let self, self.timer == new else { return }
31            self.timer = nil
32            self.onDone?(new.doneMessage)
33        }
34        // The notification shows when orgstar isn't in front, as `org-notify` does.
35        let content = UNMutableNotificationContent()
36        content.title = new.doneMessage
37        content.sound = .default
38        center.requestAuthorization(options: [.alert, .sound]) { granted, _ in
39            guard granted else { return }
40            center.add(UNNotificationRequest(identifier: Self.notification, content: content,
41                                             trigger: UNTimeIntervalNotificationTrigger(timeInterval: max(1, left), repeats: false)))
42        }
43    }
44}