SPB Git

Repository Public MIT

GlassThemeResolver.swift 8.2 KB 215 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassThemes/GlassThemeResolver.swift8// Module           : SPGlassThemes9// 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/// A theme resolved for one appearance and platform: the values components actually draw with.44public struct ResolvedGlassTheme: Equatable, Sendable {45    public let theme: GlassTheme46    public let isDark: Bool47    public let increasedContrast: Bool48    public let platform: GlassPlatform49    /// The spacing scale after the density factor.50    public let spacing: GlassSpacing5152    public var radii: GlassRadii { theme.radii }53    public var typography: GlassTypography { theme.typography }54    public var motion: GlassMotion { theme.motion }55    public var glass: GlassMaterialTokens { theme.glass }56    public var metrics: GlassControlMetrics { GlassControlMetrics(platform: platform) }57    public var hapticsEnabled: Bool { theme.hapticsEnabled }5859    /// The stored value of a role, or `nil` when the role follows the system.60    public func rgba(_ token: GlassColorToken) -> GlassRGBA? {61        let palette = theme.palette(dark: isDark)62        if increasedContrast {63            // With Increase Contrast, secondary text and separators move to the strongest text colour.64            switch token {65            case .textSecondary, .separator: return palette[.textPrimary] ?? palette[token]66            default: break67            }68        }69        return palette[token]70    }7172    /// The colour of a role: the theme value, or the system colour for that role.73    public func color(_ token: GlassColorToken) -> Color {74        if let value = rgba(token) { return Color(glass: value) }75        return GlassSystemColors.color(for: token)76    }7778    /// A legible colour for text or symbols drawn on a fill of `token` (white or near-black).79    public func onColor(_ token: GlassColorToken) -> Color {80        guard let fill = rgba(token) else { return .white }81        let dark = GlassRGBA(rgb: 0x0B0B0F)82        return GlassRGBA.white.contrastRatio(against: fill) >= dark.contrastRatio(against: fill) ? .white : Color(glass: dark)83    }8485    /// The tint applied to custom glass surfaces, if the theme asks for one.86    public var glassTint: Color? {87        theme.glass.tint.map(color)88    }8990    /// The system font for a role. Sizes follow Dynamic Type.91    public func font(_ role: GlassTextRole) -> Font {92        let design = typography.design.fontDesign93        let heading = typography.headingWeight.fontWeight94        let body = typography.bodyWeight.fontWeight95        switch role {96        case .largeTitle: return .system(.largeTitle, design: design, weight: heading)97        case .title: return .system(.title2, design: design, weight: heading)98        case .headline: return .system(.headline, design: design, weight: heading)99        case .body: return .system(.body, design: design, weight: body)100        case .callout: return .system(.callout, design: design, weight: body)101        case .caption: return .system(.caption, design: design, weight: body)102        case .monospacedValue: return .system(.title, design: design, weight: heading).monospacedDigit()103        }104    }105106    /// The animation for a speed. With Reduce Motion the result is a short cross-fade without spring or travel.107    public func animation(_ speed: GlassMotionSpeed = .standard, reduceMotion: Bool) -> Animation {108        let duration = motion.duration(speed)109        if reduceMotion { return .easeInOut(duration: min(duration, 0.2)) }110        switch motion.style {111        case .smooth: return .smooth(duration: duration)112        case .snappy: return .snappy(duration: duration)113        case .bouncy: return .bouncy(duration: duration)114        }115    }116117    /// A continuous rounded rectangle with one of the theme radii.118    public func shape(_ radius: KeyPath<GlassRadii, Double> = \.medium) -> RoundedRectangle {119        RoundedRectangle(cornerRadius: radii[keyPath: radius], style: .continuous)120    }121}122123/// Resolves themes. Pure: the same inputs always give the same result.124public enum GlassThemeResolver {125    public static func resolve(126        _ theme: GlassTheme,127        colorScheme: ColorScheme,128        contrast: ColorSchemeContrast = .standard,129        platform: GlassPlatform = .current130    ) -> ResolvedGlassTheme {131        let isDark: Bool132        switch theme.appearance {133        case .light: isDark = false134        case .dark: isDark = true135        case .system: isDark = colorScheme == .dark136        }137        return ResolvedGlassTheme(138            theme: theme,139            isDark: isDark,140            increasedContrast: contrast == .increased,141            platform: platform,142            spacing: theme.spacing.scaled(by: theme.density.spacingMultiplier)143        )144    }145}146147/// System colours used for roles a theme leaves undefined.148public enum GlassSystemColors {149    public static func color(for token: GlassColorToken) -> Color {150        switch token {151        case .primary, .accent, .focusRing: return .accentColor152        case .secondary, .textSecondary: return .secondary153        case .destructive: return .red154        case .success: return .green155        case .warning: return .orange156        case .textPrimary: return .primary157        case .background:158            #if os(macOS)159            return Color(nsColor: .windowBackgroundColor)160            #else161            return Color(uiColor: .systemBackground)162            #endif163        case .surface:164            #if os(macOS)165            return Color(nsColor: .controlBackgroundColor)166            #else167            return Color(uiColor: .secondarySystemBackground)168            #endif169        case .separator:170            #if os(macOS)171            return Color(nsColor: .separatorColor)172            #else173            return Color(uiColor: .separator)174            #endif175        }176    }177}178179extension Color {180    /// Converts a stored colour to SwiftUI at the UI boundary.181    public init(glass value: GlassRGBA) {182        self.init(.sRGB, red: value.red, green: value.green, blue: value.blue, opacity: value.alpha)183    }184}185186extension GlassRGBA {187    /// Reads the sRGB components of a SwiftUI colour in a given environment (used by the Studio colour picker).188    public init(_ color: Color, in environment: EnvironmentValues) {189        let resolved = color.resolve(in: environment)190        self.init(red: Double(resolved.red), green: Double(resolved.green), blue: Double(resolved.blue), alpha: Double(resolved.opacity))191    }192}193194extension GlassFontDesign {195    public var fontDesign: Font.Design {196        switch self {197        case .default: .default198        case .rounded: .rounded199        case .serif: .serif200        case .monospaced: .monospaced201        }202    }203}204205extension GlassFontWeight {206    public var fontWeight: Font.Weight {207        switch self {208        case .regular: .regular209        case .medium: .medium210        case .semibold: .semibold211        case .bold: .bold212        }213    }214}215
Files main
Menu

Theme