@@ -6,14 +6,12 @@ export function moveDefaultPropsToFunctionDeclaration(
66 j : JSCodeshift ,
77) {
88 source
9- . find ( j . FunctionDeclaration , {
10- id : { name : 'Component' } ,
11- } )
9+ . find ( j . FunctionDeclaration )
1210 . forEach ( component => {
1311 // Find the defaultProps assignment expression
1412 const defaultProps = source . find ( j . AssignmentExpression , {
1513 left : {
16- object : { name : 'Component' } ,
14+ object : { name : component . node . id ?. name } ,
1715 property : { name : 'defaultProps' } ,
1816 } ,
1917 } ) ;
@@ -24,33 +22,48 @@ export function moveDefaultPropsToFunctionDeclaration(
2422 const defaultValues = defaultProps . get ( 'right' ) . value . properties ;
2523
2624 // Generate a new function parameter for each default prop
27- const params = defaultValues . map ( ( prop : any ) => {
25+ const defaultParams = defaultValues . map ( ( prop : any ) => {
2826 const key = prop . key . name ;
2927 const value = prop . value . value ;
3028 // return j.objectPattern(`${key}=${JSON.stringify(value)}`);
31- return j . objectPattern ( [
32- j . objectProperty (
33- j . identifier ( key ) ,
34- j . assignmentPattern ( j . identifier ( key ) , j . literal ( value ) ) ,
35- ) ,
36- ] ) ;
29+ return j . objectProperty (
30+ j . identifier ( key ) ,
31+ j . assignmentPattern ( j . identifier ( key ) , j . literal ( value ) ) ,
32+ ) ;
3733 } ) ;
3834
35+ // Find the existing destructured props parameter, if any
36+ const existingPropsParam = component . node . params . find (
37+ param => param . type === 'ObjectPattern' ,
38+ ) ;
39+
40+ // If an existing props parameter was found, extract its properties
41+ const existingPropsProperties =
42+ existingPropsParam && 'properties' in existingPropsParam
43+ ? existingPropsParam . properties . map ( prop =>
44+ j . property ( 'init' , ( prop as any ) . key , ( prop as any ) . value ) ,
45+ )
46+ : [ ] ;
47+
48+ // Generate the new params array by concatenating the existing props properties with the default params
49+ const newParams = [
50+ j . objectPattern ( existingPropsProperties . concat ( defaultParams ) ) ,
51+ ] ;
52+
3953 // Replace the original function declaration with a new one
4054 j ( component ) . replaceWith ( nodePath =>
4155 j . functionDeclaration (
4256 nodePath . node . id ,
43- params ,
57+ newParams ,
4458 nodePath . node . body ,
4559 nodePath . node . generator ,
4660 nodePath . node . async ,
4761 ) ,
4862 ) ;
49- // Remove the
5063 } )
5164 . find ( j . AssignmentExpression , {
5265 left : {
53- object : { name : 'Component ' } ,
66+ object : { type : 'Identifier ' } ,
5467 property : { name : 'defaultProps' } ,
5568 } ,
5669 } )
0 commit comments