|
| 1 | +import { API, ASTPath, FileInfo, JSXIdentifier } from 'jscodeshift'; |
| 2 | +import { Options } from 'recast'; |
| 3 | + |
| 4 | +module.exports = (file: FileInfo, api: API, options: Options) => { |
| 5 | + const j = api.jscodeshift; |
| 6 | + const ast = j(file.source); |
| 7 | + const printOptions = options ?? { quote: 'single' }; |
| 8 | + |
| 9 | + const localTextNames = []; |
| 10 | + |
| 11 | + const secondaryProp = { |
| 12 | + type: 'JSXAttribute', |
| 13 | + name: 'secondary' |
| 14 | + }; |
| 15 | + |
| 16 | + // Find Wave Text imports and store the local names |
| 17 | + ast.find(j.ImportDeclaration, decl => decl.source.value === '@freenow/wave').forEach(decl => { |
| 18 | + j(decl) |
| 19 | + .find(j.ImportSpecifier) |
| 20 | + .forEach(spec => { |
| 21 | + if (spec.node.imported.name === 'Text') localTextNames.push(spec.node.local.name); |
| 22 | + }); |
| 23 | + }); |
| 24 | + |
| 25 | + // Search for usages of Text |
| 26 | + ast.find(j.JSXElement, { |
| 27 | + openingElement: { |
| 28 | + name: { |
| 29 | + name: name => localTextNames.includes(name) |
| 30 | + } |
| 31 | + } |
| 32 | + }).forEach(el => { |
| 33 | + j(el) |
| 34 | + // Find weak props being used |
| 35 | + .find(j.JSXAttribute, { |
| 36 | + name: name => name.name === 'weak' |
| 37 | + }) |
| 38 | + .forEach(attr => { |
| 39 | + const mutableAttr = j(attr); |
| 40 | + |
| 41 | + // Find the identifier (where the prop name is kept) |
| 42 | + const identifier: ASTPath<JSXIdentifier> = mutableAttr |
| 43 | + .find(j.JSXIdentifier, { |
| 44 | + name: 'weak' |
| 45 | + }) |
| 46 | + .get(0).node; |
| 47 | + |
| 48 | + // In case it has a boolean value (weak={false} or weak={true}) |
| 49 | + if ( |
| 50 | + attr.node.value?.type === 'JSXExpressionContainer' && |
| 51 | + attr.node.value.expression.type === 'BooleanLiteral' |
| 52 | + ) { |
| 53 | + // If weak={true} replace with secondary prop |
| 54 | + if (attr.node.value.expression.value) mutableAttr.replaceWith(secondaryProp); |
| 55 | + // Otherwise (weak={false}) remove altogether |
| 56 | + else mutableAttr.remove(); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + // For other cases, e.g. implicit value (weak), dynamic value (weak={Date.now() % 2 === 0}) |
| 61 | + // Replace the name of the prop |
| 62 | + identifier.name = 'secondary'; |
| 63 | + }); |
| 64 | + }); |
| 65 | + |
| 66 | + return ast.toSource(printOptions); |
| 67 | +}; |
0 commit comments