Anber / wyw-in-js

MIT License
191 stars 8 forks source link

Allow `replacement` argument to be a function to give access to the `tagPath` #75

Closed siriwatknp closed 2 months ago

siriwatknp commented 2 months ago

Describe the enhancement

We need to modify the tag processor at the end of the process.

Motivation

Hello, we are members of Pigment CSS team. Currently, we are implementing a tag processor that requires modifying the AST at the end of the process.

The code before the transformation:

<Component className={`test ${other}`} style={props.style} sx={sx({ bgcolor: 'red' }, Component)} />

What we want after the transformation:

<Component className={`test ${other}`} style={props.style}
  {…sx({ …our transformed values }, { className: …, style: props.style })}  // the things we want is the second argument
/>

Possible implementations

Here is a working code from my local machine:

diff --git a/packages/transform/src/utils/getTagProcessor.ts b/packages/transform/src/utils/getTagProcessor.ts
index 34954d5..a8aa343 100644
--- a/packages/transform/src/utils/getTagProcessor.ts
+++ b/packages/transform/src/utils/getTagProcessor.ts
@@ -245,11 +245,18 @@ function getBuilderForIdentifier(
     break;
   }

-  const replacer = (replacement: Expression, isPure: boolean) => {
+  const replacer = (
+    replacement: Expression | ((prev: NodePath) => Expression),
+    isPure: boolean
+  ) => {
     mutate(prev, (p) => {
-      p.replaceWith(replacement);
-      if (isPure) {
-        p.addComment('leading', '#__PURE__');
+      if (typeof replacement === 'function') {
+        replacement(p);
+      } else {
+        p.replaceWith(replacement);
+        if (isPure) {
+          p.addComment('leading', '#__PURE__');
+        }
       }
     });
   };

Related Issues

brijeshb42 commented 2 months ago

We can also open a PR with the required change.