use crate::numeric::ParseError;
use muskitty_css::parser::ComponentValue;
use muskitty_css::tokenizer::Token;
#[derive(Debug, Clone)]
pub struct VarReference {
pub name: String,
pub fallback: Option<Vec<ComponentValue>>,
}
impl VarReference {
pub fn parse(input: &str) -> Result<Self, ParseError> {
let cvs = muskitty_css::parse_list_of_component_values(input);
Self::from_cvs(&cvs)
}
pub fn from_cvs(cvs: &[ComponentValue]) -> Result<Self, ParseError> {
let func = cvs.iter().find_map(|cv| match cv {
ComponentValue::Function(f) if f.name.eq_ignore_ascii_case("var") => Some(f),
_ => None,
});
let func = func.ok_or_else(|| ParseError::new("expected var() function"))?;
Self::from_function(func)
}
pub fn from_function(func: &muskitty_css::parser::Function) -> Result<Self, ParseError> {
let first_non_ws = func
.value
.iter()
.find(|cv| !is_whitespace(cv))
.ok_or_else(|| ParseError::new("var() requires at least one argument"))?;
let name = match first_non_ws {
ComponentValue::PreservedToken(Token::Ident(s)) => {
if !is_custom_property_name(s) {
return Err(ParseError::new(format!(
"var() first argument must be a custom property name (starting with '--'), got: {s}"
)));
}
s.clone()
}
_ => {
return Err(ParseError::new(
"var() first argument must be an ident token",
))
}
};
let comma_idx = func
.value
.iter()
.position(|cv| matches!(cv, ComponentValue::PreservedToken(Token::Comma)));
let fallback = match comma_idx {
None => None,
Some(idx) => {
let after_comma = &func.value[idx + 1..];
Some(after_comma.to_vec())
}
};
Ok(VarReference { name, fallback })
}
}
pub fn is_custom_property_name(s: &str) -> bool {
s.starts_with("--") && s.len() > 2
}
fn is_whitespace(cv: &ComponentValue) -> bool {
matches!(cv, ComponentValue::PreservedToken(Token::Whitespace))
}