SPB Git

Repository Public MIT

GlassRGBA.swift 7.3 KB 187 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassTokens/GlassRGBA.swift8// Module           : SPGlassTokens9// 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 Foundation4243/// A colour in sRGB with straight alpha, independent of SwiftUI so that it can be stored, compared and validated.44///45/// Encoded as a hex string (`#RRGGBB` or `#RRGGBBAA`). Conversion to `Color` happens in `SPGlassThemes`.46public struct GlassRGBA: Hashable, Sendable {47    public let red: Double48    public let green: Double49    public let blue: Double50    public let alpha: Double5152    /// Creates a colour; components outside 0...1 and non-finite values are clamped.53    public init(red: Double, green: Double, blue: Double, alpha: Double = 1) {54        self.red = Self.clamp(red)55        self.green = Self.clamp(green)56        self.blue = Self.clamp(blue)57        self.alpha = Self.clamp(alpha)58    }5960    /// Parses `#RGB`, `#RRGGBB` or `#RRGGBBAA` (the leading `#` is optional, case is ignored).61    public init(hex: String) throws(GlassColorError) {62        var text = hex.trimmingCharacters(in: .whitespacesAndNewlines)63        if text.hasPrefix("#") { text.removeFirst() }64        guard [3, 6, 8].contains(text.count), text.allSatisfy(\.isHexDigit), text.allSatisfy(\.isASCII) else {65            throw GlassColorError.invalidHex(hex)66        }67        if text.count == 3 {68            text = text.map { "\($0)\($0)" }.joined()69        }70        guard let value = UInt64(text, radix: 16) else { throw GlassColorError.invalidHex(hex) }71        let hasAlpha = text.count == 872        let shift: UInt64 = hasAlpha ? 8 : 073        self.init(74            red: Double((value >> (16 + shift)) & 0xFF) / 255,75            green: Double((value >> (8 + shift)) & 0xFF) / 255,76            blue: Double((value >> shift) & 0xFF) / 255,77            alpha: hasAlpha ? Double(value & 0xFF) / 255 : 178        )79    }8081    /// Creates an opaque or translucent colour from a `0xRRGGBB` literal. Bits above 24 are ignored.82    public init(rgb: UInt32, alpha: Double = 1) {83        self.init(84            red: Double((rgb >> 16) & 0xFF) / 255,85            green: Double((rgb >> 8) & 0xFF) / 255,86            blue: Double(rgb & 0xFF) / 255,87            alpha: alpha88        )89    }9091    /// `0xRRGGBB` value of the colour, ignoring alpha.92    public var rgbValue: UInt32 {93        UInt32(Self.byte(red)) << 16 | UInt32(Self.byte(green)) << 8 | UInt32(Self.byte(blue))94    }9596    /// `#RRGGBB`, or `#RRGGBBAA` when the colour is not opaque. Upper case.97    public var hexString: String {98        let r = Self.byte(red), g = Self.byte(green), b = Self.byte(blue), a = Self.byte(alpha)99        return a == 255100            ? String(format: "#%02X%02X%02X", r, g, b)101            : String(format: "#%02X%02X%02X%02X", r, g, b, a)102    }103104    public var isOpaque: Bool { Self.byte(alpha) == 255 }105106    /// Returns the same colour with another alpha.107    public func opacity(_ alpha: Double) -> GlassRGBA {108        GlassRGBA(red: red, green: green, blue: blue, alpha: alpha)109    }110111    /// Source-over compositing of this colour on an opaque `background`.112    public func composited(over background: GlassRGBA) -> GlassRGBA {113        GlassRGBA(114            red: red * alpha + background.red * (1 - alpha),115            green: green * alpha + background.green * (1 - alpha),116            blue: blue * alpha + background.blue * (1 - alpha),117            alpha: 1118        )119    }120121    /// Linear interpolation towards `other` (`fraction` 0 keeps `self`, 1 gives `other`).122    public func mixed(with other: GlassRGBA, fraction: Double) -> GlassRGBA {123        let t = Self.clamp(fraction)124        return GlassRGBA(125            red: red + (other.red - red) * t,126            green: green + (other.green - green) * t,127            blue: blue + (other.blue - blue) * t,128            alpha: alpha + (other.alpha - alpha) * t129        )130    }131132    /// WCAG 2 relative luminance of the colour, ignoring alpha.133    public var relativeLuminance: Double {134        func linear(_ c: Double) -> Double {135            c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4)136        }137        return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue)138    }139140    /// WCAG 2 contrast ratio (1...21) between this colour, composited on `background`, and `background`.141    ///142    /// The ratio is exact for opaque surfaces only. Over Liquid Glass the backdrop changes with the content143    /// behind it, so a static ratio is an indication, not a guarantee.144    public func contrastRatio(against background: GlassRGBA) -> Double {145        let foreground = isOpaque ? self : composited(over: background)146        let l1 = foreground.relativeLuminance, l2 = background.relativeLuminance147        return (max(l1, l2) + 0.05) / (min(l1, l2) + 0.05)148    }149150    public static let white = GlassRGBA(red: 1, green: 1, blue: 1)151    public static let black = GlassRGBA(red: 0, green: 0, blue: 0)152153    private static func clamp(_ value: Double) -> Double {154        value.isFinite ? min(max(value, 0), 1) : 0155    }156157    private static func byte(_ value: Double) -> Int {158        Int((value * 255).rounded())159    }160}161162extension GlassRGBA: Codable {163    public init(from decoder: any Decoder) throws {164        let text = try decoder.singleValueContainer().decode(String.self)165        do {166            try self.init(hex: text)167        } catch {168            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: error.description))169        }170    }171172    public func encode(to encoder: any Encoder) throws {173        var container = encoder.singleValueContainer()174        try container.encode(hexString)175    }176}177178public enum GlassColorError: Error, Equatable, Sendable, CustomStringConvertible {179    case invalidHex(String)180181    public var description: String {182        switch self {183        case .invalidHex(let text): "Invalid colour \"\(text.prefix(32))\": expected #RGB, #RRGGBB or #RRGGBBAA."184        }185    }186}187
Files main
Menu

Theme