|
1 | | -import { CallExpression } from 'typescript'; |
| 1 | +import { |
| 2 | + CallExpression, |
| 3 | + isIdentifier, |
| 4 | + isPropertyAccessExpression, |
| 5 | + Expression, |
| 6 | +} from 'typescript'; |
2 | 7 |
|
3 | 8 | import { isHookIdentifier } from './is-hook-identifier'; |
4 | | -import { isReactApiExpression } from './is-react-api-expression'; |
| 9 | +import { |
| 10 | + RuleOptions, |
| 11 | + detectHooksFromNonReactNamespaceOptionName, |
| 12 | +} from './options'; |
5 | 13 |
|
6 | 14 | /** |
7 | 15 | * Tests if a `CallExpression` calls a React Hook |
8 | 16 | * @see https://github.com/facebook/react/blob/master/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js#L26 |
9 | 17 | */ |
10 | | -export function isHookCall({ expression }: CallExpression) { |
11 | | - return isHookAccessExpression(expression); |
| 18 | +export function isHookCall( |
| 19 | + { expression }: CallExpression, |
| 20 | + ruleOptions: RuleOptions, |
| 21 | +) { |
| 22 | + if (isIdentifier(expression) && isHookIdentifier(expression)) { |
| 23 | + return true; |
| 24 | + } else if ( |
| 25 | + isPropertyAccessExpression(expression) && |
| 26 | + isHookIdentifier(expression.name) |
| 27 | + ) { |
| 28 | + if (ruleOptions[detectHooksFromNonReactNamespaceOptionName]) { |
| 29 | + return true; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * The expression from which the property is accessed. |
| 34 | + * |
| 35 | + * @example for `React.useState`, this would be the `React` identifier |
| 36 | + */ |
| 37 | + const sourceExpression = expression.expression; |
| 38 | + |
| 39 | + return isReactIdentifier(sourceExpression); |
| 40 | + } |
| 41 | + |
| 42 | + return false; |
12 | 43 | } |
13 | 44 |
|
14 | | -/** |
15 | | - * Tests for `useHook` or `React.useHook` calls |
16 | | - */ |
17 | | -const isHookAccessExpression = isReactApiExpression(isHookIdentifier); |
| 45 | +const isReactIdentifier = (expression: Expression) => |
| 46 | + isIdentifier(expression) && expression.text === 'React'; |
0 commit comments