// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassComponents/Feedback/GlassToastCenter.swift // Module : SPGlassComponents // Repository : https://git.spboucher.ai/sp-glasskit // Project Website : https://glass.spboucher.ai // Created : 2026-12-02 // Last Modified : 2026-12-02 // // Author : Simon-Pierre Boucher // Position : Professor of Finance // Institution : Université du Québec en Outaouais (UQO) // Organization : SP Boucher // Website : https://spboucher.ai // Git : https://git.spboucher.ai // // Preferred Contact: contact@spboucher.ai // Development : dev@spboucher.ai // Support : support@spboucher.ai // Security/Admin : admin@spboucher.ai // // Copyright (c) 2026 // Simon-Pierre Boucher // All rights reserved where applicable. This file is governed by the // applicable project license, copyright notices and relevant law. // Existing third-party rights and notices remain unaffected. // // License : MIT // // Do not embed credentials, private keys, access tokens, // certificates or confidential personal information. // // ============================================================================= // END OF SP BOUCHER SOURCE HEADER // ============================================================================= import SwiftUI import Accessibility /// The optional button of a ``GlassToast`` (for example "Undo"). public struct GlassToastAction: Sendable { /// Title of the button, already localised by the host. public let title: String /// Called when the button is activated; the toast is then dismissed. public let handler: @MainActor @Sendable () -> Void public init(_ title: String, handler: @escaping @MainActor @Sendable () -> Void) { self.title = title self.handler = handler } } /// A short, transient message. /// /// A toast disappears by itself, so it must never be the only carrier of critical information: errors that /// need a decision belong in a ``GlassAlert`` or a ``GlassBanner``. public struct GlassToast: Identifiable, Sendable { /// Shortest time a toast stays on screen. Shorter durations are raised to this value. public static let minimumDuration: Duration = .seconds(2) /// Default time on screen: four seconds, or six when the toast carries an action. public static func defaultDuration(hasAction: Bool) -> Duration { hasAction ? .seconds(6) : .seconds(4) } /// Identity of the toast. Showing a toast whose `id` is already on screen replaces that toast. public let id: String /// The message, already localised by the host. public let message: String /// Optional short title shown above the message. public let title: String? /// Optional SF Symbol shown before the text. Decorative: the text carries the meaning. public let systemImage: String? /// Time on screen. `nil` keeps the toast until it is dismissed. public let duration: Duration? /// Optional action button. public let action: GlassToastAction? /// Creates a toast. /// /// - Parameters: /// - id: pass a stable identifier ("saved", "offline") to replace a toast instead of stacking duplicates. /// - duration: time on screen, at least ``minimumDuration``. Defaults to ``defaultDuration(hasAction:)``. public init( _ message: String, title: String? = nil, systemImage: String? = nil, id: String = UUID().uuidString, duration: Duration? = nil, action: GlassToastAction? = nil ) { self.id = id self.message = message self.title = title self.systemImage = systemImage self.duration = Self.effectiveDuration(duration ?? Self.defaultDuration(hasAction: action != nil)) self.action = action } private init(persistent message: String, title: String?, systemImage: String?, id: String, action: GlassToastAction?) { self.id = id self.message = message self.title = title self.systemImage = systemImage self.duration = nil self.action = action } /// A toast that stays until the user or the host dismisses it. public static func persistent( _ message: String, title: String? = nil, systemImage: String? = nil, id: String = UUID().uuidString, action: GlassToastAction? = nil ) -> GlassToast { GlassToast(persistent: message, title: title, systemImage: systemImage, id: id, action: action) } /// A requested duration raised to ``minimumDuration``. public static func effectiveDuration(_ requested: Duration) -> Duration { max(requested, minimumDuration) } /// What VoiceOver announces when the toast appears: the title, then the message. public var announcement: String { [title, message].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", ") } } /// The queue of toasts shown by ``SwiftUICore/View/glassToastHost(_:placement:)``. /// /// ```swift /// @State private var toasts = GlassToastCenter() /// … /// content.glassToastHost(toasts) /// … /// toasts.show(GlassToast("Draft saved", systemImage: "checkmark.circle")) /// ``` /// /// The centre keeps at most `capacity` toasts. When a new toast arrives while it is full, the **oldest toast /// is dropped**: the most recent event is the one the user needs to see. A toast whose `id` is already present /// replaces the existing one in place and restarts its timer. Each toast is dismissed by its own cancellable /// task; nothing is persisted. @MainActor @Observable public final class GlassToastCenter { /// The toasts on screen, oldest first. public private(set) var toasts: [GlassToast] = [] /// Largest number of toasts kept at once. public let capacity: Int @ObservationIgnored private var timers: [String: Task] = [:] @ObservationIgnored private let sleep: @Sendable (Duration) async throws -> Void @ObservationIgnored private let announce: @MainActor @Sendable (String) -> Void /// Creates a centre. /// /// - Parameters: /// - capacity: largest number of simultaneous toasts, at least 1. /// - sleep: waits for a duration; injectable so that tests control time. /// - announce: posts the accessibility announcement of a new toast. public init( capacity: Int = 3, sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, announce: @escaping @MainActor @Sendable (String) -> Void = { AccessibilityNotification.Announcement($0).post() } ) { self.capacity = max(1, capacity) self.sleep = sleep self.announce = announce } /// Shows a toast, announces it and schedules its dismissal. @discardableResult public func show(_ toast: GlassToast) -> GlassToast.ID { cancelTimer(toast.id) if let index = toasts.firstIndex(where: { $0.id == toast.id }) { toasts[index] = toast } else { toasts.append(toast) while toasts.count > capacity { let dropped = toasts.removeFirst() cancelTimer(dropped.id) } } announce(toast.announcement) if let duration = toast.duration { let id = toast.id let sleep = sleep timers[id] = Task { [weak self] in do { try await sleep(duration) } catch { return } guard !Task.isCancelled else { return } self?.expire(id) } } return toast.id } /// Shows a plain message. @discardableResult public func show(_ message: String, systemImage: String? = nil) -> GlassToast.ID { show(GlassToast(message, systemImage: systemImage)) } /// Removes a toast and cancels its timer. Unknown identifiers are ignored. public func dismiss(_ id: GlassToast.ID) { cancelTimer(id) toasts.removeAll { $0.id == id } } /// Removes every toast and cancels every timer. public func dismissAll() { for task in timers.values { task.cancel() } timers.removeAll() toasts.removeAll() } /// Runs the action of a toast, then dismisses it. public func performAction(of id: GlassToast.ID) { guard let toast = toasts.first(where: { $0.id == id }) else { return } dismiss(id) toast.action?.handler() } /// Waits until every running timer has finished. Used by tests after they let time pass. func waitForTimers() async { for task in Array(timers.values) { await task.value } } private func expire(_ id: String) { timers[id] = nil toasts.removeAll { $0.id == id } } private func cancelTimer(_ id: String) { timers.removeValue(forKey: id)?.cancel() } }