Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

boolean-prop-naming.js 8.2 KiB

3 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /**
  2. * @fileoverview Enforces consistent naming for boolean props
  3. * @author Ev Haus
  4. */
  5. 'use strict';
  6. const has = require('has');
  7. const Components = require('../util/Components');
  8. const propsUtil = require('../util/props');
  9. const docsUrl = require('../util/docsUrl');
  10. // ------------------------------------------------------------------------------
  11. // Rule Definition
  12. // ------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. docs: {
  16. category: 'Stylistic Issues',
  17. description: 'Enforces consistent naming for boolean props',
  18. recommended: false,
  19. url: docsUrl('boolean-prop-naming')
  20. },
  21. schema: [{
  22. additionalProperties: false,
  23. properties: {
  24. propTypeNames: {
  25. items: {
  26. type: 'string'
  27. },
  28. minItems: 1,
  29. type: 'array',
  30. uniqueItems: true
  31. },
  32. rule: {
  33. default: '^(is|has)[A-Z]([A-Za-z0-9]?)+',
  34. minLength: 1,
  35. type: 'string'
  36. },
  37. message: {
  38. minLength: 1,
  39. type: 'string'
  40. }
  41. },
  42. type: 'object'
  43. }]
  44. },
  45. create: Components.detect((context, components, utils) => {
  46. const sourceCode = context.getSourceCode();
  47. const config = context.options[0] || {};
  48. const rule = config.rule ? new RegExp(config.rule) : null;
  49. const propTypeNames = config.propTypeNames || ['bool'];
  50. const propWrapperFunctions = new Set(context.settings.propWrapperFunctions || []);
  51. // Remembers all Flowtype object definitions
  52. const objectTypeAnnotations = new Map();
  53. /**
  54. * Returns the prop key to ensure we handle the following cases:
  55. * propTypes: {
  56. * full: React.PropTypes.bool,
  57. * short: PropTypes.bool,
  58. * direct: bool,
  59. * required: PropTypes.bool.isRequired
  60. * }
  61. * @param {Object} node The node we're getting the name of
  62. */
  63. function getPropKey(node) {
  64. // Check for `ExperimentalSpreadProperty` (ESLint 3/4) and `SpreadElement` (ESLint 5)
  65. // so we can skip validation of those fields.
  66. // Otherwise it will look for `node.value.property` which doesn't exist and breaks ESLint.
  67. if (node.type === 'ExperimentalSpreadProperty' || node.type === 'SpreadElement') {
  68. return null;
  69. }
  70. if (node.value.property) {
  71. const name = node.value.property.name;
  72. if (name === 'isRequired') {
  73. if (node.value.object && node.value.object.property) {
  74. return node.value.object.property.name;
  75. }
  76. return null;
  77. }
  78. return name;
  79. }
  80. if (node.value.type === 'Identifier') {
  81. return node.value.name;
  82. }
  83. return null;
  84. }
  85. /**
  86. * Returns the name of the given node (prop)
  87. * @param {Object} node The node we're getting the name of
  88. */
  89. function getPropName(node) {
  90. // Due to this bug https://github.com/babel/babel-eslint/issues/307
  91. // we can't get the name of the Flow object key name. So we have
  92. // to hack around it for now.
  93. if (node.type === 'ObjectTypeProperty') {
  94. return sourceCode.getFirstToken(node).value;
  95. }
  96. return node.key.name;
  97. }
  98. /**
  99. * Checks and mark props with invalid naming
  100. * @param {Object} node The component node we're testing
  101. * @param {Array} proptypes A list of Property object (for each proptype defined)
  102. */
  103. function validatePropNaming(node, proptypes) {
  104. const component = components.get(node) || node;
  105. const invalidProps = component.invalidProps || [];
  106. (proptypes || []).forEach(prop => {
  107. const propKey = getPropKey(prop);
  108. const flowCheck = (
  109. prop.type === 'ObjectTypeProperty' &&
  110. prop.value.type === 'BooleanTypeAnnotation' &&
  111. rule.test(getPropName(prop)) === false
  112. );
  113. const regularCheck = (
  114. propKey &&
  115. propTypeNames.indexOf(propKey) >= 0 &&
  116. rule.test(getPropName(prop)) === false
  117. );
  118. if (flowCheck || regularCheck) {
  119. invalidProps.push(prop);
  120. }
  121. });
  122. components.set(node, {
  123. invalidProps: invalidProps
  124. });
  125. }
  126. /**
  127. * Reports invalid prop naming
  128. * @param {Object} component The component to process
  129. */
  130. function reportInvalidNaming(component) {
  131. component.invalidProps.forEach(propNode => {
  132. const propName = getPropName(propNode);
  133. context.report({
  134. node: propNode,
  135. message: config.message || 'Prop name ({{ propName }}) doesn\'t match rule ({{ pattern }})',
  136. data: {
  137. component: propName,
  138. propName: propName,
  139. pattern: config.rule
  140. }
  141. });
  142. });
  143. }
  144. function checkPropWrapperArguments(node, args) {
  145. if (!node || !Array.isArray(args)) {
  146. return;
  147. }
  148. args.filter(arg => arg.type === 'ObjectExpression').forEach(object => validatePropNaming(node, object.properties));
  149. }
  150. // --------------------------------------------------------------------------
  151. // Public
  152. // --------------------------------------------------------------------------
  153. return {
  154. ClassProperty: function(node) {
  155. if (!rule || !propsUtil.isPropTypesDeclaration(node)) {
  156. return;
  157. }
  158. if (node.value && node.value.type === 'CallExpression' && propWrapperFunctions.has(sourceCode.getText(node.value.callee))) {
  159. checkPropWrapperArguments(node, node.value.arguments);
  160. }
  161. if (node.value && node.value.properties) {
  162. validatePropNaming(node, node.value.properties);
  163. }
  164. if (node.typeAnnotation && node.typeAnnotation.typeAnnotation) {
  165. validatePropNaming(node, node.typeAnnotation.typeAnnotation.properties);
  166. }
  167. },
  168. MemberExpression: function(node) {
  169. if (!rule || !propsUtil.isPropTypesDeclaration(node)) {
  170. return;
  171. }
  172. const component = utils.getRelatedComponent(node);
  173. if (!component || !node.parent.right) {
  174. return;
  175. }
  176. const right = node.parent.right;
  177. if (right.type === 'CallExpression' && propWrapperFunctions.has(sourceCode.getText(right.callee))) {
  178. checkPropWrapperArguments(component.node, right.arguments);
  179. return;
  180. }
  181. validatePropNaming(component.node, node.parent.right.properties);
  182. },
  183. ObjectExpression: function(node) {
  184. if (!rule) {
  185. return;
  186. }
  187. // Search for the proptypes declaration
  188. node.properties.forEach(property => {
  189. if (!propsUtil.isPropTypesDeclaration(property)) {
  190. return;
  191. }
  192. validatePropNaming(node, property.value.properties);
  193. });
  194. },
  195. TypeAlias: function(node) {
  196. // Cache all ObjectType annotations, we will check them at the end
  197. if (node.right.type === 'ObjectTypeAnnotation') {
  198. objectTypeAnnotations.set(node.id.name, node.right);
  199. }
  200. },
  201. 'Program:exit': function() {
  202. if (!rule) {
  203. return;
  204. }
  205. const list = components.list();
  206. Object.keys(list).forEach(component => {
  207. // If this is a functional component that uses a global type, check it
  208. if (
  209. list[component].node.type === 'FunctionDeclaration' &&
  210. list[component].node.params &&
  211. list[component].node.params.length &&
  212. list[component].node.params[0].typeAnnotation
  213. ) {
  214. const typeNode = list[component].node.params[0].typeAnnotation;
  215. const annotation = typeNode.typeAnnotation;
  216. let propType;
  217. if (annotation.type === 'GenericTypeAnnotation') {
  218. propType = objectTypeAnnotations.get(annotation.id.name);
  219. } else if (annotation.type === 'ObjectTypeAnnotation') {
  220. propType = annotation;
  221. }
  222. if (propType) {
  223. validatePropNaming(list[component].node, propType.properties);
  224. }
  225. }
  226. if (!has(list, component) || (list[component].invalidProps || []).length) {
  227. reportInvalidNaming(list[component]);
  228. }
  229. });
  230. // Reset cache
  231. objectTypeAnnotations.clear();
  232. }
  233. };
  234. })
  235. };