SPB Git

Repository Public MIT

GlassToastCenter.swift 9.0 KB 242 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 Accessibility4344/// The optional button of a ``GlassToast`` (for example "Undo").45public struct GlassToastAction: Sendable {46    /// Title of the button, already localised by the host.47    public let title: String48    /// Called when the button is activated; the toast is then dismissed.49    public let handler: @MainActor @Sendable () -> Void5051    public init(_ title: String, handler: @escaping @MainActor @Sendable () -> Void) {52        self.title = title53        self.handler = handler54    }55}5657/// A short, transient message.58///59/// A toast disappears by itself, so it must never be the only carrier of critical information: errors that60/// need a decision belong in a ``GlassAlert`` or a ``GlassBanner``.61public struct GlassToast: Identifiable, Sendable {62    /// Shortest time a toast stays on screen. Shorter durations are raised to this value.63    public static let minimumDuration: Duration = .seconds(2)64    /// Default time on screen: four seconds, or six when the toast carries an action.65    public static func defaultDuration(hasAction: Bool) -> Duration {66        hasAction ? .seconds(6) : .seconds(4)67    }6869    /// Identity of the toast. Showing a toast whose `id` is already on screen replaces that toast.70    public let id: String71    /// The message, already localised by the host.72    public let message: String73    /// Optional short title shown above the message.74    public let title: String?75    /// Optional SF Symbol shown before the text. Decorative: the text carries the meaning.76    public let systemImage: String?77    /// Time on screen. `nil` keeps the toast until it is dismissed.78    public let duration: Duration?79    /// Optional action button.80    public let action: GlassToastAction?8182    /// Creates a toast.83    ///84    /// - Parameters:85    ///   - id: pass a stable identifier ("saved", "offline") to replace a toast instead of stacking duplicates.86    ///   - duration: time on screen, at least ``minimumDuration``. Defaults to ``defaultDuration(hasAction:)``.87    public init(88        _ message: String,89        title: String? = nil,90        systemImage: String? = nil,91        id: String = UUID().uuidString,92        duration: Duration? = nil,93        action: GlassToastAction? = nil94    ) {95        self.id = id96        self.message = message97        self.title = title98        self.systemImage = systemImage99        self.duration = Self.effectiveDuration(duration ?? Self.defaultDuration(hasAction: action != nil))100        self.action = action101    }102103    private init(persistent message: String, title: String?, systemImage: String?, id: String, action: GlassToastAction?) {104        self.id = id105        self.message = message106        self.title = title107        self.systemImage = systemImage108        self.duration = nil109        self.action = action110    }111112    /// A toast that stays until the user or the host dismisses it.113    public static func persistent(114        _ message: String,115        title: String? = nil,116        systemImage: String? = nil,117        id: String = UUID().uuidString,118        action: GlassToastAction? = nil119    ) -> GlassToast {120        GlassToast(persistent: message, title: title, systemImage: systemImage, id: id, action: action)121    }122123    /// A requested duration raised to ``minimumDuration``.124    public static func effectiveDuration(_ requested: Duration) -> Duration {125        max(requested, minimumDuration)126    }127128    /// What VoiceOver announces when the toast appears: the title, then the message.129    public var announcement: String {130        [title, message].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", ")131    }132}133134/// The queue of toasts shown by ``SwiftUICore/View/glassToastHost(_:placement:)``.135///136/// ```swift137/// @State private var toasts = GlassToastCenter()138/// …139/// content.glassToastHost(toasts)140/// …141/// toasts.show(GlassToast("Draft saved", systemImage: "checkmark.circle"))142/// ```143///144/// The centre keeps at most `capacity` toasts. When a new toast arrives while it is full, the **oldest toast145/// is dropped**: the most recent event is the one the user needs to see. A toast whose `id` is already present146/// replaces the existing one in place and restarts its timer. Each toast is dismissed by its own cancellable147/// task; nothing is persisted.148@MainActor149@Observable150public final class GlassToastCenter {151    /// The toasts on screen, oldest first.152    public private(set) var toasts: [GlassToast] = []153    /// Largest number of toasts kept at once.154    public let capacity: Int155156    @ObservationIgnored private var timers: [String: Task<Void, Never>] = [:]157    @ObservationIgnored private let sleep: @Sendable (Duration) async throws -> Void158    @ObservationIgnored private let announce: @MainActor @Sendable (String) -> Void159160    /// Creates a centre.161    ///162    /// - Parameters:163    ///   - capacity: largest number of simultaneous toasts, at least 1.164    ///   - sleep: waits for a duration; injectable so that tests control time.165    ///   - announce: posts the accessibility announcement of a new toast.166    public init(167        capacity: Int = 3,168        sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) },169        announce: @escaping @MainActor @Sendable (String) -> Void = { AccessibilityNotification.Announcement($0).post() }170    ) {171        self.capacity = max(1, capacity)172        self.sleep = sleep173        self.announce = announce174    }175176    /// Shows a toast, announces it and schedules its dismissal.177    @discardableResult178    public func show(_ toast: GlassToast) -> GlassToast.ID {179        cancelTimer(toast.id)180        if let index = toasts.firstIndex(where: { $0.id == toast.id }) {181            toasts[index] = toast182        } else {183            toasts.append(toast)184            while toasts.count > capacity {185                let dropped = toasts.removeFirst()186                cancelTimer(dropped.id)187            }188        }189        announce(toast.announcement)190        if let duration = toast.duration {191            let id = toast.id192            let sleep = sleep193            timers[id] = Task { [weak self] in194                do { try await sleep(duration) } catch { return }195                guard !Task.isCancelled else { return }196                self?.expire(id)197            }198        }199        return toast.id200    }201202    /// Shows a plain message.203    @discardableResult204    public func show(_ message: String, systemImage: String? = nil) -> GlassToast.ID {205        show(GlassToast(message, systemImage: systemImage))206    }207208    /// Removes a toast and cancels its timer. Unknown identifiers are ignored.209    public func dismiss(_ id: GlassToast.ID) {210        cancelTimer(id)211        toasts.removeAll { $0.id == id }212    }213214    /// Removes every toast and cancels every timer.215    public func dismissAll() {216        for task in timers.values { task.cancel() }217        timers.removeAll()218        toasts.removeAll()219    }220221    /// Runs the action of a toast, then dismisses it.222    public func performAction(of id: GlassToast.ID) {223        guard let toast = toasts.first(where: { $0.id == id }) else { return }224        dismiss(id)225        toast.action?.handler()226    }227228    /// Waits until every running timer has finished. Used by tests after they let time pass.229    func waitForTimers() async {230        for task in Array(timers.values) { await task.value }231    }232233    private func expire(_ id: String) {234        timers[id] = nil235        toasts.removeAll { $0.id == id }236    }237238    private func cancelTimer(_ id: String) {239        timers.removeValue(forKey: id)?.cancel()240    }241}242
Files main
Menu

Theme