Skip to main content

stylex_transform/shared/utils/css/validators/
unprefixed_custom_properties.rs

1use swc_core::css::ast::{
2  ComponentValue, Declaration, Function, FunctionName, QualifiedRule, Rule, Stylesheet,
3};
4
5use crate::shared::utils::css::common::get_value_from_ident;
6#[cfg(test)]
7use crate::shared::utils::css::common::swc_parse_css;
8use stylex_constants::constants::messages::UNPREFIXED_CUSTOM_PROPERTIES;
9fn process_function(func: &Function) {
10  if let FunctionName::Ident(func_name_ident) = &func.name {
11    let func_name = get_value_from_ident(func_name_ident);
12    if func_name == "var"
13      && let Some(ComponentValue::Ident(ident)) = func.value.first()
14    {
15      let value = get_value_from_ident(ident.as_ref());
16      assert!(value.starts_with("--"), "{}", UNPREFIXED_CUSTOM_PROPERTIES);
17    }
18  }
19}
20
21fn process_declaration(declaration: &Declaration) {
22  for value in declaration.value.iter() {
23    if let ComponentValue::Function(func) = value {
24      process_function(func);
25    }
26  }
27}
28
29fn process_qualified_rule(qualified_rule: &QualifiedRule) {
30  for declaration in qualified_rule.block.value.iter() {
31    if let ComponentValue::Declaration(declaration) = declaration {
32      process_declaration(declaration);
33    }
34  }
35}
36
37pub(crate) fn unprefixed_custom_properties_validator(ast: &Stylesheet) {
38  for rule in ast.rules.iter() {
39    if let Rule::QualifiedRule(qualified_rule) = rule {
40      process_qualified_rule(qualified_rule);
41    }
42  }
43}
44
45#[test]
46#[should_panic(expected = "Unprefixed custom properties")]
47fn disallow_unprefixed_custom_properties() {
48  let (result, _) = swc_parse_css("* { color: var(foo); }");
49
50  unprefixed_custom_properties_validator(&result.unwrap());
51}