SPB Git

Repository Public MIT

GlassAlert.swift 9.1 KB 238 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 SwiftUI4243/// Role of a button in a ``GlassAlert``.44public enum GlassAlertButtonRole: String, CaseIterable, Sendable {45    /// A regular choice.46    case `default`47    /// Leaves without doing anything. At most one per alert.48    case cancel49    /// Deletes or cannot be undone. Never the default action.50    case destructive5152    /// The system role; `nil` for a regular button.53    public var buttonRole: ButtonRole? {54        switch self {55        case .default: nil56        case .cancel: .cancel57        case .destructive: .destructive58        }59    }60}6162/// One button of a ``GlassAlert``.63public struct GlassAlertButton: Sendable {64    /// Title, already localised by the host.65    public let title: String66    public let role: GlassAlertButtonRole67    /// Called after the alert is dismissed by this button.68    public let action: @MainActor @Sendable () -> Void6970    public init(_ title: String, role: GlassAlertButtonRole = .default, action: @escaping @MainActor @Sendable () -> Void = {}) {71        self.title = title72        self.role = role73        self.action = action74    }7576    /// A cancel button. Without a title it reads "Cancel" in the language of GlassKit's resources.77    public static func cancel(_ title: String? = nil, action: @escaping @MainActor @Sendable () -> Void = {}) -> GlassAlertButton {78        GlassAlertButton(title ?? GlassL10n.string(.cancel), role: .cancel, action: action)79    }8081    /// A destructive button.82    public static func destructive(_ title: String, action: @escaping @MainActor @Sendable () -> Void) -> GlassAlertButton {83        GlassAlertButton(title, role: .destructive, action: action)84    }85}8687/// How a ``GlassAlert`` is presented.88public enum GlassAlertStyle: String, CaseIterable, Sendable {89    /// A modal `alert`, for information the user must acknowledge or a decision with one or two choices.90    case alert91    /// A `confirmationDialog` attached to the view, for confirming an action the user just started.92    case confirmation93}9495/// The description of an alert or a confirmation dialog.96///97/// ```swift98/// @State private var alert: GlassAlert?99/// …100/// Button("Delete") {101///     alert = GlassAlert(title: "Delete this draft?", message: "This cannot be undone.", style: .confirmation,102///                        buttons: [.destructive("Delete") { delete() }, .cancel()])103/// }104/// .glassAlert($alert)105/// ```106///107/// The system draws the alert. Before presentation the buttons go through ``GlassAlertValidator``: one cancel108/// button at most, a cancel button whenever a destructive one is offered, safe ordering, and a default action109/// that is never destructive.110public struct GlassAlert: Identifiable, Sendable {111    public let id: String112    /// Title, already localised by the host.113    public let title: String114    /// Optional explanation, already localised by the host.115    public let message: String?116    public let style: GlassAlertStyle117    /// The buttons as given by the host. ``validatedButtons`` is what is presented.118    public let buttons: [GlassAlertButton]119120    public init(121        title: String,122        message: String? = nil,123        style: GlassAlertStyle = .alert,124        buttons: [GlassAlertButton] = [],125        id: String = UUID().uuidString126    ) {127        self.id = id128        self.title = title129        self.message = message130        self.style = style131        self.buttons = buttons132    }133134    /// The buttons actually presented, in presentation order.135    public var validatedButtons: [GlassAlertButton] {136        GlassAlertValidator.validated(buttons, style: style)137    }138}139140/// The rules that make the buttons of an alert safe.141public enum GlassAlertValidator {142    /// Returns the buttons to present.143    ///144    /// 1. Only the first cancel button keeps its role; later ones become regular buttons.145    /// 2. An alert without buttons gets "OK"; a confirmation without buttons gets "Cancel".146    /// 3. When a destructive button exists and no cancel button does, "Cancel" is added.147    /// 4. Order: regular buttons, then destructive ones, then cancel — each group in its original order.148    public static func validated(149        _ buttons: [GlassAlertButton],150        style: GlassAlertStyle,151        okTitle: String = GlassL10n.string(.ok),152        cancelTitle: String = GlassL10n.string(.cancel)153    ) -> [GlassAlertButton] {154        var regular: [GlassAlertButton] = []155        var destructive: [GlassAlertButton] = []156        var cancel: GlassAlertButton?157        for button in buttons {158            switch button.role {159            case .default:160                regular.append(button)161            case .destructive:162                destructive.append(button)163            case .cancel:164                if cancel == nil {165                    cancel = button166                } else {167                    regular.append(GlassAlertButton(button.title, role: .default, action: button.action))168                }169            }170        }171        if regular.isEmpty, destructive.isEmpty, cancel == nil {172            switch style {173            case .alert: regular.append(GlassAlertButton(okTitle))174            case .confirmation: cancel = GlassAlertButton(cancelTitle, role: .cancel)175            }176        }177        if !destructive.isEmpty, cancel == nil {178            cancel = GlassAlertButton(cancelTitle, role: .cancel)179        }180        return regular + destructive + (cancel.map { [$0] } ?? [])181    }182183    /// Index, in a validated list, of the button triggered by Return: the first regular button, otherwise the184    /// cancel button. Never a destructive button.185    public static func defaultButtonIndex(in validated: [GlassAlertButton]) -> Int? {186        validated.firstIndex { $0.role == .default } ?? validated.firstIndex { $0.role == .cancel }187    }188}189190extension View {191    /// Presents the alert or confirmation dialog described by `alert`; it is set back to `nil` on dismissal.192    public func glassAlert(_ alert: Binding<GlassAlert?>) -> some View {193        modifier(GlassAlertModifier(alert: alert))194    }195}196197private struct GlassAlertModifier: ViewModifier {198    @Binding var alert: GlassAlert?199200    func body(content: Content) -> some View {201        content202            .alert(Text(verbatim: alert?.title ?? ""), isPresented: isPresented(.alert), presenting: alert) { value in203                GlassAlertButtons(buttons: value.validatedButtons)204            } message: { value in205                if let message = value.message { Text(verbatim: message) }206            }207            .confirmationDialog(Text(verbatim: alert?.title ?? ""), isPresented: isPresented(.confirmation), titleVisibility: .visible, presenting: alert) { value in208                GlassAlertButtons(buttons: value.validatedButtons)209            } message: { value in210                if let message = value.message { Text(verbatim: message) }211            }212    }213214    private func isPresented(_ style: GlassAlertStyle) -> Binding<Bool> {215        Binding {216            alert?.style == style217        } set: { isPresented in218            if !isPresented, alert?.style == style { alert = nil }219        }220    }221}222223private struct GlassAlertButtons: View {224    let buttons: [GlassAlertButton]225226    var body: some View {227        let defaultIndex = GlassAlertValidator.defaultButtonIndex(in: buttons)228        ForEach(Array(buttons.enumerated()), id: \.offset) { index, button in229            if index == defaultIndex, button.role == .default {230                Button(button.title, role: button.role.buttonRole, action: button.action)231                    .keyboardShortcut(.defaultAction)232            } else {233                Button(button.title, role: button.role.buttonRole, action: button.action)234            }235        }236    }237}238
Files main
Menu

Theme