SPB Git

Repository Public MIT

GlassAlert.swift 9.2 KB 242 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Feedback/GlassAlert.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 SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// Role of a button in a ``GlassAlert``.48public enum GlassAlertButtonRole: String, CaseIterable, Sendable {49    /// A regular choice.50    case `default`51    /// Leaves without doing anything. At most one per alert.52    case cancel53    /// Deletes or cannot be undone. Never the default action.54    case destructive5556    /// The system role; `nil` for a regular button.57    public var buttonRole: ButtonRole? {58        switch self {59        case .default: nil60        case .cancel: .cancel61        case .destructive: .destructive62        }63    }64}6566/// One button of a ``GlassAlert``.67public struct GlassAlertButton: Sendable {68    /// Title, already localised by the host.69    public let title: String70    public let role: GlassAlertButtonRole71    /// Called after the alert is dismissed by this button.72    public let action: @MainActor @Sendable () -> Void7374    public init(_ title: String, role: GlassAlertButtonRole = .default, action: @escaping @MainActor @Sendable () -> Void = {}) {75        self.title = title76        self.role = role77        self.action = action78    }7980    /// A cancel button. Without a title it reads "Cancel" in the language of GlassKit's resources.81    public static func cancel(_ title: String? = nil, action: @escaping @MainActor @Sendable () -> Void = {}) -> GlassAlertButton {82        GlassAlertButton(title ?? GlassL10n.string(.cancel), role: .cancel, action: action)83    }8485    /// A destructive button.86    public static func destructive(_ title: String, action: @escaping @MainActor @Sendable () -> Void) -> GlassAlertButton {87        GlassAlertButton(title, role: .destructive, action: action)88    }89}9091/// How a ``GlassAlert`` is presented.92public enum GlassAlertStyle: String, CaseIterable, Sendable {93    /// A modal `alert`, for information the user must acknowledge or a decision with one or two choices.94    case alert95    /// A `confirmationDialog` attached to the view, for confirming an action the user just started.96    case confirmation97}9899/// The description of an alert or a confirmation dialog.100///101/// ```swift102/// @State private var alert: GlassAlert?103/// …104/// Button("Delete") {105///     alert = GlassAlert(title: "Delete this draft?", message: "This cannot be undone.", style: .confirmation,106///                        buttons: [.destructive("Delete") { delete() }, .cancel()])107/// }108/// .glassAlert($alert)109/// ```110///111/// The system draws the alert. Before presentation the buttons go through ``GlassAlertValidator``: one cancel112/// button at most, a cancel button whenever a destructive one is offered, safe ordering, and a default action113/// that is never destructive.114public struct GlassAlert: Identifiable, Sendable {115    public let id: String116    /// Title, already localised by the host.117    public let title: String118    /// Optional explanation, already localised by the host.119    public let message: String?120    public let style: GlassAlertStyle121    /// The buttons as given by the host. ``validatedButtons`` is what is presented.122    public let buttons: [GlassAlertButton]123124    public init(125        title: String,126        message: String? = nil,127        style: GlassAlertStyle = .alert,128        buttons: [GlassAlertButton] = [],129        id: String = UUID().uuidString130    ) {131        self.id = id132        self.title = title133        self.message = message134        self.style = style135        self.buttons = buttons136    }137138    /// The buttons actually presented, in presentation order.139    public var validatedButtons: [GlassAlertButton] {140        GlassAlertValidator.validated(buttons, style: style)141    }142}143144/// The rules that make the buttons of an alert safe.145public enum GlassAlertValidator {146    /// Returns the buttons to present.147    ///148    /// 1. Only the first cancel button keeps its role; later ones become regular buttons.149    /// 2. An alert without buttons gets "OK"; a confirmation without buttons gets "Cancel".150    /// 3. When a destructive button exists and no cancel button does, "Cancel" is added.151    /// 4. Order: regular buttons, then destructive ones, then cancel — each group in its original order.152    public static func validated(153        _ buttons: [GlassAlertButton],154        style: GlassAlertStyle,155        okTitle: String = GlassL10n.string(.ok),156        cancelTitle: String = GlassL10n.string(.cancel)157    ) -> [GlassAlertButton] {158        var regular: [GlassAlertButton] = []159        var destructive: [GlassAlertButton] = []160        var cancel: GlassAlertButton?161        for button in buttons {162            switch button.role {163            case .default:164                regular.append(button)165            case .destructive:166                destructive.append(button)167            case .cancel:168                if cancel == nil {169                    cancel = button170                } else {171                    regular.append(GlassAlertButton(button.title, role: .default, action: button.action))172                }173            }174        }175        if regular.isEmpty, destructive.isEmpty, cancel == nil {176            switch style {177            case .alert: regular.append(GlassAlertButton(okTitle))178            case .confirmation: cancel = GlassAlertButton(cancelTitle, role: .cancel)179            }180        }181        if !destructive.isEmpty, cancel == nil {182            cancel = GlassAlertButton(cancelTitle, role: .cancel)183        }184        return regular + destructive + (cancel.map { [$0] } ?? [])185    }186187    /// Index, in a validated list, of the button triggered by Return: the first regular button, otherwise the188    /// cancel button. Never a destructive button.189    public static func defaultButtonIndex(in validated: [GlassAlertButton]) -> Int? {190        validated.firstIndex { $0.role == .default } ?? validated.firstIndex { $0.role == .cancel }191    }192}193194extension View {195    /// Presents the alert or confirmation dialog described by `alert`; it is set back to `nil` on dismissal.196    public func glassAlert(_ alert: Binding<GlassAlert?>) -> some View {197        modifier(GlassAlertModifier(alert: alert))198    }199}200201private struct GlassAlertModifier: ViewModifier {202    @Binding var alert: GlassAlert?203204    func body(content: Content) -> some View {205        content206            .alert(Text(verbatim: alert?.title ?? ""), isPresented: isPresented(.alert), presenting: alert) { value in207                GlassAlertButtons(buttons: value.validatedButtons)208            } message: { value in209                if let message = value.message { Text(verbatim: message) }210            }211            .confirmationDialog(Text(verbatim: alert?.title ?? ""), isPresented: isPresented(.confirmation), titleVisibility: .visible, presenting: alert) { value in212                GlassAlertButtons(buttons: value.validatedButtons)213            } message: { value in214                if let message = value.message { Text(verbatim: message) }215            }216    }217218    private func isPresented(_ style: GlassAlertStyle) -> Binding<Bool> {219        Binding {220            alert?.style == style221        } set: { isPresented in222            if !isPresented, alert?.style == style { alert = nil }223        }224    }225}226227private struct GlassAlertButtons: View {228    let buttons: [GlassAlertButton]229230    var body: some View {231        let defaultIndex = GlassAlertValidator.defaultButtonIndex(in: buttons)232        ForEach(Array(buttons.enumerated()), id: \.offset) { index, button in233            if index == defaultIndex, button.role == .default {234                Button(button.title, role: button.role.buttonRole, action: button.action)235                    .keyboardShortcut(.defaultAction)236            } else {237                Button(button.title, role: button.role.buttonRole, action: button.action)238            }239        }240    }241}242
Files main
Menu

Theme