Skip to content

Commit

Permalink
Add support for variable reference to sort-prop-types (fixes #622)
Browse files Browse the repository at this point in the history
  • Loading branch information
yannickcr committed Jan 7, 2017
1 parent 682ae68 commit 13806f1
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
35 changes: 30 additions & 5 deletions lib/rules/sort-prop-types.js
Expand Up @@ -3,6 +3,10 @@
*/
'use strict';

var find = require('array.prototype.find');

var variableUtil = require('../util/variable');

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
Expand Down Expand Up @@ -150,11 +154,32 @@ module.exports = {
},

MemberExpression: function(node) {
if (isPropTypesDeclaration(node.property)) {
var right = node.parent.right;
if (right && right.type === 'ObjectExpression') {
checkSorted(right.properties);
}
if (!isPropTypesDeclaration(node.property)) {
return;
}
var right = node.parent.right;
var declarations;
switch (right && right.type) {
case 'ObjectExpression':
declarations = right.properties;
break;
case 'Identifier':
var variable = find(variableUtil.variablesInScope(context), function (item) {
return item.name === right.name;
});
if (
!variable || !variable.defs[0] ||
!variable.defs[0].node.init || !variable.defs[0].node.init.properties
) {
break;
}
declarations = variable.defs[0].node.init.properties;
break;
default:
break;
}
if (declarations) {
checkSorted(declarations);
}
},

Expand Down
27 changes: 27 additions & 0 deletions tests/lib/rules/sort-prop-types.js
Expand Up @@ -323,6 +323,15 @@ ruleTester.run('sort-prop-types', rule, {
'}'
].join('\n'),
parser: 'babel-eslint'
}, {
code: [
'const propTypes = require(\'./externalPropTypes\')',
'const TextFieldLabel = (props) => {',
' return <div />;',
'};',
'TextFieldLabel.propTypes = propTypes;'
].join('\n'),
parserOptions: parserOptions
}],

invalid: [{
Expand Down Expand Up @@ -624,5 +633,23 @@ ruleTester.run('sort-prop-types', rule, {
column: 5,
type: 'Property'
}]
}, {
code: [
'const propTypes = {',
' b: PropTypes.string,',
' a: PropTypes.string,',
'};',
'const TextFieldLabel = (props) => {',
' return <div />;',
'};',
'TextFieldLabel.propTypes = propTypes;'
].join('\n'),
parserOptions: parserOptions,
errors: [{
message: ERROR_MESSAGE,
line: 3,
column: 3,
type: 'Property'
}]
}]
});

0 comments on commit 13806f1

Please sign in to comment.