SPB Git

Repository Public MIT

GlassButtonChrome.swift 6.4 KB 152 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Support/GlassButtonChrome.swift8// Module           : SPGlassComponents9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0313//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/// Visual weight of a glass button.44public enum GlassButtonVariant: String, CaseIterable, Sendable {45    /// The system glass button style. For most actions.46    case regular47    /// The system prominent glass style, filled with the theme's primary colour. One per view at most.48    case prominent49}5051extension GlassControlSize {52    /// The matching system control size.53    public var controlSize: ControlSize {54        switch self {55        case .small: .small56        case .regular: .regular57        case .large: .large58        }59    }60}6162extension View {63    /// Applies the system glass button style for a variant.64    ///65    /// The system draws the control, including its own Reduce Transparency treatment. When Reduce Transparency66    /// is *simulated* through ``SwiftUICore/View/glassSimulatedAccessibility(reduceTransparency:reduceMotion:)``,67    /// the bordered system styles stand in for the glass ones.68    public func glassButtonChrome(_ variant: GlassButtonVariant, role: ButtonRole? = nil, size: GlassControlSize = .regular) -> some View {69        modifier(GlassButtonChromeModifier(variant: variant, role: role, size: size))70    }71}7273extension View {74    /// Keeps the label of a prominent glass button legible. Apply it to the label, inside the button.75    ///76    /// The system draws the label of a prominent button in white. A fill that is pale in the current77    /// appearance (Obsidian's primary in dark mode, the System theme's light blue in dark mode) would leave78    /// white on a light colour: the label then takes a near-black. With a darker fill, or a regular button,79    /// nothing changes and the system's white stays.80    public func glassButtonLabelContrast(_ variant: GlassButtonVariant, role: ButtonRole? = nil) -> some View {81        modifier(GlassButtonLabelContrastModifier(variant: variant, role: role))82    }83}8485/// Decides when white no longer reads on a prominent fill. Pure.86public enum GlassButtonContrast {87    /// Contrast ratio of white text below which a dark label is used instead. It is deliberately lower than88    /// 4.5: saturated mid-tones such as the system blue keep the platform's white label.89    public static let minimumWhiteContrast = 2.59091    /// Whether a fill with these linear RGB components (0 to 1) needs a dark label.92    public static func needsDarkLabel(linearRed: Double, linearGreen: Double, linearBlue: Double) -> Bool {93        let luminance = 0.2126 * linearRed + 0.7152 * linearGreen + 0.0722 * linearBlue94        return 1.05 / (luminance + 0.05) < minimumWhiteContrast95    }96}9798private struct GlassButtonLabelContrastModifier: ViewModifier {99    @GlassThemed private var theme100    @Environment(\.self) private var environment101    let variant: GlassButtonVariant102    let role: ButtonRole?103104    func body(content: Content) -> some View {105        if variant == .prominent, environment.isEnabled {106            // Set in both cases: a container's own foreground style (a card footer, a secondary caption)107            // would otherwise be inherited by the label and dim it on the filled button.108            content.foregroundStyle(needsDarkLabel ? Color(red: 0.043, green: 0.043, blue: 0.059) : Color.white)109        } else {110            content111        }112    }113114    /// The fill is resolved in the environment, so that system colours (the System theme) count too.115    private var needsDarkLabel: Bool {116        let fill = theme.color(role == .destructive ? .destructive : .primary).resolve(in: environment)117        return GlassButtonContrast.needsDarkLabel(linearRed: Double(fill.linearRed), linearGreen: Double(fill.linearGreen), linearBlue: Double(fill.linearBlue))118    }119}120121private struct GlassButtonChromeModifier: ViewModifier {122    @GlassThemed private var theme123    @Environment(\.glassAccessibilityOverrides) private var overrides124    let variant: GlassButtonVariant125    let role: ButtonRole?126    let size: GlassControlSize127128    func body(content: Content) -> some View {129        styled(content)130            .controlSize(size.controlSize)131            .tint(tint)132    }133134    @ViewBuilder135    private func styled(_ content: Content) -> some View {136        let simulatedOpaque = overrides.reduceTransparency == true137        switch (variant, simulatedOpaque) {138        case (.regular, false): content.buttonStyle(.glass)139        case (.prominent, false): content.buttonStyle(.glassProminent)140        case (.regular, true): content.buttonStyle(.bordered)141        case (.prominent, true): content.buttonStyle(.borderedProminent)142        }143    }144145    /// Prominent buttons take the theme's primary colour, destructive ones the destructive colour.146    /// A regular, non-destructive button keeps the system's untinted glass.147    private var tint: Color? {148        if role == .destructive { return theme.color(.destructive) }149        return variant == .prominent ? theme.color(.primary) : nil150    }151}152
Files main
Menu

Theme