use std::collections::BTreeMap;
#[derive(Debug, thiserror::Error)]
pub enum TokenLoadError {
#[error("invalid JSON: {0}")]
Parse(#[from] serde_json::Error),
#[error("{path}: unknown token path")]
UnknownPath { path: String },
#[error("{path}: alias {alias:?} does not resolve to any known token")]
BadAlias { path: String, alias: String },
#[error("{path}: alias cycle: {cycle}")]
AliasCycle { path: String, cycle: String },
#[error("{path}: expected {expected}, found {found}")]
WrongType { path: String, expected: &'static str, found: String },
#[error("{path}: invalid colour value {value:?}: {source}")]
InvalidColor {
path: String,
value: String,
#[source]
source: crate::tokens::color::ColorParseError,
},
#[error("{path}: token set does not define this required token")]
MissingRequired { path: String },
#[error("{path}: color/geometry tokens must not alias app.* (found {alias:?})")]
CoreAliasIntoApp { path: String, alias: String },
#[error("{path}: no app token at this path")]
AppTokenMissing { path: String },
}
#[derive(Debug, Clone)]
pub(crate) enum TokenNodeRaw {
Group(BTreeMap<String, TokenNodeRaw>),
Leaf(TokenLeafRaw),
}
#[derive(Debug, Clone)]
pub(crate) struct TokenLeafRaw {
pub value: RawValue,
pub type_hint: Option<String>,
pub modifier: Option<ModifierRaw>,
}
#[derive(Debug, Clone)]
pub(crate) enum RawValue {
Alias(String),
String(String),
Number(f64),
}
#[derive(Debug, Clone)]
pub(crate) enum ModifierRaw {
Alpha(f32),
Mix { with: String, t: f32 },
}
#[derive(Debug, Clone, Default)]
pub(crate) struct TokenFileRaw {
pub name: Option<String>,
pub leaves: BTreeMap<String, TokenLeafRaw>,
pub component: BTreeMap<(String, String), TokenLeafRaw>,
}
impl TokenFileRaw {
pub(crate) fn parse(json: &str) -> Result<Self, TokenLoadError> {
let value: serde_json::Value = serde_json::from_str(json)?;
let root = value.as_object().ok_or_else(|| TokenLoadError::WrongType {
path: "<root>".to_string(),
expected: "object",
found: describe_kind(&value),
})?;
let mut name = None;
let mut leaves = BTreeMap::new();
let mut component = BTreeMap::new();
for (key, val) in root {
if let Some(meta) = key.strip_prefix('$') {
if meta == "name" {
let s = val.as_str().ok_or_else(|| TokenLoadError::WrongType {
path: "$name".to_string(),
expected: "string",
found: describe_kind(val),
})?;
name = Some(s.to_string());
}
continue;
}
match key.as_str() {
"color" => flatten("color", node_from_json("color", val)?, &mut leaves),
"geometry" => flatten("geometry", node_from_json("geometry", val)?, &mut leaves),
"app" => flatten("app", node_from_json("app", val)?, &mut leaves),
"component" => parse_component(val, &mut component)?,
_ => return Err(TokenLoadError::UnknownPath { path: key.clone() }),
}
}
Ok(Self { name, leaves, component })
}
}
fn node_from_json(path: &str, value: &serde_json::Value) -> Result<TokenNodeRaw, TokenLoadError> {
let obj = value.as_object().ok_or_else(|| TokenLoadError::WrongType {
path: path.to_string(),
expected: "object",
found: describe_kind(value),
})?;
if obj.contains_key("$value") {
Ok(TokenNodeRaw::Leaf(parse_leaf_obj(path, obj)?))
} else {
let mut children = BTreeMap::new();
for (key, val) in obj {
let child_path = format!("{path}.{key}");
children.insert(key.clone(), node_from_json(&child_path, val)?);
}
Ok(TokenNodeRaw::Group(children))
}
}
fn flatten(prefix: &str, node: TokenNodeRaw, out: &mut BTreeMap<String, TokenLeafRaw>) {
match node {
TokenNodeRaw::Leaf(leaf) => {
out.insert(prefix.to_string(), leaf);
}
TokenNodeRaw::Group(children) => {
for (key, child) in children {
let path = format!("{prefix}.{key}");
flatten(&path, child, out);
}
}
}
}
fn parse_component(
value: &serde_json::Value,
out: &mut BTreeMap<(String, String), TokenLeafRaw>,
) -> Result<(), TokenLoadError> {
let widgets = value.as_object().ok_or_else(|| TokenLoadError::WrongType {
path: "component".to_string(),
expected: "object",
found: describe_kind(value),
})?;
for (widget, keys_value) in widgets {
let keys = keys_value
.as_object()
.ok_or_else(|| TokenLoadError::UnknownPath { path: format!("component.{widget}") })?;
for (key, leaf_value) in keys {
let path = format!("component.{widget}.{key}");
let obj = leaf_value
.as_object()
.filter(|o| o.contains_key("$value"))
.ok_or_else(|| TokenLoadError::UnknownPath { path: path.clone() })?;
let leaf = parse_leaf_obj(&path, obj)?;
out.insert((widget.clone(), key.clone()), leaf);
}
}
Ok(())
}
fn parse_leaf_obj(
path: &str,
obj: &serde_json::Map<String, serde_json::Value>,
) -> Result<TokenLeafRaw, TokenLoadError> {
let value_field = obj
.get("$value")
.ok_or_else(|| TokenLoadError::UnknownPath { path: path.to_string() })?;
let type_hint = match obj.get("$type") {
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(other) => {
return Err(TokenLoadError::WrongType {
path: path.to_string(),
expected: "string",
found: describe_kind(other),
});
}
None => None,
};
let value = match value_field {
serde_json::Value::String(s) => match s.strip_prefix('{').and_then(|r| r.strip_suffix('}')) {
Some(inner) => RawValue::Alias(inner.to_string()),
None => RawValue::String(s.clone()),
},
serde_json::Value::Number(n) => {
let n = n.as_f64().ok_or_else(|| TokenLoadError::WrongType {
path: path.to_string(),
expected: "finite number",
found: n.to_string(),
})?;
RawValue::Number(n)
}
other => {
return Err(TokenLoadError::WrongType {
path: path.to_string(),
expected: "string or number",
found: describe_kind(other),
});
}
};
let modifier = match obj.get("$extensions") {
Some(serde_json::Value::Object(ext)) => parse_modifier(path, ext)?,
Some(other) => {
return Err(TokenLoadError::WrongType {
path: path.to_string(),
expected: "object",
found: describe_kind(other),
});
}
None => None,
};
Ok(TokenLeafRaw { value, type_hint, modifier })
}
fn parse_modifier(
path: &str,
ext: &serde_json::Map<String, serde_json::Value>,
) -> Result<Option<ModifierRaw>, TokenLoadError> {
if let Some(alpha) = ext.get("uzor.alpha") {
let a = alpha.as_f64().ok_or_else(|| TokenLoadError::WrongType {
path: path.to_string(),
expected: "number",
found: describe_kind(alpha),
})?;
return Ok(Some(ModifierRaw::Alpha(a as f32)));
}
if let Some(mix) = ext.get("uzor.mix") {
let obj = mix.as_object().ok_or_else(|| TokenLoadError::WrongType {
path: path.to_string(),
expected: "object",
found: describe_kind(mix),
})?;
let with_raw = obj.get("with").and_then(|v| v.as_str()).ok_or_else(|| TokenLoadError::WrongType {
path: path.to_string(),
expected: "string 'with'",
found: "missing 'with'".to_string(),
})?;
let with = with_raw
.strip_prefix('{')
.and_then(|r| r.strip_suffix('}'))
.unwrap_or(with_raw)
.to_string();
let t = obj.get("t").and_then(|v| v.as_f64()).ok_or_else(|| TokenLoadError::WrongType {
path: path.to_string(),
expected: "number 't'",
found: "missing 't'".to_string(),
})?;
return Ok(Some(ModifierRaw::Mix { with, t: t as f32 }));
}
Ok(None)
}
fn describe_kind(value: &serde_json::Value) -> String {
match value {
serde_json::Value::Null => "null".to_string(),
serde_json::Value::Bool(_) => "boolean".to_string(),
serde_json::Value::Number(n) => format!("number ({n})"),
serde_json::Value::String(s) => format!("string {s:?}"),
serde_json::Value::Array(_) => "array".to_string(),
serde_json::Value::Object(_) => "object".to_string(),
}
}