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 hasOtherProperties(node) {
const properties = astUtil.getComponentProperties(node);
return properties.some((property) => {
const name = astUtil.getPropertyName(property);
const isDisplayName = name === 'displayName';
const isPropTypes = name === 'propTypes' || ((name === 'props') && property.typeAnnotation);
const contextTypes = name === 'contextTypes';
const defaultProps = name === 'defaultProps';
const isUselessConstructor = property.kind === 'constructor'
&& !!property.value.body
&& isRedundantSuperCall(property.value.body.body, property.value.params);
const isRender = name === 'render';
return !isDisplayName && !isPropTypes && !contextTypes && !defaultProps && !isUselessConstructor && !isRender;
});
} | Check if a given AST node have any other properties the ones available in stateless components
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if the node has at least one other property, false if not. | hasOtherProperties ( 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 markSCUAsDeclared(node) {
components.set(node, {
hasSCU: true,
});
} | Mark component as pure as declared
@param {ASTNode} node The AST node being checked. | markSCUAsDeclared ( 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 markChildContextTypesAsDeclared(node) {
components.set(node, {
hasChildContextTypes: true,
});
} | Mark childContextTypes as declared
@param {ASTNode} node The AST node being checked. | markChildContextTypesAsDeclared ( 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 markThisAsUsed(node) {
components.set(node, {
useThis: true,
});
} | Mark a setState as used
@param {ASTNode} node The AST node being checked. | markThisAsUsed ( 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 markPropsOrContextAsUsed(node) {
components.set(node, {
usePropsOrContext: true,
});
} | Mark a props or context as used
@param {ASTNode} node The AST node being checked. | markPropsOrContextAsUsed ( 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 markRefAsUsed(node) {
components.set(node, {
useRef: true,
});
} | Mark a ref as used
@param {ASTNode} node The AST node being checked. | markRefAsUsed ( 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 markReturnAsInvalid(node) {
components.set(node, {
invalidReturn: true,
});
} | Mark return as invalid
@param {ASTNode} node The AST node being checked. | markReturnAsInvalid ( 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 markDecoratorsAsUsed(node) {
components.set(node, {
useDecorators: true,
});
} | Mark a ClassDeclaration as having used decorators
@param {ASTNode} node The AST node being checked. | markDecoratorsAsUsed ( 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 isCreateElementWithProps(node, context) {
return isCreateElement(context, node)
&& node.arguments.length > 1
&& node.arguments[1].type === 'ObjectExpression';
} | Checks if the node is a createElement call with a props literal.
@param {ASTNode} node - The AST node being checked.
@param {Context} context - The AST node being checked.
@returns {boolean} - True if node is a createElement call with a props
object literal, False if not. | isCreateElementWithProps ( node , context ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-children-prop.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-children-prop.js | MIT |
function getNodeIndent(node) {
let src = getText(context, node, node.loc.start.column + extraColumnStart);
const lines = src.split('\n');
src = lines[0];
let regExp;
if (indentType === 'space') {
regExp = /^[ ]+/;
} else {
regExp = /^[\t]+/;
}
const indent = regExp.exec(src);
const useOperator = /^([ ]|[\t])*[:]/.test(src) || /^([ ]|[\t])*[?]/.test(src);
const useBracket = /[<]/.test(src);
line.currentOperator = false;
if (useOperator) {
line.isUsingOperator = true;
line.currentOperator = true;
} else if (useBracket) {
line.isUsingOperator = false;
}
return indent ? indent[0].length : 0;
} | Get node indent
@param {ASTNode} node Node to examine
@return {number} Indent | getNodeIndent ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent-props.js | MIT |
function checkNodesIndent(nodes, indent) {
let nestedIndent = indent;
nodes.forEach((node) => {
const nodeIndent = getNodeIndent(node);
if (
line.isUsingOperator
&& !line.currentOperator
&& indentSize !== 'first'
&& !ignoreTernaryOperator
) {
nestedIndent += indentSize;
line.isUsingOperator = false;
}
if (
node.type !== 'ArrayExpression' && node.type !== 'ObjectExpression'
&& nodeIndent !== nestedIndent && astUtil.isNodeFirstInLine(context, node)
) {
report(node, nestedIndent, nodeIndent);
}
});
} | Check indent for nodes list
@param {ASTNode[]} nodes list of node objects
@param {number} indent needed indent | checkNodesIndent ( nodes , indent ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent-props.js | MIT |
function report(node, needed, gotten) {
const msgContext = {
needed,
type: indentType,
characters: needed === 1 ? 'character' : 'characters',
gotten,
};
reportC(context, messages.wrongIndent, 'wrongIndent', {
node,
data: msgContext,
fix(fixer) {
return fixer.replaceTextRange([node.range[0] - node.loc.start.column, node.range[0]],
repeat(indentType === 'space' ? ' ' : '\t', needed)
);
},
});
}
/**
* Get node indent
* @param {ASTNode} node Node to examine
* @return {number} Indent
*/
function getNodeIndent(node) {
let src = getText(context, node, node.loc.start.column + extraColumnStart);
const lines = src.split('\n');
src = lines[0];
let regExp;
if (indentType === 'space') {
regExp = /^[ ]+/;
} else {
regExp = /^[\t]+/;
}
const indent = regExp.exec(src);
const useOperator = /^([ ]|[\t])*[:]/.test(src) || /^([ ]|[\t])*[?]/.test(src);
const useBracket = /[<]/.test(src);
line.currentOperator = false;
if (useOperator) {
line.isUsingOperator = true;
line.currentOperator = true;
} else if (useBracket) {
line.isUsingOperator = false;
}
return indent ? indent[0].length : 0;
}
/**
* Check indent for nodes list
* @param {ASTNode[]} nodes list of node objects
* @param {number} indent needed indent
*/
function checkNodesIndent(nodes, indent) {
let nestedIndent = indent;
nodes.forEach((node) => {
const nodeIndent = getNodeIndent(node);
if (
line.isUsingOperator
&& !line.currentOperator
&& indentSize !== 'first'
&& !ignoreTernaryOperator
) {
nestedIndent += indentSize;
line.isUsingOperator = false;
}
if (
node.type !== 'ArrayExpression' && node.type !== 'ObjectExpression'
&& nodeIndent !== nestedIndent && astUtil.isNodeFirstInLine(context, node)
) {
report(node, nestedIndent, nodeIndent);
}
});
}
return {
JSXOpeningElement(node) {
if (!node.attributes.length) {
return;
}
let propIndent;
if (indentSize === 'first') {
const firstPropNode = node.attributes[0];
propIndent = firstPropNode.loc.start.column;
} else {
const elementIndent = getNodeIndent(node);
propIndent = elementIndent + indentSize;
}
checkNodesIndent(node.attributes, propIndent);
},
};
},
}; | Reports a given indent violation and properly pluralizes the message
@param {ASTNode} node Node violating the indent rule
@param {number} needed Expected indentation character count
@param {number} gotten Indentation character count in the actual node/code | report ( node , needed , gotten ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent-props.js | MIT |
function isIgnored(name) {
return ignored.indexOf(name) !== -1;
} | Checks if the prop is ignored
@param {string} name Name of the prop to check.
@returns {boolean} True if the prop is ignored, false if not. | isIgnored ( name ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prop-types.js | MIT |
function internalIsDeclaredInComponent(declaredPropTypes, keyList) {
for (let i = 0, j = keyList.length; i < j; i++) {
const key = keyList[i];
const propType = (
declaredPropTypes && (
// Check if this key is declared
(declaredPropTypes[key] // If not, check if this type accepts any key
|| declaredPropTypes.__ANY_KEY__) // eslint-disable-line no-underscore-dangle
)
);
if (!propType) {
// If it's a computed property, we can't make any further analysis, but is valid
return key === '__COMPUTED_PROP__';
}
if (typeof propType === 'object' && !propType.type) {
return true;
}
// Consider every children as declared
if (propType.children === true || propType.containsUnresolvedSpread || propType.containsIndexers) {
return true;
}
if (propType.acceptedProperties) {
return key in propType.acceptedProperties;
}
if (propType.type === 'union') {
// If we fall in this case, we know there is at least one complex type in the union
if (i + 1 >= j) {
// this is the last key, accept everything
return true;
}
// non trivial, check all of them
const unionTypes = propType.children;
const unionPropType = {};
for (let k = 0, z = unionTypes.length; k < z; k++) {
unionPropType[key] = unionTypes[k];
const isValid = internalIsDeclaredInComponent(
unionPropType,
keyList.slice(i)
);
if (isValid) {
return true;
}
}
// every possible union were invalid
return false;
}
declaredPropTypes = propType.children;
}
return true;
} | Internal: Checks if the prop is declared
@param {Object} declaredPropTypes Description of propTypes declared in the current component
@param {string[]} keyList Dot separated name of the prop to check.
@returns {boolean} True if the prop is declared, false if not. | internalIsDeclaredInComponent ( declaredPropTypes , keyList ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prop-types.js | MIT |
function isDeclaredInComponent(node, names) {
while (node) {
const component = components.get(node);
const isDeclared = component && component.confidence >= 2
&& internalIsDeclaredInComponent(component.declaredPropTypes || {}, names);
if (isDeclared) {
return true;
}
node = node.parent;
}
return false;
} | Checks if the prop is declared
@param {ASTNode} node The AST node being checked.
@param {string[]} names List of names of the prop to check.
@returns {boolean} True if the prop is declared, false if not. | isDeclaredInComponent ( node , names ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prop-types.js | MIT |
function checkNestedComponent(component, list) {
const componentIsMemo = component.node.callee && component.node.callee.name === 'memo';
const argumentIsForwardRef = component.node.arguments && component.node.arguments[0].callee && component.node.arguments[0].callee.name === 'forwardRef';
if (componentIsMemo && argumentIsForwardRef) {
const forwardComponent = list.find(
(innerComponent) => (
innerComponent.node.range[0] === component.node.arguments[0].range[0]
&& innerComponent.node.range[0] === component.node.arguments[0].range[0]
));
const isValidated = mustBeValidated(forwardComponent);
const isIgnorePropsValidation = forwardComponent.ignorePropsValidation;
return isIgnorePropsValidation || isValidated;
}
} | @param {Object} component The current component to process
@param {Array} list The all components to process
@returns {boolean} True if the component is nested False if not. | checkNestedComponent ( component , list ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/prop-types.js | MIT |
function checkCreateProps(context, node, attribute) {
const propsArg = node.arguments[1];
if (!propsArg || propsArg.type !== 'ObjectExpression') {
return; // can't check variables, computed, or shorthands
}
for (const prop of propsArg.properties) {
if (!prop.key || prop.key.type !== 'Identifier') {
// eslint-disable-next-line no-continue
continue; // cannot check computed keys
}
if (prop.key.name !== attribute) {
// eslint-disable-next-line no-continue
continue; // ignore not this attribute
}
if (!COMPONENT_ATTRIBUTE_MAP.get(attribute).has(node.arguments[0].value)) {
const tagNames = Array.from(
COMPONENT_ATTRIBUTE_MAP.get(attribute).values(),
(tagName) => `"<${tagName}>"`
).join(', ');
report(context, messages.onlyMeaningfulFor, 'onlyMeaningfulFor', {
node: prop.key,
data: {
attributeName: attribute,
tagNames,
},
suggest: false,
});
// eslint-disable-next-line no-continue
continue;
}
if (prop.method) {
report(context, messages.noMethod, 'noMethod', {
node: prop,
data: {
attributeName: attribute,
},
suggest: false,
});
// eslint-disable-next-line no-continue
continue;
}
if (prop.shorthand || prop.computed) {
// eslint-disable-next-line no-continue
continue; // cannot check these
}
if (prop.value.type === 'ArrayExpression') {
prop.value.elements.forEach((value) => {
checkPropValidValue(context, node, value, attribute);
});
// eslint-disable-next-line no-continue
continue;
}
checkPropValidValue(context, node, prop.value, attribute);
}
} | @param {*} context
@param {*} node
@param {string} attribute | checkCreateProps ( context , node , attribute ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-invalid-html-attribute.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-invalid-html-attribute.js | MIT |
function nestedPropTypes(prop) {
return (
prop.type === 'Property'
&& astUtil.isCallExpression(prop.value)
);
} | Checks if prop is nested
@param {Object} prop Property object, single prop type declaration
@returns {boolean} | nestedPropTypes ( prop ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function getPropKey(node) {
// Check for `ExperimentalSpreadProperty` (eslint 3/4) and `SpreadElement` (eslint 5)
// so we can skip validation of those fields.
// Otherwise it will look for `node.value.property` which doesn't exist and breaks eslint.
if (node.type === 'ExperimentalSpreadProperty' || node.type === 'SpreadElement') {
return null;
}
if (node.value && node.value.property) {
const name = node.value.property.name;
if (name === 'isRequired') {
if (node.value.object && node.value.object.property) {
return node.value.object.property.name;
}
return null;
}
return name;
}
if (node.value && node.value.type === 'Identifier') {
return node.value.name;
}
return null;
} | Returns the prop key to ensure we handle the following cases:
propTypes: {
full: React.PropTypes.bool,
short: PropTypes.bool,
direct: bool,
required: PropTypes.bool.isRequired
}
@param {Object} node The node we're getting the name of
@returns {string | null} | getPropKey ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function getPropName(node) {
// Due to this bug https://github.com/babel/babel-eslint/issues/307
// we can't get the name of the Flow object key name. So we have
// to hack around it for now.
if (node.type === 'ObjectTypeProperty') {
return getSourceCode(context).getFirstToken(node).value;
}
return node.key.name;
} | Returns the name of the given node (prop)
@param {Object} node The node we're getting the name of
@returns {string} | getPropName ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function flowCheck(prop) {
return (
prop.type === 'ObjectTypeProperty'
&& prop.value.type === 'BooleanTypeAnnotation'
&& rule.test(getPropName(prop)) === false
);
} | Checks if prop is declared in flow way
@param {Object} prop Property object, single prop type declaration
@returns {boolean} | flowCheck ( prop ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function regularCheck(prop) {
const propKey = getPropKey(prop);
return (
propKey
&& propTypeNames.indexOf(propKey) >= 0
&& rule.test(getPropName(prop)) === false
);
} | Checks if prop is declared in regular way
@param {Object} prop Property object, single prop type declaration
@returns {boolean} | regularCheck ( prop ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function runCheck(proptypes, addInvalidProp) {
if (proptypes) {
proptypes.forEach((prop) => {
if (config.validateNested && nestedPropTypes(prop)) {
runCheck(prop.value.arguments[0].properties, addInvalidProp);
return;
}
if (flowCheck(prop) || regularCheck(prop) || tsCheck(prop)) {
addInvalidProp(prop);
}
});
}
} | Runs recursive check on all proptypes
@param {Array} proptypes A list of Property object (for each proptype defined)
@param {Function} addInvalidProp callback to run for each error | runCheck ( proptypes , addInvalidProp ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function validatePropNaming(node, proptypes) {
const component = components.get(node) || node;
const invalidProps = component.invalidProps || [];
runCheck(proptypes, (prop) => {
invalidProps.push(prop);
});
components.set(node, {
invalidProps,
});
} | Checks and mark props with invalid naming
@param {Object} node The component node we're testing
@param {Array} proptypes A list of Property object (for each proptype defined) | validatePropNaming ( node , proptypes ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function reportInvalidNaming(component) {
component.invalidProps.forEach((propNode) => {
const propName = getPropName(propNode);
report(context, config.message || messages.patternMismatch, !config.message && 'patternMismatch', {
node: propNode,
data: {
component: propName,
propName,
pattern: config.rule,
},
});
});
} | Reports invalid prop naming
@param {Object} component The component to process | reportInvalidNaming ( component ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/boolean-prop-naming.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/boolean-prop-naming.js | MIT |
function reportInvalidDefaultProps(propTypes, defaultProps) {
// If this defaultProps is "unresolved" or the propTypes is undefined, then we should ignore
// this component and not report any errors for it, to avoid false-positives with e.g.
// external defaultProps/propTypes declarations or spread operators.
if (defaultProps === 'unresolved' || !propTypes || Object.keys(propTypes).length === 0) {
return;
}
Object.keys(defaultProps).forEach((defaultPropName) => {
const defaultProp = defaultProps[defaultPropName];
const prop = propTypes[defaultPropName];
if (prop && (allowRequiredDefaults || !prop.isRequired)) {
return;
}
if (prop) {
report(context, messages.requiredHasDefault, 'requiredHasDefault', {
node: defaultProp.node,
data: {
name: defaultPropName,
},
});
} else {
report(context, messages.defaultHasNoType, 'defaultHasNoType', {
node: defaultProp.node,
data: {
name: defaultPropName,
},
});
}
});
} | Reports all defaultProps passed in that don't have an appropriate propTypes counterpart.
@param {Object[]} propTypes Array of propTypes to check.
@param {Object} defaultProps Object of defaultProps to check. Keys are the props names.
@return {void} | reportInvalidDefaultProps ( propTypes , defaultProps ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/default-props-match-prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/default-props-match-prop-types.js | MIT |
function nodeDescriptor(n) {
return n.openingElement ? n.openingElement.name.name : getText(context, n).replace(/\n/g, '');
} | @param {ASTNode} n
@returns {string} | nodeDescriptor ( n ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-one-expression-per-line.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-one-expression-per-line.js | MIT |
function findObjectProp(node, propName, seenProps) {
if (!node.properties) {
return false;
}
return node.properties.find((prop) => {
if (prop.type === 'Property') {
return prop.key.name === propName;
}
if (prop.type === 'ExperimentalSpreadProperty' || prop.type === 'SpreadElement') {
const variable = findSpreadVariable(node, prop.argument.name);
if (variable && variable.defs.length && variable.defs[0].node.init) {
if (seenProps.indexOf(prop.argument.name) > -1) {
return false;
}
const newSeenProps = seenProps.concat(prop.argument.name || []);
return findObjectProp(variable.defs[0].node.init, propName, newSeenProps);
}
}
return false;
});
} | Takes a ObjectExpression and returns the value of the prop if it has it
@param {object} node - ObjectExpression node
@param {string} propName - name of the prop to look for
@param {string[]} seenProps
@returns {object | boolean} | findObjectProp ( node , propName , seenProps ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-danger-with-children.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-danger-with-children.js | MIT |
function findJsxProp(node, propName) {
const attributes = node.openingElement.attributes;
return attributes.find((attribute) => {
if (attribute.type === 'JSXSpreadAttribute') {
const variable = findSpreadVariable(node, attribute.argument.name);
if (variable && variable.defs.length && variable.defs[0].node.init) {
return findObjectProp(variable.defs[0].node.init, propName, []);
}
}
return attribute.name && attribute.name.name === propName;
});
} | Takes a JSXElement and returns the value of the prop if it has it
@param {object} node - JSXElement node
@param {string} propName - name of the prop to look for
@returns {object | boolean} | findJsxProp ( node , propName ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-danger-with-children.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-danger-with-children.js | MIT |
function isLineBreak(node) {
const isLiteral = node.type === 'Literal' || node.type === 'JSXText';
const isMultiline = node.loc.start.line !== node.loc.end.line;
const isWhiteSpaces = jsxUtil.isWhiteSpaces(node.value);
return isLiteral && isMultiline && isWhiteSpaces;
} | Checks to see if a node is a line break
@param {ASTNode} node The AST node being checked
@returns {boolean} True if node is a line break, false if not | isLineBreak ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-danger-with-children.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-danger-with-children.js | MIT |
function addVariableNameToSet(violationType, variableName, blockStart) {
blockVariableNameSets[blockStart][violationType].add(variableName);
} | @param {string | number} violationType
@param {unknown} variableName
@param {string | number} blockStart | addVariableNameToSet ( violationType , variableName , blockStart ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-bind.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-bind.js | MIT |
function isValidHTMLTagInJSX(childNode) {
const tagConvention = /^[a-z][^-]*$/;
if (tagConvention.test(childNode.parent.name.name)) {
return !childNode.parent.attributes.some((attrNode) => (
attrNode.type === 'JSXAttribute'
&& attrNode.name.type === 'JSXIdentifier'
&& attrNode.name.name === 'is'
// To learn more about custom web components and `is` attribute,
// see https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-customized-builtin-example
));
}
return false;
} | Checks if a node's parent is a JSX tag that is written with lowercase letters,
and is not a custom web component. Custom web components have a hyphen in tag name,
or have an `is="some-elem"` attribute.
Note: does not check if a tag's parent against a list of standard HTML/DOM tags. For example,
a `<fake>`'s child would return `true` because "fake" is written only with lowercase letters
without a hyphen and does not have a `is="some-elem"` attribute.
@param {Object} childNode - JSX element being tested.
@returns {boolean} Whether or not the node name match the JSX tag convention. | isValidHTMLTagInJSX ( childNode ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function normalizeAttributeCase(name) {
return DOM_PROPERTIES_IGNORE_CASE.find((element) => element.toLowerCase() === name.toLowerCase()) || name;
} | Checks if the attribute name is included in the attributes that are excluded
from the camel casing.
// returns 'charSet'
@example normalizeAttributeCase('charset')
Note - these exclusions are not made by React core team, but `eslint-plugin-react` community.
@param {string} name - Attribute name to be normalized
@returns {string} Result | normalizeAttributeCase ( name ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function isValidDataAttribute(name) {
return !/^data-xml/i.test(name) && /^data-[^:]*$/.test(name);
} | Checks if an attribute name is a valid `data-*` attribute:
if the name starts with "data-" and has alphanumeric words (browsers require lowercase, but React and TS lowercase them),
not start with any casing of "xml", and separated by hyphens (-) (which is also called "kebab case" or "dash case"),
then the attribute is a valid data attribute.
@param {string} name - Attribute name to be tested
@returns {boolean} Result | isValidDataAttribute ( name ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function hasUpperCaseCharacter(name) {
return name.toLowerCase() !== name;
} | Checks if an attribute name has at least one uppercase characters
@param {string} name
@returns {boolean} Result | hasUpperCaseCharacter ( name ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function isValidAriaAttribute(name) {
return ARIA_PROPERTIES.some((element) => element === name);
} | Checks if an attribute name is a standard aria attribute by compering it to a list
of standard aria property names
@param {string} name - Attribute name to be tested
@returns {boolean} Result | isValidAriaAttribute ( name ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function getTagName(node) {
if (
node
&& node.parent
&& node.parent.name
) {
return node.parent.name.name;
}
return null;
} | Extracts the tag name for the JSXAttribute
@param {JSXAttribute} node - JSXAttribute being tested.
@returns {string | null} tag name | getTagName ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function tagNameHasDot(node) {
return !!(
node.parent
&& node.parent.name
&& node.parent.name.type === 'JSXMemberExpression'
);
} | Test wether the tag name for the JSXAttribute is
something like <Foo.bar />
@param {JSXAttribute} node - JSXAttribute being tested.
@returns {boolean} result | tagNameHasDot ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function getStandardName(name, context) {
if (has(DOM_ATTRIBUTE_NAMES, name)) {
return DOM_ATTRIBUTE_NAMES[/** @type {keyof DOM_ATTRIBUTE_NAMES} */ (name)];
}
if (has(SVGDOM_ATTRIBUTE_NAMES, name)) {
return SVGDOM_ATTRIBUTE_NAMES[/** @type {keyof SVGDOM_ATTRIBUTE_NAMES} */ (name)];
}
const names = getDOMPropertyNames(context);
// Let's find a possible attribute match with a case-insensitive search.
return names.find((element) => element.toLowerCase() === name.toLowerCase());
} | Get the standard name of the attribute.
@param {string} name - Name of the attribute.
@param {object} context - eslint context
@returns {string | undefined} The standard name of the attribute, or undefined if no standard name was found. | getStandardName ( name , context ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unknown-property.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unknown-property.js | MIT |
function getStringFromValue(value, targetValue) {
if (value) {
if (value.type === 'Literal') {
return value.value;
}
if (value.type === 'JSXExpressionContainer') {
if (value.expression.type === 'TemplateLiteral') {
return value.expression.quasis[0].value.cooked;
}
const expr = value.expression;
if (expr && expr.type === 'ConditionalExpression') {
const relValues = [expr.consequent.value, expr.alternate.value];
if (targetValue.type === 'JSXExpressionContainer' && targetValue.expression && targetValue.expression.type === 'ConditionalExpression') {
const targetTestCond = targetValue.expression.test.name;
const relTestCond = value.expression.test.name;
if (targetTestCond === relTestCond) {
const targetBlankIndex = [targetValue.expression.consequent.value, targetValue.expression.alternate.value].indexOf('_blank');
return relValues[targetBlankIndex];
}
}
return relValues;
}
return expr.value;
}
}
return null;
} | Get the string(s) from a value
@param {ASTNode} value The AST node being checked.
@param {ASTNode} targetValue The AST node being checked.
@returns {string | string[] | null} The string value, or null if not a string. | getStringFromValue ( value , targetValue ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-target-blank.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-target-blank.js | MIT |
function checkSorted(declarations) {
// Declarations will be `undefined` if the `shape` is not a literal. For
// example, if it is a propType imported from another file.
if (!declarations) {
return;
}
function fix(fixer) {
return propTypesSortUtil.fixPropTypesSort(
context,
fixer,
declarations,
ignoreCase,
requiredFirst,
callbacksLast,
noSortAlphabetically,
sortShapeProp,
checkTypes
);
}
const callbackPropsLastSeen = new WeakSet();
const requiredPropsFirstSeen = new WeakSet();
const propsNotSortedSeen = new WeakSet();
declarations.reduce((prev, curr, idx, decls) => {
if (curr.type === 'ExperimentalSpreadProperty' || curr.type === 'SpreadElement') {
return decls[idx + 1];
}
let prevPropName = getKey(context, prev);
let currentPropName = getKey(context, curr);
const previousIsRequired = propTypesSortUtil.isRequiredProp(prev);
const currentIsRequired = propTypesSortUtil.isRequiredProp(curr);
const previousIsCallback = propTypesSortUtil.isCallbackPropName(prevPropName);
const currentIsCallback = propTypesSortUtil.isCallbackPropName(currentPropName);
if (ignoreCase) {
prevPropName = String(prevPropName).toLowerCase();
currentPropName = String(currentPropName).toLowerCase();
}
if (requiredFirst) {
if (previousIsRequired && !currentIsRequired) {
// Transition between required and non-required. Don't compare for alphabetical.
return curr;
}
if (!previousIsRequired && currentIsRequired) {
// Encountered a non-required prop after a required prop
if (!requiredPropsFirstSeen.has(curr)) {
requiredPropsFirstSeen.add(curr);
report(context, messages.requiredPropsFirst, 'requiredPropsFirst', {
node: curr,
fix,
});
}
return curr;
}
}
if (callbacksLast) {
if (!previousIsCallback && currentIsCallback) {
// Entering the callback prop section
return curr;
}
if (previousIsCallback && !currentIsCallback) {
// Encountered a non-callback prop after a callback prop
if (!callbackPropsLastSeen.has(prev)) {
callbackPropsLastSeen.add(prev);
report(context, messages.callbackPropsLast, 'callbackPropsLast', {
node: prev,
fix,
});
}
return prev;
}
}
if (!noSortAlphabetically && currentPropName < prevPropName) {
if (!propsNotSortedSeen.has(curr)) {
propsNotSortedSeen.add(curr);
report(context, messages.propsNotSorted, 'propsNotSorted', {
node: curr,
fix,
});
}
return prev;
}
return curr;
}, declarations[0]);
} | Checks if propTypes declarations are sorted
@param {Array} declarations The array of AST nodes being checked.
@returns {void} | checkSorted ( declarations ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/sort-prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-prop-types.js | MIT |
function isPropUsed(node, prop) {
const usedPropTypes = node.usedPropTypes || [];
for (let i = 0, l = usedPropTypes.length; i < l; i++) {
const usedProp = usedPropTypes[i];
if (
prop.type === 'shape'
|| prop.type === 'exact'
|| prop.name === '__ANY_KEY__'
|| usedProp.name === prop.name
) {
return true;
}
}
return false;
} | Checks if a prop is used
@param {ASTNode} node The AST node being checked.
@param {Object} prop Declared prop object
@returns {boolean} True if the prop is used, false if not. | isPropUsed ( node , prop ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unused-prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unused-prop-types.js | MIT |
function reportUnusedPropType(component, props) {
// Skip props that check instances
if (props === true) {
return;
}
Object.keys(props || {}).forEach((key) => {
const prop = props[key];
// Skip props that check instances
if (prop === true) {
return;
}
if ((prop.type === 'shape' || prop.type === 'exact') && configuration.skipShapeProps) {
return;
}
if (prop.node && prop.node.typeAnnotation && prop.node.typeAnnotation.typeAnnotation
&& prop.node.typeAnnotation.typeAnnotation.type === 'TSNeverKeyword') {
return;
}
if (prop.node && !isIgnored(prop.fullName) && !isPropUsed(component, prop)) {
report(context, messages.unusedPropType, 'unusedPropType', {
node: prop.node.key || prop.node,
data: {
name: prop.fullName,
},
});
}
if (prop.children) {
reportUnusedPropType(component, prop.children);
}
});
} | Used to recursively loop through each declared prop type
@param {Object} component The component to process
@param {ASTNode[]|true} props List of props to validate | reportUnusedPropType ( component , props ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unused-prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unused-prop-types.js | MIT |
function reportUnusedPropTypes(component) {
reportUnusedPropType(component, component.declaredPropTypes);
} | Reports unused proptypes for a given component
@param {Object} component The component to process | reportUnusedPropTypes ( component ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-unused-prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-unused-prop-types.js | MIT |
function isDefaultPropsDeclaration(node) {
const propName = getPropertyName(node);
return (propName === 'defaultProps' || propName === 'getDefaultProps');
} | Checks if the Identifier node passed in looks like a defaultProps declaration.
@param {ASTNode} node The node to check. Must be an Identifier node.
@returns {boolean} `true` if the node is a defaultProps declaration, `false` if not | isDefaultPropsDeclaration ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/sort-default-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-default-props.js | MIT |
function findVariableByName(node, name) {
const variable = variableUtil.getVariableFromContext(context, node, name);
if (!variable || !variable.defs[0] || !variable.defs[0].node) {
return null;
}
if (variable.defs[0].node.type === 'TypeAlias') {
return variable.defs[0].node.right;
}
return variable.defs[0].node.init;
} | Find a variable by name in the current scope.
@param {ASTNode} node The node to look for.
@param {string} name Name of the variable to look for.
@returns {ASTNode|null} Return null if the variable could not be found, ASTNode otherwise. | findVariableByName ( node , name ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/sort-default-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-default-props.js | MIT |
function checkSorted(declarations) {
// function fix(fixer) {
// return propTypesSortUtil.fixPropTypesSort(context, fixer, declarations, ignoreCase);
// }
declarations.reduce((prev, curr, idx, decls) => {
if (/Spread(?:Property|Element)$/.test(curr.type)) {
return decls[idx + 1];
}
let prevPropName = getKey(prev);
let currentPropName = getKey(curr);
if (ignoreCase) {
prevPropName = prevPropName.toLowerCase();
currentPropName = currentPropName.toLowerCase();
}
if (currentPropName < prevPropName) {
report(context, messages.propsNotSorted, 'propsNotSorted', {
node: curr,
// fix
});
return prev;
}
return curr;
}, declarations[0]);
} | Checks if defaultProps declarations are sorted
@param {Array} declarations The array of AST nodes being checked.
@returns {void} | checkSorted ( declarations ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/sort-default-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/sort-default-props.js | MIT |
function isForwardRefIdentifier(node) {
return node.type === 'Identifier' && node.name === 'forwardRef';
} | @param {ASTNode} node
@returns {boolean} If the node represents the identifier `forwardRef`. | isForwardRefIdentifier ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/forward-ref-uses-ref.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/forward-ref-uses-ref.js | MIT |
function isForwardRefCall(node) {
return (
node.type === 'CallExpression'
&& (
isForwardRefIdentifier(node.callee)
|| (node.callee.type === 'MemberExpression' && isForwardRefIdentifier(node.callee.property))
)
);
} | @param {ASTNode} node
@returns {boolean} If the node represents a function call `forwardRef()` or `React.forwardRef()`. | isForwardRefCall ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/forward-ref-uses-ref.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/forward-ref-uses-ref.js | MIT |
function isOnlyWhitespace(text) {
return text.trim().length === 0;
} | @param {string} text
@returns {boolean} | isOnlyWhitespace ( text ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function isFragmentWithOnlyTextAndIsNotChild(node) {
return node.children.length === 1
&& isJSXText(node.children[0])
&& !(node.parent.type === 'JSXElement' || node.parent.type === 'JSXFragment');
} | Somehow fragment like this is useful: <Foo content={<>ee eeee eeee ...</>} />
@param {ASTNode} node
@returns {boolean} | isFragmentWithOnlyTextAndIsNotChild ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function trimLikeReact(text) {
const leadingSpaces = /^\s*/.exec(text)[0];
const trailingSpaces = /\s*$/.exec(text)[0];
const start = arrayIncludes(leadingSpaces, '\n') ? leadingSpaces.length : 0;
const end = arrayIncludes(trailingSpaces, '\n') ? text.length - trailingSpaces.length : text.length;
return text.slice(start, end);
} | @param {string} text
@returns {string} | trimLikeReact ( text ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function isKeyedElement(node) {
return node.type === 'JSXElement'
&& node.openingElement.attributes
&& node.openingElement.attributes.some(jsxUtil.isJSXAttributeKey);
} | Test if node is like `<Fragment key={_}>_</Fragment>`
@param {JSXElement} node
@returns {boolean} | isKeyedElement ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function isPaddingSpaces(node) {
return isJSXText(node)
&& isOnlyWhitespace(node.raw)
&& arrayIncludes(node.raw, '\n');
} | Test whether a node is an padding spaces trimmed by react runtime.
@param {ASTNode} node
@returns {boolean} | isPaddingSpaces ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function hasLessThanTwoChildren(node) {
if (!node || !node.children) {
return true;
}
/** @type {ASTNode[]} */
const nonPaddingChildren = node.children.filter(
(child) => !isPaddingSpaces(child)
);
if (nonPaddingChildren.length < 2) {
return !containsCallExpression(nonPaddingChildren[0]);
}
} | Test whether a JSXElement has less than two children, excluding paddings spaces.
@param {JSXElement|JSXFragment} node
@returns {boolean} | hasLessThanTwoChildren ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function isChildOfHtmlElement(node) {
return node.parent.type === 'JSXElement'
&& node.parent.openingElement.name.type === 'JSXIdentifier'
&& /^[a-z]+$/.test(node.parent.openingElement.name.name);
} | @param {JSXElement|JSXFragment} node
@returns {boolean} | isChildOfHtmlElement ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function isChildOfComponentElement(node) {
return node.parent.type === 'JSXElement'
&& !isChildOfHtmlElement(node)
&& !jsxUtil.isFragment(node.parent, reactPragma, fragmentPragma);
} | @param {JSXElement|JSXFragment} node
@return {boolean} | isChildOfComponentElement ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function getFix(node) {
if (!canFix(node)) {
return undefined;
}
return function fix(fixer) {
const opener = node.type === 'JSXFragment' ? node.openingFragment : node.openingElement;
const closer = node.type === 'JSXFragment' ? node.closingFragment : node.closingElement;
const childrenText = opener.selfClosing ? '' : getText(context).slice(opener.range[1], closer.range[0]);
return fixer.replaceText(node, trimLikeReact(childrenText));
};
} | @param {ASTNode} node
@returns {Function | undefined} | getFix ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-useless-fragment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-useless-fragment.js | MIT |
function isDangerous(name) {
return has(DANGEROUS_PROPERTIES, name);
} | Checks if a JSX attribute is dangerous.
@param {string} name - Name of the attribute to check.
@returns {boolean} Whether or not the attribute is dangerous. | isDangerous ( name ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-danger.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-danger.js | MIT |
function hasPureRenderDecorator(node) {
if (node.decorators && node.decorators.length) {
for (let i = 0, l = node.decorators.length; i < l; i++) {
if (
node.decorators[i].expression
&& node.decorators[i].expression.callee
&& node.decorators[i].expression.callee.object
&& node.decorators[i].expression.callee.object.name === 'reactMixin'
&& node.decorators[i].expression.callee.property
&& node.decorators[i].expression.callee.property.name === 'decorate'
&& node.decorators[i].expression.arguments
&& node.decorators[i].expression.arguments.length
&& node.decorators[i].expression.arguments[0].name === 'PureRenderMixin'
) {
return true;
}
}
}
return false;
} | Checks to see if our component is decorated by PureRenderMixin via reactMixin
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if node is decorated with a PureRenderMixin, false if not. | hasPureRenderDecorator ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-optimization.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-optimization.js | MIT |
function hasCustomDecorator(node) {
const allowLength = allowDecorators.length;
if (allowLength && node.decorators && node.decorators.length) {
for (let i = 0; i < allowLength; i++) {
for (let j = 0, l = node.decorators.length; j < l; j++) {
const expression = node.decorators[j].expression;
if (
expression
&& expression.name === allowDecorators[i]
) {
return true;
}
}
}
}
return false;
} | Checks to see if our component is custom decorated
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if node is decorated name with a custom decorated, false if not. | hasCustomDecorator ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-optimization.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-optimization.js | MIT |
function isSCUDeclared(node) {
return !!node && node.name === 'shouldComponentUpdate';
} | Checks if we are declaring a shouldComponentUpdate method
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if we are declaring a shouldComponentUpdate method, false if not. | isSCUDeclared ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-optimization.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-optimization.js | MIT |
function isPureRenderDeclared(node) {
let hasPR = false;
if (node.value && node.value.elements) {
for (let i = 0, l = node.value.elements.length; i < l; i++) {
if (node.value.elements[i] && node.value.elements[i].name === 'PureRenderMixin') {
hasPR = true;
break;
}
}
}
return (
!!node
&& node.key.name === 'mixins'
&& hasPR
);
} | Checks if we are declaring a PureRenderMixin mixin
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if we are declaring a PureRenderMixin method, false if not. | isPureRenderDeclared ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-optimization.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-optimization.js | MIT |
function reportMissingOptimization(component) {
report(context, messages.noShouldComponentUpdate, 'noShouldComponentUpdate', {
node: component.node,
});
} | Reports missing optimization for a given component
@param {Object} component The component to process | reportMissingOptimization ( component ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-optimization.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-optimization.js | MIT |
function isFunctionInClass(node) {
let blockNode;
let scope = getScope(context, node);
while (scope) {
blockNode = scope.block;
if (blockNode && blockNode.type === 'ClassDeclaration') {
return true;
}
scope = scope.upper;
}
return false;
} | Checks if we are declaring function in class
@param {ASTNode} node
@returns {boolean} True if we are declaring function in class, false if not. | isFunctionInClass ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-optimization.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-optimization.js | MIT |
function getGroupsOfSortableAttributes(attributes, context) {
const sourceCode = getSourceCode(context);
const sortableAttributeGroups = [];
let groupCount = 0;
function addtoSortableAttributeGroups(attribute) {
sortableAttributeGroups[groupCount - 1].push(attribute);
}
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
const nextAttribute = attributes[i + 1];
const attributeline = attribute.loc.start.line;
let comment = [];
try {
comment = sourceCode.getCommentsAfter(attribute);
} catch (e) { /**/ }
const lastAttr = attributes[i - 1];
const attrIsSpread = attribute.type === 'JSXSpreadAttribute';
// If we have no groups or if the last attribute was JSXSpreadAttribute
// then we start a new group. Append attributes to the group until we
// come across another JSXSpreadAttribute or exhaust the array.
if (
!lastAttr
|| (lastAttr.type === 'JSXSpreadAttribute' && !attrIsSpread)
) {
groupCount += 1;
sortableAttributeGroups[groupCount - 1] = [];
}
if (!attrIsSpread) {
if (comment.length === 0) {
attributeMap.set(attribute, { end: attribute.range[1], hasComment: false });
addtoSortableAttributeGroups(attribute);
} else {
const firstComment = comment[0];
const commentline = firstComment.loc.start.line;
if (comment.length === 1) {
if (attributeline + 1 === commentline && nextAttribute) {
attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
addtoSortableAttributeGroups(attribute);
i += 1;
} else if (attributeline === commentline) {
if (firstComment.type === 'Block' && nextAttribute) {
attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
i += 1;
} else if (firstComment.type === 'Block') {
attributeMap.set(attribute, { end: firstComment.range[1], hasComment: true });
} else {
attributeMap.set(attribute, { end: firstComment.range[1], hasComment: false });
}
addtoSortableAttributeGroups(attribute);
}
} else if (comment.length > 1 && attributeline + 1 === comment[1].loc.start.line && nextAttribute) {
const commentNextAttribute = sourceCode.getCommentsAfter(nextAttribute);
attributeMap.set(attribute, { end: nextAttribute.range[1], hasComment: true });
if (
commentNextAttribute.length === 1
&& nextAttribute.loc.start.line === commentNextAttribute[0].loc.start.line
) {
attributeMap.set(attribute, { end: commentNextAttribute[0].range[1], hasComment: true });
}
addtoSortableAttributeGroups(attribute);
i += 1;
}
}
}
}
return sortableAttributeGroups;
} | Create an array of arrays where each subarray is composed of attributes
that are considered sortable.
@param {Array<JSXSpreadAttribute|JSXAttribute>} attributes
@param {Object} context The context of the rule
@return {Array<Array<JSXAttribute>>} | getGroupsOfSortableAttributes ( attributes , context ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-sort-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-sort-props.js | MIT |
function handleOpeningElement(node) {
markVariableAsUsed(pragma, node, context);
} | @param {ASTNode} node
@returns {void} | handleOpeningElement ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-uses-react.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-uses-react.js | MIT |
function checkProperties(declarations) {
if (declarations) {
declarations.forEach((declaration) => {
if (declaration.type !== 'Property') {
return;
}
let target;
let value = declaration.value;
if (
value.type === 'MemberExpression'
&& value.property
&& value.property.name
&& value.property.name === 'isRequired'
) {
value = value.object;
}
if (astUtil.isCallExpression(value)) {
if (!isPropTypesPackage(value.callee)) {
return;
}
value.arguments.forEach((arg) => {
const name = arg.type === 'MemberExpression' ? arg.property.name : arg.name;
reportIfForbidden(name, declaration, name);
});
value = value.callee;
}
if (!isPropTypesPackage(value)) {
return;
}
if (value.property) {
target = value.property.name;
} else if (value.type === 'Identifier') {
target = value.name;
}
reportIfForbidden(target, declaration, target);
});
}
} | Checks if propTypes declarations are forbidden
@param {Array} declarations The array of AST nodes being checked.
@returns {void} | checkProperties ( declarations ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/forbid-prop-types.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/forbid-prop-types.js | MIT |
function isRefsUsage(node) {
return !!(
(componentUtil.getParentES6Component(context, node) || componentUtil.getParentES5Component(context, node))
&& node.object.type === 'ThisExpression'
&& node.property.name === 'refs'
);
} | Checks if we are using refs
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if we are using refs, false if not. | isRefsUsage ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-string-refs.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-string-refs.js | MIT |
function isRefAttribute(node) {
return node.type === 'JSXAttribute'
&& !!node.name
&& node.name.name === 'ref';
} | Checks if we are using a ref attribute
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if we are using a ref attribute, false if not. | isRefAttribute ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-string-refs.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-string-refs.js | MIT |
function containsStringLiteral(node) {
return !!node.value
&& node.value.type === 'Literal'
&& typeof node.value.value === 'string';
} | Checks if a node contains a string value
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if the node contains a string value, false if not. | containsStringLiteral ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-string-refs.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-string-refs.js | MIT |
function containsStringExpressionContainer(node) {
return !!node.value
&& node.value.type === 'JSXExpressionContainer'
&& node.value.expression
&& ((node.value.expression.type === 'Literal' && typeof node.value.expression.value === 'string')
|| (node.value.expression.type === 'TemplateLiteral' && detectTemplateLiterals));
} | Checks if a node contains a string value within a jsx expression
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if the node contains a string value within a jsx expression, false if not. | containsStringExpressionContainer ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/no-string-refs.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/no-string-refs.js | MIT |
function reportPropTypesWithoutDefault(propTypes, defaultProps) {
entries(propTypes).forEach((propType) => {
const propName = propType[0];
const prop = propType[1];
if (!prop.node) {
return;
}
if (prop.isRequired) {
if (forbidDefaultForRequired && defaultProps[propName]) {
report(context, messages.noDefaultWithRequired, 'noDefaultWithRequired', {
node: prop.node,
data: { name: propName },
});
}
return;
}
if (defaultProps[propName]) {
return;
}
report(context, messages.shouldHaveDefault, 'shouldHaveDefault', {
node: prop.node,
data: { name: propName },
});
});
} | Reports all propTypes passed in that don't have a defaultProps counterpart.
@param {Object[]} propTypes List of propTypes to check.
@param {Object} defaultProps Object of defaultProps to check. Keys are the props names.
@return {void} | reportPropTypesWithoutDefault ( propTypes , defaultProps ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-default-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-default-props.js | MIT |
function reportFunctionComponent(componentNode, declaredPropTypes, defaultProps) {
if (defaultProps) {
report(context, messages.noDefaultPropsWithFunction, 'noDefaultPropsWithFunction', {
node: componentNode,
});
}
const props = componentNode.params[0];
const propTypes = declaredPropTypes;
if (!props) {
return;
}
if (props.type === 'Identifier') {
const hasOptionalProp = values(propTypes).some((propType) => !propType.isRequired);
if (hasOptionalProp) {
report(context, messages.destructureInSignature, 'destructureInSignature', {
node: props,
});
}
} else if (props.type === 'ObjectPattern') {
// Filter required props with default value and report error
props.properties.filter((prop) => {
const propName = prop && prop.key && prop.key.name;
const isPropRequired = propTypes[propName] && propTypes[propName].isRequired;
return propTypes[propName] && isPropRequired && !isPropWithNoDefaulVal(prop);
}).forEach((prop) => {
report(context, messages.noDefaultWithRequired, 'noDefaultWithRequired', {
node: prop,
data: { name: prop.key.name },
});
});
// Filter non required props with no default value and report error
props.properties.filter((prop) => {
const propName = prop && prop.key && prop.key.name;
const isPropRequired = propTypes[propName] && propTypes[propName].isRequired;
return propTypes[propName] && !isPropRequired && isPropWithNoDefaulVal(prop);
}).forEach((prop) => {
report(context, messages.shouldAssignObjectDefault, 'shouldAssignObjectDefault', {
node: prop,
data: { name: prop.key.name },
});
});
}
} | If functions option is 'defaultArguments', reports defaultProps is used and all params that doesn't initialized.
@param {Object} componentNode Node of component.
@param {Object[]} declaredPropTypes List of propTypes to check `isRequired`.
@param {Object} defaultProps Object of defaultProps to check used. | reportFunctionComponent ( componentNode , declaredPropTypes , defaultProps ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-default-props.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-default-props.js | MIT |
function markReturnStatementPresent(node) {
components.set(node, {
hasReturnStatement: true,
});
} | Mark a return statement as present
@param {ASTNode} node The AST node being checked. | markReturnStatementPresent ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-render-return.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-render-return.js | MIT |
function findRenderMethod(node) {
const properties = astUtil.getComponentProperties(node);
return properties
.filter((property) => astUtil.getPropertyName(property) === 'render' && property.value)
.find((property) => astUtil.isFunctionLikeExpression(property.value));
} | Find render method in a given AST node
@param {ASTNode} node The component to find render method.
@returns {ASTNode} Method node if found, undefined if not. | findRenderMethod ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/require-render-return.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/require-render-return.js | MIT |
function getFixerFunction(node, needed) {
const indent = repeat(indentChar, needed);
if (node.type === 'JSXText' || node.type === 'Literal') {
return function fix(fixer) {
const regExp = /\n[\t ]*(\S)/g;
const fixedText = node.raw.replace(regExp, (match, p1) => `\n${indent}${p1}`);
return fixer.replaceText(node, fixedText);
};
}
if (node.type === 'ReturnStatement') {
const raw = getText(context, node);
const lines = raw.split('\n');
if (lines.length > 1) {
return function fix(fixer) {
const lastLineStart = raw.lastIndexOf('\n');
const lastLine = raw.slice(lastLineStart).replace(/^\n[\t ]*(\S)/, (match, p1) => `\n${indent}${p1}`);
return fixer.replaceTextRange(
[node.range[0] + lastLineStart, node.range[1]],
lastLine
);
};
}
}
return function fix(fixer) {
return fixer.replaceTextRange(
[node.range[0] - node.loc.start.column, node.range[0]],
indent
);
};
} | Responsible for fixing the indentation issue fix
@param {ASTNode} node Node violating the indent rule
@param {number} needed Expected indentation character count
@returns {Function} function to be executed by the fixer
@private | getFixerFunction ( node , needed ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent.js | MIT |
function getNodeIndent(node, byLastLine, excludeCommas) {
let src = getText(context, node, node.loc.start.column + extraColumnStart);
const lines = src.split('\n');
if (byLastLine) {
src = lines[lines.length - 1];
} else {
src = lines[0];
}
const skip = excludeCommas ? ',' : '';
let regExp;
if (indentType === 'space') {
regExp = new RegExp(`^[ ${skip}]+`);
} else {
regExp = new RegExp(`^[\t${skip}]+`);
}
const indent = regExp.exec(src);
return indent ? indent[0].length : 0;
} | Get node indent
@param {ASTNode} node Node to examine
@param {boolean} [byLastLine] get indent of node's last line
@param {boolean} [excludeCommas] skip comma on start of line
@return {number} Indent | getNodeIndent ( node , byLastLine , excludeCommas ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent.js | MIT |
function isRightInLogicalExp(node) {
return (
node.parent
&& node.parent.parent
&& node.parent.parent.type === 'LogicalExpression'
&& node.parent.parent.right === node.parent
&& !indentLogicalExpressions
);
} | Check if the node is the right member of a logical expression
@param {ASTNode} node The node to check
@return {boolean} true if its the case, false if not | isRightInLogicalExp ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent.js | MIT |
function isAlternateInConditionalExp(node) {
return (
node.parent
&& node.parent.parent
&& node.parent.parent.type === 'ConditionalExpression'
&& node.parent.parent.alternate === node.parent
&& getSourceCode(context).getTokenBefore(node).value !== '('
);
} | Check if the node is the alternate member of a conditional expression
@param {ASTNode} node The node to check
@return {boolean} true if its the case, false if not | isAlternateInConditionalExp ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent.js | MIT |
function isSecondOrSubsequentExpWithinDoExp(node) {
/*
It returns true when node.parent.parent.parent.parent matches:
DoExpression({
...,
body: BlockStatement({
...,
body: [
..., // 1-n times
ExpressionStatement({
...,
expression: JSXElement({
...,
openingElement: JSXOpeningElement() // the node
})
}),
... // 0-n times
]
})
})
except:
DoExpression({
...,
body: BlockStatement({
...,
body: [
ExpressionStatement({
...,
expression: JSXElement({
...,
openingElement: JSXOpeningElement() // the node
})
}),
... // 0-n times
]
})
})
*/
const isInExpStmt = (
node.parent
&& node.parent.parent
&& node.parent.parent.type === 'ExpressionStatement'
);
if (!isInExpStmt) {
return false;
}
const expStmt = node.parent.parent;
const isInBlockStmtWithinDoExp = (
expStmt.parent
&& expStmt.parent.type === 'BlockStatement'
&& expStmt.parent.parent
&& expStmt.parent.parent.type === 'DoExpression'
);
if (!isInBlockStmtWithinDoExp) {
return false;
}
const blockStmt = expStmt.parent;
const blockStmtFirstExp = blockStmt.body[0];
return !(blockStmtFirstExp === expStmt);
} | Check if the node is within a DoExpression block but not the first expression (which need to be indented)
@param {ASTNode} node The node to check
@return {boolean} true if its the case, false if not | isSecondOrSubsequentExpWithinDoExp ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent.js | MIT |
function checkNodesIndent(node, indent, excludeCommas) {
const nodeIndent = getNodeIndent(node, false, excludeCommas);
const isCorrectRightInLogicalExp = isRightInLogicalExp(node) && (nodeIndent - indent) === indentSize;
const isCorrectAlternateInCondExp = isAlternateInConditionalExp(node) && (nodeIndent - indent) === 0;
if (
nodeIndent !== indent
&& astUtil.isNodeFirstInLine(context, node)
&& !isCorrectRightInLogicalExp
&& !isCorrectAlternateInCondExp
) {
report(node, indent, nodeIndent);
}
} | Check indent for nodes list
@param {ASTNode} node The node to check
@param {number} indent needed indent
@param {boolean} [excludeCommas] skip comma on start of line | checkNodesIndent ( node , indent , excludeCommas ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-indent.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-indent.js | MIT |
function findParent(node, predicate) {
let n = node;
while (n) {
if (predicate(n)) {
return n;
}
n = n.parent;
}
return undefined;
} | Find a parent that satisfy the given predicate
@param {ASTNode} node
@param {(node: ASTNode) => boolean} predicate
@returns {ASTNode | undefined} | findParent ( node , predicate ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/destructuring-assignment.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/destructuring-assignment.js | MIT |
function markDisplayNameAsDeclared(node) {
components.set(node, {
hasDisplayName: true,
});
} | Mark a prop type as declared
@param {ASTNode} node The AST node being checked. | markDisplayNameAsDeclared ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/display-name.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/display-name.js | MIT |
function isNestedMemo(node) {
return astUtil.isCallExpression(node)
&& node.arguments
&& astUtil.isCallExpression(node.arguments[0])
&& utils.isPragmaComponentWrapper(node);
} | Checks if React.forwardRef is nested inside React.memo
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if React.forwardRef is nested inside React.memo, false if not. | isNestedMemo ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/display-name.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/display-name.js | MIT |
function reportMissingDisplayName(component) {
if (
testReactVersion(context, '^0.14.10 || ^15.7.0 || >= 16.12.0')
&& isNestedMemo(component.node)
) {
return;
}
report(context, messages.noDisplayName, 'noDisplayName', {
node: component.node,
});
} | Reports missing display name for a given component
@param {Object} component The component to process | reportMissingDisplayName ( component ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/display-name.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/display-name.js | MIT |
function reportMissingContextDisplayName(contextObj) {
report(context, messages.noContextDisplayName, 'noContextDisplayName', {
node: contextObj.node,
});
} | Reports missing display name for a given context object
@param {Object} contextObj The context object to process | reportMissingContextDisplayName ( contextObj ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/display-name.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/display-name.js | MIT |
function hasTranspilerName(node) {
const namedObjectAssignment = (
node.type === 'ObjectExpression'
&& node.parent
&& node.parent.parent
&& node.parent.parent.type === 'AssignmentExpression'
&& (
!node.parent.parent.left.object
|| node.parent.parent.left.object.name !== 'module'
|| node.parent.parent.left.property.name !== 'exports'
)
);
const namedObjectDeclaration = (
node.type === 'ObjectExpression'
&& node.parent
&& node.parent.parent
&& node.parent.parent.type === 'VariableDeclarator'
);
const namedClass = (
(node.type === 'ClassDeclaration' || node.type === 'ClassExpression')
&& node.id
&& !!node.id.name
);
const namedFunctionDeclaration = (
(node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression')
&& node.id
&& !!node.id.name
);
const namedFunctionExpression = (
astUtil.isFunctionLikeExpression(node)
&& node.parent
&& (node.parent.type === 'VariableDeclarator' || node.parent.type === 'Property' || node.parent.method === true)
&& (!node.parent.parent || !componentUtil.isES5Component(node.parent.parent, context))
);
if (
namedObjectAssignment || namedObjectDeclaration
|| namedClass
|| namedFunctionDeclaration || namedFunctionExpression
) {
return true;
}
return false;
} | Checks if the component have a name set by the transpiler
@param {ASTNode} node The AST node being checked.
@returns {boolean} True if component has a name, false if not. | hasTranspilerName ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/display-name.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/display-name.js | MIT |
function checkIdentifierInJSX(node) {
let scope = eslintUtil.getScope(context, node);
const sourceCode = eslintUtil.getSourceCode(context);
const sourceType = sourceCode.ast.sourceType;
const scopeUpperBound = !allowGlobals && sourceType === 'module' ? 'module' : 'global';
let variables = scope.variables;
let i;
let len;
// Ignore 'this' keyword (also maked as JSXIdentifier when used in JSX)
if (node.name === 'this') {
return;
}
while (scope.type !== scopeUpperBound && scope.type !== 'global') {
scope = scope.upper;
variables = scope.variables.concat(variables);
}
if (scope.childScopes.length) {
variables = scope.childScopes[0].variables.concat(variables);
// Temporary fix for babel-eslint
if (scope.childScopes[0].childScopes.length) {
variables = scope.childScopes[0].childScopes[0].variables.concat(variables);
}
}
for (i = 0, len = variables.length; i < len; i++) {
if (variables[i].name === node.name) {
return;
}
}
report(context, messages.undefined, 'undefined', {
node,
data: {
identifier: node.name,
},
});
} | Compare an identifier with the variables declared in the scope
@param {ASTNode} node - Identifier or JSXIdentifier node
@returns {void} | checkIdentifierInJSX ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-undef.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-undef.js | MIT |
function trimIfString(value) {
return typeof value === 'string' ? value.trim() : value;
} | @param {unknown} value
@returns {string | unknown} | trimIfString ( value ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function normalizeConfig(config) {
/** @type {Config} */
const normalizedConfig = Object.assign(normalizeElementConfig(config), {
elementOverrides: {},
});
if (config.elementOverrides) {
normalizedConfig.elementOverrides = fromEntries(
flatMap(
iterFrom(entries(config.elementOverrides)),
(entry) => {
const elementName = entry[0];
const rawElementConfig = entry[1];
if (!reOverridableElement.test(elementName)) {
return [];
}
return [[
elementName,
Object.assign(normalizeElementConfig(rawElementConfig), {
type: 'override',
name: elementName,
allowElement: !!rawElementConfig.allowElement,
applyToNestedElements: typeof rawElementConfig.applyToNestedElements === 'undefined' || !!rawElementConfig.applyToNestedElements,
}),
]];
}
)
);
}
return normalizedConfig;
} | Normalizes the config and applies default values to all config options
@param {RawConfig} config
@returns {Config} | normalizeConfig ( config ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function isRequireStatement(node) {
if (node.type === 'CallExpression') {
if (node.callee.type === 'Identifier') {
return node.callee.name === 'require';
}
}
if (node.type === 'MemberExpression') {
return isRequireStatement(node.object);
}
return false;
} | Determines if the given expression is a require statement. Supports
nested MemberExpresions. ie `require('foo').nested.property`
@param {ASTNode} node
@returns {boolean} | isRequireStatement ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function getJSXElementAncestors(node) {
/** @type {ASTNode[]} */
const ancestors = [];
let current = node;
while (current) {
if (current.type === 'JSXElement') {
ancestors.push(current);
}
current = current.parent;
}
return ancestors;
} | Gets all JSXElement ancestor nodes for the given node
@param {ASTNode} node
@returns {ASTNode[]} | getJSXElementAncestors ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function getParentIgnoringBinaryExpressions(node) {
let current = node;
while (current.parent.type === 'BinaryExpression') {
current = current.parent;
}
return current.parent;
} | @param {ASTNode} node
@returns {ASTNode} | getParentIgnoringBinaryExpressions ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function getParentAndGrandParent(node) {
const parent = getParentIgnoringBinaryExpressions(node);
return {
parent,
grandParent: parent.parent,
};
} | @param {ASTNode} node
@returns {{ parent: ASTNode, grandParent: ASTNode }} | getParentAndGrandParent ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function isViableTextNode(node, resolvedConfig) {
const textValues = iterFrom([trimIfString(node.raw), trimIfString(node.value)]);
if (some(textValues, (value) => resolvedConfig.allowedStrings.has(value))) {
return false;
}
const parent = getParentIgnoringBinaryExpressions(node);
let isStandardJSXNode = false;
if (typeof node.value === 'string' && !reIsWhiteSpace.test(node.value) && standardJSXNodeParentTypes.has(parent.type)) {
if (resolvedConfig.noAttributeStrings) {
isStandardJSXNode = parent.type === 'JSXAttribute' || parent.type === 'JSXElement';
} else {
isStandardJSXNode = parent.type !== 'JSXAttribute';
}
}
if (resolvedConfig.noStrings) {
return isStandardJSXNode;
}
return isStandardJSXNode && parent.type !== 'JSXExpressionContainer';
} | Determines whether a given node's value and its immediate parent are
viable text nodes that can/should be reported on
@param {ASTNode} node
@param {ResolvedConfig} resolvedConfig
@returns {boolean} | isViableTextNode ( node , resolvedConfig ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function getOverrideConfig(node) {
if (!hasElementOverrides) {
return;
}
const allAncestorElements = getJSXElementAncestors(node);
if (!allAncestorElements.length) {
return;
}
for (const ancestorElement of allAncestorElements) {
const isClosestJSXAncestor = ancestorElement === allAncestorElements[0];
const ancestor = getJSXElementName(ancestorElement);
if (ancestor) {
if (ancestor.name) {
const ancestorElements = config.elementOverrides[ancestor.name];
const ancestorConfig = ancestor.compoundName
? config.elementOverrides[ancestor.compoundName] || ancestorElements
: ancestorElements;
if (ancestorConfig) {
if (isClosestJSXAncestor || ancestorConfig.applyToNestedElements) {
return ancestorConfig;
}
}
}
}
}
} | Gets an override config for a given node. For any given node, we also
need to traverse the ancestor tree to determine if an ancestor's config
will also apply to the current node.
@param {ASTNode} node
@returns {OverrideConfig | undefined} | getOverrideConfig ( node ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function shouldAllowElement(resolvedConfig) {
return resolvedConfig.type === 'override' && 'allowElement' in resolvedConfig && !!resolvedConfig.allowElement;
} | @param {ResolvedConfig} resolvedConfig
@returns {boolean} | shouldAllowElement ( resolvedConfig ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function defaultMessageId(ancestorIsJSXElement, resolvedConfig) {
if (resolvedConfig.noAttributeStrings && !ancestorIsJSXElement) {
return resolvedConfig.type === 'override' ? 'noStringsInAttributesInElement' : 'noStringsInAttributes';
}
if (resolvedConfig.noStrings) {
return resolvedConfig.type === 'override' ? 'noStringsInJSXInElement' : 'noStringsInJSX';
}
return resolvedConfig.type === 'override' ? 'literalNotInJSXExpressionInElement' : 'literalNotInJSXExpression';
} | @param {boolean} ancestorIsJSXElement
@param {ResolvedConfig} resolvedConfig
@returns {string} | defaultMessageId ( ancestorIsJSXElement , resolvedConfig ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-no-literals.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-no-literals.js | MIT |
function isMultiline(left, right) {
return left.loc.end.line !== right.loc.start.line;
} | Determines whether two adjacent tokens have a newline between them.
@param {Object} left - The left token object.
@param {Object} right - The right token object.
@returns {boolean} Whether or not there is a newline between the tokens. | isMultiline ( left , right ) | javascript | jsx-eslint/eslint-plugin-react | lib/rules/jsx-curly-spacing.js | https://github.com/jsx-eslint/eslint-plugin-react/blob/master/lib/rules/jsx-curly-spacing.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.