// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassComponents/Feedback/GlassAlert.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 /// Role of a button in a ``GlassAlert``. public enum GlassAlertButtonRole: String, CaseIterable, Sendable { /// A regular choice. case `default` /// Leaves without doing anything. At most one per alert. case cancel /// Deletes or cannot be undone. Never the default action. case destructive /// The system role; `nil` for a regular button. public var buttonRole: ButtonRole? { switch self { case .default: nil case .cancel: .cancel case .destructive: .destructive } } } /// One button of a ``GlassAlert``. public struct GlassAlertButton: Sendable { /// Title, already localised by the host. public let title: String public let role: GlassAlertButtonRole /// Called after the alert is dismissed by this button. public let action: @MainActor @Sendable () -> Void public init(_ title: String, role: GlassAlertButtonRole = .default, action: @escaping @MainActor @Sendable () -> Void = {}) { self.title = title self.role = role self.action = action } /// A cancel button. Without a title it reads "Cancel" in the language of GlassKit's resources. public static func cancel(_ title: String? = nil, action: @escaping @MainActor @Sendable () -> Void = {}) -> GlassAlertButton { GlassAlertButton(title ?? GlassL10n.string(.cancel), role: .cancel, action: action) } /// A destructive button. public static func destructive(_ title: String, action: @escaping @MainActor @Sendable () -> Void) -> GlassAlertButton { GlassAlertButton(title, role: .destructive, action: action) } } /// How a ``GlassAlert`` is presented. public enum GlassAlertStyle: String, CaseIterable, Sendable { /// A modal `alert`, for information the user must acknowledge or a decision with one or two choices. case alert /// A `confirmationDialog` attached to the view, for confirming an action the user just started. case confirmation } /// The description of an alert or a confirmation dialog. /// /// ```swift /// @State private var alert: GlassAlert? /// … /// Button("Delete") { /// alert = GlassAlert(title: "Delete this draft?", message: "This cannot be undone.", style: .confirmation, /// buttons: [.destructive("Delete") { delete() }, .cancel()]) /// } /// .glassAlert($alert) /// ``` /// /// The system draws the alert. Before presentation the buttons go through ``GlassAlertValidator``: one cancel /// button at most, a cancel button whenever a destructive one is offered, safe ordering, and a default action /// that is never destructive. public struct GlassAlert: Identifiable, Sendable { public let id: String /// Title, already localised by the host. public let title: String /// Optional explanation, already localised by the host. public let message: String? public let style: GlassAlertStyle /// The buttons as given by the host. ``validatedButtons`` is what is presented. public let buttons: [GlassAlertButton] public init( title: String, message: String? = nil, style: GlassAlertStyle = .alert, buttons: [GlassAlertButton] = [], id: String = UUID().uuidString ) { self.id = id self.title = title self.message = message self.style = style self.buttons = buttons } /// The buttons actually presented, in presentation order. public var validatedButtons: [GlassAlertButton] { GlassAlertValidator.validated(buttons, style: style) } } /// The rules that make the buttons of an alert safe. public enum GlassAlertValidator { /// Returns the buttons to present. /// /// 1. Only the first cancel button keeps its role; later ones become regular buttons. /// 2. An alert without buttons gets "OK"; a confirmation without buttons gets "Cancel". /// 3. When a destructive button exists and no cancel button does, "Cancel" is added. /// 4. Order: regular buttons, then destructive ones, then cancel — each group in its original order. public static func validated( _ buttons: [GlassAlertButton], style: GlassAlertStyle, okTitle: String = GlassL10n.string(.ok), cancelTitle: String = GlassL10n.string(.cancel) ) -> [GlassAlertButton] { var regular: [GlassAlertButton] = [] var destructive: [GlassAlertButton] = [] var cancel: GlassAlertButton? for button in buttons { switch button.role { case .default: regular.append(button) case .destructive: destructive.append(button) case .cancel: if cancel == nil { cancel = button } else { regular.append(GlassAlertButton(button.title, role: .default, action: button.action)) } } } if regular.isEmpty, destructive.isEmpty, cancel == nil { switch style { case .alert: regular.append(GlassAlertButton(okTitle)) case .confirmation: cancel = GlassAlertButton(cancelTitle, role: .cancel) } } if !destructive.isEmpty, cancel == nil { cancel = GlassAlertButton(cancelTitle, role: .cancel) } return regular + destructive + (cancel.map { [$0] } ?? []) } /// Index, in a validated list, of the button triggered by Return: the first regular button, otherwise the /// cancel button. Never a destructive button. public static func defaultButtonIndex(in validated: [GlassAlertButton]) -> Int? { validated.firstIndex { $0.role == .default } ?? validated.firstIndex { $0.role == .cancel } } } extension View { /// Presents the alert or confirmation dialog described by `alert`; it is set back to `nil` on dismissal. public func glassAlert(_ alert: Binding) -> some View { modifier(GlassAlertModifier(alert: alert)) } } private struct GlassAlertModifier: ViewModifier { @Binding var alert: GlassAlert? func body(content: Content) -> some View { content .alert(Text(verbatim: alert?.title ?? ""), isPresented: isPresented(.alert), presenting: alert) { value in GlassAlertButtons(buttons: value.validatedButtons) } message: { value in if let message = value.message { Text(verbatim: message) } } .confirmationDialog(Text(verbatim: alert?.title ?? ""), isPresented: isPresented(.confirmation), titleVisibility: .visible, presenting: alert) { value in GlassAlertButtons(buttons: value.validatedButtons) } message: { value in if let message = value.message { Text(verbatim: message) } } } private func isPresented(_ style: GlassAlertStyle) -> Binding { Binding { alert?.style == style } set: { isPresented in if !isPresented, alert?.style == style { alert = nil } } } } private struct GlassAlertButtons: View { let buttons: [GlassAlertButton] var body: some View { let defaultIndex = GlassAlertValidator.defaultButtonIndex(in: buttons) ForEach(Array(buttons.enumerated()), id: \.offset) { index, button in if index == defaultIndex, button.role == .default { Button(button.title, role: button.role.buttonRole, action: button.action) .keyboardShortcut(.defaultAction) } else { Button(button.title, role: button.role.buttonRole, action: button.action) } } } }