SPB Git

Repository Public MIT

GlassThemeResolver.swift 8.6 KB 220 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: GlassSpacing51    /// Roles left to the system whose system colour, in the view's environment, is light enough to need a52    /// dark label. A system colour has no stored value, so this is measured where the environment is known.53    public var systemRolesNeedingDarkLabel: Set<GlassColorToken> = []5455    public var radii: GlassRadii { theme.radii }56    public var typography: GlassTypography { theme.typography }57    public var motion: GlassMotion { theme.motion }58    public var glass: GlassMaterialTokens { theme.glass }59    public var metrics: GlassControlMetrics { GlassControlMetrics(platform: platform) }60    public var hapticsEnabled: Bool { theme.hapticsEnabled }6162    /// The stored value of a role, or `nil` when the role follows the system.63    public func rgba(_ token: GlassColorToken) -> GlassRGBA? {64        let palette = theme.palette(dark: isDark)65        if increasedContrast {66            // With Increase Contrast, secondary text and separators move to the strongest text colour.67            switch token {68            case .textSecondary, .separator: return palette[.textPrimary] ?? palette[token]69            default: break70            }71        }72        return palette[token]73    }7475    /// The colour of a role: the theme value, or the system colour for that role.76    public func color(_ token: GlassColorToken) -> Color {77        if let value = rgba(token) { return Color(glass: value) }78        return GlassSystemColors.color(for: token)79    }8081    /// A legible colour for text or symbols drawn on a fill of `token` (white or near-black).82    public func onColor(_ token: GlassColorToken) -> Color {83        let dark = GlassRGBA(rgb: 0x0B0B0F)84        guard let fill = rgba(token) else {85            return systemRolesNeedingDarkLabel.contains(token) ? Color(glass: dark) : .white86        }87        return GlassRGBA.white.contrastRatio(against: fill) >= dark.contrastRatio(against: fill) ? .white : Color(glass: dark)88    }8990    /// The tint applied to custom glass surfaces, if the theme asks for one.91    public var glassTint: Color? {92        theme.glass.tint.map(color)93    }9495    /// The system font for a role. Sizes follow Dynamic Type.96    public func font(_ role: GlassTextRole) -> Font {97        let design = typography.design.fontDesign98        let heading = typography.headingWeight.fontWeight99        let body = typography.bodyWeight.fontWeight100        switch role {101        case .largeTitle: return .system(.largeTitle, design: design, weight: heading)102        case .title: return .system(.title2, design: design, weight: heading)103        case .headline: return .system(.headline, design: design, weight: heading)104        case .body: return .system(.body, design: design, weight: body)105        case .callout: return .system(.callout, design: design, weight: body)106        case .caption: return .system(.caption, design: design, weight: body)107        case .monospacedValue: return .system(.title, design: design, weight: heading).monospacedDigit()108        }109    }110111    /// The animation for a speed. With Reduce Motion the result is a short cross-fade without spring or travel.112    public func animation(_ speed: GlassMotionSpeed = .standard, reduceMotion: Bool) -> Animation {113        let duration = motion.duration(speed)114        if reduceMotion { return .easeInOut(duration: min(duration, 0.2)) }115        switch motion.style {116        case .smooth: return .smooth(duration: duration)117        case .snappy: return .snappy(duration: duration)118        case .bouncy: return .bouncy(duration: duration)119        }120    }121122    /// A continuous rounded rectangle with one of the theme radii.123    public func shape(_ radius: KeyPath<GlassRadii, Double> = \.medium) -> RoundedRectangle {124        RoundedRectangle(cornerRadius: radii[keyPath: radius], style: .continuous)125    }126}127128/// Resolves themes. Pure: the same inputs always give the same result.129public enum GlassThemeResolver {130    public static func resolve(131        _ theme: GlassTheme,132        colorScheme: ColorScheme,133        contrast: ColorSchemeContrast = .standard,134        platform: GlassPlatform = .current135    ) -> ResolvedGlassTheme {136        let isDark: Bool137        switch theme.appearance {138        case .light: isDark = false139        case .dark: isDark = true140        case .system: isDark = colorScheme == .dark141        }142        return ResolvedGlassTheme(143            theme: theme,144            isDark: isDark,145            increasedContrast: contrast == .increased,146            platform: platform,147            spacing: theme.spacing.scaled(by: theme.density.spacingMultiplier)148        )149    }150}151152/// System colours used for roles a theme leaves undefined.153public enum GlassSystemColors {154    public static func color(for token: GlassColorToken) -> Color {155        switch token {156        case .primary, .accent, .focusRing: return .accentColor157        case .secondary, .textSecondary: return .secondary158        case .destructive: return .red159        case .success: return .green160        case .warning: return .orange161        case .textPrimary: return .primary162        case .background:163            #if os(macOS)164            return Color(nsColor: .windowBackgroundColor)165            #else166            return Color(uiColor: .systemBackground)167            #endif168        case .surface:169            #if os(macOS)170            return Color(nsColor: .controlBackgroundColor)171            #else172            return Color(uiColor: .secondarySystemBackground)173            #endif174        case .separator:175            #if os(macOS)176            return Color(nsColor: .separatorColor)177            #else178            return Color(uiColor: .separator)179            #endif180        }181    }182}183184extension Color {185    /// Converts a stored colour to SwiftUI at the UI boundary.186    public init(glass value: GlassRGBA) {187        self.init(.sRGB, red: value.red, green: value.green, blue: value.blue, opacity: value.alpha)188    }189}190191extension GlassRGBA {192    /// Reads the sRGB components of a SwiftUI colour in a given environment (used by the Studio colour picker).193    public init(_ color: Color, in environment: EnvironmentValues) {194        let resolved = color.resolve(in: environment)195        self.init(red: Double(resolved.red), green: Double(resolved.green), blue: Double(resolved.blue), alpha: Double(resolved.opacity))196    }197}198199extension GlassFontDesign {200    public var fontDesign: Font.Design {201        switch self {202        case .default: .default203        case .rounded: .rounded204        case .serif: .serif205        case .monospaced: .monospaced206        }207    }208}209210extension GlassFontWeight {211    public var fontWeight: Font.Weight {212        switch self {213        case .regular: .regular214        case .medium: .medium215        case .semibold: .semibold216        case .bold: .bold217        }218    }219}220
Files main
Menu

Theme