code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
function getFirstNodeInLine(context, node) { const sourceCode = getSourceCode(context); let token = node; let lines; do { token = sourceCode.getTokenBefore(token); lines = token.type === 'JSXText' ? token.value.split('\n') : null; } while ( token.type === 'JSXText' && /^\s*$/.test(lines[lines.length - 1]) ); return token; }
Gets the first node in a line from the initial node, excluding whitespace. @param {Object} context The node to check @param {ASTNode} node The node to check @return {ASTNode} the first node in the line
getFirstNodeInLine ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isNodeFirstInLine(context, node) { const token = getFirstNodeInLine(context, node); const startLine = node.loc.start.line; const endLine = token ? token.loc.end.line : -1; return startLine !== endLine; }
Checks if the node is the first in its line, excluding whitespace. @param {Object} context The node to check @param {ASTNode} node The node to check @return {boolean} true if it's the first node in its line
isNodeFirstInLine ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isFunctionLikeExpression(node) { return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'; }
Checks if the node is a function or arrow function expression. @param {ASTNode} node The node to check @return {boolean} true if it's a function-like expression
isFunctionLikeExpression ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isFunction(node) { return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; }
Checks if the node is a function. @param {ASTNode} node The node to check @return {boolean} true if it's a function
isFunction ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isFunctionLike(node) { return node.type === 'FunctionDeclaration' || isFunctionLikeExpression(node); }
Checks if node is a function declaration or expression or arrow function. @param {ASTNode} node The node to check @return {boolean} true if it's a function-like
isFunctionLike ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isClass(node) { return node.type === 'ClassDeclaration' || node.type === 'ClassExpression'; }
Checks if the node is a class. @param {ASTNode} node The node to check @return {boolean} true if it's a class
isClass ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function inConstructor(context, node) { let scope = getScope(context, node); while (scope) { // @ts-ignore if (scope.block && scope.block.parent && scope.block.parent.kind === 'constructor') { return true; } scope = scope.upper; } return false; }
Check if we are in a class constructor @param {Context} context @param {ASTNode} node The AST node being checked. @return {boolean}
inConstructor ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function stripQuotes(string) { return string.replace(/^'|'$/g, ''); }
Removes quotes from around an identifier. @param {string} string the identifier to strip @returns {string}
stripQuotes ( string )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function getKeyValue(context, node) { if (node.type === 'ObjectTypeProperty') { const tokens = getFirstTokens(context, node, 2); return (tokens[0].value === '+' || tokens[0].value === '-' ? tokens[1].value : stripQuotes(tokens[0].value) ); } if (node.type === 'GenericTypeAnnotation') { return node.id.name; } if (node.type === 'ObjectTypeAnnotation') { return; } const key = node.key || node.argument; if (!key) { return; } return key.type === 'Identifier' ? key.name : key.value; }
Retrieve the name of a key node @param {Context} context The AST node with the key. @param {any} node The AST node with the key. @return {string | undefined} the name of the key
getKeyValue ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isParenthesized(context, node) { const sourceCode = getSourceCode(context); const previousToken = sourceCode.getTokenBefore(node); const nextToken = sourceCode.getTokenAfter(node); return !!previousToken && !!nextToken && previousToken.value === '(' && previousToken.range[1] <= node.range[0] && nextToken.value === ')' && nextToken.range[0] >= node.range[1]; }
Checks if a node is surrounded by parenthesis. @param {object} context - Context from the rule @param {ASTNode} node - Node to be checked @returns {boolean}
isParenthesized ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isAssignmentLHS(node) { return ( node.parent && node.parent.type === 'AssignmentExpression' && node.parent.left === node ); }
Checks if a node is being assigned a value: props.bar = 'bar' @param {ASTNode} node The AST node being checked. @returns {boolean}
isAssignmentLHS ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function isCallExpression(node) { return node && node.type === 'CallExpression'; }
Matcher used to check whether given node is a `CallExpression` @param {ASTNode} node The AST node @returns {boolean} True if node is a `CallExpression`, false if not
isCallExpression ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
function unwrapTSAsExpression(node) { return isTSAsExpression(node) ? node.expression : node; }
Extracts the expression node that is wrapped inside a TS type assertion @param {ASTNode} node - potential TS node @returns {ASTNode} - unwrapped expression node
unwrapTSAsExpression ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/ast.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/ast.js
MIT
module.exports = function isDestructuredFromPragmaImport(context, node, variable) { const pragma = pragmaUtil.getFromContext(context); const variableInScope = variableUtil.getVariableFromContext(context, node, variable); if (variableInScope) { const latestDef = variableUtil.getLatestVariableDefinition(variableInScope); if (latestDef) { // check if latest definition is a variable declaration: 'variable = value' if (latestDef.node.type === 'VariableDeclarator' && latestDef.node.init) { // check for: 'variable = pragma.variable' if ( latestDef.node.init.type === 'MemberExpression' && latestDef.node.init.object.type === 'Identifier' && latestDef.node.init.object.name === pragma ) { return true; } // check for: '{variable} = pragma' if ( latestDef.node.init.type === 'Identifier' && latestDef.node.init.name === pragma ) { return true; } // "require('react')" let requireExpression = null; // get "require('react')" from: "{variable} = require('react')" if (astUtil.isCallExpression(latestDef.node.init)) { requireExpression = latestDef.node.init; } // get "require('react')" from: "variable = require('react').variable" if ( !requireExpression && latestDef.node.init.type === 'MemberExpression' && astUtil.isCallExpression(latestDef.node.init.object) ) { requireExpression = latestDef.node.init.object; } // check proper require. if ( requireExpression && requireExpression.callee && requireExpression.callee.name === 'require' && requireExpression.arguments[0] && requireExpression.arguments[0].value === pragma.toLocaleLowerCase() ) { return true; } return false; } // latest definition is an import declaration: import {<variable>} from 'react' if ( latestDef.parent && latestDef.parent.type === 'ImportDeclaration' && latestDef.parent.source.value === pragma.toLocaleLowerCase() ) { return true; } } } return false; };
Check if variable is destructured from pragma import @param {Context} context eslint context @param {ASTNode} node The AST node to check @param {string} variable The variable name to check @returns {boolean} True if createElement is destructured from the pragma
isDestructuredFromPragmaImport ( context , node , variable )
javascript
jsx-eslint/eslint-plugin-react
lib/util/isDestructuredFromPragmaImport.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/isDestructuredFromPragmaImport.js
MIT
set(name, allNames) { if (!hasBeenWritten) { // copy on write propVariables = new Map(propVariables); Object.assign(stack[stack.length - 1], { propVariables, hasBeenWritten: true }); stack[stack.length - 1].hasBeenWritten = true; } return propVariables.set(name, allNames); },
Add a variable name to the current scope @param {string} name @param {string[]} allNames Example: `props.a.b` should be formatted as `['a', 'b']` @returns {Map<string, string[]>}
set ( name , allNames )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
get(name) { return propVariables.get(name); },
Get the definition of a variable. @param {string} name @returns {string[]} Example: `props.a.b` is represented by `['a', 'b']`
get ( name )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function isCommonVariableNameForProps(name) { return name === 'props' || name === 'nextProps' || name === 'prevProps'; }
Checks if the string is one of `props`, `nextProps`, or `prevProps` @param {string} name The AST node being checked. @returns {boolean} True if the prop name matches
isCommonVariableNameForProps ( name )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function mustBeValidated(component) { return !!(component && !component.ignorePropsValidation); }
Checks if the component must be validated @param {Object} component The component to process @returns {boolean} True if the component must be validated, false if not.
mustBeValidated ( component )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function inLifeCycleMethod(context, node, checkAsyncSafeLifeCycles) { let scope = getScope(context, node); while (scope) { if (scope.block && scope.block.parent && scope.block.parent.key) { const name = scope.block.parent.key.name; if (LIFE_CYCLE_METHODS.indexOf(name) >= 0) { return true; } if (checkAsyncSafeLifeCycles && ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(name) >= 0) { return true; } } scope = scope.upper; } return false; }
Check if we are in a lifecycle method @param {object} context @param {ASTNode} node The AST node being checked. @param {boolean} checkAsyncSafeLifeCycles @return {boolean} true if we are in a class constructor, false if not
inLifeCycleMethod ( context , node , checkAsyncSafeLifeCycles )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function isNodeALifeCycleMethod(node, checkAsyncSafeLifeCycles) { if (node.key) { if (node.kind === 'constructor') { return true; } const nodeKeyName = node.key.name; if (typeof nodeKeyName !== 'string') { return false; } if (LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0) { return true; } if (checkAsyncSafeLifeCycles && ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0) { return true; } } return false; }
Returns true if the given node is a React Component lifecycle method @param {ASTNode} node The AST node being checked. @param {boolean} checkAsyncSafeLifeCycles @return {boolean} True if the node is a lifecycle method
isNodeALifeCycleMethod ( node , checkAsyncSafeLifeCycles )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function isInLifeCycleMethod(node, checkAsyncSafeLifeCycles) { if ( (node.type === 'MethodDefinition' || node.type === 'Property') && isNodeALifeCycleMethod(node, checkAsyncSafeLifeCycles) ) { return true; } if (node.parent) { return isInLifeCycleMethod(node.parent, checkAsyncSafeLifeCycles); } return false; }
Returns true if the given node is inside a React Component lifecycle method. @param {ASTNode} node The AST node being checked. @param {boolean} checkAsyncSafeLifeCycles @return {boolean} True if the node is inside a lifecycle method
isInLifeCycleMethod ( node , checkAsyncSafeLifeCycles )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function isSetStateUpdater(node) { const unwrappedParentCalleeNode = astUtil.isCallExpression(node.parent) && astUtil.unwrapTSAsExpression(node.parent.callee); return unwrappedParentCalleeNode && unwrappedParentCalleeNode.property && unwrappedParentCalleeNode.property.name === 'setState' // Make sure we are in the updater not the callback && node.parent.arguments[0] === node; }
Check if a function node is a setState updater @param {ASTNode} node a function node @return {boolean}
isSetStateUpdater ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function isInClassComponent(context, node) { return !!(componentUtil.getParentES6Component(context, node) || componentUtil.getParentES5Component(context, node)); }
@param {Context} context @param {ASTNode} node @returns {boolean}
isInClassComponent ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function isThisDotProps(node) { return !!node && node.type === 'MemberExpression' && astUtil.unwrapTSAsExpression(node.object).type === 'ThisExpression' && node.property.name === 'props'; }
Checks if the node is `this.props` @param {ASTNode|undefined} node @returns {boolean}
isThisDotProps ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function hasSpreadOperator(context, node) { const tokens = getSourceCode(context).getTokens(node); return tokens.length && tokens[0].value === '...'; }
Checks if the prop has spread operator. @param {object} context @param {ASTNode} node The AST node being marked. @returns {boolean} True if the prop has spread operator, false if not.
hasSpreadOperator ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function isPropTypesUsageByMemberExpression(context, node, utils, checkAsyncSafeLifeCycles) { const unwrappedObjectNode = astUtil.unwrapTSAsExpression(node.object); if (isInClassComponent(context, node)) { // this.props.* if (isThisDotProps(unwrappedObjectNode)) { return true; } // props.* or prevProps.* or nextProps.* if ( isCommonVariableNameForProps(unwrappedObjectNode.name) && (inLifeCycleMethod(context, node, checkAsyncSafeLifeCycles) || astUtil.inConstructor(context, node)) ) { return true; } // this.setState((_, props) => props.*)) if (isPropArgumentInSetStateUpdater(context, node, unwrappedObjectNode.name)) { return true; } return false; } // props.* in function component return unwrappedObjectNode.name === 'props' && !astUtil.isAssignmentLHS(node); }
Checks if the node is a propTypes usage of the form `this.props.*`, `props.*`, `prevProps.*`, or `nextProps.*`. @param {Context} context @param {ASTNode} node @param {Object} utils @param {boolean} checkAsyncSafeLifeCycles @returns {boolean}
isPropTypesUsageByMemberExpression ( context , node , utils , checkAsyncSafeLifeCycles )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function getPropertyName(context, node, utils, checkAsyncSafeLifeCycles) { const property = node.property; if (property) { switch (property.type) { case 'Identifier': if (node.computed) { return '__COMPUTED_PROP__'; } return property.name; case 'MemberExpression': return; case 'Literal': // Accept computed properties that are literal strings if (typeof property.value === 'string') { return property.value; } // Accept number as well but only accept props[123] if (typeof property.value === 'number') { if (isPropTypesUsageByMemberExpression(context, node, utils, checkAsyncSafeLifeCycles)) { return property.raw; } } // falls through default: if (node.computed) { return '__COMPUTED_PROP__'; } break; } } }
Retrieve the name of a property node @param {Context} context @param {ASTNode} node The AST node with the property. @param {Object} utils @param {boolean} checkAsyncSafeLifeCycles @return {string|undefined} the name of the property or undefined if not found
getPropertyName ( context , node , utils , checkAsyncSafeLifeCycles )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function markDestructuredFunctionArgumentsAsUsed(node) { const param = node.params && isSetStateUpdater(node) ? node.params[1] : node.params[0]; const destructuring = param && ( param.type === 'ObjectPattern' || ((param.type === 'AssignmentPattern') && (param.left.type === 'ObjectPattern')) ); if (destructuring && (components.get(node) || components.get(node.parent))) { markPropTypesAsUsed(node); } }
@param {ASTNode} node We expect either an ArrowFunctionExpression, FunctionDeclaration, or FunctionExpression
markDestructuredFunctionArgumentsAsUsed ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function handleFunctionLikeExpressions(node) { pushScope(); handleSetStateUpdater(node); markDestructuredFunctionArgumentsAsUsed(node); }
Handle both stateless functions and setState updater functions. @param {ASTNode} node We expect either an ArrowFunctionExpression, FunctionDeclaration, or FunctionExpression
handleFunctionLikeExpressions ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function markPropTypesAsUsed(node, parentNames) { parentNames = parentNames || []; let type; let name; let allNames; let properties; if (astUtil.isMemberExpression(node)) { name = getPropertyName(context, node, utils, checkAsyncSafeLifeCycles); if (name) { allNames = parentNames.concat(name); const parent = node.parent; if ( // Match props.foo.bar, don't match bar[props.foo] parent.type === 'MemberExpression' && 'object' in parent && parent.object === node ) { markPropTypesAsUsed(parent, allNames); } // Handle the destructuring part of `const {foo} = props.a.b` if ( astUtil.isVariableDeclarator(parent) && parent.id.type === 'ObjectPattern' ) { parent.id.parent = parent; // patch for bug in eslint@4 in which ObjectPattern has no parent markPropTypesAsUsed(parent.id, allNames); } // const a = props.a if ( astUtil.isVariableDeclarator(parent) && parent.id.type === 'Identifier' ) { propVariables.set(parent.id.name, allNames); } // Do not mark computed props as used. type = name !== '__COMPUTED_PROP__' ? 'direct' : null; } } else if (astUtil.isFunctionLike(node)) { if (node.params.length > 0) { type = 'destructuring'; const propParam = isSetStateUpdater(node) ? node.params[1] : node.params[0]; properties = propParam.type === 'AssignmentPattern' ? propParam.left.properties : propParam.properties; } } else if (astUtil.isObjectPattern(node)) { type = 'destructuring'; properties = node.properties; } else if (node.type !== 'TSEmptyBodyFunctionExpression') { throw new Error(`${node.type} ASTNodes are not handled by markPropTypesAsUsed`); } const component = components.get(utils.getParentComponent(node)); const usedPropTypes = (component && component.usedPropTypes) || []; let ignoreUnusedPropTypesValidation = (component && component.ignoreUnusedPropTypesValidation) || false; if (type === 'direct') { // Ignore Object methods if (!(name in Object.prototype)) { const reportedNode = node.property; usedPropTypes.push({ name, allNames, node: reportedNode, }); } } else if (type === 'destructuring') { for (let k = 0, l = (properties || []).length; k < l; k++) { if (hasSpreadOperator(context, properties[k]) || properties[k].computed) { ignoreUnusedPropTypesValidation = true; break; } const propName = astUtil.getKeyValue(context, properties[k]); if (!propName || properties[k].type !== 'Property') { break; } usedPropTypes.push({ allNames: parentNames.concat([propName]), name: propName, node: properties[k], }); if (properties[k].value.type === 'ObjectPattern') { markPropTypesAsUsed(properties[k].value, parentNames.concat([propName])); } else if (properties[k].value.type === 'Identifier') { propVariables.set(properties[k].value.name, parentNames.concat(propName)); } } } components.set(component ? component.node : node, { usedPropTypes, ignoreUnusedPropTypesValidation, }); } /** * @param {ASTNode} node We expect either an ArrowFunctionExpression, * FunctionDeclaration, or FunctionExpression */ function markDestructuredFunctionArgumentsAsUsed(node) { const param = node.params && isSetStateUpdater(node) ? node.params[1] : node.params[0]; const destructuring = param && ( param.type === 'ObjectPattern' || ((param.type === 'AssignmentPattern') && (param.left.type === 'ObjectPattern')) ); if (destructuring && (components.get(node) || components.get(node.parent))) { markPropTypesAsUsed(node); } } function handleSetStateUpdater(node) { if (!node.params || node.params.length < 2 || !isSetStateUpdater(node)) { return; } markPropTypesAsUsed(node); } /** * Handle both stateless functions and setState updater functions. * @param {ASTNode} node We expect either an ArrowFunctionExpression, * FunctionDeclaration, or FunctionExpression */ function handleFunctionLikeExpressions(node) { pushScope(); handleSetStateUpdater(node); markDestructuredFunctionArgumentsAsUsed(node); } function handleCustomValidators(component) { const propTypes = component.declaredPropTypes; if (!propTypes) { return; } Object.keys(propTypes).forEach((key) => { const node = propTypes[key].node; if (node && node.value && astUtil.isFunctionLikeExpression(node.value)) { markPropTypesAsUsed(node.value); } }); } return { VariableDeclarator(node) { const unwrappedInitNode = astUtil.unwrapTSAsExpression(node.init); // let props = this.props if (isThisDotProps(unwrappedInitNode) && isInClassComponent(context, node) && node.id.type === 'Identifier') { propVariables.set(node.id.name, []); } // Only handles destructuring if (node.id.type !== 'ObjectPattern' || !unwrappedInitNode) { return; } // let {props: {firstname}} = this const propsProperty = node.id.properties.find((property) => ( property.key && (property.key.name === 'props' || property.key.value === 'props') )); if (unwrappedInitNode.type === 'ThisExpression' && propsProperty && propsProperty.value.type === 'ObjectPattern') { markPropTypesAsUsed(propsProperty.value); return; } // let {props} = this if (unwrappedInitNode.type === 'ThisExpression' && propsProperty && propsProperty.value.name === 'props') { propVariables.set('props', []); return; } // let {firstname} = props if ( isCommonVariableNameForProps(unwrappedInitNode.name) && (utils.getParentStatelessComponent(node) || isInLifeCycleMethod(node, checkAsyncSafeLifeCycles)) ) { markPropTypesAsUsed(node.id); return; } // let {firstname} = this.props if (isThisDotProps(unwrappedInitNode) && isInClassComponent(context, node)) { markPropTypesAsUsed(node.id); return; } // let {firstname} = thing, where thing is defined by const thing = this.props.**.* if (propVariables.get(unwrappedInitNode.name)) { markPropTypesAsUsed(node.id, propVariables.get(unwrappedInitNode.name)); } }, FunctionDeclaration: handleFunctionLikeExpressions, ArrowFunctionExpression: handleFunctionLikeExpressions, FunctionExpression: handleFunctionLikeExpressions, 'FunctionDeclaration:exit': popScope, 'ArrowFunctionExpression:exit': popScope, 'FunctionExpression:exit': popScope, JSXSpreadAttribute(node) { const component = components.get(utils.getParentComponent(node)); components.set(component ? component.node : node, { ignoreUnusedPropTypesValidation: node.argument.type !== 'ObjectExpression', }); }, 'MemberExpression, OptionalMemberExpression'(node) { if (isPropTypesUsageByMemberExpression(context, node, utils, checkAsyncSafeLifeCycles)) { markPropTypesAsUsed(node); return; } const propVariable = propVariables.get(astUtil.unwrapTSAsExpression(node.object).name); if (propVariable) { markPropTypesAsUsed(node, propVariable); } }, ObjectPattern(node) { // If the object pattern is a destructured props object in a lifecycle // method -- mark it for used props. if (isNodeALifeCycleMethod(node.parent.parent, checkAsyncSafeLifeCycles) && node.properties.length > 0) { markPropTypesAsUsed(node.parent); } }, 'Program:exit'() { values(components.list()) .filter((component) => mustBeValidated(component)) .forEach((component) => { handleCustomValidators(component); }); }, }; };
Mark a prop type as used @param {ASTNode} node The AST node being marked. @param {string[]} [parentNames]
markPropTypesAsUsed ( node , parentNames )
javascript
jsx-eslint/eslint-plugin-react
lib/util/usedPropTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/usedPropTypes.js
MIT
function log(message) { if (!/=-(f|-format)=/.test(process.argv.join('='))) { // eslint-disable-next-line no-console console.log(message); } }
Logs out a message if there is no format option set. @param {string} message - Message to log.
log ( message )
javascript
jsx-eslint/eslint-plugin-react
lib/util/log.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/log.js
MIT
function getCreateClassFromContext(context) { let pragma = 'createReactClass'; // .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings) if (context.settings.react && context.settings.react.createClass) { pragma = context.settings.react.createClass; } if (!JS_IDENTIFIER_REGEX.test(pragma)) { throw new Error(`createClass pragma ${pragma} is not a valid function name`); } return pragma; }
@param {Context} context @returns {string}
getCreateClassFromContext ( context )
javascript
jsx-eslint/eslint-plugin-react
lib/util/pragma.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/pragma.js
MIT
function markDefaultPropsAsUnresolved(component) { components.set(component.node, { defaultProps: 'unresolved', }); }
Marks a component's DefaultProps declaration as "unresolved". A component's DefaultProps is marked as "unresolved" if we cannot safely infer the values of its defaultProps declarations without risking false negatives. @param {Object} component The component to mark. @returns {void}
markDefaultPropsAsUnresolved ( component )
javascript
jsx-eslint/eslint-plugin-react
lib/util/defaultProps.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/defaultProps.js
MIT
function addDefaultPropsToComponent(component, defaultProps) { // Early return if this component's defaultProps is already marked as "unresolved". if (component.defaultProps === 'unresolved') { return; } if (defaultProps === 'unresolved') { markDefaultPropsAsUnresolved(component); return; } const defaults = component.defaultProps || {}; const newDefaultProps = Object.assign( {}, defaults, fromEntries(defaultProps.map((prop) => [prop.name, prop])) ); components.set(component.node, { defaultProps: newDefaultProps, }); }
Adds defaultProps to the component passed in. @param {ASTNode} component The component to add the defaultProps to. @param {Object[]|'unresolved'} defaultProps defaultProps to add to the component or the string "unresolved" if this component has defaultProps that can't be resolved. @returns {void}
addDefaultPropsToComponent ( component , defaultProps )
javascript
jsx-eslint/eslint-plugin-react
lib/util/defaultProps.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/defaultProps.js
MIT
function isFunctionType(node) { if (!node) return false; const nodeType = node.type; return nodeType === 'FunctionDeclaration' || nodeType === 'FunctionExpression' || nodeType === 'ArrowFunctionExpression'; }
Check if node is function type. @param {ASTNode} node @returns {boolean}
isFunctionType ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function isSuperTypeParameterPropsDeclaration(node) { if (node && (node.type === 'ClassDeclaration' || node.type === 'ClassExpression')) { const parameters = propsUtil.getSuperTypeArguments(node); if (parameters && parameters.params.length > 0) { return true; } } return false; }
Checks if we are declaring a props as a generic type in a flow-annotated class. @param {ASTNode} node the AST node being checked. @returns {boolean} True if the node is a class with generic prop types, false if not.
isSuperTypeParameterPropsDeclaration ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function isInsideClassBody(node) { let parent = node.parent; while (parent) { if (parent.type === 'ClassBody') { return true; } parent = parent.parent; } return false; }
Checks if a node is inside a class body. @param {ASTNode} node the AST node being checked. @returns {boolean} True if the node has a ClassBody ancestor, false if not.
isInsideClassBody ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function typeScope() { return stack[stack.length - 1]; }
Returns the full scope. @returns {Object} The whole scope.
typeScope ( )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function getInTypeScope(key) { return stack[stack.length - 1][key]; }
Gets a node from the scope. @param {string} key The name of the identifier to access. @returns {ASTNode} The ASTNode associated with the given identifier.
getInTypeScope ( key )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function setInTypeScope(key, value) { stack[stack.length - 1][key] = value; return value; }
Sets the new value in the scope. @param {string} key The name of the identifier to access @param {ASTNode} value The new value for the identifier. @returns {ASTNode} The ASTNode associated with the given identifier.
setInTypeScope ( key , value )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function hasCustomValidator(validator) { return customValidators.indexOf(validator) !== -1; }
Checks if prop should be validated by plugin-react-proptypes @param {string} validator Name of validator to check. @returns {boolean} True if validator should be checked by custom validator.
hasCustomValidator ( validator )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function resolveTypeAnnotation(node) { let annotation = (node.left && node.left.typeAnnotation) || node.typeAnnotation || node; while (annotation && (annotation.type === 'TypeAnnotation' || annotation.type === 'NullableTypeAnnotation')) { annotation = annotation.typeAnnotation; } if (annotation.type === 'GenericTypeAnnotation' && getInTypeScope(annotation.id.name)) { return getInTypeScope(annotation.id.name); } return annotation; }
Resolve the type annotation for a given node. Flow annotations are sometimes wrapped in outer `TypeAnnotation` and `NullableTypeAnnotation` nodes which obscure the annotation we're interested in. This method also resolves type aliases where possible. @param {ASTNode} node The annotation or a node containing the type annotation. @returns {ASTNode} The resolved type annotation for the node.
resolveTypeAnnotation ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function buildTypeAnnotationDeclarationTypes(annotation, parentName, seen) { if (typeof seen === 'undefined') { // Keeps track of annotations we've already seen to // prevent problems with recursive types. seen = new Set(); } if (seen.has(annotation)) { // This must be a recursive type annotation, so just accept anything. return {}; } seen.add(annotation); if (annotation.type in typeDeclarationBuilders) { return typeDeclarationBuilders[annotation.type](annotation, parentName, seen); } return {}; }
Creates the representation of the React props type annotation for the component. The representation is used to verify nested used properties. @param {ASTNode} annotation Type annotation for the props class property. @param {string} parentName @param {Set<ASTNode>} [seen] @return {Object} The representation of the declaration, empty object means the property is declared without the need for further analysis.
buildTypeAnnotationDeclarationTypes ( annotation , parentName , seen )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function declarePropTypesForObjectTypeAnnotation(propTypes, declaredPropTypes) { let ignorePropsValidation = false; iterateProperties(context, propTypes.properties, (key, value, propNode) => { if (!value) { ignorePropsValidation = ignorePropsValidation || propNode.type !== 'ObjectTypeSpreadProperty'; return; } const types = buildTypeAnnotationDeclarationTypes(value, key); types.fullName = key; types.name = key; types.node = propNode; types.isRequired = !propNode.optional; declaredPropTypes[key] = types; }, (spreadNode) => { const key = astUtil.getKeyValue(context, spreadNode); const spreadAnnotation = getInTypeScope(key); if (!spreadAnnotation) { ignorePropsValidation = true; } else { const spreadIgnoreValidation = declarePropTypesForObjectTypeAnnotation(spreadAnnotation, declaredPropTypes); ignorePropsValidation = ignorePropsValidation || spreadIgnoreValidation; } }); return ignorePropsValidation; }
Marks all props found inside ObjectTypeAnnotation as declared. Modifies the declaredProperties object @param {ASTNode} propTypes @param {Object} declaredPropTypes @returns {boolean} True if propTypes should be ignored (e.g. when a type can't be resolved, when it is imported)
declarePropTypesForObjectTypeAnnotation ( propTypes , declaredPropTypes )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function declarePropTypesForIntersectionTypeAnnotation(propTypes, declaredPropTypes) { return propTypes.types.some((annotation) => { if (annotation.type === 'ObjectTypeAnnotation') { return declarePropTypesForObjectTypeAnnotation(annotation, declaredPropTypes); } if (annotation.type === 'UnionTypeAnnotation') { return true; } // Type can't be resolved if (!annotation.id) { return true; } const typeNode = getInTypeScope(annotation.id.name); if (!typeNode) { return true; } if (typeNode.type === 'IntersectionTypeAnnotation') { return declarePropTypesForIntersectionTypeAnnotation(typeNode, declaredPropTypes); } return declarePropTypesForObjectTypeAnnotation(typeNode, declaredPropTypes); }); }
Marks all props found inside IntersectionTypeAnnotation as declared. Since InterSectionTypeAnnotations can be nested, this handles recursively. Modifies the declaredPropTypes object @param {ASTNode} propTypes @param {Object} declaredPropTypes @returns {boolean} True if propTypes should be ignored (e.g. when a type can't be resolved, when it is imported)
declarePropTypesForIntersectionTypeAnnotation ( propTypes , declaredPropTypes )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function resolveValueForIdentifierNode(node, rootNode, callback) { if ( rootNode && node && node.type === 'Identifier' ) { const scope = getScope(context, rootNode); const identVariable = scope.variableScope.variables.find( (variable) => variable.name === node.name ); if (identVariable) { const definition = identVariable.defs[identVariable.defs.length - 1]; callback(definition.node.init); } } }
Resolve node of type Identifier when building declaration types. @param {ASTNode} node @param {ASTNode} rootNode @param {Function} callback called with the resolved value only if resolved.
resolveValueForIdentifierNode ( node , rootNode , callback )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function getLeftMostTypeName(node) { if (node.name) return node.name; if (node.left) return getLeftMostTypeName(node.left); }
Returns the left most typeName of a node, e.g: FC<Props>, React.FC<Props> The representation is used to verify nested used properties. @param {ASTNode} node @return {string | undefined}
getLeftMostTypeName ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function filterInterfaceOrTypeAlias(node) { return ( astUtil.isTSInterfaceDeclaration(node) || astUtil.isTSTypeAliasDeclaration(node) ); }
Returns true if the node is either a interface or type alias declaration @param {ASTNode} node @return {boolean}
filterInterfaceOrTypeAlias ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function filterInterfaceOrAliasByName(node, typeName) { return ( node.id && node.id.name === typeName ) || ( node.declaration && node.declaration.id && node.declaration.id.name === typeName ); }
Returns true if the interface or type alias declaration node name matches the type-name str @param {ASTNode} node @param {string} typeName @return {boolean}
filterInterfaceOrAliasByName ( node , typeName )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
visitTSNode(node) { if (!node) return; if (astUtil.isTSTypeAnnotation(node)) { const typeAnnotation = node.typeAnnotation; this.visitTSNode(typeAnnotation); } else if (astUtil.isTSTypeReference(node)) { this.searchDeclarationByName(node); } else if (astUtil.isTSInterfaceHeritage(node)) { this.searchDeclarationByName(node); } else if (astUtil.isTSTypeLiteral(node)) { // Check node is an object literal if (Array.isArray(node.members)) { this.foundDeclaredPropertiesList = this.foundDeclaredPropertiesList.concat(node.members); } } else if (astUtil.isTSIntersectionType(node)) { this.convertIntersectionTypeToPropTypes(node); } else if (astUtil.isTSParenthesizedType(node)) { const typeAnnotation = node.typeAnnotation; this.visitTSNode(typeAnnotation); } else if (astUtil.isTSTypeParameterInstantiation(node)) { if (Array.isArray(node.params)) { node.params.forEach((x) => this.visitTSNode(x)); } } else { this.shouldIgnorePropTypes = true; } }
The node will be distribute to different function. @param {ASTNode} node
visitTSNode ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
const candidateTypes = this.sourceCode.ast.body.filter((item) => astUtil.isTSTypeDeclaration(item));
From line 577 to line 581, and line 588 to line 590 are trying to handle typescript-eslint-parser Need to be deprecated after remove typescript-eslint-parser support.
(anonymous)
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
searchDeclarationByName(node) { let typeName; if (astUtil.isTSTypeReference(node)) { typeName = node.typeName.name; const leftMostName = getLeftMostTypeName(node.typeName); const shouldTraverseTypeParams = genericReactTypesImport.has(leftMostName); const nodeTypeArguments = propsUtil.getTypeArguments(node); if (shouldTraverseTypeParams && nodeTypeArguments && nodeTypeArguments.length !== 0) { // All react Generic types are derived from: // type PropsWithChildren<P> = P & { children?: ReactNode | undefined } // So we should construct an optional children prop this.shouldSpecifyOptionalChildrenProps = true; const rightMostName = getRightMostTypeName(node.typeName); if ( leftMostName === 'React' && ( rightMostName === 'HTMLAttributes' || rightMostName === 'HTMLElement' || rightMostName === 'HTMLProps' ) ) { this.shouldSpecifyClassNameProp = true; } const importedName = localToImportedMap[rightMostName]; const idx = genericTypeParamIndexWherePropsArePresent[ leftMostName !== rightMostName ? rightMostName : importedName ]; const nextNode = nodeTypeArguments.params[idx]; this.visitTSNode(nextNode); return; } } else if (astUtil.isTSInterfaceHeritage(node)) { if (!node.expression && node.id) { typeName = node.id.name; } else { typeName = node.expression.name; } } if (!typeName) { this.shouldIgnorePropTypes = true; return; } if (typeName === 'ReturnType') { this.convertReturnTypeToPropTypes(node, this.rootNode); return; } // Prevent recursive inheritance will cause maximum callstack. if (this.referenceNameMap.has(typeName)) { this.shouldIgnorePropTypes = true; return; } // Add typeName to Set and consider it as traversed. this.referenceNameMap.add(typeName); /** * From line 577 to line 581, and line 588 to line 590 are trying to handle typescript-eslint-parser * Need to be deprecated after remove typescript-eslint-parser support. */ const candidateTypes = this.sourceCode.ast.body.filter((item) => astUtil.isTSTypeDeclaration(item)); const declarations = flatMap( candidateTypes, (type) => ( type.declarations || ( type.declaration && type.declaration.declarations ) || type.declaration ) ); // we tried to find either an interface or a type with the TypeReference name const typeDeclaration = declarations.filter((dec) => dec.id.name === typeName); const interfaceDeclarations = this.sourceCode.ast.body .filter(filterInterfaceOrTypeAlias) .filter((item) => filterInterfaceOrAliasByName(item, typeName)) .map((item) => (item.declaration || item)); if (typeDeclaration.length !== 0) { typeDeclaration.map((t) => t.init || t.typeAnnotation).forEach(this.visitTSNode, this); } else if (interfaceDeclarations.length !== 0) { interfaceDeclarations.forEach(this.traverseDeclaredInterfaceOrTypeAlias, this); } else { this.shouldIgnorePropTypes = true; } }
Search TSInterfaceDeclaration or TSTypeAliasDeclaration, by using TSTypeReference and TSInterfaceHeritage name. @param {ASTNode} node
searchDeclarationByName ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
traverseDeclaredInterfaceOrTypeAlias(node) { if (astUtil.isTSInterfaceDeclaration(node)) { // Handle TSInterfaceDeclaration interface Props { name: string, id: number}, should put in properties list directly; this.foundDeclaredPropertiesList = this.foundDeclaredPropertiesList.concat(node.body.body); } // Handle TSTypeAliasDeclaration type Props = {name:string} if (astUtil.isTSTypeAliasDeclaration(node)) { const typeAnnotation = node.typeAnnotation; this.visitTSNode(typeAnnotation); } if (Array.isArray(node.extends)) { node.extends.forEach((x) => this.visitTSNode(x)); // This line is trying to handle typescript-eslint-parser // typescript-eslint-parser extension is name as heritage } else if (Array.isArray(node.heritage)) { node.heritage.forEach((x) => this.visitTSNode(x)); } }
Traverse TSInterfaceDeclaration and TSTypeAliasDeclaration which retrieve from function searchDeclarationByName; @param {ASTNode} node
traverseDeclaredInterfaceOrTypeAlias ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function markAnnotatedFunctionArgumentsAsDeclared(node, rootNode) { if (!node.params || !node.params.length) { return; } let propTypesArguments = null; if (node.parent) { propTypesArguments = propsUtil.getTypeArguments(node.parent); } if ( node.parent && node.parent.callee && propTypesArguments && propTypesArguments.params && ( node.parent.callee.name === 'forwardRef' || ( node.parent.callee.object && node.parent.callee.property && node.parent.callee.object.name === 'React' && node.parent.callee.property.name === 'forwardRef' ) ) ) { const declaredPropTypes = {}; const obj = new DeclarePropTypesForTSTypeAnnotation(propTypesArguments.params[1], declaredPropTypes, rootNode); components.set(node, { declaredPropTypes: obj.declaredPropTypes, ignorePropsValidation: obj.shouldIgnorePropTypes, }); return; } const siblingIdentifier = node.parent && node.parent.id; const siblingHasTypeAnnotation = siblingIdentifier && siblingIdentifier.typeAnnotation; const isNodeAnnotated = annotations.isAnnotatedFunctionPropsDeclaration(node, context); if (!isNodeAnnotated && !siblingHasTypeAnnotation) { return; } // https://github.com/jsx-eslint/eslint-plugin-react/issues/2784 if (isInsideClassBody(node) && !astUtil.isFunction(node)) { return; } // Should ignore function that not return JSXElement if (!utils.isReturningJSXOrNull(node) || startWithCapitalizedLetter(node)) { return; } if (isNodeAnnotated) { const param = node.params[0]; if (param.typeAnnotation && param.typeAnnotation.typeAnnotation && param.typeAnnotation.typeAnnotation.type === 'UnionTypeAnnotation') { param.typeAnnotation.typeAnnotation.types.forEach((annotation) => { if (annotation.type === 'GenericTypeAnnotation') { markPropTypesAsDeclared(node, resolveTypeAnnotation(annotation), rootNode); } else { markPropTypesAsDeclared(node, annotation, rootNode); } }); } else { markPropTypesAsDeclared(node, resolveTypeAnnotation(param), rootNode); } } else { // implements what's discussed here: https://github.com/jsx-eslint/eslint-plugin-react/issues/2777#issuecomment-683944481 const annotation = siblingIdentifier.typeAnnotation.typeAnnotation; if ( annotation && annotation.type !== 'TSTypeReference' && propsUtil.getTypeArguments(annotation) == null ) { return; } if (!isValidReactGenericTypeAnnotation(annotation)) return; markPropTypesAsDeclared(node, resolveTypeAnnotation(siblingIdentifier), rootNode); } }
@param {ASTNode} node We expect either an ArrowFunctionExpression, FunctionDeclaration, or FunctionExpression @param {ASTNode} rootNode
markAnnotatedFunctionArgumentsAsDeclared ( node , rootNode )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function resolveSuperParameterPropsType(node) { let propsParameterPosition; const parameters = propsUtil.getSuperTypeArguments(node); try { // Flow <=0.52 had 3 required TypedParameters of which the second one is the Props. // Flow >=0.53 has 2 optional TypedParameters of which the first one is the Props. propsParameterPosition = testFlowVersion(context, '>= 0.53.0') ? 0 : 1; } catch (e) { // In case there is no flow version defined, we can safely assume that when there are 3 Props we are dealing with version <= 0.52 propsParameterPosition = parameters.params.length <= 2 ? 0 : 1; } let annotation = parameters.params[propsParameterPosition]; while (annotation && (annotation.type === 'TypeAnnotation' || annotation.type === 'NullableTypeAnnotation')) { annotation = annotation.typeAnnotation; } if (annotation && annotation.type === 'GenericTypeAnnotation' && getInTypeScope(annotation.id.name)) { return getInTypeScope(annotation.id.name); } return annotation; }
Resolve the type annotation for a given class declaration node. @param {ASTNode} node The annotation or a node containing the type annotation. @returns {ASTNode} The resolved type annotation for the node.
resolveSuperParameterPropsType ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function isAnnotatedClassPropsDeclaration(node) { if (node && (node.type === 'ClassProperty' || node.type === 'PropertyDefinition')) { const tokens = getFirstTokens(context, node, 2); if ( node.typeAnnotation && ( tokens[0].value === 'props' || (tokens[1] && tokens[1].value === 'props') ) ) { return true; } } return false; }
Checks if we are declaring a `props` class property with a flow type annotation. @param {ASTNode} node The AST node being checked. @returns {boolean} True if the node is a type annotated props declaration, false if not.
isAnnotatedClassPropsDeclaration ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypes.js
MIT
function getValueName(node) { return node.type === 'Property' && node.value.property && node.value.property.name; }
Returns the value name of a node. @param {ASTNode} node the node to check. @returns {string} The name of the node.
getValueName ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypesSort.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypesSort.js
MIT
function isRequiredProp(node) { return getValueName(node) === 'isRequired'; }
Checks if the prop is required or not. @param {ASTNode} node the prop to check. @returns {boolean} true if the prop is required.
isRequiredProp ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypesSort.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypesSort.js
MIT
function isCallbackPropName(propName) { return /^on[A-Z]/.test(propName); }
Checks if the proptype is a callback by checking if it starts with 'on'. @param {string} propName the name of the proptype to check. @returns {boolean} true if the proptype is a callback.
isCallbackPropName ( propName )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypesSort.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypesSort.js
MIT
function isShapeProp(node) { return !!( node && node.callee && node.callee.property && node.callee.property.name === 'shape' ); }
Checks if the prop is PropTypes.shape. @param {ASTNode} node the prop to check. @returns {boolean} true if the prop is PropTypes.shape.
isShapeProp ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypesSort.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypesSort.js
MIT
function getShapeProperties(node) { return node.arguments && node.arguments[0] && node.arguments[0].properties; }
Returns the properties of a PropTypes.shape. @param {ASTNode} node the prop to check. @returns {Array} the properties of the PropTypes.shape node.
getShapeProperties ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypesSort.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypesSort.js
MIT
function sorter(a, b, context, ignoreCase, requiredFirst, callbacksLast, noSortAlphabetically) { const aKey = String(astUtil.getKeyValue(context, a)); const bKey = String(astUtil.getKeyValue(context, b)); if (requiredFirst) { if (isRequiredProp(a) && !isRequiredProp(b)) { return -1; } if (!isRequiredProp(a) && isRequiredProp(b)) { return 1; } } if (callbacksLast) { if (isCallbackPropName(aKey) && !isCallbackPropName(bKey)) { return 1; } if (!isCallbackPropName(aKey) && isCallbackPropName(bKey)) { return -1; } } if (!noSortAlphabetically) { if (ignoreCase) { return aKey.localeCompare(bKey); } if (aKey < bKey) { return -1; } if (aKey > bKey) { return 1; } } return 0; }
Compares two elements. @param {ASTNode} a the first element to compare. @param {ASTNode} b the second element to compare. @param {Context} context The context of the two nodes. @param {boolean=} ignoreCase whether or not to ignore case when comparing the two elements. @param {boolean=} requiredFirst whether or not to sort required elements first. @param {boolean=} callbacksLast whether or not to sort callbacks after everything else. @param {boolean=} noSortAlphabetically whether or not to disable alphabetical sorting of the elements. @returns {number} the sort order of the two elements.
sorter ( a , b , context , ignoreCase , requiredFirst , callbacksLast , noSortAlphabetically )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypesSort.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypesSort.js
MIT
function fixPropTypesSort( context, fixer, declarations, ignoreCase, requiredFirst, callbacksLast, noSortAlphabetically, sortShapeProp, checkTypes ) { function sortInSource(allNodes, source) { const originalSource = source; const sourceCode = getSourceCode(context); for (let i = 0; i < allNodes.length; i++) { const node = allNodes[i]; let commentAfter = []; let commentBefore = []; let newStart = 0; let newEnd = 0; try { commentBefore = sourceCode.getCommentsBefore(node); commentAfter = sourceCode.getCommentsAfter(node); } catch (e) { /**/ } if (commentAfter.length === 0 || commentBefore.length === 0) { newStart = node.range[0]; newEnd = node.range[1]; } const firstCommentBefore = commentBefore[0]; if (commentBefore.length >= 1) { newStart = firstCommentBefore.range[0]; } const lastCommentAfter = commentAfter[commentAfter.length - 1]; if (commentAfter.length >= 1) { newEnd = lastCommentAfter.range[1]; } commentnodeMap.set(node, { start: newStart, end: newEnd, hasComment: true }); } const nodeGroups = allNodes.reduce((acc, curr) => { if (curr.type === 'ExperimentalSpreadProperty' || curr.type === 'SpreadElement') { acc.push([]); } else { acc[acc.length - 1].push(curr); } return acc; }, [[]]); nodeGroups.forEach((nodes) => { const sortedAttributes = toSorted( nodes, (a, b) => sorter(a, b, context, ignoreCase, requiredFirst, callbacksLast, noSortAlphabetically) ); const sourceCodeText = getText(context); let separator = ''; source = nodes.reduceRight((acc, attr, index) => { const sortedAttr = sortedAttributes[index]; const commentNode = commentnodeMap.get(sortedAttr); let sortedAttrText = sourceCodeText.slice(commentNode.start, commentNode.end); const sortedAttrTextLastChar = sortedAttrText[sortedAttrText.length - 1]; if (!separator && [';', ','].some((allowedSep) => sortedAttrTextLastChar === allowedSep)) { separator = sortedAttrTextLastChar; } if (sortShapeProp && isShapeProp(sortedAttr.value)) { const shape = getShapeProperties(sortedAttr.value); if (shape) { const attrSource = sortInSource( shape, originalSource ); sortedAttrText = attrSource.slice(sortedAttr.range[0], sortedAttr.range[1]); } } const sortedAttrTextVal = checkTypes && !sortedAttrText.endsWith(separator) ? `${sortedAttrText}${separator}` : sortedAttrText; return `${acc.slice(0, commentnodeMap.get(attr).start)}${sortedAttrTextVal}${acc.slice(commentnodeMap.get(attr).end)}`; }, source); }); return source; } const source = sortInSource(declarations, getText(context)); const rangeStart = commentnodeMap.get(declarations[0]).start; const rangeEnd = commentnodeMap.get(declarations[declarations.length - 1]).end; return fixer.replaceTextRange([rangeStart, rangeEnd], source.slice(rangeStart, rangeEnd)); }
Fixes sort order of prop types. @param {Context} context the second element to compare. @param {Fixer} fixer the first element to compare. @param {Array} declarations The context of the two nodes. @param {boolean=} ignoreCase whether or not to ignore case when comparing the two elements. @param {boolean=} requiredFirst whether or not to sort required elements first. @param {boolean=} callbacksLast whether or not to sort callbacks after everything else. @param {boolean=} noSortAlphabetically whether or not to disable alphabetical sorting of the elements. @param {boolean=} sortShapeProp whether or not to sort propTypes defined in PropTypes.shape. @param {boolean=} checkTypes whether or not sorting of prop type definitions are checked. @returns {Object|*|{range, text}} the sort order of the two elements.
fixPropTypesSort ( context , fixer , declarations , ignoreCase , requiredFirst , callbacksLast , noSortAlphabetically , sortShapeProp , checkTypes )
javascript
jsx-eslint/eslint-plugin-react
lib/util/propTypesSort.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/util/propTypesSort.js
MIT
function checkFunctionsBlockStatement(node) { if (astUtil.isFunctionLikeExpression(node)) { if (node.body.type === 'BlockStatement') { getReturnStatements(node.body) .filter((returnStatement) => returnStatement && returnStatement.argument) .forEach((returnStatement) => { checkIteratorElement(returnStatement.argument); }); } } }
Checks if the given node is a function expression or arrow function, and checks if there is a missing key prop in return statement's arguments @param {ASTNode} node
checkFunctionsBlockStatement ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-key.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-key.js
MIT
function generateErrorMessageWithParentName(parentName) { return `Do not define components during render. React will see a new component type on every render and destroy the entire subtree’s DOM nodes and state (https://reactjs.org/docs/reconciliation.html#elements-of-different-types). Instead, move this component definition out of the parent component${parentName ? ` “${parentName}” ` : ' '}and pass data as props.`; }
Generate error message with given parent component name @param {string} parentName Name of the parent component, if known @returns {string} Error message with parent component name
generateErrorMessageWithParentName ( parentName )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function propMatchesRenderPropPattern(text, pattern) { return typeof text === 'string' && minimatch(text, pattern); }
Check whether given text matches the pattern passed in. @param {string} text Text to validate @param {string} pattern Pattern to match against @returns {boolean}
propMatchesRenderPropPattern ( text , pattern )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function getClosestMatchingParent(node, context, matcher) { if (!node || !node.parent || node.parent.type === 'Program') { return; } if (matcher(node.parent, context)) { return node.parent; } return getClosestMatchingParent(node.parent, context, matcher); }
Get closest parent matching given matcher @param {ASTNode} node The AST node @param {Context} context eslint context @param {Function} matcher Method used to match the parent @returns {ASTNode} The matching parent node, if any
getClosestMatchingParent ( node , context , matcher )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isCreateElementMatcher(node, context) { return ( astUtil.isCallExpression(node) && isCreateElement(context, node) ); }
Matcher used to check whether given node is a `createElement` call @param {ASTNode} node The AST node @param {Context} context eslint context @returns {boolean} True if node is a `createElement` call, false if not
isCreateElementMatcher ( node , context )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isObjectExpressionMatcher(node) { return node && node.type === 'ObjectExpression'; }
Matcher used to check whether given node is a `ObjectExpression` @param {ASTNode} node The AST node @returns {boolean} True if node is a `ObjectExpression`, false if not
isObjectExpressionMatcher ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isJSXExpressionContainerMatcher(node) { return node && node.type === 'JSXExpressionContainer'; }
Matcher used to check whether given node is a `JSXExpressionContainer` @param {ASTNode} node The AST node @returns {boolean} True if node is a `JSXExpressionContainer`, false if not
isJSXExpressionContainerMatcher ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isJSXAttributeOfExpressionContainerMatcher(node) { return ( node && node.type === 'JSXAttribute' && node.value && node.value.type === 'JSXExpressionContainer' ); }
Matcher used to check whether given node is a `JSXAttribute` of `JSXExpressionContainer` @param {ASTNode} node The AST node @returns {boolean} True if node is a `JSXAttribute` of `JSXExpressionContainer`, false if not
isJSXAttributeOfExpressionContainerMatcher ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isPropertyOfObjectExpressionMatcher(node) { return ( node && node.parent && node.parent.type === 'Property' ); }
Matcher used to check whether given node is an object `Property` @param {ASTNode} node The AST node @returns {boolean} True if node is a `Property`, false if not
isPropertyOfObjectExpressionMatcher ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isMapCall(node) { return ( node && node.callee && node.callee.property && node.callee.property.name === 'map' ); }
Check whether given node or its parent is directly inside `map` call ```jsx {items.map(item => <li />)} ``` @param {ASTNode} node The AST node @returns {boolean} True if node is directly inside `map` call, false if not
isMapCall ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isReturnStatementOfHook(node, context) { if ( !node || !node.parent || node.parent.type !== 'ReturnStatement' ) { return false; } const callExpression = getClosestMatchingParent(node, context, astUtil.isCallExpression); return ( callExpression && callExpression.callee && HOOK_REGEXP.test(callExpression.callee.name) ); }
Check whether given node is `ReturnStatement` of a React hook @param {ASTNode} node The AST node @param {Context} context eslint context @returns {boolean} True if node is a `ReturnStatement` of a React hook, false if not
isReturnStatementOfHook ( node , context )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isComponentInRenderProp(node, context, propNamePattern) { if ( node && node.parent && node.parent.type === 'Property' && node.parent.key && propMatchesRenderPropPattern(node.parent.key.name, propNamePattern) ) { return true; } // Check whether component is a render prop used as direct children, e.g. <Component>{() => <div />}</Component> if ( node && node.parent && node.parent.type === 'JSXExpressionContainer' && node.parent.parent && node.parent.parent.type === 'JSXElement' ) { return true; } const jsxExpressionContainer = getClosestMatchingParent(node, context, isJSXExpressionContainerMatcher); // Check whether prop name indicates accepted patterns if ( jsxExpressionContainer && jsxExpressionContainer.parent && jsxExpressionContainer.parent.type === 'JSXAttribute' && jsxExpressionContainer.parent.name && jsxExpressionContainer.parent.name.type === 'JSXIdentifier' ) { const propName = jsxExpressionContainer.parent.name.name; // Starts with render, e.g. <Component renderFooter={() => <div />} /> if (propMatchesRenderPropPattern(propName, propNamePattern)) { return true; } // Uses children prop explicitly, e.g. <Component children={() => <div />} /> if (propName === 'children') { return true; } } return false; }
Check whether given node is declared inside a render prop ```jsx <Component renderFooter={() => <div />} /> <Component>{() => <div />}</Component> ``` @param {ASTNode} node The AST node @param {Context} context eslint context @param {string} propNamePattern a pattern to match render props against @returns {boolean} True if component is declared inside a render prop, false if not
isComponentInRenderProp ( node , context , propNamePattern )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isDirectValueOfRenderProperty(node, propNamePattern) { return ( node && node.parent && node.parent.type === 'Property' && node.parent.key && node.parent.key.type === 'Identifier' && propMatchesRenderPropPattern(node.parent.key.name, propNamePattern) ); }
Check whether given node is declared directly inside a render property ```jsx const rows = { render: () => <div /> } <Component rows={ [{ render: () => <div /> }] } /> ``` @param {ASTNode} node The AST node @param {string} propNamePattern The pattern to match render props against @returns {boolean} True if component is declared inside a render property, false if not
isDirectValueOfRenderProperty ( node , propNamePattern )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function resolveComponentName(node) { const parentName = node.id && node.id.name; if (parentName) return parentName; return ( node.type === 'ArrowFunctionExpression' && node.parent && node.parent.id && node.parent.id.name ); }
Resolve the component name of given node @param {ASTNode} node The AST node of the component @returns {string} Name of the component, if any
resolveComponentName ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isInsideRenderMethod(node) { const parentComponent = utils.getParentComponent(node); if (!parentComponent || parentComponent.type !== 'ClassDeclaration') { return false; } return ( node && node.parent && node.parent.type === 'MethodDefinition' && node.parent.key && node.parent.key.name === 'render' ); }
Check whether given node is declared inside class component's render block ```jsx class Component extends React.Component { render() { class NestedClassComponent extends React.Component { ... ``` @param {ASTNode} node The AST node being checked @returns {boolean} True if node is inside class component's render block, false if not
isInsideRenderMethod ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isFunctionComponentInsideClassComponent(node) { const parentComponent = utils.getParentComponent(node); const parentStatelessComponent = utils.getParentStatelessComponent(node); return ( parentComponent && parentStatelessComponent && parentComponent.type === 'ClassDeclaration' && utils.getStatelessComponent(parentStatelessComponent) && utils.isReturningJSX(node) ); }
Check whether given node is a function component declared inside class component. Util's component detection fails to detect function components inside class components. ```jsx class Component extends React.Component { render() { const NestedComponent = () => <div />; ... ``` @param {ASTNode} node The AST node being checked @returns {boolean} True if given node a function component declared inside class component, false if not
isFunctionComponentInsideClassComponent ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isComponentInsideCreateElementsProp(node) { if (!components.get(node)) { return false; } const createElementParent = getClosestMatchingParent(node, context, isCreateElementMatcher); return ( createElementParent && createElementParent.arguments && createElementParent.arguments[1] === getClosestMatchingParent(node, context, isObjectExpressionMatcher) ); }
Check whether given node is declared inside `createElement` call's props ```js React.createElement(Component, { footer: () => React.createElement("div", null) }) ``` @param {ASTNode} node The AST node @returns {boolean} True if node is declare inside `createElement` call's props, false if not
isComponentInsideCreateElementsProp ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isComponentInProp(node) { if (isPropertyOfObjectExpressionMatcher(node)) { return utils.isReturningJSX(node); } const jsxAttribute = getClosestMatchingParent(node, context, isJSXAttributeOfExpressionContainerMatcher); if (!jsxAttribute) { return isComponentInsideCreateElementsProp(node); } return utils.isReturningJSX(node); }
Check whether given node is declared inside a component/object prop. ```jsx <Component footer={() => <div />} /> { footer: () => <div /> } ``` @param {ASTNode} node The AST node being checked @returns {boolean} True if node is a component declared inside prop, false if not
isComponentInProp ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function isStatelessComponentReturningNull(node) { const component = utils.getStatelessComponent(node); return component && !utils.isReturningJSX(component); }
Check whether given node is a stateless component returning non-JSX ```jsx {{ a: () => null }} ``` @param {ASTNode} node The AST node being checked @returns {boolean} True if node is a stateless component returning non-JSX, false if not
isStatelessComponentReturningNull ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function validate(node) { if (!node || !node.parent) { return; } const isDeclaredInsideProps = isComponentInProp(node); if ( !components.get(node) && !isFunctionComponentInsideClassComponent(node) && !isDeclaredInsideProps) { return; } if ( // Support allowAsProps option (isDeclaredInsideProps && (allowAsProps || isComponentInRenderProp(node, context, propNamePattern))) // Prevent reporting components created inside Array.map calls || isMapCall(node) || isMapCall(node.parent) // Do not mark components declared inside hooks (or falsy '() => null' clean-up methods) || isReturnStatementOfHook(node, context) // Do not mark objects containing render methods || isDirectValueOfRenderProperty(node, propNamePattern) // Prevent reporting nested class components twice || isInsideRenderMethod(node) // Prevent falsely reporting detected "components" which do not return JSX || isStatelessComponentReturningNull(node) ) { return; } // Get the closest parent component const parentComponent = getClosestMatchingParent( node, context, (nodeToMatch) => components.get(nodeToMatch) ); if (parentComponent) { const parentName = resolveComponentName(parentComponent); // Exclude lowercase parents, e.g. function createTestComponent() // React-dom prevents creating lowercase components if (parentName && parentName[0] === parentName[0].toLowerCase()) { return; } let message = generateErrorMessageWithParentName(parentName); // Add information about allowAsProps option when component is declared inside prop if (isDeclaredInsideProps && !allowAsProps) { message += COMPONENT_AS_PROPS_INFO; } report(context, message, null, { node, }); } }
Check whether given node is a unstable nested component @param {ASTNode} node The AST node being checked
validate ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unstable-nested-components.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unstable-nested-components.js
MIT
function checkText(context, node) { // since babel-eslint has the wrong node.raw, we'll get the source text const rawValue = getText(context, node); if (/^\s*\/(\/|\*)/m.test(rawValue)) {
@param {Context} context @param {ASTNode} node @returns {void}
checkText ( context , node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-no-comment-textnodes.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-comment-textnodes.js
MIT
const checkAttributesAndReport = (node, propSet) => { if (!propSet.has('checked')) { return; } if (!options.ignoreExclusiveCheckedAttribute && propSet.has('defaultChecked')) { reportExclusiveCheckedAttribute(node); } if ( !options.ignoreMissingProperties && !(propSet.has('onChange') || propSet.has('readOnly')) ) { reportMissingProperty(node); } };
@param {ASTNode} node @param {Set<string>} propSet @returns {void}
checkAttributesAndReport
javascript
jsx-eslint/eslint-plugin-react
lib/rules/checked-requires-onchange-or-readonly.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/checked-requires-onchange-or-readonly.js
MIT
function getUnsafeMethods() { return Object.keys(unsafe); }
Returns a list of unsafe methods @returns {Array} A list of unsafe methods
getUnsafeMethods ( )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unsafe.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unsafe.js
MIT
function isUnsafe(method) { const unsafeMethods = getUnsafeMethods(); return unsafeMethods.indexOf(method) !== -1; }
Checks if a passed method is unsafe @param {string} method Life cycle method @returns {boolean} Returns true for unsafe methods, otherwise returns false
isUnsafe ( method )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unsafe.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unsafe.js
MIT
function checkUnsafe(node, method) { if (!isUnsafe(method)) { return; } const meta = unsafe[method]; const newMethod = meta.newMethod; const details = meta.details; const propertyNode = astUtil.getComponentProperties(node) .find((property) => astUtil.getPropertyName(property) === method); report(context, messages.unsafeMethod, 'unsafeMethod', { node: propertyNode, data: { method, newMethod, details, }, }); }
Reports the error for an unsafe method @param {ASTNode} node The AST node being checked @param {string} method Life cycle method
checkUnsafe ( node , method )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unsafe.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unsafe.js
MIT
function getLifeCycleMethods(node) { const properties = astUtil.getComponentProperties(node); return properties.map((property) => astUtil.getPropertyName(property)); }
Returns life cycle methods if available @param {ASTNode} node The AST node being checked. @returns {Array} The array of methods.
getLifeCycleMethods ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unsafe.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unsafe.js
MIT
function checkLifeCycleMethods(node) { if (componentUtil.isES5Component(node, context) || componentUtil.isES6Component(node, context)) { const methods = getLifeCycleMethods(node); methods .sort((a, b) => a.localeCompare(b)) .forEach((method) => checkUnsafe(node, method)); } }
Checks life cycle methods @param {ASTNode} node The AST node being checked.
checkLifeCycleMethods ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/no-unsafe.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unsafe.js
MIT
function isAlways(configuration, exceptions, propName) { const isException = exceptions.has(propName); if (configuration === ALWAYS) { return !isException; } return isException; }
@param {string} configuration @param {Set<string>} exceptions @param {string} propName @returns {boolean} propName
isAlways ( configuration , exceptions , propName )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/jsx-boolean-value.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-boolean-value.js
MIT
function isForbidden(forbidMap, prop, tagName) { const options = forbidMap.get(prop); return options && ( typeof tagName === 'undefined' || !options.disallowList || options.disallowList.indexOf(tagName) !== -1 ); }
@param {Map<string, object>} forbidMap // { disallowList: null | string[], message: null | string } @param {string} prop @param {string} tagName @returns {boolean}
isForbidden ( forbidMap , prop , tagName )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/forbid-dom-props.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/forbid-dom-props.js
MIT
function isSingleSuperCall(body) { return ( body.length === 1 && body[0].type === 'ExpressionStatement' && astUtil.isCallExpression(body[0].expression) && body[0].expression.callee.type === 'Super' ); }
Checks whether a given array of statements is a single call of `super`. @see eslint no-useless-constructor rule @param {ASTNode[]} body - An array of statements to check. @returns {boolean} `true` if the body is a single call of `super`.
isSingleSuperCall ( body )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT
function isSimple(node) { return node.type === 'Identifier' || node.type === 'RestElement'; }
Checks whether a given node is a pattern which doesn't have any side effects. Default parameters and Destructuring parameters can have side effects. @see eslint no-useless-constructor rule @param {ASTNode} node - A pattern node. @returns {boolean} `true` if the node doesn't have any side effects.
isSimple ( node )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT
function isSpreadArguments(superArgs) { return ( superArgs.length === 1 && superArgs[0].type === 'SpreadElement' && superArgs[0].argument.type === 'Identifier' && superArgs[0].argument.name === 'arguments' ); }
Checks whether a given array of expressions is `...arguments` or not. `super(...arguments)` passes all arguments through. @see eslint no-useless-constructor rule @param {ASTNode[]} superArgs - An array of expressions to check. @returns {boolean} `true` if the superArgs is `...arguments`.
isSpreadArguments ( superArgs )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT
function isValidIdentifierPair(ctorParam, superArg) { return ( ctorParam.type === 'Identifier' && superArg.type === 'Identifier' && ctorParam.name === superArg.name ); }
Checks whether given 2 nodes are identifiers which have the same name or not. @see eslint no-useless-constructor rule @param {ASTNode} ctorParam - A node to check. @param {ASTNode} superArg - A node to check. @returns {boolean} `true` if the nodes are identifiers which have the same name.
isValidIdentifierPair ( ctorParam , superArg )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT
function isValidRestSpreadPair(ctorParam, superArg) { return ( ctorParam.type === 'RestElement' && superArg.type === 'SpreadElement' && isValidIdentifierPair(ctorParam.argument, superArg.argument) ); }
Checks whether given 2 nodes are a rest/spread pair which has the same values. @see eslint no-useless-constructor rule @param {ASTNode} ctorParam - A node to check. @param {ASTNode} superArg - A node to check. @returns {boolean} `true` if the nodes are a rest/spread pair which has the same values.
isValidRestSpreadPair ( ctorParam , superArg )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT
function isValidPair(ctorParam, superArg) { return ( isValidIdentifierPair(ctorParam, superArg) || isValidRestSpreadPair(ctorParam, superArg) ); }
Checks whether given 2 nodes have the same value or not. @see eslint no-useless-constructor rule @param {ASTNode} ctorParam - A node to check. @param {ASTNode} superArg - A node to check. @returns {boolean} `true` if the nodes have the same value or not.
isValidPair ( ctorParam , superArg )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT
function isPassingThrough(ctorParams, superArgs) { if (ctorParams.length !== superArgs.length) { return false; } for (let i = 0; i < ctorParams.length; ++i) { if (!isValidPair(ctorParams[i], superArgs[i])) { return false; } } return true; }
Checks whether the parameters of a constructor and the arguments of `super()` have the same values or not. @see eslint no-useless-constructor rule @param {ASTNode[]} ctorParams - The parameters of a constructor to check. @param {ASTNode} superArgs - The arguments of `super()` to check. @returns {boolean} `true` if those have the same values.
isPassingThrough ( ctorParams , superArgs )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT
function isRedundantSuperCall(body, ctorParams) { return ( isSingleSuperCall(body) && ctorParams.every(isSimple) && ( isSpreadArguments(body[0].expression.arguments) || isPassingThrough(ctorParams, body[0].expression.arguments) ) ); }
Checks whether the constructor body is a redundant super call. @see eslint no-useless-constructor rule @param {Array} body - constructor body content. @param {Array} ctorParams - The params to check against super call. @returns {boolean} true if the constructor body is redundant
isRedundantSuperCall ( body , ctorParams )
javascript
jsx-eslint/eslint-plugin-react
lib/rules/prefer-stateless-function.js
https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prefer-stateless-function.js
MIT