Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature]: Convert React {array.map()} expressions to <For> #7

Open
viridia opened this issue Feb 13, 2023 · 0 comments
Open

[Feature]: Convert React {array.map()} expressions to <For> #7

viridia opened this issue Feb 13, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@viridia
Copy link

viridia commented Feb 13, 2023

Input code

export const Looper = () => {
  return <div>
    {array.map(el => <div>{el.name}</div>)}
  </div>;
}

Expected Output

import { For } from 'solid-js';

export const Looper = () => {
  return <div>
    <For each={array}>
      {(el => <div>{el.name}</div>)}
    </For>
  </div>;
}

Additional context

Here's a codemod which does this:

import {
  ASTPath,
  CallExpression,
  FunctionExpression,
  ImportDeclaration,
  MemberExpression,
  Transform,
} from 'jscodeshift';

const transform: Transform = (file, api, options) => {
  const j = api.jscodeshift;
  const root = j(file.source);
  const importsRequired = new Set<string>();

  // Replace JSX expression {<expression>.map(fn)} with <For each={expression}>{fn}</For>
  root
    .find(j.JSXExpressionContainer)
    .filter(path => {
      // We only care about JSX expression containers whose parents are JSX elements.
      // (in other words, exclude attribute expressions.)
      if (
        path.parent.node.type === 'JSXElement' &&
        path.node.expression.type === 'CallExpression'
      ) {
        const call = path.node.expression;
        if (
          call.callee.type === 'MemberExpression' &&
          call.callee.property.type === 'Identifier' &&
          call.callee.property.name === 'map'
        ) {
          return true;
        }
      }
      return false;
    })
    .replaceWith(path => {
      const call = path.node.expression as CallExpression;
      const callee = call.callee as MemberExpression;
      importsRequired.add('For');
      return j.jsxElement.from({
        openingElement: j.jsxOpeningElement(j.jsxIdentifier('For'), [
          j.jsxAttribute.from({
            name: j.jsxIdentifier('each'),
            value: j.jsxExpressionContainer.from({
              expression: callee.object,
            }),
          }),
        ]),
        closingElement: j.jsxClosingElement(j.jsxIdentifier('For')),
        selfClosing: false,
        children: [
          j.jsxExpressionContainer.from({
            expression: call.arguments.at(0) as FunctionExpression,
          }),
        ],
      });
    });

  // See whether we need to add any imports
  if (importsRequired.size > 0) {
    // Look for solid-js import
    let lastImport: ASTPath<ImportDeclaration> | null = null;
    let solidImport = root
      .find(j.ImportDeclaration)
      .forEach(path => {
        lastImport = path;
      })
      .filter(path => path.node.source.value === 'solid-js')
      .forEach(path => {
        if (!path.node.specifiers) {
          path.node.specifiers = [];
        }
        path.node.specifiers?.forEach(spec => {
          if (spec.type === 'ImportSpecifier') {
            importsRequired.delete(spec.imported.name);
          }
        });

        for (const symbol of importsRequired) {
          path.node.specifiers.push(
            j.importSpecifier.from({
              imported: j.jsxIdentifier(symbol),
            })
          );
        }
      });

    if (solidImport.length == 0) {
      // Insert new solid import statement.
      const solidImport = j.importDeclaration.from({
        source: j.stringLiteral('solid-js'),
        specifiers: Array.from(importsRequired).map(symbol =>
          j.importSpecifier.from({
            imported: j.jsxIdentifier(symbol),
          })
        ),
      });
      lastImport!.insertAfter(solidImport);
    }
  }

  return root.toSource({ quote: 'single' });
};

export default transform;
@viridia viridia added the enhancement New feature or request label Feb 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant