Skip to main content

egui_pop_tokens/
file.rs

1//! Token files: the DTCG tree (JSON or YAML) read into a flat map of tokens by path.
2
3use std::collections::BTreeMap;
4use std::path::Path;
5
6use serde_json::{Map, Value as Json};
7
8use crate::Error;
9use crate::cache::{Cache, CacheError, Compiler};
10
11/// What compiles a YAML token file into the JSON tree the cache keeps:
12/// its version is this crate's with a revision (raised when the tree a
13/// file compiles to changes), so a new egui-pop ignores the entries of
14/// the one before.
15pub const TOKENS_COMPILER: Compiler<'static> = Compiler {
16    name: "tokens",
17    version: concat!(env!("CARGO_PKG_VERSION"), "+1"),
18};
19
20/// A token as written in a file: its value may still be an alias.
21#[derive(Clone, Debug, PartialEq)]
22pub struct RawToken {
23    /// `$type`, given on the token or inherited from a group.
24    pub ty: Option<String>,
25    /// `$value`, as written.
26    pub value: Json,
27    /// `$description`.
28    pub description: Option<String>,
29    /// `$extensions`, kept as written.
30    pub extensions: Option<Json>,
31}
32
33impl RawToken {
34    /// The path this token aliases, when its value is a whole-value
35    /// reference such as `"{gray.2}"`.
36    pub fn alias(&self) -> Option<&str> {
37        alias_target(&self.value)
38    }
39}
40
41/// The path a whole-value reference (`"{gray.2}"`) names.
42pub fn alias_target(value: &Json) -> Option<&str> {
43    let target = value.as_str()?.strip_prefix('{')?.strip_suffix('}')?;
44    (!target.is_empty() && !target.contains(['{', '}'])).then_some(target)
45}
46
47/// A token file: a theme, a density overlay or any other layer.
48///
49/// Its tokens are keyed by their dotted path (`surface.panel`). At the
50/// root, `$extends` names the theme this file builds on (every token not
51/// given here comes from it), `$description` describes the file and
52/// `$extensions` is kept as written.
53#[derive(Clone, Debug, PartialEq)]
54pub struct TokenFile {
55    pub name: String,
56    pub description: Option<String>,
57    pub extends: Option<String>,
58    /// The root `$extensions`, kept as written.
59    pub extensions: Option<Json>,
60    pub tokens: BTreeMap<String, RawToken>,
61}
62
63impl TokenFile {
64    /// An empty file, to fill by hand.
65    pub fn new(name: impl Into<String>) -> TokenFile {
66        TokenFile {
67            name: name.into(),
68            description: None,
69            extends: None,
70            extensions: None,
71            tokens: BTreeMap::new(),
72        }
73    }
74
75    /// Reads a token file under the given name: JSON when its text
76    /// starts with `{`, YAML otherwise (the same tree, with comments).
77    pub fn parse(name: &str, text: &str) -> Result<TokenFile, Error> {
78        let root: Json = if crate::yaml::is_json(text) {
79            json(name, text.as_bytes())?
80        } else {
81            crate::yaml::parse(name, text)?
82        };
83        TokenFile::from_tree(name, &root)
84    }
85
86    /// [`TokenFile::parse`] for a file read from `source`, its YAML
87    /// compiled through a cache ([`crate::cache`]): on a hit the JSON the
88    /// YAML was compiled to is read; on a miss or a stale entry the YAML
89    /// is parsed (its problems are the error, and are not cached) and its
90    /// JSON kept. JSON files are read as they are. The second value is
91    /// the entry that could not be written: the file is read uncached.
92    pub fn parse_cached(
93        name: &str,
94        text: &str,
95        source: &Path,
96        cache: &Cache,
97    ) -> (Result<TokenFile, Error>, Option<CacheError>) {
98        if !cache.is_on() || crate::yaml::is_json(text) {
99            return (TokenFile::parse(name, text), None);
100        }
101        let contents = text.as_bytes();
102        if let Some(compiled) = cache.get(&TOKENS_COMPILER, source, contents)
103            && let Ok(root) = json(name, &compiled)
104        {
105            return (TokenFile::from_tree(name, &root), None);
106        }
107        let root = match crate::yaml::parse(name, text) {
108            Ok(root) => root,
109            Err(e) => return (Err(e), None),
110        };
111        let unwritten = serde_json::to_vec(&root)
112            .ok()
113            .and_then(|bytes| cache.put(&TOKENS_COMPILER, source, contents, &bytes).err());
114        (TokenFile::from_tree(name, &root), unwritten)
115    }
116
117    /// Reads a token file from disk under the given name, its YAML
118    /// through a cache ([`TokenFile::parse_cached`]).
119    pub fn read(
120        name: &str,
121        path: &Path,
122        cache: &Cache,
123    ) -> (Result<TokenFile, Error>, Option<CacheError>) {
124        match std::fs::read_to_string(path) {
125            Ok(text) => TokenFile::parse_cached(name, &text, path, cache),
126            Err(e) => (
127                Err(Error::Io {
128                    file: path.display().to_string(),
129                    message: e.to_string(),
130                }),
131                None,
132            ),
133        }
134    }
135
136    /// A token file from its tree (DTCG, as JSON).
137    pub(crate) fn from_tree(name: &str, root: &Json) -> Result<TokenFile, Error> {
138        let obj = root.as_object().ok_or_else(|| Error::Malformed {
139            file: name.to_string(),
140            path: String::new(),
141            reason: "the root is not a map of groups and tokens".into(),
142        })?;
143        let mut tokens = BTreeMap::new();
144        walk(name, obj, "", None, &mut tokens)?;
145        let extends = match obj.get("$extends") {
146            None => None,
147            Some(Json::String(s)) => Some(s.clone()),
148            Some(other) => {
149                return Err(Error::Malformed {
150                    file: name.to_string(),
151                    path: "$extends".into(),
152                    reason: format!("`{other}` is not a theme name"),
153                });
154            }
155        };
156        Ok(TokenFile {
157            name: name.to_string(),
158            description: obj
159                .get("$description")
160                .and_then(Json::as_str)
161                .map(String::from),
162            extends,
163            extensions: obj.get("$extensions").cloned(),
164            tokens,
165        })
166    }
167}
168
169impl TokenFile {
170    /// The file as DTCG JSON: `$description`, `$extends` and
171    /// `$extensions` at the root, then each token nested in groups by
172    /// its path, with its `$type`, `$value`, `$description` and
173    /// `$extensions`. [`TokenFile::parse`] reads it back as it was.
174    pub fn to_json(&self) -> Json {
175        let mut root = Map::new();
176        if let Some(d) = &self.description {
177            root.insert("$description".into(), Json::String(d.clone()));
178        }
179        if let Some(e) = &self.extends {
180            root.insert("$extends".into(), Json::String(e.clone()));
181        }
182        if let Some(x) = &self.extensions {
183            root.insert("$extensions".into(), x.clone());
184        }
185        for (path, token) in &self.tokens {
186            let parts: Vec<&str> = path.split('.').collect();
187            let Some((leaf, groups)) = parts.split_last() else {
188                continue;
189            };
190            let mut node = &mut root;
191            for part in groups {
192                let child = node
193                    .entry((*part).to_string())
194                    .or_insert_with(|| Json::Object(Map::new()));
195                if !child.is_object() {
196                    *child = Json::Object(Map::new());
197                }
198                let Json::Object(map) = child else {
199                    unreachable!("made an object above")
200                };
201                node = map;
202            }
203            let mut entry = Map::new();
204            if let Some(ty) = &token.ty {
205                entry.insert("$type".into(), Json::String(ty.clone()));
206            }
207            entry.insert("$value".into(), token.value.clone());
208            if let Some(d) = &token.description {
209                entry.insert("$description".into(), Json::String(d.clone()));
210            }
211            if let Some(x) = &token.extensions {
212                entry.insert("$extensions".into(), x.clone());
213            }
214            node.insert((*leaf).to_string(), Json::Object(entry));
215        }
216        Json::Object(root)
217    }
218
219    /// [`TokenFile::to_json`], indented for people.
220    pub fn to_json_pretty(&self) -> String {
221        serde_json::to_string_pretty(&self.to_json()).unwrap_or_default()
222    }
223}
224
225fn json(name: &str, bytes: &[u8]) -> Result<Json, Error> {
226    serde_json::from_slice(bytes).map_err(|e| Error::Json {
227        file: name.to_string(),
228        message: e.to_string(),
229    })
230}
231
232fn walk(
233    file: &str,
234    obj: &Map<String, Json>,
235    prefix: &str,
236    group_type: Option<&str>,
237    out: &mut BTreeMap<String, RawToken>,
238) -> Result<(), Error> {
239    let own_type = obj.get("$type").and_then(Json::as_str).or(group_type);
240    for (key, v) in obj {
241        if key.starts_with('$') {
242            continue;
243        }
244        let path = if prefix.is_empty() {
245            key.clone()
246        } else {
247            format!("{prefix}.{key}")
248        };
249        let malformed = |reason: &str| Error::Malformed {
250            file: file.to_string(),
251            path: path.clone(),
252            reason: reason.to_string(),
253        };
254        if key.contains(['.', '{', '}']) {
255            return Err(malformed("names may not contain `.`, `{` or `}`"));
256        }
257        let Some(child) = v.as_object() else {
258            return Err(malformed("is neither a token (with $value) nor a group"));
259        };
260        if let Some(value) = child.get("$value") {
261            out.insert(
262                path,
263                RawToken {
264                    ty: child
265                        .get("$type")
266                        .and_then(Json::as_str)
267                        .or(own_type)
268                        .map(String::from),
269                    value: value.clone(),
270                    description: child
271                        .get("$description")
272                        .and_then(Json::as_str)
273                        .map(String::from),
274                    extensions: child.get("$extensions").cloned(),
275                },
276            );
277        } else {
278            walk(file, child, &path, own_type, out)?;
279        }
280    }
281    Ok(())
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use serde_json::json;
288
289    #[test]
290    fn groups_flatten_and_pass_their_type_down() {
291        let f = TokenFile::parse(
292            "t",
293            r##"{
294              "$description": "a test",
295              "$extensions": { "org.example": { "kept": true } },
296              "gray": { "$type": "color", "$description": "a scale",
297                        "1": { "$value": "#111111", "$extensions": { "org.example": 1 } } },
298              "space": { "s": { "$type": "dimension", "$value": "4px", "$description": "small" } },
299              "alias": { "$value": "{gray.1}" }
300            }"##,
301        )
302        .unwrap();
303        assert_eq!(f.description.as_deref(), Some("a test"));
304        assert_eq!(
305            f.extensions,
306            Some(json!({ "org.example": { "kept": true } }))
307        );
308        let gray = &f.tokens["gray.1"];
309        assert_eq!(gray.ty.as_deref(), Some("color"));
310        assert_eq!(gray.extensions, Some(json!({ "org.example": 1 })));
311        assert_eq!(f.tokens["space.s"].description.as_deref(), Some("small"));
312        assert_eq!(f.tokens["alias"].alias(), Some("gray.1"));
313        assert_eq!(f.tokens["alias"].ty, None);
314        assert_eq!(f.tokens.len(), 3);
315    }
316
317    #[test]
318    fn malformed_files_say_where() {
319        let err = TokenFile::parse("t", r#"{ "a": { "b": 3 } }"#).unwrap_err();
320        assert!(
321            matches!(err, Error::Malformed { ref path, .. } if path == "a.b"),
322            "{err}"
323        );
324        assert!(matches!(
325            TokenFile::parse("t", "[1]"),
326            Err(Error::Malformed { .. })
327        ));
328        assert!(matches!(
329            TokenFile::parse("t", "{"),
330            Err(Error::Json { .. })
331        ));
332        assert!(matches!(
333            TokenFile::parse("t", r#"{ "a.b": { "$value": 1 } }"#),
334            Err(Error::Malformed { .. })
335        ));
336    }
337
338    #[test]
339    fn a_file_written_out_reads_back_the_same() {
340        let text = r##"{
341          "$description": "edited",
342          "$extends": "pop-dark",
343          "$extensions": { "org.example": { "version": 1 } },
344          "surface": { "$type": "color", "panel": { "$value": "#101010", "$description": "panels" } },
345          "radius": { "widget": { "$type": "dimension", "$value": { "value": 2, "unit": "px" } } },
346          "focus": { "ring": { "$type": "color", "$value": "{blue.9}" } }
347        }"##;
348        let f = TokenFile::parse("t", text).unwrap();
349        let back = TokenFile::parse("t", &f.to_json_pretty()).unwrap();
350        assert_eq!(back, f);
351        assert_eq!(back.extends.as_deref(), Some("pop-dark"));
352        assert_eq!(back.tokens["focus.ring"].alias(), Some("blue.9"));
353    }
354
355    #[test]
356    fn only_whole_value_references_are_aliases() {
357        assert_eq!(alias_target(&json!("{a.b}")), Some("a.b"));
358        assert_eq!(alias_target(&json!("{}")), None);
359        assert_eq!(alias_target(&json!("x{a}")), None);
360        assert_eq!(alias_target(&json!(3)), None);
361    }
362}