* Find the root JSX element returned by a component function. * Searches for function declarations, arrow functions, and export defaults.
( j: any, root: any, componentName: string, )
| 55 | * Searches for function declarations, arrow functions, and export defaults. |
| 56 | */ |
| 57 | function findComponentRootJSX( |
| 58 | j: any, |
| 59 | root: any, |
| 60 | componentName: string, |
| 61 | ): any | null { |
| 62 | let funcBody: any = null; |
| 63 | let isExpressionBody = false; |
| 64 | |
| 65 | // 1. FunctionDeclaration: function ComponentName() {} |
| 66 | root.find(j.FunctionDeclaration).forEach((p: any) => { |
| 67 | if (p.node.id?.name === componentName) { |
| 68 | funcBody = p.node.body; |
| 69 | } |
| 70 | }); |
| 71 | |
| 72 | // 2. VariableDeclarator: const ComponentName = () => {} or function expression |
| 73 | if (!funcBody) { |
| 74 | root.find(j.VariableDeclarator).forEach((p: any) => { |
| 75 | if (p.node.id?.name === componentName) { |
| 76 | const init = p.node.init; |
| 77 | if (init?.type === "ArrowFunctionExpression") { |
| 78 | if (init.body?.type === "BlockStatement") { |
| 79 | funcBody = init.body; |
| 80 | } else { |
| 81 | // Expression body: () => <div /> |
| 82 | funcBody = init.body; |
| 83 | isExpressionBody = true; |
| 84 | } |
| 85 | } else if (init?.type === "FunctionExpression") { |
| 86 | funcBody = init.body; |
| 87 | } |
| 88 | } |
| 89 | }); |
| 90 | } |
| 91 | |
| 92 | // 3. ExportDefaultDeclaration with FunctionDeclaration |
| 93 | if (!funcBody) { |
| 94 | root.find(j.ExportDefaultDeclaration).forEach((p: any) => { |
| 95 | const decl = p.node.declaration; |
| 96 | if (decl?.type === "FunctionDeclaration" && decl.id?.name === componentName) { |
| 97 | funcBody = decl.body; |
| 98 | } |
| 99 | // Also handle: export default function() {} — anonymous default |
| 100 | if (decl?.type === "FunctionDeclaration" && !decl.id && componentName === "default") { |
| 101 | funcBody = decl.body; |
| 102 | } |
| 103 | // Arrow function default export |
| 104 | if (decl?.type === "ArrowFunctionExpression") { |
| 105 | if (decl.body?.type === "BlockStatement") { |
| 106 | funcBody = decl.body; |
| 107 | } else { |
| 108 | funcBody = decl.body; |
| 109 | isExpressionBody = true; |
| 110 | } |
| 111 | } |
| 112 | }); |
| 113 | } |
| 114 |