1use 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
11pub const TOKENS_COMPILER: Compiler<'static> = Compiler {
16 name: "tokens",
17 version: concat!(env!("CARGO_PKG_VERSION"), "+1"),
18};
19
20#[derive(Clone, Debug, PartialEq)]
22pub struct RawToken {
23 pub ty: Option<String>,
25 pub value: Json,
27 pub description: Option<String>,
29 pub extensions: Option<Json>,
31}
32
33impl RawToken {
34 pub fn alias(&self) -> Option<&str> {
37 alias_target(&self.value)
38 }
39}
40
41pub 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#[derive(Clone, Debug, PartialEq)]
54pub struct TokenFile {
55 pub name: String,
56 pub description: Option<String>,
57 pub extends: Option<String>,
58 pub extensions: Option<Json>,
60 pub tokens: BTreeMap<String, RawToken>,
61}
62
63impl TokenFile {
64 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 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 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 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 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 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 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}