use crate::template::Theme;
use serde_json::{Map, Value};
pub fn build_context(data: &Value, theme: &Theme) -> Value {
let mut ctx = match data {
Value::Object(map) => map.clone(),
_ => Map::new(),
};
let mut theme_obj = Map::new();
let mut tokens = Map::new();
for (key, value) in &theme.tokens {
tokens.insert(key.clone(), value.clone());
}
theme_obj.insert("tokens".to_string(), Value::Object(tokens));
theme_obj.insert("name".to_string(), Value::String(theme.name.clone()));
ctx.insert("theme".to_string(), Value::Object(theme_obj));
Value::Object(ctx)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
fn theme(tokens: &[(&str, Value)]) -> Theme {
let mut map = BTreeMap::new();
for (k, v) in tokens {
map.insert(k.to_string(), v.clone());
}
Theme {
name: "test".to_string(),
display_name: "Test".to_string(),
description: String::new(),
tokens: map,
host_config: Value::Null,
}
}
#[test]
fn test_context_has_data_fields() {
let data = serde_json::json!({"title": "Hello"});
let ctx = build_context(&data, &theme(&[]));
assert_eq!(ctx["title"], "Hello");
}
#[test]
fn test_context_has_theme_tokens() {
let theme = theme(&[("color_primary", Value::from("#0d9488"))]);
let ctx = build_context(&Value::Null, &theme);
assert_eq!(ctx["theme"]["tokens"]["color_primary"], "#0d9488");
}
#[test]
fn test_context_data_doesnt_clobber_theme() {
let data = serde_json::json!({"theme": "SHOULD_BE_OVERWRITTEN"});
let ctx = build_context(&data, &theme(&[]));
assert!(ctx["theme"].is_object());
}
}