Skip to main content

egui_pop_tokens/
value.rs

1//! Token values: the DTCG types this crate reads, from their JSON form.
2
3use serde_json::{Value as Json, json};
4
5use crate::Color;
6
7/// Pixels in one `rem`, for dimensions given in `rem`.
8pub const PX_PER_REM: f32 = 16.0;
9
10/// A token's value, resolved and typed.
11#[derive(Clone, Debug, PartialEq)]
12#[non_exhaustive]
13pub enum Value {
14    /// `color`.
15    Color(Color),
16    /// `dimension`, in logical pixels.
17    Dimension(f32),
18    /// `number`.
19    Number(f32),
20    /// `duration`, in milliseconds.
21    Duration(f32),
22    /// `fontFamily`: families, the first preferred.
23    FontFamily(Vec<String>),
24    /// A type this crate does not interpret (`shadow`, `typography`, a
25    /// tool's own): the raw JSON value, kept as written.
26    Other(Json),
27}
28
29impl Value {
30    /// Reads a raw value (aliases already followed) as the given DTCG type.
31    pub fn parse(ty: &str, raw: &Json) -> Result<Value, String> {
32        match ty {
33            "color" => parse_color(raw).map(Value::Color),
34            "dimension" => parse_dimension(raw).map(Value::Dimension),
35            "number" => raw
36                .as_f64()
37                .map(|v| Value::Number(v as f32))
38                .ok_or_else(|| format!("`{raw}` is not a number")),
39            "duration" => parse_duration(raw).map(Value::Duration),
40            "fontFamily" => match raw {
41                Json::String(s) => Ok(Value::FontFamily(vec![s.clone()])),
42                Json::Array(a) => a
43                    .iter()
44                    .map(|f| {
45                        f.as_str()
46                            .map(String::from)
47                            .ok_or_else(|| format!("`{f}` is not a font family name"))
48                    })
49                    .collect::<Result<_, _>>()
50                    .map(Value::FontFamily),
51                _ => Err(format!("`{raw}` is not a font family or a list of them")),
52            },
53            _ => Ok(Value::Other(raw.clone())),
54        }
55    }
56
57    /// The value back in DTCG form (colours as hex strings, dimensions and
58    /// durations as objects).
59    pub fn to_json(&self) -> Json {
60        match self {
61            Value::Color(c) => json!(c.to_hex()),
62            Value::Dimension(d) => json!({ "value": d, "unit": "px" }),
63            Value::Number(n) => json!(n),
64            Value::Duration(ms) => json!({ "value": ms, "unit": "ms" }),
65            Value::FontFamily(f) => json!(f),
66            Value::Other(raw) => raw.clone(),
67        }
68    }
69
70    /// A short human form: `#f0c060`, `4px`, `120ms`.
71    pub fn display(&self) -> String {
72        match self {
73            Value::Color(c) => c.to_hex(),
74            Value::Dimension(d) => format!("{d}px"),
75            Value::Number(n) => format!("{n}"),
76            Value::Duration(ms) => format!("{ms}ms"),
77            Value::FontFamily(f) => f.join(", "),
78            Value::Other(raw) => raw.to_string(),
79        }
80    }
81}
82
83fn parse_color(raw: &Json) -> Result<Color, String> {
84    let bad = |why: &str| format!("`{raw}` is not a color: {why}");
85    match raw {
86        // Hex strings: the format before DTCG 2025.10, still widely used.
87        Json::String(s) => Color::from_hex(s).ok_or_else(|| bad("expected #rrggbb or #rrggbbaa")),
88        Json::Object(o) => {
89            let alpha = match o.get("alpha") {
90                None => 1.0,
91                Some(a) => a.as_f64().ok_or_else(|| bad("alpha is not a number"))? as f32,
92            };
93            let space = o.get("colorSpace").and_then(Json::as_str);
94            let components = o.get("components").and_then(Json::as_array);
95            let read = || -> Result<[f32; 3], String> {
96                let c = components
97                    .filter(|c| c.len() == 3)
98                    .ok_or_else(|| bad("expected three components"))?;
99                let mut out = [0.0; 3];
100                for (slot, v) in out.iter_mut().zip(c) {
101                    // `none` (a missing component) counts as zero.
102                    *slot = match v {
103                        Json::String(s) if s == "none" => 0.0,
104                        _ => v
105                            .as_f64()
106                            .ok_or_else(|| bad("a component is not a number"))?
107                            as f32,
108                    };
109                }
110                Ok(out)
111            };
112            let from_space = match space {
113                Some("srgb") => Some(read().map(|[r, g, b]| Color { r, g, b, a: alpha })),
114                Some("srgb-linear") => {
115                    Some(read().map(|[r, g, b]| Color::from_linear(r, g, b, alpha)))
116                }
117                Some("oklch") => Some(read().map(|[l, c, h]| Color::from_oklch(l, c, h, alpha))),
118                Some("oklab") => Some(read().map(|[l, a, b]| {
119                    Color::from_oklab(f64::from(l), f64::from(a), f64::from(b), alpha)
120                })),
121                _ => None,
122            };
123            match from_space {
124                Some(color) => color,
125                // A colour space not read here: the `hex` fallback the
126                // format provides for such readers.
127                None => o
128                    .get("hex")
129                    .and_then(Json::as_str)
130                    .and_then(Color::from_hex)
131                    .map(|c| Color { a: alpha, ..c })
132                    .ok_or_else(|| {
133                        bad(&format!(
134                            "color space {} is not read and no hex fallback is given",
135                            space.unwrap_or("(none)")
136                        ))
137                    }),
138            }
139        }
140        _ => Err(bad("expected a string or an object")),
141    }
142}
143
144fn parse_dimension(raw: &Json) -> Result<f32, String> {
145    let unit = |value: f64, unit: &str| match unit {
146        "px" => Ok(value as f32),
147        "rem" => Ok(value as f32 * PX_PER_REM),
148        other => Err(format!("`{raw}`: unit `{other}` is not px or rem")),
149    };
150    match raw {
151        Json::Object(o) => {
152            let v = o
153                .get("value")
154                .and_then(Json::as_f64)
155                .ok_or_else(|| format!("`{raw}` is not a dimension"))?;
156            unit(v, o.get("unit").and_then(Json::as_str).unwrap_or(""))
157        }
158        // `"4px"`: the format before DTCG 2025.10.
159        Json::String(s) => {
160            let split = s
161                .find(|c: char| c.is_ascii_alphabetic())
162                .ok_or_else(|| format!("`{raw}` has no unit"))?;
163            let v: f64 = s[..split]
164                .trim()
165                .parse()
166                .map_err(|_| format!("`{raw}` is not a dimension"))?;
167            unit(v, &s[split..])
168        }
169        _ => Err(format!("`{raw}` is not a dimension")),
170    }
171}
172
173fn parse_duration(raw: &Json) -> Result<f32, String> {
174    let unit = |value: f64, unit: &str| match unit {
175        "ms" => Ok(value as f32),
176        "s" => Ok(value as f32 * 1000.0),
177        other => Err(format!("`{raw}`: unit `{other}` is not ms or s")),
178    };
179    match raw {
180        Json::Object(o) => {
181            let v = o
182                .get("value")
183                .and_then(Json::as_f64)
184                .ok_or_else(|| format!("`{raw}` is not a duration"))?;
185            unit(v, o.get("unit").and_then(Json::as_str).unwrap_or(""))
186        }
187        Json::String(s) => {
188            let split = s
189                .find(|c: char| c.is_ascii_alphabetic())
190                .ok_or_else(|| format!("`{raw}` has no unit"))?;
191            let v: f64 = s[..split]
192                .trim()
193                .parse()
194                .map_err(|_| format!("`{raw}` is not a duration"))?;
195            unit(v, &s[split..])
196        }
197        _ => Err(format!("`{raw}` is not a duration")),
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn colors_in_every_accepted_form() {
207        let c = |raw: Json| Value::parse("color", &raw);
208        let gold = Value::Color(Color::from_hex("#f0c060").unwrap());
209        assert_eq!(c(json!("#f0c060")), Ok(gold.clone()));
210        assert_eq!(
211            c(json!({"colorSpace": "srgb", "components": [1, 0, 0], "alpha": 0.5})),
212            Ok(Value::Color(Color {
213                a: 0.5,
214                ..Color::rgb(1.0, 0.0, 0.0)
215            }))
216        );
217        let Ok(Value::Color(oklch)) =
218            c(json!({"colorSpace": "oklch", "components": [0.832, 0.126, 83]}))
219        else {
220            panic!("oklch is read");
221        };
222        assert_eq!(oklch.to_hex(), "#f0c060");
223        assert_eq!(
224            c(json!({"colorSpace": "display-p3", "components": [1, 0, 0], "hex": "#f0c060"})),
225            Ok(gold)
226        );
227        assert!(c(json!({"colorSpace": "display-p3", "components": [1, 0, 0]})).is_err());
228        assert!(c(json!(12)).is_err());
229    }
230
231    #[test]
232    fn dimensions_and_durations() {
233        assert_eq!(
234            Value::parse("dimension", &json!({"value": 4, "unit": "px"})),
235            Ok(Value::Dimension(4.0))
236        );
237        assert_eq!(
238            Value::parse("dimension", &json!({"value": 0.5, "unit": "rem"})),
239            Ok(Value::Dimension(8.0))
240        );
241        assert_eq!(
242            Value::parse("dimension", &json!("6px")),
243            Ok(Value::Dimension(6.0))
244        );
245        assert!(Value::parse("dimension", &json!("6em")).is_err());
246        assert_eq!(
247            Value::parse("duration", &json!({"value": 0.2, "unit": "s"})),
248            Ok(Value::Duration(200.0))
249        );
250        assert_eq!(
251            Value::parse("duration", &json!("120ms")),
252            Ok(Value::Duration(120.0))
253        );
254    }
255
256    #[test]
257    fn unknown_types_are_kept_raw() {
258        let shadow = json!({"color": "#000000", "offsetX": "1px"});
259        assert_eq!(Value::parse("shadow", &shadow), Ok(Value::Other(shadow)));
260    }
261}