Cotton code
161 lines · 7.3 KB · SwiftRaw
// The OS permission, and the one inline ask.//// **Registration never prompts.** The prompt is spent from exactly two places// — `/settings#notifications` (4h's screen) and one inline moment — and the// token path is not one of them. That separation is structural:// ``NotificationAuthority/read()`` cannot prompt and// ``NotificationAuthority/ask()`` is the only function that can.//// **The inline ask, and why there are two moments.** iOS grants exactly one// prompt per install. Cotton spends it the first time someone gives a todo an// HOUR — the only action in the app that has no point unless something says the// hour has come, so the question and the reason are the same gesture. Giving a// todo a DAY does not trigger it: a date is filing, and plenty of people// schedule days without ever wanting to be interrupted. Chat is the second// moment: the first message someone SENDS, because the reply is the whole// reason for a push and a person who installed Cotton to talk to somebody may// never give a todo an hour. Whichever comes first spends the prompt; the other// then finds `askedAt` set and stays quiet.import Foundation#if canImport(UIKit)import UIKit#endif/// Three states, because "not granted" hides the only distinction that matters:/// `undetermined` can still be asked, `denied` cannot and needs Settings.public enum NotificationPermission: String, Sendable, CaseIterable {    case granted    case denied    case undetermined}/// The OS, behind a seam.public protocol NotificationAuthority: Sendable {    /// What the OS currently thinks. NEVER prompts.    func read() async -> NotificationPermission    /// Ask. Only ever called from a moment the person can connect to the    /// question — the caller owns that judgement, this owns the prompt.    func ask() async -> NotificationPermission    /// Ask APNs for a token. Called only once the permission is `granted`,    /// never before and never as part of asking.    func registerForRemoteNotifications() async}/// Who wants to know when the answer changes.////// A `Set` kept for exactly this, and it exists for ONE named failure:/// *without it, whatever hands the push token to the server keeps its stale/// "undetermined" until the next foreground, and the first message someone sent/// earns no reply push until they backgrounded the app.*////// That is not hypothetical here. `/settings#notifications` is the one screen/// whose SUBJECT is the permission, and its Allow button reaches/// `NotificationAuthority.ask()` — while APNs registration, the token hand-off/// and the reminder pass all live behind `NotificationsModel.refresh()`, which/// otherwise runs only from `RootView`'s `.active` arm. Granting on that screen/// would schedule nothing until the app was backgrounded and brought back.////// It lives HERE, beside the authority that fires it, rather than beside the/// screen that made it necessary: the asker and the reader are in different/// lanes, and a broadcast whose publisher and subscriber are in different files/// only works if there is one of it.////// A `final class` with a lock rather than an actor, because a subscriber has/// to be told SYNCHRONOUSLY inside the ask that changed the answer, which is/// what makes "once per ask" assertable.public final class NotificationPermissionChanges: @unchecked Sendable {    /// The one every real reader shares, which is what makes a broadcast from    /// `SystemNotificationAuthority` reach a subscriber somewhere else.    public static let shared = NotificationPermissionChanges()    private let lock = NSLock()    private var listeners: [Int: @Sendable () -> Void] = [:]    private var nextId = 0    public init() {}    /// Subscribe, and get the unsubscribe back — the TypeScript's own shape,    /// which is what makes "stops telling a subscriber that unsubscribed"    /// expressible without a token type.    public func subscribe(_ listener: @escaping @Sendable () -> Void) -> @Sendable () -> Void {        lock.lock()        nextId += 1        let id = nextId        listeners[id] = listener        lock.unlock()        return { [weak self] in            guard let self else { return }            self.lock.lock()            self.listeners[id] = nil            self.lock.unlock()        }    }    /// Tell everyone. Called once per ask, whatever the answer — including a    /// refusal, because "they said no" is a change too.    public func notify() {        lock.lock()        let current = Array(listeners.values)        lock.unlock()        for listener in current { listener() }    }}/// The real one — over ``CapabilityAuthority``, which is the one place in this/// app that talks to `UNUserNotificationCenter` (and to every other permission/// API).////// **This type survives the move because it does something the authority does/// not**: it BROADCASTS. `NotificationPermissionChanges` is what tells the/// reminder pass and the token hand-off that the answer changed, and without/// that a permission granted on the settings screen schedules nothing until the/// app is backgrounded and brought back. So the ask goes through the authority/// and the broadcast stays here — three callers already reach this shape, and/// `NotificationAuthority` is the seam their tests fake.public struct SystemNotificationAuthority: NotificationAuthority {    private let capabilities: any CapabilityAuthority    public init(capabilities: any CapabilityAuthority = SystemCapabilityAuthority()) {        self.capabilities = capabilities    }    public func read() async -> NotificationPermission {        // A permission read must never be the thing that breaks a screen, so an        // unreadable state reads as "cannot schedule" and the settings block        // says so.        Self.permission(await capabilities.status(.notifications))    }    public func ask() async -> NotificationPermission {        // Broadcast ONCE per ask, whatever the answer, and from the one place        // every asker goes through — the settings screen's Allow button, the        // inline ask and the alarms screen all land here. A refusal is a change        // too: the reminder pass wipes on `denied` exactly as it schedules on        // `granted`.        defer { NotificationPermissionChanges.shared.notify() }        return Self.permission(await capabilities.ask(.notifications))    }    /// Three states from five, and the fold is deliberate: this screen's    /// question is only ever "can it be asked, or does it need Settings", and    /// `restricted` and `unavailable` answer that the same way `denied` does.    public static func permission(_ access: CapabilityAccess) -> NotificationPermission {        switch access {        case .authorized: return .granted        case .notDetermined: return .undetermined        case .denied, .restricted, .unavailable: return .denied        }    }    @MainActor    public func registerForRemoteNotifications() async {        #if canImport(UIKit)        UIApplication.shared.registerForRemoteNotifications()        #else        // The Mac never registers for remote notifications: it IS the server        // that would send them. `CottonKit` compiles for macOS since H2, and        // this authority is only ever constructed by the phone's app target.        #endif    }}