1use std::collections::HashMap;
16use std::sync::LazyLock;
17
18use serde::Deserialize;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
22#[serde(rename_all = "lowercase")]
23pub enum Neutral {
24 Black,
25 White,
26}
27
28#[derive(Debug, Clone, Deserialize)]
29pub struct Slot {
30 pub id: String,
32 pub name: String,
33 #[serde(default)]
35 pub hue: Option<f64>,
36 #[serde(default)]
38 pub neutral: Option<Neutral>,
39 pub hex: String,
41}
42
43#[derive(Deserialize)]
46struct Retired {
47 ids: HashMap<String, String>,
48 hexes: HashMap<String, String>,
49}
50
51#[derive(Deserialize)]
52struct PaletteFile {
53 slots: Vec<Slot>,
54 retired: Retired,
55}
56
57static PALETTE: LazyLock<PaletteFile> = LazyLock::new(|| {
58 serde_json::from_str(include_str!("../../../../schema/color-palette.json")).expect("schema/color-palette.json parses")
59});
60
61const NEUTRAL_MAX_CHROMA: f64 = 0.02;
64const NEUTRAL_SPLIT_LIGHTNESS: f64 = 0.5;
66
67pub fn slots() -> &'static [Slot] {
69 &PALETTE.slots
70}
71
72fn hue_slots() -> impl Iterator<Item = (&'static Slot, f64)> {
75 slots().iter().filter_map(|s| s.hue.map(|h| (s, h)))
76}
77
78fn current(id: &str) -> Option<&'static Slot> {
79 slots().iter().find(|s| s.id == id)
80}
81
82pub fn slot_by_id(id: &str) -> Option<&'static Slot> {
85 let id = id.trim().to_ascii_lowercase();
86 current(&id).or_else(|| PALETTE.retired.ids.get(&id).and_then(|now| current(now)))
87}
88
89fn srgb_to_linear(c: f64) -> f64 {
90 if c <= 0.04045 {
91 c / 12.92
92 } else {
93 ((c + 0.055) / 1.055).powf(2.4)
94 }
95}
96
97fn oklch(hex: &str) -> Option<(f64, f64, f64)> {
100 let hex = hex.trim();
101 let b = hex.as_bytes();
102 if b.len() != 7 || b[0] != b'#' || !b[1..].iter().all(u8::is_ascii_hexdigit) {
103 return None;
104 }
105 let ch = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).map(|v| srgb_to_linear(f64::from(v) / 255.0));
106 let (r, g, bl) = (ch(1).ok()?, ch(3).ok()?, ch(5).ok()?);
107 let l = (0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * bl).cbrt();
108 let m = (0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * bl).cbrt();
109 let s = (0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * bl).cbrt();
110 let lightness = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
111 let a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
112 let bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
113 let h = bb.atan2(a).to_degrees();
114 Some((lightness, a.hypot(bb), if h < 0.0 { h + 360.0 } else { h }))
115}
116
117pub fn oklch_hue(hex: &str) -> Option<f64> {
121 oklch(hex).map(|(_, _, h)| h)
122}
123
124pub fn hue_distance(a: f64, b: f64) -> f64 {
126 ((a - b + 540.0).rem_euclid(360.0) - 180.0).abs()
127}
128
129fn nearest_hue_slot(hue: f64) -> &'static Slot {
130 let mut best = &slots()[0];
131 let mut best_d = f64::MAX;
132 for (s, h) in hue_slots() {
133 let d = hue_distance(hue, h);
134 if d < best_d {
135 best_d = d;
136 best = s;
137 }
138 }
139 best
140}
141
142pub fn snap_hex(hex: &str) -> Option<&'static Slot> {
149 let (l, c, h) = oklch(hex)?;
150 if let Some(now) = PALETTE.retired.hexes.get(&hex.trim().to_ascii_lowercase()) {
151 return current(now);
152 }
153 if c < NEUTRAL_MAX_CHROMA {
154 return current(if l < NEUTRAL_SPLIT_LIGHTNESS { "black" } else { "white" });
155 }
156 Some(nearest_hue_slot(h))
157}
158
159fn fnv1a(id: &str) -> u64 {
160 let mut hash: u64 = 0xcbf29ce484222325;
161 for b in id.as_bytes() {
162 hash ^= u64::from(*b);
163 hash = hash.wrapping_mul(0x100000001b3);
164 }
165 hash
166}
167
168fn usage<S: AsRef<str>>(taken: impl IntoIterator<Item = S>) -> Vec<usize> {
171 let hues: Vec<&'static Slot> = hue_slots().map(|(s, _)| s).collect();
172 let mut counts = vec![0usize; hues.len()];
173 for hex in taken {
174 let Some(slot) = snap_hex(hex.as_ref()) else { continue };
175 if let Some(i) = hues.iter().position(|s| s.id == slot.id) {
176 counts[i] += 1;
177 }
178 }
179 counts
180}
181
182pub fn pick_slot<S: AsRef<str>>(agent_id: &str, taken: impl IntoIterator<Item = S>) -> &'static Slot {
188 let hues: Vec<&'static Slot> = hue_slots().map(|(s, _)| s).collect();
189 let n = hues.len();
190 let counts = usage(taken);
191 let min = counts.iter().copied().min().unwrap_or(0);
192 let start = (fnv1a(agent_id) % n as u64) as usize;
193 let i = (0..n).map(|k| (start + k) % n).find(|&i| counts[i] == min).unwrap_or(start);
194 hues[i]
195}
196
197pub fn farthest_free_slot<S: AsRef<str>>(
201 used: impl IntoIterator<Item = S>,
202) -> &'static Slot {
203 let all: Vec<(&'static Slot, f64)> = hue_slots().collect();
204 let counts = usage(used);
205 let min = counts.iter().copied().min().unwrap_or(0);
206 let taken: Vec<f64> = (0..all.len()).filter(|&i| counts[i] > 0).map(|i| all[i].1).collect();
207 let nearest = |hue: f64| taken.iter().map(|t| hue_distance(hue, *t)).fold(f64::MAX, f64::min);
208 let mut best = 0;
209 let mut best_d = -1.0;
210 for i in (0..all.len()).filter(|&i| counts[i] == min) {
211 let d = if taken.is_empty() { 0.0 } else { nearest(all[i].1) };
212 if d > best_d + 1e-9 {
213 best_d = d;
214 best = i;
215 }
216 }
217 all[best].0
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223
224 const THE_16: [(&str, &str, &str); 16] = [
226 ("crimson", "#e8777f", "red"),
227 ("red", "#e87b64", "red"),
228 ("orange", "#e28247", "orange"),
229 ("amber", "#d48d24", "amber"),
230 ("yellow", "#bb9c12", "yellow"),
231 ("lime", "#9aa932", "yellow"),
232 ("green", "#75b255", "green"),
233 ("jade", "#47b777", "jade"),
234 ("teal", "#00b89e", "teal"),
235 ("cyan", "#00b4be", "teal"),
236 ("sky", "#00aedd", "sky"),
237 ("azure", "#53a3f2", "blue"),
238 ("indigo", "#8297f5", "violet"),
239 ("violet", "#ae88e7", "violet"),
240 ("magenta", "#ce7cc8", "magenta"),
241 ("pink", "#e276a0", "rose"),
242 ];
243
244 fn id_of(hex: &str) -> Option<&'static str> {
245 snap_hex(hex).map(|s| s.id.as_str())
246 }
247
248 #[test]
249 fn twelve_hues_in_hue_order_then_black_and_white() {
250 let s = slots();
251 assert_eq!(s.len(), 14);
252 let hues: Vec<f64> = hue_slots().map(|(_, h)| h).collect();
253 assert_eq!(hues.len(), 12);
254 for w in hues.windows(2) {
255 assert!(w[0] < w[1], "{} before {}", w[0], w[1]);
256 }
257 assert!(s[..12].iter().all(|x| x.hue.is_some() && x.neutral.is_none()), "the hues come first");
258 assert_eq!((s[12].id.as_str(), s[12].neutral, s[12].hex.as_str()), ("black", Some(Neutral::Black), "#000000"));
259 assert_eq!((s[13].id.as_str(), s[13].neutral, s[13].hex.as_str()), ("white", Some(Neutral::White), "#ffffff"));
260 assert!(s[12..].iter().all(|x| x.hue.is_none()));
261 let mut ids: Vec<_> = s.iter().map(|x| x.id.as_str()).collect();
262 ids.sort_unstable();
263 ids.dedup();
264 assert_eq!(ids.len(), 14, "ids are unique");
265 for x in s {
266 assert!(oklch_hue(&x.hex).is_some(), "{} has a valid hex", x.id);
267 assert_eq!(x.id, x.name.to_ascii_lowercase());
268 }
269 }
270
271 #[test]
272 fn each_hex_snaps_back_to_its_own_slot_and_a_hue_within_half_a_degree() {
273 for x in slots() {
274 assert_eq!(id_of(&x.hex), Some(x.id.as_str()));
275 if let Some(hue) = x.hue {
276 assert!(hue_distance(oklch_hue(&x.hex).unwrap(), hue) < 0.5, "{}", x.id);
277 }
278 }
279 }
280
281 #[test]
282 fn the_sixteen_before_go_where_the_spec_says_by_hex_and_by_id() {
283 for (id, hex, now) in THE_16 {
284 assert_eq!(id_of(hex), Some(now), "{id} {hex}");
285 assert_eq!(id_of(&hex.to_uppercase()), Some(now), "{id} in upper case");
286 assert_eq!(slot_by_id(id).map(|s| s.id.as_str()), Some(now), "{id}");
287 }
288 assert_eq!(slot_by_id(" Azure ").map(|s| s.id.as_str()), Some("blue"));
289 assert!(slot_by_id("mauve").is_none());
290 for now in PALETTE.retired.ids.values().chain(PALETTE.retired.hexes.values()) {
292 assert!(current(now).is_some(), "{now}");
293 }
294 assert_eq!(PALETTE.retired.hexes.len(), 16);
295 }
296
297 #[test]
298 fn the_older_tailwind_colours_keep_their_meaning() {
299 let old = [
300 "#ef4444", "#f97316", "#f59e0b", "#eab308", "#84cc16", "#22c55e", "#14b8a6", "#06b6d4", "#3b82f6",
301 "#6366f1", "#8b5cf6", "#d946ef", "#ec4899", "#f43f5e",
302 ];
303 for hex in old {
304 assert!(snap_hex(hex).unwrap().hue.is_some(), "{hex} is a hue");
305 }
306 assert_eq!(id_of("#14b8a6"), Some("teal"));
308 assert_eq!(id_of("#ec4899"), Some("rose"));
309 assert_eq!(id_of("#a855f7"), Some("violet"));
310 assert_eq!(id_of("#f59e0b"), Some("amber"));
311 assert_eq!(id_of("#3b82f6"), Some("blue"));
312 }
313
314 #[test]
315 fn a_grey_is_black_or_white_and_a_faint_colour_is_still_a_hue() {
316 assert_eq!(id_of("#000000"), Some("black"));
317 assert_eq!(id_of("#ffffff"), Some("white"));
318 assert_eq!(id_of("#FFFFFF"), Some("white"));
319 assert_eq!(id_of("#1a1a1a"), Some("black"));
320 assert_eq!(id_of("#808080"), Some("white"), "a mid grey is nearer White in lightness");
321 assert_eq!(id_of("#5b5b5b"), Some("black"));
322 assert_eq!(id_of("#64748b"), Some("blue"));
324 }
325
326 #[test]
327 fn junk_is_not_a_colour() {
328 for bad in ["", "#fff", "red", "#gggggg", "#3b82f6; }", "3b82f6", "#3B82F66"] {
329 assert!(snap_hex(bad).is_none(), "{bad}");
330 }
331 assert!(snap_hex("#3B82F6").is_some(), "upper case is fine");
332 }
333
334 #[test]
335 fn pick_is_deterministic_and_never_a_neutral() {
336 let none: [&str; 0] = [];
337 for id in ["a", "b", "0d5b45f1-9b2c-4a7e-8f3d-1234567890ab", ""] {
338 let p = pick_slot(id, none);
339 assert_eq!(p.id, pick_slot(id, none).id);
340 assert!(p.hue.is_some(), "{id} got {}", p.id);
341 }
342 for i in 0..200 {
343 assert!(pick_slot(&format!("agent-{i}"), none).neutral.is_none());
344 }
345 }
346
347 #[test]
348 fn twenty_five_agents_use_no_hue_more_than_three_times() {
349 let mut taken: Vec<String> = Vec::new();
350 for i in 0..25 {
351 taken.push(pick_slot(&format!("agent-{i}"), &taken).hex.clone());
352 }
353 let counts = usage(&taken);
354 assert_eq!(counts.len(), 12);
355 assert!(counts.iter().all(|c| *c <= 3), "{counts:?}");
356 assert_eq!(usage(&taken[..12]).iter().filter(|c| **c == 1).count(), 12);
358 }
359
360 #[test]
361 fn a_black_or_white_agent_counts_against_no_hue() {
362 assert_eq!(usage(["#000000", "#ffffff", "#808080"]), vec![0; 12]);
363 let none: [&str; 0] = [];
364 assert_eq!(pick_slot("someone", ["#000000", "#ffffff"]).id, pick_slot("someone", none).id);
365 }
366
367 #[test]
368 fn a_new_profile_takes_an_unused_hue_far_from_the_used_ones() {
369 let none: [&str; 0] = [];
370 assert_eq!(farthest_free_slot(none).id, "rose");
371 let first = farthest_free_slot(none);
372 let second = farthest_free_slot([first.hex.as_str()]);
373 assert!(hue_distance(first.hue.unwrap(), second.hue.unwrap()) > 150.0, "{} then {}", first.id, second.id);
374 let used: Vec<&str> = slots().iter().filter(|s| s.id != "jade").map(|s| s.hex.as_str()).collect();
376 assert_eq!(farthest_free_slot(used).id, "jade");
377 let hues: Vec<&str> = hue_slots().map(|(s, _)| s.hex.as_str()).collect();
379 assert!(farthest_free_slot(hues).hue.is_some());
380 assert!(farthest_free_slot(["#000000"]).hue.is_some());
381 }
382
383 #[test]
384 fn hue_distance_wraps() {
385 assert!((hue_distance(357.0, 17.0) - 20.0).abs() < 1e-9);
386 assert!((hue_distance(10.0, 190.0) - 180.0).abs() < 1e-9);
387 }
388}