From a8210a7bbf3a0701a468b65fd8261d032008dab8 Mon Sep 17 00:00:00 2001 From: Convly Date: Mon, 18 Mar 2024 12:02:28 +0100 Subject: [PATCH] chore: add example codemod for react transformations --- .../examples/disable-jsx-buttons.code.ts | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 packages/utils/upgrade/resources/examples/disable-jsx-buttons.code.ts diff --git a/packages/utils/upgrade/resources/examples/disable-jsx-buttons.code.ts b/packages/utils/upgrade/resources/examples/disable-jsx-buttons.code.ts new file mode 100644 index 0000000000..60aa33eaf6 --- /dev/null +++ b/packages/utils/upgrade/resources/examples/disable-jsx-buttons.code.ts @@ -0,0 +1,42 @@ +import type { Transform } from 'jscodeshift'; +import { relative } from 'node:path'; + +const transform: Transform = (file, api) => { + const j = api.jscodeshift; + const root = j.withParser('JSX')(file.source); + + const isReactFile = file.path.endsWith('.jsx') || file.path.endsWith('.tsx'); + + if (!isReactFile) { + return root.toSource(); + } + + const fileName = relative(process.cwd(), file.path); + + console.log(`Found React file: ${fileName}`); + + const buttons = root.findJSXElements('Button'); + + console.log(`Found ${buttons.length} buttons in ${fileName}`); + + buttons.forEach((button) => { + const { openingElement } = button.node; + const isDisabled = openingElement.attributes.some( + (attribute) => j.JSXAttribute.check(attribute) && attribute.name.name === 'disabled' + ); + + console.log(`Is disabled? ${isDisabled}`); + + if (!isDisabled) { + openingElement.attributes.push( + j.jsxAttribute(j.jsxIdentifier('disabled'), j.jsxExpressionContainer(j.literal(true))) + ); + + console.log('Added the disabled attribute'); + } + }); + + return root.toSource(); +}; + +export default transform;