SPB Git

Repository Public MIT

GlassThemeEnvironment.swift 5.4 KB 138 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassThemes/GlassThemeEnvironment.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 SwiftUI4243extension EnvironmentValues {44    /// The theme of this part of the view tree. Defaults to ``GlassTheme/system``.45    @Entry public var glassTheme: GlassTheme = .system46}4748extension View {49    /// Applies a theme to this view and its descendants.50    ///51    /// The theme travels through the environment: sibling subtrees can use different themes and a nested call52    /// replaces the theme for its own subtree only. A theme whose appearance is `.light` or `.dark` also sets53    /// the colour scheme of the subtree, so system controls match it.54    public func glassTheme(_ theme: GlassTheme) -> some View {55        modifier(GlassThemeModifier(theme: theme))56    }5758    /// Adjusts the inherited theme for this subtree, for example a tighter radius inside one panel.59    public func glassThemeOverride(_ transform: @escaping @Sendable (inout GlassTheme) -> Void) -> some View {60        modifier(GlassThemeOverrideModifier(transform: transform))61    }62}6364private struct GlassThemeModifier: ViewModifier {65    let theme: GlassTheme6667    func body(content: Content) -> some View {68        switch theme.appearance {69        case .system:70            content.environment(\.glassTheme, theme)71        case .light:72            content.environment(\.glassTheme, theme).environment(\.colorScheme, .light)73        case .dark:74            content.environment(\.glassTheme, theme).environment(\.colorScheme, .dark)75        }76    }77}7879private struct GlassThemeOverrideModifier: ViewModifier {80    @Environment(\.glassTheme) private var inherited81    let transform: @Sendable (inout GlassTheme) -> Void8283    func body(content: Content) -> some View {84        content.glassTheme(GlassThemeOverride.apply(transform, to: inherited))85    }86}8788/// The override rule, exposed so that it can be tested without a view hierarchy.89public enum GlassThemeOverride {90    public static func apply(_ transform: (inout GlassTheme) -> Void, to inherited: GlassTheme) -> GlassTheme {91        var theme = inherited92        transform(&theme)93        return theme94    }95}9697/// The resolved theme of the current environment.98///99/// ```swift100/// struct Row: View {101///     @GlassThemed private var theme102///     var body: some View {103///         Text("Title").font(theme.font(.headline)).foregroundStyle(theme.color(.textPrimary))104///     }105/// }106/// ```107///108/// Resolution reads the theme, the colour scheme and the contrast setting of the view's own environment, so109/// a view always matches the appearance it is displayed in.110@MainActor111@propertyWrapper112public struct GlassThemed: DynamicProperty {113    @Environment(\.glassTheme) private var theme114    @Environment(\.colorScheme) private var colorScheme115    @Environment(\.colorSchemeContrast) private var contrast116    @Environment(\.self) private var environment117118    public init() {}119120    public var wrappedValue: ResolvedGlassTheme {121        var resolved = GlassThemeResolver.resolve(theme, colorScheme: colorScheme, contrast: contrast)122        // Fill roles the theme leaves to the system (the accent colour, the system red…) are measured in123        // this environment, so that labels drawn on them stay legible whatever the host's accent is.124        let systemFills = Self.fillRoles.filter { resolved.rgba($0) == nil }125        if !systemFills.isEmpty {126            resolved.systemRolesNeedingDarkLabel = Set(systemFills.filter { token in127                let fill = resolved.color(token).resolve(in: environment)128                let luminance = 0.2126 * Double(fill.linearRed) + 0.7152 * Double(fill.linearGreen) + 0.0722 * Double(fill.linearBlue)129                // White wins unless near-black has the better contrast ratio on this fill.130                return 1.05 / (luminance + 0.05) < (luminance + 0.05) / 0.0537131            })132        }133        return resolved134    }135136    private static let fillRoles: [GlassColorToken] = [.primary, .secondary, .accent, .destructive, .success, .warning]137}138
Files main
Menu

Theme