SPB Git

Repository Public MIT

GlassToastCenter.swift 9.1 KB 246 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Feedback/GlassToastCenter.swift8// Module           : SPGlassComponents9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import Accessibility43import SPGlassCore44import SPGlassTokens45import SPGlassThemes46import SPGlassEffects4748/// The optional button of a ``GlassToast`` (for example "Undo").49public struct GlassToastAction: Sendable {50    /// Title of the button, already localised by the host.51    public let title: String52    /// Called when the button is activated; the toast is then dismissed.53    public let handler: @MainActor @Sendable () -> Void5455    public init(_ title: String, handler: @escaping @MainActor @Sendable () -> Void) {56        self.title = title57        self.handler = handler58    }59}6061/// A short, transient message.62///63/// A toast disappears by itself, so it must never be the only carrier of critical information: errors that64/// need a decision belong in a ``GlassAlert`` or a ``GlassBanner``.65public struct GlassToast: Identifiable, Sendable {66    /// Shortest time a toast stays on screen. Shorter durations are raised to this value.67    public static let minimumDuration: Duration = .seconds(2)68    /// Default time on screen: four seconds, or six when the toast carries an action.69    public static func defaultDuration(hasAction: Bool) -> Duration {70        hasAction ? .seconds(6) : .seconds(4)71    }7273    /// Identity of the toast. Showing a toast whose `id` is already on screen replaces that toast.74    public let id: String75    /// The message, already localised by the host.76    public let message: String77    /// Optional short title shown above the message.78    public let title: String?79    /// Optional SF Symbol shown before the text. Decorative: the text carries the meaning.80    public let systemImage: String?81    /// Time on screen. `nil` keeps the toast until it is dismissed.82    public let duration: Duration?83    /// Optional action button.84    public let action: GlassToastAction?8586    /// Creates a toast.87    ///88    /// - Parameters:89    ///   - id: pass a stable identifier ("saved", "offline") to replace a toast instead of stacking duplicates.90    ///   - duration: time on screen, at least ``minimumDuration``. Defaults to ``defaultDuration(hasAction:)``.91    public init(92        _ message: String,93        title: String? = nil,94        systemImage: String? = nil,95        id: String = UUID().uuidString,96        duration: Duration? = nil,97        action: GlassToastAction? = nil98    ) {99        self.id = id100        self.message = message101        self.title = title102        self.systemImage = systemImage103        self.duration = Self.effectiveDuration(duration ?? Self.defaultDuration(hasAction: action != nil))104        self.action = action105    }106107    private init(persistent message: String, title: String?, systemImage: String?, id: String, action: GlassToastAction?) {108        self.id = id109        self.message = message110        self.title = title111        self.systemImage = systemImage112        self.duration = nil113        self.action = action114    }115116    /// A toast that stays until the user or the host dismisses it.117    public static func persistent(118        _ message: String,119        title: String? = nil,120        systemImage: String? = nil,121        id: String = UUID().uuidString,122        action: GlassToastAction? = nil123    ) -> GlassToast {124        GlassToast(persistent: message, title: title, systemImage: systemImage, id: id, action: action)125    }126127    /// A requested duration raised to ``minimumDuration``.128    public static func effectiveDuration(_ requested: Duration) -> Duration {129        max(requested, minimumDuration)130    }131132    /// What VoiceOver announces when the toast appears: the title, then the message.133    public var announcement: String {134        [title, message].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", ")135    }136}137138/// The queue of toasts shown by ``SwiftUICore/View/glassToastHost(_:placement:)``.139///140/// ```swift141/// @State private var toasts = GlassToastCenter()142/// …143/// content.glassToastHost(toasts)144/// …145/// toasts.show(GlassToast("Draft saved", systemImage: "checkmark.circle"))146/// ```147///148/// The centre keeps at most `capacity` toasts. When a new toast arrives while it is full, the **oldest toast149/// is dropped**: the most recent event is the one the user needs to see. A toast whose `id` is already present150/// replaces the existing one in place and restarts its timer. Each toast is dismissed by its own cancellable151/// task; nothing is persisted.152@MainActor153@Observable154public final class GlassToastCenter {155    /// The toasts on screen, oldest first.156    public private(set) var toasts: [GlassToast] = []157    /// Largest number of toasts kept at once.158    public let capacity: Int159160    @ObservationIgnored private var timers: [String: Task<Void, Never>] = [:]161    @ObservationIgnored private let sleep: @Sendable (Duration) async throws -> Void162    @ObservationIgnored private let announce: @MainActor @Sendable (String) -> Void163164    /// Creates a centre.165    ///166    /// - Parameters:167    ///   - capacity: largest number of simultaneous toasts, at least 1.168    ///   - sleep: waits for a duration; injectable so that tests control time.169    ///   - announce: posts the accessibility announcement of a new toast.170    public init(171        capacity: Int = 3,172        sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) },173        announce: @escaping @MainActor @Sendable (String) -> Void = { AccessibilityNotification.Announcement($0).post() }174    ) {175        self.capacity = max(1, capacity)176        self.sleep = sleep177        self.announce = announce178    }179180    /// Shows a toast, announces it and schedules its dismissal.181    @discardableResult182    public func show(_ toast: GlassToast) -> GlassToast.ID {183        cancelTimer(toast.id)184        if let index = toasts.firstIndex(where: { $0.id == toast.id }) {185            toasts[index] = toast186        } else {187            toasts.append(toast)188            while toasts.count > capacity {189                let dropped = toasts.removeFirst()190                cancelTimer(dropped.id)191            }192        }193        announce(toast.announcement)194        if let duration = toast.duration {195            let id = toast.id196            let sleep = sleep197            timers[id] = Task { [weak self] in198                do { try await sleep(duration) } catch { return }199                guard !Task.isCancelled else { return }200                self?.expire(id)201            }202        }203        return toast.id204    }205206    /// Shows a plain message.207    @discardableResult208    public func show(_ message: String, systemImage: String? = nil) -> GlassToast.ID {209        show(GlassToast(message, systemImage: systemImage))210    }211212    /// Removes a toast and cancels its timer. Unknown identifiers are ignored.213    public func dismiss(_ id: GlassToast.ID) {214        cancelTimer(id)215        toasts.removeAll { $0.id == id }216    }217218    /// Removes every toast and cancels every timer.219    public func dismissAll() {220        for task in timers.values { task.cancel() }221        timers.removeAll()222        toasts.removeAll()223    }224225    /// Runs the action of a toast, then dismisses it.226    public func performAction(of id: GlassToast.ID) {227        guard let toast = toasts.first(where: { $0.id == id }) else { return }228        dismiss(id)229        toast.action?.handler()230    }231232    /// Waits until every running timer has finished. Used by tests after they let time pass.233    func waitForTimers() async {234        for task in Array(timers.values) { await task.value }235    }236237    private func expire(_ id: String) {238        timers[id] = nil239        toasts.removeAll { $0.id == id }240    }241242    private func cancelTimer(_ id: String) {243        timers.removeValue(forKey: id)?.cancel()244    }245}246
Files main
Menu

Theme