SPB Git

Repository Public MIT

GlassTone.swift 9.0 KB 207 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Feedback/GlassTone.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/// The colours of an opaque surface tinted with a status colour, with a measured text contrast.44public struct GlassTintedColors: Equatable, Sendable {45    /// Fill of the surface: the theme surface mixed with a little of the tint.46    public let background: GlassRGBA47    /// Text colour, at least 4.5:1 against `background` (WCAG AA) always reachable on an opaque fill.48    public let foreground: GlassRGBA49    /// Colour of the icon and the outline: the tint when it reaches 3:1 against `background`, else `foreground`.50    public let accent: GlassRGBA5152    /// Share of the tint in the background.53    public static let tintFraction = 0.145455    /// Derives the colours from three theme roles. Pure, so that contrast can be tested for every theme.56    ///57    /// - Parameter fraction: share of the tint in the background, ``tintFraction`` by default.58    public static func resolve(tint: GlassRGBA, surface: GlassRGBA, text: GlassRGBA, fraction: Double = tintFraction) -> GlassTintedColors {59        let base = surface.isOpaque ? surface : surface.opacity(1)60        let background = base.mixed(with: tint.opacity(1), fraction: min(max(fraction, 0), 1))61        let foreground = legible(preferred: text.opacity(1), on: background, minimum: 4.5)62        let accent = tint.opacity(1).contrastRatio(against: background) >= 3 ? tint.opacity(1) : foreground63        return GlassTintedColors(background: background, foreground: foreground, accent: accent)64    }6566    /// `preferred` when it reaches `minimum` against `background`, otherwise white or black, whichever67    /// contrasts more.68    public static func legible(preferred: GlassRGBA, on background: GlassRGBA, minimum: Double) -> GlassRGBA {69        if preferred.contrastRatio(against: background) >= minimum { return preferred }70        // Against any opaque background, the better of pure white and pure black reaches at least 4.58:1.71        return GlassRGBA.white.contrastRatio(against: background) >= GlassRGBA.black.contrastRatio(against: background) ? .white : .black72    }73}7475/// SwiftUI colours of a tinted opaque surface for the current theme.76struct GlassTintedPalette {77    let background: Color78    let foreground: Color79    /// Colour of icons and edges: the tint when it is visible enough on `background`.80    let accent: Color8182    /// Uses measured colours when the theme defines the three roles. A theme that follows the system colours83    /// cannot be measured: the surface is then mixed by SwiftUI, text keeps the primary label colour and84    /// icons keep the system status colour, which the system already adapts to both appearances.85    init(_ token: GlassColorToken, theme: ResolvedGlassTheme, fraction: Double = GlassTintedColors.tintFraction) {86        if let tint = theme.rgba(token), let surface = theme.rgba(.surface), let text = theme.rgba(.textPrimary) {87            let colors = GlassTintedColors.resolve(tint: tint, surface: surface, text: text, fraction: fraction)88            background = Color(glass: colors.background)89            foreground = Color(glass: colors.foreground)90            accent = Color(glass: colors.accent)91        } else {92            background = theme.color(.surface).mix(with: theme.color(token), by: fraction)93            foreground = theme.color(.textPrimary)94            accent = theme.color(token)95        }96    }97}9899/// A solid status fill with its legible content colour.100struct GlassSolidPalette {101    let fill: Color102    let content: Color103104    /// A defined role is filled solid and uses `theme.onColor`. An undefined role follows the system colour:105    /// it is resolved in the given environment and the content is white or near-black, whichever contrasts106    /// more with it.107    init(_ token: GlassColorToken, theme: ResolvedGlassTheme, environment: EnvironmentValues) {108        fill = theme.color(token)109        if theme.rgba(token) != nil {110            content = theme.onColor(token)111        } else {112            let resolved = GlassRGBA(theme.color(token), in: environment).opacity(1)113            let dark = GlassRGBA(rgb: 0x0B0B0F)114            content = GlassRGBA.white.contrastRatio(against: resolved) >= dark.contrastRatio(against: resolved) ? .white : Color(glass: dark)115        }116    }117}118119/// SwiftUI colours of a status-tinted opaque area, for content components built on the kit.120public struct GlassTintedSwatch {121    /// Fill: the theme surface mixed with a little of the tint.122    public let background: Color123    /// Text colour on `background`.124    public let foreground: Color125    /// Icon and edge colour on `background`.126    public let accent: Color127128    /// - Parameters:129    ///   - token: the status colour role.130    ///   - fraction: share of the tint in the background.131    public init(_ token: GlassColorToken, theme: ResolvedGlassTheme, fraction: Double = GlassTintedColors.tintFraction) {132        let palette = GlassTintedPalette(token, theme: theme, fraction: fraction)133        background = palette.background134        foreground = palette.foreground135        accent = palette.accent136    }137}138139/// A small rounded tile holding one SF Symbol, tinted with a tone.140///141/// ```swift142/// GlassIconTile(systemImage: "shippingbox", tone: .accent)143/// ```144///145/// The tile is decoration for a row, a banner or a timeline event: it is hidden from assistive technologies,146/// so the text next to it must carry the meaning.147public struct GlassIconTile: View {148    @GlassThemed private var theme149    private let systemImage: String150    private let tone: GlassBadgeTone151    private let size: CGFloat152153    /// - Parameters:154    ///   - tone: selects the colour of the symbol and of the tile's light fill.155    ///   - size: side of the tile in points, at least 16.156    public init(systemImage: String, tone: GlassBadgeTone = .accent, size: CGFloat = 32) {157        self.systemImage = systemImage158        self.tone = tone159        self.size = max(16, size)160    }161162    public var body: some View {163        let colors = colors164        Image(systemName: systemImage)165            .font(.system(size: size * 0.46, weight: .semibold))166            .foregroundStyle(colors.glyph)167            .frame(width: size, height: size)168            .background(colors.fill, in: RoundedRectangle(cornerRadius: size * 0.3, style: .continuous))169            .accessibilityHidden(true)170    }171172    private var colors: (fill: Color, glyph: Color) {173        guard let token = tone.colorToken else {174            return (theme.color(.textPrimary).opacity(0.08), theme.color(.textSecondary))175        }176        let palette = GlassTintedPalette(token, theme: theme, fraction: 0.16)177        return (palette.background, palette.accent)178    }179}180181/// Meaning of a ``GlassBadge``; it selects the colour and, for a status badge, the symbol.182public enum GlassBadgeTone: String, CaseIterable, Sendable {183    case neutral, accent, success, warning, critical184185    /// Theme colour role of the fill; `nil` for the neutral surface.186    public var colorToken: GlassColorToken? {187        switch self {188        case .neutral: nil189        case .accent: .accent190        case .success: .success191        case .warning: .warning192        case .critical: .destructive193        }194    }195196    /// Symbol of a status badge. Every tone has a different shape, so the status survives without colour.197    public var statusSystemImage: String {198        switch self {199        case .neutral: "circle.fill"200        case .accent: "info.circle.fill"201        case .success: "checkmark.circle.fill"202        case .warning: "exclamationmark.triangle.fill"203        case .critical: "xmark.octagon.fill"204        }205    }206}207
Files main
Menu

Theme