SPB Git

Repository Public MIT

GlassToast.swift 7.3 KB 170 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Feedback/GlassToast.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 SwiftUI4243/// Edge of the host where toasts appear.44public enum GlassToastPlacement: String, CaseIterable, Sendable {45    case top, bottom4647    /// Alignment of the toast stack inside the host.48    public var alignment: Alignment {49        self == .top ? .top : .bottom50    }5152    /// Edge the toasts slide in from when motion is allowed.53    public var edge: Edge {54        self == .top ? .top : .bottom55    }56}5758extension View {59    /// Shows the toasts of a ``GlassToastCenter`` above this view, inside its safe area.60    ///61    /// Apply it once, near the root of a scene. The centre is also placed in the environment, so descendants62    /// can post with `@Environment(GlassToastCenter.self)`.63    public func glassToastHost(_ center: GlassToastCenter, placement: GlassToastPlacement = .bottom) -> some View {64        modifier(GlassToastHostModifier(center: center, placement: placement))65    }66}6768private struct GlassToastHostModifier: ViewModifier {69    @GlassThemed private var theme70    @GlassAccessibility private var accessibility71    let center: GlassToastCenter72    let placement: GlassToastPlacement7374    func body(content: Content) -> some View {75        content76            .environment(center)77            .overlay(alignment: placement.alignment) {78                // One group: neighbouring toasts are glass surfaces that must be rendered together.79                GlassGroup(spacing: theme.spacing.xs) {80                    VStack(spacing: theme.spacing.xs) {81                        ForEach(center.toasts) { toast in82                            GlassToastView(toast: toast, onAction: { center.performAction(of: toast.id) }, onDismiss: { center.dismiss(toast.id) })83                                .transition(accessibility.reduceMotion ? .opacity : .move(edge: placement.edge).combined(with: .opacity))84                        }85                    }86                }87                .padding(theme.spacing.md)88                .animation(theme.animation(.standard, reduceMotion: accessibility.reduceMotion), value: center.toasts.map(\.id))89            }90    }91}9293/// One toast drawn on a glass surface. ``SwiftUICore/View/glassToastHost(_:placement:)`` creates these views;94/// use it directly only to show a toast you manage yourself.95public struct GlassToastView: View {96    @GlassThemed private var theme97    private let toast: GlassToast98    private let onAction: @MainActor () -> Void99    private let onDismiss: (@MainActor () -> Void)?100101    /// - Parameters:102    ///   - onAction: called when the toast's action button is activated.103    ///   - onDismiss: when set, a dismiss button is shown.104    public init(toast: GlassToast, onAction: @escaping @MainActor () -> Void = {}, onDismiss: (@MainActor () -> Void)? = nil) {105        self.toast = toast106        self.onAction = onAction107        self.onDismiss = onDismiss108    }109110    public var body: some View {111        HStack(alignment: .center, spacing: theme.spacing.sm) {112            if let systemImage = toast.systemImage {113                Image(systemName: systemImage)114                    .font(.system(.subheadline, weight: .semibold))115                    .foregroundStyle(theme.color(.textPrimary))116                    .frame(width: 30, height: 30)117                    .background(theme.color(.textPrimary).opacity(0.1), in: Circle())118                    .accessibilityHidden(true)119            }120            VStack(alignment: .leading, spacing: 1) {121                if let title = toast.title, !title.isEmpty {122                    Text(verbatim: title)123                        .font(theme.font(.callout).weight(.semibold))124                    Text(verbatim: toast.message)125                        .font(theme.font(.callout))126                        .opacity(0.8)127                } else {128                    Text(verbatim: toast.message)129                        .font(theme.font(.callout).weight(.medium))130                }131            }132            .foregroundStyle(theme.color(.textPrimary))133            .frame(maxWidth: .infinity, alignment: .leading)134            .accessibilityElement(children: .combine)135            // Plain system buttons: the toast is the glass surface, and glass never sits inside glass.136            if let action = toast.action {137                Button(action: onAction) {138                    Text(verbatim: action.title)139                        .font(theme.font(.callout).weight(.semibold))140                        .foregroundStyle(theme.color(.textPrimary))141                        .padding(.horizontal, theme.spacing.sm)142                        .padding(.vertical, theme.spacing.xxs + 2)143                        .background(theme.color(.textPrimary).opacity(0.1), in: Capsule())144                }145                .buttonStyle(.plain)146                .glassMinimumHitTarget()147            }148            if let onDismiss {149                Button(action: onDismiss) {150                    Label(GlassL10n.string(.dismiss), systemImage: "xmark")151                        .labelStyle(.iconOnly)152                        .font(.system(.footnote, weight: .bold))153                        .foregroundStyle(theme.color(.textSecondary))154                }155                .buttonStyle(.plain)156                .glassMinimumHitTarget()157            }158        }159        .padding(.leading, theme.spacing.sm)160        .padding(.trailing, toast.action == nil && onDismiss == nil ? theme.spacing.md : theme.spacing.xxs)161        .padding(.vertical, theme.spacing.xxs)162        .frame(minHeight: 52)163        .frame(maxWidth: 480)164        // Neutral glass: a theme's glass tint would make the message hard to read.165        .glassSurface(.regular.tinted(.none), in: theme.shape(\.large))166        .accessibilityElement(children: .contain)167        .accessibilityLabel(GlassL10n.string(.notification))168    }169}170
Files main
Menu

Theme