state-in-constructor.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * @fileoverview Enforce the state initialization style to be either in a constructor or with a class property
  3. * @author Kanitkorn Sujautra
  4. */
  5. 'use strict';
  6. const astUtil = require('../util/ast');
  7. const componentUtil = require('../util/componentUtil');
  8. const docsUrl = require('../util/docsUrl');
  9. const report = require('../util/report');
  10. // ------------------------------------------------------------------------------
  11. // Rule Definition
  12. // ------------------------------------------------------------------------------
  13. const messages = {
  14. stateInitConstructor: 'State initialization should be in a constructor',
  15. stateInitClassProp: 'State initialization should be in a class property',
  16. };
  17. module.exports = {
  18. meta: {
  19. docs: {
  20. description: 'Enforce class component state initialization style',
  21. category: 'Stylistic Issues',
  22. recommended: false,
  23. url: docsUrl('state-in-constructor'),
  24. },
  25. messages,
  26. schema: [{
  27. enum: ['always', 'never'],
  28. }],
  29. },
  30. create(context) {
  31. const option = context.options[0] || 'always';
  32. return {
  33. 'ClassProperty, PropertyDefinition'(node) {
  34. if (
  35. option === 'always'
  36. && !node.static
  37. && node.key.name === 'state'
  38. && componentUtil.getParentES6Component(context)
  39. ) {
  40. report(context, messages.stateInitConstructor, 'stateInitConstructor', {
  41. node,
  42. });
  43. }
  44. },
  45. AssignmentExpression(node) {
  46. if (
  47. option === 'never'
  48. && componentUtil.isStateMemberExpression(node.left)
  49. && astUtil.inConstructor(context)
  50. && componentUtil.getParentES6Component(context)
  51. ) {
  52. report(context, messages.stateInitClassProp, 'stateInitClassProp', {
  53. node,
  54. });
  55. }
  56. },
  57. };
  58. },
  59. };