Skip to content

Commit b92d2b2

Browse files
committed
Add realization code for jsx-sort-prop-types rule.
1 parent a697753 commit b92d2b2

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

lib/rules/jsx-sort-prop-types.js

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/**
2+
* @fileoverview Enforce propTypes declarations alphabetical sorting
3+
*/
4+
'use strict';
5+
6+
// ------------------------------------------------------------------------------
7+
// Rule Definition
8+
// ------------------------------------------------------------------------------
9+
10+
module.exports = function(context) {
11+
12+
var configuration = context.options[0] || {};
13+
var ignoreCase = configuration.ignoreCase || false;
14+
15+
/**
16+
* Checks if node is `propTypes` declaration
17+
* @param {ASTNode} node The AST node being checked.
18+
* @returns {Boolean} True if node is `propTypes` declaration, false if not.
19+
*/
20+
function isPropTypesDeclaration(node) {
21+
22+
// Special case for class properties
23+
// (babel-eslint does not expose property name so we have to rely on tokens)
24+
if (node.type === 'ClassProperty') {
25+
var tokens = context.getFirstTokens(node, 2);
26+
if (tokens[0].value === 'propTypes' || tokens[1].value === 'propTypes') {
27+
return true;
28+
}
29+
return false;
30+
}
31+
32+
return Boolean(
33+
node &&
34+
node.name === 'propTypes'
35+
);
36+
}
37+
38+
/**
39+
* Checks if propTypes declarations are sorted
40+
* @param {Array} declarations The array of AST nodes being checked.
41+
* @returns {void}
42+
*/
43+
function checkSorted(declarations) {
44+
declarations.reduce(function(prev, curr) {
45+
var prevPropName = prev.key.name;
46+
var currenPropName = curr.key.name;
47+
48+
if (ignoreCase) {
49+
prevPropName = prevPropName.toLowerCase();
50+
currenPropName = currenPropName.toLowerCase();
51+
}
52+
53+
if (currenPropName < prevPropName) {
54+
context.report(curr, 'Prop types declarations should be sorted alphabetically');
55+
return prev;
56+
}
57+
58+
return curr;
59+
}, declarations[0]);
60+
}
61+
62+
return {
63+
ClassProperty: function(node) {
64+
if (isPropTypesDeclaration(node) && node.value.type === 'ObjectExpression') {
65+
checkSorted(node.value.properties);
66+
}
67+
},
68+
69+
MemberExpression: function(node) {
70+
if (isPropTypesDeclaration(node.property)) {
71+
var right = node.parent.right;
72+
if (right && right.type === 'ObjectExpression') {
73+
checkSorted(right.properties);
74+
}
75+
}
76+
},
77+
78+
ObjectExpression: function(node) {
79+
node.properties.forEach(function(property) {
80+
if (!isPropTypesDeclaration(property.key)) {
81+
return;
82+
}
83+
if (property.value.type === 'ObjectExpression') {
84+
checkSorted(property.value.properties);
85+
}
86+
});
87+
}
88+
89+
};
90+
};

0 commit comments

Comments
 (0)