1use std::collections::HashMap;
18
19use crate::{Color, Theme};
20
21#[derive(Clone, Debug, PartialEq)]
23pub struct PaletteColor {
24 pub dark: String,
25 pub light: String,
26}
27
28impl PaletteColor {
29 pub fn same(spec: impl Into<String>) -> Self {
30 let spec = spec.into();
31 Self { dark: spec.clone(), light: spec }
32 }
33
34 pub fn by_mode(dark: impl Into<String>, light: impl Into<String>) -> Self {
35 Self { dark: dark.into(), light: light.into() }
36 }
37
38 pub fn for_theme(&self, dark: bool) -> &str {
40 if dark { &self.dark } else { &self.light }
41 }
42}
43
44pub type Palette = Vec<(String, PaletteColor)>;
46
47pub fn resolve_in(colors: &HashMap<String, Color>, spec: &str) -> Option<Color> {
49 let spec = spec.trim();
50 let (name, alpha) = match spec.rsplit_once('/') {
51 Some((name, pct)) => (name.trim(), Some(pct.trim().trim_end_matches('%').parse::<f32>().ok()? / 100.0)),
52 None => (spec, None),
53 };
54 let base = match name {
57 _ if name.starts_with('#') => Color::from_hex(name),
58 "white" => Some(Color::WHITE),
59 "black" => Some(Color::rgb(0, 0, 0)),
60 "transparent" => Some(Color::TRANSPARENT),
61 _ => colors.get(name).copied().or_else(|| colors.get(&name.replace('-', "_")).copied()),
62 }?;
63 Some(match alpha {
64 Some(a) => base.with_opacity(a.clamp(0.0, 1.0)),
65 None => base,
66 })
67}
68
69pub fn is_named(spec: &str) -> bool {
71 let s = spec.trim();
72 !s.is_empty() && !s.starts_with('#')
73}
74
75impl Theme {
76 pub fn resolve_color(&self, spec: &str) -> Option<Color> {
78 resolve_in(&self.colors, spec)
79 }
80
81 pub fn unknown_color_tokens(&self) -> Vec<(String, String)> {
85 let mut out = Vec::new();
86 for (key, style) in &self.styles {
87 for props in [&style.base, &style.hover, &style.pressed, &style.focused, &style.checked, &style.disabled] {
88 for c in [&props.fill, &props.text, &props.border_color].into_iter().flatten() {
89 if let crate::theme::ColorRef::Token(name) = c
90 && name != "transparent"
91 && self.resolve_color(name).is_none()
92 && !out.iter().any(|(k, n)| k == key && n == name)
93 {
94 out.push((key.clone(), name.clone()));
95 }
96 }
97 }
98 }
99 out.sort();
100 out
101 }
102
103 pub fn apply_palette(&mut self, palette: &Palette) {
106 let mut pending: Vec<&(String, PaletteColor)> = palette.iter().collect();
107 while !pending.is_empty() {
108 let before = pending.len();
109 pending.retain(|(name, color)| {
110 let spec = color.for_theme(self.dark);
111 match self.resolve_color(spec) {
113 Some(c) => {
114 self.colors.insert(name.clone(), c);
115 false
116 }
117 None => true,
118 }
119 });
120 if pending.len() == before {
121 break;
122 }
123 }
124 }
125}