@@ -9,47 +9,32 @@ module.exports = elementType => {
99 // Initialize empty object to store the setters and getter
1010 let ast = JSXParser . parse ( elementType ) ;
1111 const hookState = { } ;
12- // All module exports will always start off as a single 'FunctionDeclaration' type
12+
1313 while ( Object . hasOwnProperty . call ( ast , 'body' ) ) {
14- // Traverse down .body once before invoking parsing logic and will loop through any .body after
1514 ast = ast . body ;
1615 const statements = [ ] ;
1716
18- function saveAstHooks ( st ) {
19- st . forEach ( ( el , i ) => {
20- if ( el . match ( / _ u s e / ) ) hookState [ el ] = statements [ i + 2 ] ;
21- } ) ;
22- }
23-
24- function findHookDeclarations ( astVal ) {
25- astVal . forEach ( elem => {
17+ /** All module exports always start off as a single 'FunctionDeclaration' type
18+ * Other types: "BlockStatement" / "ExpressionStatement" / "ReturnStatement"
19+ * Iterate through AST of every function declaration
20+ * Check within each function declaration if there are hook declarations */
21+ ast . forEach ( functionDec => {
22+ let body ;
23+ if ( functionDec . expression ) body = functionDec . expression . body . body ;
24+ else body = functionDec . body . body ;
25+ // Traverse through the function's funcDecs and Expression Statements
26+ body . forEach ( elem => {
2627 if ( elem . type === 'VariableDeclaration' ) {
27- elem . declarations . forEach ( decClar => {
28- statements . push ( decClar . id . name ) ;
28+ elem . declarations . forEach ( hook => {
29+ statements . push ( hook . id . name ) ;
2930 } ) ;
3031 }
3132 } ) ;
32- }
33-
34- // handle useState useContext
35- if ( ast [ 0 ] . expression . body . body ) {
36- ast = ast [ 0 ] . expression . body . body ;
37- // Hook Declarations will only be under 'VariableDeclaration' type
38- findHookDeclarations ( ast ) ;
3933 // Iterate array and determine getter/setters based on pattern
40- saveAstHooks ( statements ) ; // add key-value to hookState
41- } else {
42- // TODO test if this is needed, backward compatibility?
43- // Iterate through AST of every function declaration
44- // Check within each function declaration if there are hook declarations
45- ast . forEach ( functionDec => {
46- const { body } = functionDec . body ;
47- // Traverse through the function's funcDecs and Expression Statements
48- findHookDeclarations ( body ) ;
49- // Iterate array and determine getter/setters based on pattern
50- saveAstHooks ( statements ) ; // add key-value to hookState
34+ statements . forEach ( ( el , i ) => {
35+ if ( el . match ( / _ u s e / ) ) hookState [ el ] = statements [ i + 2 ] ;
5136 } ) ;
52- }
37+ } ) ;
5338 }
5439 return hookState ;
5540} ;
0 commit comments