Skip to content

Commit

Permalink
feat(icon): Optional codemod for migrating enums
Browse files Browse the repository at this point in the history
  • Loading branch information
rivka-ungar committed Oct 16, 2024
1 parent 100ae62 commit b17c54e
Show file tree
Hide file tree
Showing 4 changed files with 781 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { TransformationContext } from "../../../../types";
import { getCoreImportsForFile, getPropValue, setPropValue, wrap } from "../../../../src/utils";
import enumToStringMapping from "./enumMappings.json";

const enumToString: Record<string, string> = 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);
Original file line number Diff line number Diff line change
@@ -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(`<Button kind={Button.kinds.PRIMARY}/>`),
prependImport(`<Button kind="primary"/>`),
"should update enum"
);

defineInlineTest(
transform,
{},
prependImport(`<Button kind={Button.kinds.SECONDARY} size={Button.sizes.SMALL} />`),
prependImport(`<Button kind="secondary" size="small" />`),
"should update enum"
);

defineInlineTest(
transform,
{},
`
import { Button } from "another-library";
<Button size={Button.sizes.SMALL} />
`,
`
import { Button } from "another-library";
<Button size={Button.sizes.SMALL} />
`,
"should not change component is not imported from vibe"
);
});
Loading

0 comments on commit b17c54e

Please sign in to comment.