egui_pop_model/admin/
template.rs1use serde_json::Value as Json;
8
9use super::hooks::Values;
10
11pub fn expand(template: &Json, values: &Values) -> (Json, Vec<String>) {
14 let mut missing = Vec::new();
15 let out = walk(template, values, &mut missing);
16 (out, missing)
17}
18
19fn walk(t: &Json, values: &Values, missing: &mut Vec<String>) -> Json {
20 match t {
21 Json::String(s) => {
22 if let Some(name) = s.strip_prefix("${").and_then(|r| r.strip_suffix('}'))
23 && !name.contains("${")
24 {
25 return match values.get(name) {
26 Some(v) => v.clone(),
27 None => {
28 missing.push(name.into());
29 t.clone()
30 }
31 };
32 }
33 let mut out = String::new();
34 let mut rest = s.as_str();
35 while let Some(start) = rest.find("${") {
36 out.push_str(&rest[..start]);
37 let after = &rest[start + 2..];
38 match after.find('}') {
39 Some(end) => {
40 let name = &after[..end];
41 match values.get(name) {
42 Some(Json::String(v)) => out.push_str(v),
43 Some(v) => out.push_str(&v.to_string()),
44 None => {
45 missing.push(name.into());
46 out.push_str(&rest[start..start + 3 + end]);
47 }
48 }
49 rest = &after[end + 1..];
50 }
51 None => {
52 out.push_str(&rest[start..]);
53 rest = "";
54 }
55 }
56 }
57 out.push_str(rest);
58 Json::String(out)
59 }
60 Json::Array(a) => Json::Array(a.iter().map(|x| walk(x, values, missing)).collect()),
61 Json::Object(o) => Json::Object(
62 o.iter()
63 .map(|(k, v)| (k.clone(), walk(v, values, missing)))
64 .collect(),
65 ),
66 other => other.clone(),
67 }
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73 use serde_json::json;
74
75 #[test]
76 fn templates_take_values_whole_or_as_text() {
77 let mut v = Values::new();
78 v.insert("copies".into(), json!(2));
79 v.insert("row.id".into(), json!("disk-a"));
80 let (out, missing) = expand(
81 &json!({"n": "${copies}", "volume": "${row.id}", "label": "Copy ${copies} to ${row.id}", "x": ["${none}", 3]}),
82 &v,
83 );
84 assert_eq!(
85 out,
86 json!({"n": 2, "volume": "disk-a", "label": "Copy 2 to disk-a", "x": ["${none}", 3]})
87 );
88 assert_eq!(missing, vec!["none".to_string()]);
89 }
90}