diff --git a/packages/codemod/transformations/core/v2-to-v3/optional/Enums-migration.ts b/packages/codemod/transformations/core/v2-to-v3/optional/Enums-migration.ts new file mode 100644 index 0000000000..5b576d6518 --- /dev/null +++ b/packages/codemod/transformations/core/v2-to-v3/optional/Enums-migration.ts @@ -0,0 +1,47 @@ +import { TransformationContext } from "../../../../types"; +import { getCoreImportsForFile, getPropValue, setPropValue, wrap } from "../../../../src/utils"; +import enumToStringMapping from "./enumMappings.json"; + +const enumToString: Record = enumToStringMapping; + +/** + * Replace enums with string equivalent + */ +function transform({ j, root }: TransformationContext) { + const coreImports = getCoreImportsForFile(root); + + const importedComponents = coreImports + .find(j.ImportSpecifier) + .nodes() + .map(importSpecifier => { + if (importSpecifier.local && importSpecifier.local.name) { + return importSpecifier.local.name; + } + return null; + }) + .filter(Boolean); + + const allElements = root.find(j.JSXElement).nodes(); // Get the nodes array + + const elements = allElements.filter(path => { + const openingElement = path.openingElement; + const elementName = openingElement.name.type === "JSXIdentifier" ? openingElement.name.name : null; + return elementName && importedComponents.includes(elementName); + }); + + if (!elements.length) return; + elements.forEach(elementPath => { + const props = j(elementPath).find(j.JSXOpeningElement).find(j.JSXAttribute); + props.forEach(prop => { + const propValue = getPropValue(j, prop.node) as string; + if (enumToString[propValue]) { + setPropValue(j, prop, { + value: enumToString[propValue], + type: "Literal" + }); + } + }); + }); +} + +export default wrap(transform); diff --git a/packages/codemod/transformations/core/v2-to-v3/optional/__tests__/Enums-migration.test.ts b/packages/codemod/transformations/core/v2-to-v3/optional/__tests__/Enums-migration.test.ts new file mode 100644 index 0000000000..a8553ace7f --- /dev/null +++ b/packages/codemod/transformations/core/v2-to-v3/optional/__tests__/Enums-migration.test.ts @@ -0,0 +1,41 @@ +import transform from "../Enums-migration"; +import { defineInlineTest } from "jscodeshift/src/testUtils"; + +function prependImport(source: string): string { + return ` + import { Button } from "monday-ui-react-core"; + ${source} + `; +} + +describe("Enums migration", () => { + defineInlineTest( + transform, + {}, + prependImport(`