|
| 1 | +import chalk from "chalk"; |
| 2 | +import moveAndRenameImport from "../../../utils/moveAndRenameImport"; |
| 3 | +import removePropsFromComponent from "../../../utils/removeProps"; |
| 4 | + |
| 5 | +/** |
| 6 | + * @param {import('jscodeshift').FileInfo} file |
| 7 | + * @param {import('jscodeshift').API} api |
| 8 | + */ |
| 9 | +export default function transformer(file, api, options, ...rest) { |
| 10 | + const j = api.jscodeshift; |
| 11 | + |
| 12 | + let root: any; |
| 13 | + try { |
| 14 | + root = j(file.source); |
| 15 | + } catch { |
| 16 | + return file.source; |
| 17 | + } |
| 18 | + |
| 19 | + const toName = "CopyButton"; |
| 20 | + const localName = moveAndRenameImport(j, root, { |
| 21 | + fromImport: "@navikt/ds-react-internal", |
| 22 | + toImport: "@navikt/ds-react", |
| 23 | + fromName: "CopyToClipboard", |
| 24 | + toName, |
| 25 | + }); |
| 26 | + |
| 27 | + if (localName === null) { |
| 28 | + return root.toSource(options.printOptions); |
| 29 | + } |
| 30 | + |
| 31 | + /* Finds and replaces import from CopyToClipboard -> CopyButton */ |
| 32 | + |
| 33 | + if (root.findJSXElements(localName)) { |
| 34 | + removePropsFromComponent(j, root, localName, [ |
| 35 | + "popoverText", |
| 36 | + "popoverPlacement", |
| 37 | + "iconPosition", |
| 38 | + "variant", |
| 39 | + ]); |
| 40 | + |
| 41 | + const component = root.findJSXElements(localName); |
| 42 | + |
| 43 | + component.forEach((node) => { |
| 44 | + const children = node.node.children; |
| 45 | + let flagged = false; |
| 46 | + if ( |
| 47 | + children.length > 0 && |
| 48 | + !node.node.openingElement.attributes.some( |
| 49 | + (attr) => attr.name.name === "text" |
| 50 | + ) |
| 51 | + ) { |
| 52 | + if (children.length === 1 && children[0].type === "JSXText") { |
| 53 | + node.node.openingElement.attributes.push( |
| 54 | + j.jsxAttribute( |
| 55 | + j.jsxIdentifier("text"), |
| 56 | + j.literal(children[0].value.trim()) |
| 57 | + ) |
| 58 | + ); |
| 59 | + } else { |
| 60 | + flagged = true; |
| 61 | + console.log( |
| 62 | + chalk.yellow( |
| 63 | + `\n\nWarning: Detected advanced children-type!\nCodemod can't convert into "text" prop so you will need to update this manually.` |
| 64 | + ) |
| 65 | + ); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + if (!flagged) { |
| 70 | + node.node.children = []; |
| 71 | + node.node.openingElement.selfClosing = true; |
| 72 | + node.node.closingElement = null; |
| 73 | + } |
| 74 | + }); |
| 75 | + |
| 76 | + const compRoot = root.find(j.JSXElement, { |
| 77 | + openingElement: { name: { name: localName } }, |
| 78 | + }); |
| 79 | + |
| 80 | + compRoot.forEach((x) => { |
| 81 | + x.node.openingElement.name.name = "CopyButton"; |
| 82 | + if (x.node.children.length > 0) { |
| 83 | + x.node.closingElement.name.name = "CopyButton"; |
| 84 | + } |
| 85 | + }); |
| 86 | + } |
| 87 | + |
| 88 | + return root.toSource(options.printOptions); |
| 89 | +} |
0 commit comments