//! The phone's generated design system: `Palette.xcassets` and //! `Palette.swift`. //! //! The asset catalogue is the phone's answer where the Mac chose a plain Swift //! source. The Mac builds with `swift build` and assembles its bundle by hand, //! so a compiled `Assets.car` would have cost it actool and `Bundle.module` for //! nothing. The phone is an Xcode app: the catalogue is where a colour lives, //! and `Bundle.module` is already there. The hexes ALSO ship as a //! `CottonPalette` value type, the Mac's shape, so a test can assert the //! numbers without loading a bundle. //! //! **Every colorset carries ONE colour.** The app is light-only: there is no //! theme choice, no dark mode and no system-appearance switch, so no colorset //! carries a `luminosity` entry and nothing the system decides can repaint a //! screen. The brand's fixed charcoal (`Palettes.graphite`) is a value, not an //! appearance, and reaches only the surfaces that name it. //! //! Determinism is a requirement: `--check` compares bytes. Nothing here reads //! the clock or the filesystem. use cotton_core::design::palette::Palette; use cotton_core::design::palette::{ colorsets, PaletteSlot, Sidebar, SidebarSlot, Status, StatusSlot, GRAPHITE, PAPER, SIDEBAR, STATUS, }; use crate::swift::{generated_header, swift_str}; // ── The asset catalogue ─────────────────────────────────────────────────── /// The four channels an `.xcassets` colorset wants, from `#RRGGBB` or /// `#RRGGBBAA`. pub fn channels(hex: &str) -> Result<[String; 4], String> { let digits = hex.strip_prefix('#').unwrap_or(hex); if (digits.len() != 6 && digits.len() != 8) || !digits.chars().all(|ch| ch.is_ascii_hexdigit()) { return Err(format!( "cotton-gen: not a #RRGGBB or #RRGGBBAA colour: {hex}" )); } let byte = |at: usize| format!("0x{}", digits[at * 2..at * 2 + 2].to_ascii_uppercase()); let alpha_byte: u32 = if digits.len() == 8 { u32::from_str_radix(&digits[6..8], 16).expect("hex digits") } else { 255 }; Ok([ byte(0), byte(1), byte(2), // Three decimals is what Xcode itself writes, and it is exact enough // that a byte round-trips: 46/255 = 0.180, and 0.180 × 255 = 45.9 → 46. format!("{:.3}", f64::from(alpha_byte) / 255.0), ]) } fn color_entry(hex: &str) -> Result { let [red, green, blue, alpha] = channels(hex)?; Ok(format!( " {{\n\ \x20 \"color\": {{\n\ \x20 \"color-space\": \"srgb\",\n\ \x20 \"components\": {{\n\ \x20 \"alpha\": \"{alpha}\",\n\ \x20 \"blue\": \"{blue}\",\n\ \x20 \"green\": \"{green}\",\n\ \x20 \"red\": \"{red}\"\n\ \x20 }}\n\ \x20 }},\n\ \x20 \"idiom\": \"universal\"\n\ \x20 }}" )) } /// One colorset's `Contents.json`, as two-space JSON with a trailing newline. /// /// ONE colour entry, with no `appearances` key: a second entry tagged /// `luminosity: dark` is exactly what let the operating system repaint the /// app, and the app is light-only. /// /// This is CLOSE to what Xcode writes but not identical — Xcode puts spaces /// around the colon (`"key" : "value"`) and the Node generator's /// `JSON.stringify` could not, so the committed bytes carry the Node shape and /// this renderer reproduces it. Opening the catalogue in Xcode and saving it /// therefore does produce a diff, which `--check` will call drift; the fix is /// to run the generator, never to keep Xcode's copy. pub fn render_colorset(hex: &str) -> Result { Ok(format!( "{{\n \"colors\": [\n{}\n ],\n \"info\": {{\n \"author\": \"xcode\",\n \"version\": 1\n }}\n}}\n", color_entry(hex)? )) } pub fn render_catalogue_root() -> String { "{\n \"info\": {\n \"author\": \"xcode\",\n \"version\": 1\n }\n}\n".to_string() } // ── Palette.swift ───────────────────────────────────────────────────────── fn palette_body(palette: &Palette, indent: &str) -> String { PaletteSlot::ALL .iter() .map(|slot| { format!( "{indent}{}: CottonColor({})", slot.as_str(), swift_str(palette.slot(*slot)) ) }) .collect::>() .join(",\n") } fn status_body(status: &Status, indent: &str) -> String { StatusSlot::ALL .iter() .map(|slot| { format!( "{indent}{}: CottonColor({})", slot.as_str(), swift_str(status.slot(*slot)) ) }) .collect::>() .join(",\n") } fn sidebar_body(sidebar: &Sidebar, indent: &str) -> String { SidebarSlot::ALL .iter() .map(|slot| { format!( "{indent}{}: CottonColor({})", slot.as_str(), swift_str(sidebar.slot(*slot)) ) }) .collect::>() .join(",\n") } pub fn render_palette() -> String { let slot_fields = PaletteSlot::ALL .iter() .map(|slot| format!(" public let {}: CottonColor", slot.as_str())) .collect::>() .join("\n"); let status_fields = StatusSlot::ALL .iter() .map(|slot| format!(" public let {}: CottonColor", slot.as_str())) .collect::>() .join("\n"); let sidebar_fields = SidebarSlot::ALL .iter() .map(|slot| format!(" public let {}: CottonColor", slot.as_str())) .collect::>() .join("\n"); let slot_cases = PaletteSlot::ALL .iter() .map(|slot| format!(" case {}", slot.as_str())) .collect::>() .join("\n"); let status_cases = StatusSlot::ALL .iter() .map(|slot| format!(" case {}", slot.asset_name())) .collect::>() .join("\n"); let sidebar_cases = SidebarSlot::ALL .iter() .map(|slot| format!(" case {}", slot.asset_name())) .collect::>() .join("\n"); let accessors = colorsets() .iter() .map(|(asset, _)| { format!( " /// The `{asset}` colorset — one colour, because the app is light-only.\n public static var {asset}: Color {{ ColorSlot.{asset}.color }}" ) }) .collect::>() .join("\n"); let ui_accessors = colorsets() .iter() .map(|(asset, _)| { format!(" public static var {asset}: UIColor {{ ColorSlot.{asset}.uiColor }}") }) .collect::>() .join("\n"); let authored_base = PaletteSlot::ALL .iter() .map(|slot| { let name = slot.as_str(); format!(" case .{name}: return paper.{name}") }) .collect::>() .join("\n"); let authored_status = StatusSlot::ALL .iter() .map(|slot| { format!( " case .{}: return status.{}", slot.asset_name(), slot.as_str() ) }) .collect::>() .join("\n"); let authored_sidebar = SidebarSlot::ALL .iter() .map(|slot| { format!( " case .{}: return sidebar.{}", slot.asset_name(), slot.as_str() ) }) .collect::>() .join("\n"); let header = generated_header("cotton-core — design/palette.rs"); let paper = palette_body(&PAPER, " "); let graphite = palette_body(&GRAPHITE, " "); let status = status_body(&STATUS, " "); let sidebar = sidebar_body(&SIDEBAR, " "); let paper_name = swift_str(PAPER.name); let graphite_name = swift_str(GRAPHITE.name); format!( r#"{header} // // THE ONE PLACE A COLOUR MAY BE WRITTEN. Every other Swift source reads a role // off `CottonColors` (or off a `CottonPalette` handed to it); `PaletteGuardTests` // reads the sources and fails on a hex, a `Color(red:`, or a bare asset name // spelled anywhere else. // // ONE palette — `paper` — plus the status colours and the Mac sidebar's. **The app is light-only**: // there is no theme choice, no dark mode and no system-appearance switch, so a // colorset carries one colour and nothing the operating system decides can // repaint a screen. // // `graphite` is the BRAND's fixed charcoal and is not an appearance: it is read // as authored VALUES by the surfaces that are charcoal whatever the app is // doing — the app-icon tile and the ground the logo is set on. Nothing // resolves to it. // // `sidebar` is the Mac window's charcoal column — five opaque values read by // `Boot/HomeSidebar.swift` alone. Chrome, not an appearance: the content beside // it is still paper. // // The COLOUR RULE the app is bound by lives above this file and cannot be // expressed in it: monochrome plus ONE accent, colour never names a kind, and // no user-chosen colour renders anywhere. Twenty-four roles is the whole surface; // there is no twenty-fifth and no per-record tint. import SwiftUI #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif /// One colour, as the record wrote it: `#RRGGBB` or `#RRGGBBAA`. /// /// The value type exists beside the asset catalogue so a test can assert the /// NUMBERS without loading a bundle, and so a caller that needs a colour where /// no trait collection is resolvable (a snapshot, a computed blend) has one. public struct CottonColor: Equatable, Sendable {{ public let hex: String public init(_ hex: String) {{ self.hex = hex }} /// The four channels, 0…1. public var components: (red: Double, green: Double, blue: Double, alpha: Double) {{ let digits = Array(hex.dropFirst()) func channel(_ at: Int) -> Double {{ guard digits.count >= (at + 1) * 2 else {{ return 1 }} let pair = String(digits[at * 2 ... at * 2 + 1]) return Double(UInt8(pair, radix: 16) ?? 0) / 255 }} return (channel(0), channel(1), channel(2), digits.count >= 8 ? channel(3) : 1) }} public var color: Color {{ let parts = components return Color( .sRGB, red: parts.red, green: parts.green, blue: parts.blue, opacity: parts.alpha ) }} #if canImport(UIKit) public var uiColor: UIColor {{ let parts = components return UIColor( red: parts.red, green: parts.green, blue: parts.blue, alpha: parts.alpha ) }} #elseif canImport(AppKit) public var nsColor: NSColor {{ let parts = components return NSColor( srgbRed: parts.red, green: parts.green, blue: parts.blue, alpha: parts.alpha ) }} #endif }} /// The status colours. public struct CottonStatus: Equatable, Sendable {{ {status_fields} }} /// The Mac sidebar's charcoal, opaque. public struct CottonSidebar: Equatable, Sendable {{ {sidebar_fields} }} /// One palette: every role a surface can paint with. public struct CottonPalette: Equatable, Sendable {{ /// The stable registry id. public let name: String {slot_fields} public let status: CottonStatus }} /// Every colorset in `Palette.xcassets`, by name — so no call site spells one. public enum ColorSlot: String, CaseIterable, Sendable {{ {slot_cases} {status_cases} {sidebar_cases} /// The asset name, which IS the case name. Total by construction. public var assetName: String {{ rawValue }} #if canImport(UIKit) /// The colorset's colour. One value per colorset — the trait collection /// has nothing to choose between, which is what light-only means. public var color: Color {{ Color(assetName, bundle: .module) }} public var uiColor: UIColor {{ // A missing colorset is a build that shipped without its resources — // louder here than a silently black screen. guard let found = UIColor(named: assetName, in: .module, compatibleWith: nil) else {{ preconditionFailure("Palette.xcassets has no colorset named \(assetName)") }} return found }} #elseif canImport(AppKit) /// The Mac's, from the authored hex — NEVER the colorset. `Bundle.module` /// on an INSTALLED copy is a `fatalError`: the accessor looks beside the /// executable and in the build directory, and a packaged app has neither. /// And whether the catalogue is even compiled is the toolchain's choice — /// SwiftPM's Swift Build system runs actool and writes an `Assets.car`, /// the older native build system copies `Palette.xcassets` RAW, and under /// that one a colour reached by name had nothing to resolve against and /// drew as nothing (measured 2026-09-12, the phone's screens white with /// invisible ink in the Mac's window). Pictures are read through whichever /// layout the build wrote (`CottonPaper/Resources.swift`); a COLOUR needs no /// bundle at all, so the Mac reads the hex this file already carries — /// one declaration, two renderers. It is a STATIC colour: the Mac app /// pins `NSAppearance(named: .aqua)` at boot, so there is no appearance /// for a dynamic provider to answer. public var color: Color {{ Color(nsColor: nsColor) }} public var nsColor: NSColor {{ authored.nsColor }} #endif /// The authored hex for this role. public var authored: CottonColor {{ Palettes.authored(self) }} }} /// The typed accessors — `CottonColors.accent`, never `Color("accent")`. public enum CottonColors {{ {accessors} }} /// The same twenty-four as `UIColor`, for the UIKit seams (a text view's tint) /// that cannot take a SwiftUI `Color`. UIKit's only: /// since H2 this file compiles for macOS too, where the palette is `Color`. #if canImport(UIKit) public enum CottonUIColors {{ {ui_accessors} }} #endif public enum Palettes {{ /// **The app's palette, and the only one it wears.** Every colorset is /// this palette's value. public static let paper = CottonPalette( name: {paper_name}, {paper}, status: status ) /// **The brand's fixed charcoal — not an appearance and not a choice.** /// /// Nothing resolves to this. It is read as VALUES by the surfaces that are /// charcoal whatever the app is doing: the app-icon tile and the ground /// the logo is set on. public static let graphite = CottonPalette( name: {graphite_name}, {graphite}, status: status ) public static let status = CottonStatus( {status} ) /// The Mac window's sidebar: charcoal chrome beside the paper. public static let sidebar = CottonSidebar( {sidebar} ) /// The authored hex behind a colorset. Total over `ColorSlot`, which is /// what makes the catalogue and the value type unable to drift: both are /// generated from the same record, and this switch names every case. public static func authored(_ slot: ColorSlot) -> CottonColor {{ switch slot {{ {authored_base} {authored_status} {authored_sidebar} }} }} }} "# ) } #[cfg(test)] #[path = "ios_tests.rs"] mod tests;