stylex_transform/shared/utils/core/
js_to_expr.rs1use indexmap::IndexMap;
2use stylex_macros::stylex_unreachable;
3use swc_core::ecma::ast::{Expr, PropOrSpread};
4
5use crate::shared::enums::data_structures::flat_compiled_styles_value::FlatCompiledStylesValue;
6use crate::shared::structures::types::{FlatCompiledStyles, StylesObjectMap};
7use crate::shared::utils::ast::convertors::{
8 create_bool_expr, create_null_expr, create_number_expr,
9};
10use stylex_ast::ast::factories::{
11 create_key_value_prop, create_object_expression, create_string_key_value_prop,
12};
13
14pub(crate) fn remove_objects_with_spreads(obj: &StylesObjectMap) -> StylesObjectMap {
15 let mut new_obj = IndexMap::with_capacity(obj.len());
16
17 for (key, value) in obj.iter() {
18 new_obj.insert(key.clone(), value.clone());
19 }
20
21 new_obj
22}
23
24#[derive(Debug, PartialEq, Clone)]
25pub(crate) enum NestedStringObject {
26 FlatCompiledStyles(StylesObjectMap),
27 FlatCompiledStylesValues(FlatCompiledStyles),
28}
29
30impl NestedStringObject {
31 pub(crate) fn _as_styles(&self) -> Option<&StylesObjectMap> {
32 match self {
33 NestedStringObject::FlatCompiledStyles(obj) => Some(obj),
34 _ => None,
35 }
36 }
37
38 pub(crate) fn as_values(&self) -> Option<&FlatCompiledStyles> {
39 match self {
40 NestedStringObject::FlatCompiledStylesValues(obj) => Some(obj),
41 _ => None,
42 }
43 }
44}
45
46pub(crate) fn convert_object_to_ast(obj: &NestedStringObject) -> Expr {
47 let mut props: Vec<PropOrSpread> = vec![];
48
49 match obj {
50 NestedStringObject::FlatCompiledStyles(obj) => {
51 for (key, value) in obj.iter() {
52 let expr = convert_object_to_ast(&NestedStringObject::FlatCompiledStylesValues(
53 (**value).clone(),
54 ));
55
56 let prop = create_key_value_prop(key.as_str(), expr);
57
58 props.push(prop);
59 }
60 },
61 NestedStringObject::FlatCompiledStylesValues(obj) => {
62 for (key, value) in obj.iter() {
63 let prop = match value.as_ref() {
64 FlatCompiledStylesValue::String(value) => {
65 if let Ok(num) = value.parse::<f64>() {
66 create_key_value_prop(key.as_str(), create_number_expr(num))
67 } else {
68 create_string_key_value_prop(key.as_str(), value.as_str())
69 }
70 },
71 FlatCompiledStylesValue::Null => create_key_value_prop(key.as_str(), create_null_expr()),
72 FlatCompiledStylesValue::Bool(value) => {
73 create_key_value_prop(key.as_str(), create_bool_expr(*value))
74 },
75 _ => {
76 stylex_unreachable!("Encountered an unsupported value type during AST conversion.")
77 },
78 };
79
80 props.push(prop);
81 }
82 },
83 }
84
85 create_object_expression(props)
86}