Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/ThemeEngine/ThemeColor.swift10// Description : Platform-neutral colour and gradient tokens with hex11// coding, mixing and WCAG contrast maths.12// Module : ThemeEngine13// Repository : https://git.spboucher.ai/sp-keyboard14// Created : 2026-12-0115// Last Modified : 2026-12-0116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091/// sRGB colour with straight alpha, components in 0...1. Encoded as `#RRGGBB` or `#RRGGBBAA`.92public struct RGBA: Hashable, Sendable, Codable {93 public var r: Double94 public var g: Double95 public var b: Double96 public var a: Double9798 public init(r: Double, g: Double, b: Double, a: Double = 1) {99 self.r = r.clamped01100 self.g = g.clamped01101 self.b = b.clamped01102 self.a = a.clamped01103 }104105 public init?(hex: String) {106 var text = hex.trimmingCharacters(in: .whitespaces)107 if text.hasPrefix("#") { text.removeFirst() }108 guard text.count == 6 || text.count == 8, let value = UInt64(text, radix: 16) else { return nil }109 if text.count == 6 {110 self.init(r: Double((value >> 16) & 0xFF) / 255, g: Double((value >> 8) & 0xFF) / 255, b: Double(value & 0xFF) / 255)111 } else {112 self.init(r: Double((value >> 24) & 0xFF) / 255, g: Double((value >> 16) & 0xFF) / 255,113 b: Double((value >> 8) & 0xFF) / 255, a: Double(value & 0xFF) / 255)114 }115 }116117 /// Literal used by the built-in palettes; traps on a malformed constant, which a unit test covers.118 public init(_ hex: String) {119 guard let color = RGBA(hex: hex) else { preconditionFailure("invalid colour literal \(hex)") }120 self = color121 }122123 public var hex: String {124 let parts = [r, g, b].map { Int(($0 * 255).rounded()) }125 let base = String(format: "#%02X%02X%02X", parts[0], parts[1], parts[2])126 return a >= 0.999 ? base : base + String(format: "%02X", Int((a * 255).rounded()))127 }128129 public init(from decoder: Decoder) throws {130 let container = try decoder.singleValueContainer()131 let text = try container.decode(String.self)132 guard let color = RGBA(hex: text) else {133 throw DecodingError.dataCorruptedError(in: container, debugDescription: "invalid colour")134 }135 self = color136 }137138 public func encode(to encoder: Encoder) throws {139 var container = encoder.singleValueContainer()140 try container.encode(hex)141 }142143 public func opacity(_ alpha: Double) -> RGBA { RGBA(r: r, g: g, b: b, a: alpha) }144145 public func mixed(with other: RGBA, _ t: Double) -> RGBA {146 let k = t.clamped01147 return RGBA(r: r + (other.r - r) * k, g: g + (other.g - g) * k, b: b + (other.b - b) * k, a: a + (other.a - a) * k)148 }149150 /// This colour drawn over an opaque backdrop.151 public func composited(over backdrop: RGBA) -> RGBA {152 RGBA(r: r * a + backdrop.r * (1 - a), g: g * a + backdrop.g * (1 - a), b: b * a + backdrop.b * (1 - a), a: 1)153 }154155 /// WCAG 2 relative luminance of the opaque colour.156 public var luminance: Double {157 func linear(_ c: Double) -> Double { c <= 0.03928 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4) }158 return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)159 }160161 /// WCAG 2 contrast ratio between two opaque colours, 1...21.162 public func contrast(with other: RGBA) -> Double {163 let (l1, l2) = (max(luminance, other.luminance), min(luminance, other.luminance))164 return (l1 + 0.05) / (l2 + 0.05)165 }166167 public static let white = RGBA(r: 1, g: 1, b: 1)168 public static let black = RGBA(r: 0, g: 0, b: 0)169 public static let clear = RGBA(r: 0, g: 0, b: 0, a: 0)170}171172/// Linear gradient: 1 to 6 colours, angle in degrees (0 = left→right, 90 = top→bottom).173public struct GradientSpec: Hashable, Sendable, Codable {174 public var colors: [RGBA]175 public var angle: Double176177 public init(_ colors: [RGBA], angle: Double = 90) {178 self.colors = colors179 self.angle = angle180 }181182 public static func solid(_ color: RGBA) -> GradientSpec { GradientSpec([color]) }183184 /// Mean colour, used for contrast estimates.185 public var average: RGBA {186 guard !colors.isEmpty else { return .black }187 let n = Double(colors.count)188 return RGBA(r: colors.map(\.r).reduce(0, +) / n, g: colors.map(\.g).reduce(0, +) / n,189 b: colors.map(\.b).reduce(0, +) / n, a: colors.map(\.a).reduce(0, +) / n)190 }191192 /// Unit-square start and end points for the angle.193 public var unitPoints: (start: (x: Double, y: Double), end: (x: Double, y: Double)) {194 let radians = angle * .pi / 180195 let (dx, dy) = (cos(radians) / 2, sin(radians) / 2)196 return ((0.5 - dx, 0.5 - dy), (0.5 + dx, 0.5 + dy))197 }198}199200extension Double {201 var clamped01: Double { isNaN ? 0 : Swift.min(1, Swift.max(0, self)) }202 func clamped(_ range: ClosedRange<Double>) -> Double { isNaN ? range.lowerBound : Swift.min(range.upperBound, Swift.max(range.lowerBound, self)) }203}204