eslint-plugin-reactxp
Version:
ESlint rules for ReactXP
100 lines (99 loc) • 3.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var experimental_utils_1 = require("@typescript-eslint/experimental-utils");
var utils_1 = require("../utils");
var LIFECYCLE_METHODS = new Set([
'UNSAFE_componentWillReceiveProps',
'componentWillReceiveProps',
'UNSAFE_componentWillUpdate',
'componentWillUpdate',
'getSnapshotBeforeUpdate',
'shouldComponentUpdate',
'componentDidUpdate',
]);
exports.default = (0, utils_1.createRule)({
name: 'incorrect-this-props',
meta: {
docs: {
description: "Disallow use \"this.props\" in methods with the \"props\" argument",
recommended: 'error',
},
messages: {
incorrectThisPropsError: "\"this.props\" referenced within method that takes \"props\" input parameter.",
},
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create: function (context) {
var stack = [];
/**
* isProps
* checks if the identifier name is `props`
* @param node
* @returns {boolean}
*/
function isProps(node) {
return node.type === experimental_utils_1.AST_NODE_TYPES.Identifier && node.name === 'props';
}
/**
* hasParamProps
* checks if a method contains argument with the name `props`
* @param node
* @returns {boolean}
*/
function hasParamProps(node) {
return (node.value.type === experimental_utils_1.AST_NODE_TYPES.FunctionExpression &&
!!node.value.params.find(isProps));
}
/**
* enterMethod
* @param node
* @returns {void}
*/
function enterMethod(node) {
stack.push(node.key.type === experimental_utils_1.AST_NODE_TYPES.Identifier &&
LIFECYCLE_METHODS.has(node.key.name) &&
hasParamProps(node));
}
/**
* exitFunction
* @param node
* @returns {void}
*/
function exitFunction() {
stack.pop();
}
/**
* checkThisProps
* @param node
* @returns {void}
*/
function checkThisProps(node) {
if (!stack[stack.length - 1]) {
return;
}
var parent = node.parent;
if (!parent) {
return;
}
var grandParent = parent.parent;
if (!grandParent) {
return;
}
var isAssigned = grandParent.type === experimental_utils_1.AST_NODE_TYPES.VariableDeclarator &&
grandParent.id.type === experimental_utils_1.AST_NODE_TYPES.Identifier;
if (parent.type === experimental_utils_1.AST_NODE_TYPES.MemberExpression &&
parent.property.type === experimental_utils_1.AST_NODE_TYPES.Identifier &&
parent.property.name === 'props' &&
!isAssigned) {
context.report({ node: parent, messageId: 'incorrectThisPropsError' });
}
}
return {
MethodDefinition: enterMethod,
'MethodDefinition:exit': exitFunction,
ThisExpression: checkThisProps,
};
},
});