Skip to content

Commit

Permalink
add support for $ methods
Browse files Browse the repository at this point in the history
  • Loading branch information
benStre committed Sep 3, 2024
1 parent 685a532 commit 8b63963
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 4 deletions.
30 changes: 29 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,35 @@ test!(
array.map((item) => {
return <span>{item}</span>
})
}
}
</div>
"#
);


test!(
Syntax::Es(EsSyntax {
jsx: true,
..Default::default()
},),
|_| TransformVisitor,
t19,
r#"<div>
{
array.map((item) => {
return <span>{item * 2}</span>
})
}
{
array.filter((item) => {
return <span>{item * 2}</span>
})
}
{
array.normalMethod((item) => {
return <span>{item * 2}</span>
})
}
</div>
"#
);
34 changes: 34 additions & 0 deletions src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ impl Visit for VariableCollector {
}
}


const DOLLAR_METHODS: [&'static str; 3] = [
"map",
"filter",
"reduce",
];


pub struct TransformVisitor;

impl TransformVisitor {
Expand Down Expand Up @@ -103,6 +111,32 @@ impl TransformVisitor {

// convert array.map(() => {}) to array.$.map(() => {})
// TODO
Expr::Call(c)
if c.callee.is_expr()
&& c.callee.as_expr().unwrap().is_member()
// any DOLLAR_METHODS
&& DOLLAR_METHODS.iter().any(|m| c.callee.as_expr().unwrap().as_member().unwrap().prop.is_ident_with(m)) =>
// && (c.callee.as_expr().unwrap().as_member().unwrap().prop.is_ident_with("map")) =>
{
let member = c.callee.as_expr().unwrap().as_member().unwrap();
let obj = member.obj.clone();
let prop = member.prop.clone();

Box::new(Expr::Call(CallExpr {
span: c.span,
callee: Callee::Expr(Box::new(Expr::Member(MemberExpr {
span: DUMMY_SP,
obj: obj,
prop: MemberProp::Ident(IdentName::from(
format!("$.{}", prop.as_ident().unwrap().sym).to_string()
)),
}))),
args: c.args.clone(),
type_args: Take::dummy(),
ctxt: Default::default(),
}))
}


// already has an always() or $$() wrapper
Expr::Call(c)
Expand Down
6 changes: 3 additions & 3 deletions tests/__swc_snapshots__/src/lib.rs/t18.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<div>
{always(()=>array.map((item)=>{
return <span>{item}</span>;
}))}
{array.$.map((item)=>{
return <span>{item}</span>;
})}
</div>;
11 changes: 11 additions & 0 deletions tests/__swc_snapshots__/src/lib.rs/t19.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<div>
{array.$.map((item)=>{
return <span>{item * 2}</span>;
})}
{array.$.filter((item)=>{
return <span>{item * 2}</span>;
})}
{always(()=>array.normalMethod((item)=>{
return <span>{item * 2}</span>;
}))}
</div>;

0 comments on commit 8b63963

Please sign in to comment.