@@ -9,47 +9,32 @@ module.exports = elementType => {
9
9
// Initialize empty object to store the setters and getter
10
10
let ast = JSXParser . parse ( elementType ) ;
11
11
const hookState = { } ;
12
- // All module exports will always start off as a single 'FunctionDeclaration' type
12
+
13
13
while ( Object . hasOwnProperty . call ( ast , 'body' ) ) {
14
- // Traverse down .body once before invoking parsing logic and will loop through any .body after
15
14
ast = ast . body ;
16
15
const statements = [ ] ;
17
16
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 => {
26
27
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 ) ;
29
30
} ) ;
30
31
}
31
32
} ) ;
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 ) ;
39
33
// 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 ] ;
51
36
} ) ;
52
- }
37
+ } ) ;
53
38
}
54
39
return hookState ;
55
40
} ;
0 commit comments