SPB Git

Repository Public License

LunarRGBA.swift 4.5 KB 106 lines swift

1import SwiftUI23/// A colour stored as plain sRGB components.4///5/// Themes are data: keeping colours as numbers (rather than `Color`) makes them `Sendable`, `Codable`, exportable to6/// `tokens.json`, and lets the test-suite compute WCAG contrast ratios without resolving anything through the UI.7/// `LunarRGBA` conforms to `ShapeStyle`, so it can be passed directly to `foregroundStyle`, `fill`, `stroke`…8public struct LunarRGBA: Hashable, Sendable, Codable {9    public var red: Double10    public var green: Double11    public var blue: Double12    public var alpha: Double1314    public init(red: Double, green: Double, blue: Double, alpha: Double = 1) {15        self.red = red.clamped0116        self.green = green.clamped0117        self.blue = blue.clamped0118        self.alpha = alpha.clamped0119    }2021    /// `0xRRGGBB`.22    public init(hex: UInt32, alpha: Double = 1) {23        self.init(red: Double((hex >> 16) & 0xFF) / 255,24                  green: Double((hex >> 8) & 0xFF) / 255,25                  blue: Double(hex & 0xFF) / 255,26                  alpha: alpha)27    }2829    /// Parses `#RGB`, `#RRGGBB` or `#RRGGBBAA` (the leading `#` is optional). Returns `nil` for anything else.30    public init?(hexString: String) {31        var text = hexString.trimmingCharacters(in: .whitespacesAndNewlines)32        if text.hasPrefix("#") { text.removeFirst() }33        guard text.allSatisfy(\.isHexDigit) else { return nil }34        if text.count == 3 { text = text.map { "\($0)\($0)" }.joined() }35        guard text.count == 6 || text.count == 8, let value = UInt64(text, radix: 16) else { return nil }36        if text.count == 6 {37            self.init(hex: UInt32(value))38        } else {39            self.init(hex: UInt32(value >> 8), alpha: Double(value & 0xFF) / 255)40        }41    }4243    /// `#RRGGBB`, or `#RRGGBBAA` when the colour is not opaque.44    public var hexString: String {45        let r = Int((red * 255).rounded()), g = Int((green * 255).rounded()), b = Int((blue * 255).rounded())46        let a = Int((alpha * 255).rounded())47        return a == 25548            ? String(format: "#%02X%02X%02X", r, g, b)49            : String(format: "#%02X%02X%02X%02X", r, g, b, a)50    }5152    public var color: Color { Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha) }5354    /// Same colour with another alpha.55    public func withAlpha(_ alpha: Double) -> LunarRGBA {56        LunarRGBA(red: red, green: green, blue: blue, alpha: alpha)57    }5859    /// Linear interpolation in sRGB towards `other` (`0` = self, `1` = other). Alpha is interpolated too.60    public func mixed(with other: LunarRGBA, _ amount: Double) -> LunarRGBA {61        let t = amount.clamped0162        return LunarRGBA(red: red + (other.red - red) * t,63                         green: green + (other.green - green) * t,64                         blue: blue + (other.blue - blue) * t,65                         alpha: alpha + (other.alpha - alpha) * t)66    }6768    /// Source-over compositing of a translucent colour on an opaque backdrop.69    public func composited(over backdrop: LunarRGBA) -> LunarRGBA {70        LunarRGBA(red: red * alpha + backdrop.red * (1 - alpha),71                  green: green * alpha + backdrop.green * (1 - alpha),72                  blue: blue * alpha + backdrop.blue * (1 - alpha),73                  alpha: 1)74    }7576    // MARK: WCAG 2.x7778    /// WCAG relative luminance of the colour (alpha ignored; composite first when translucent).79    public var relativeLuminance: Double {80        func linear(_ c: Double) -> Double { c <= 0.03928 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4) }81        return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue)82    }8384    /// WCAG contrast ratio (1…21) between this colour and `other`. A translucent receiver is composited on `other`.85    public func contrastRatio(against other: LunarRGBA) -> Double {86        let foreground = alpha < 1 ? composited(over: other) : self87        let a = foreground.relativeLuminance, b = other.relativeLuminance88        return (max(a, b) + 0.05) / (min(a, b) + 0.05)89    }9091    public static let white = LunarRGBA(hex: 0xFFFFFF)92    public static let black = LunarRGBA(hex: 0x000000)93    public static let clear = LunarRGBA(red: 0, green: 0, blue: 0, alpha: 0)94}9596extension LunarRGBA: ShapeStyle {97    public func resolve(in environment: EnvironmentValues) -> Color.Resolved {98        Color.Resolved(colorSpace: .sRGB, red: Float(red), green: Float(green), blue: Float(blue),99                       opacity: Float(alpha))100    }101}102103extension Double {104    fileprivate var clamped01: Double { Swift.min(1, Swift.max(0, self)) }105}106
Files main
Menu

Theme