state-in-constructor.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 Components = require('../util/Components');
  7. const docsUrl = require('../util/docsUrl');
  8. // ------------------------------------------------------------------------------
  9. // Rule Definition
  10. // ------------------------------------------------------------------------------
  11. module.exports = {
  12. meta: {
  13. docs: {
  14. description: 'State initialization in an ES6 class component should be in a constructor',
  15. category: 'Stylistic Issues',
  16. recommended: false,
  17. url: docsUrl('state-in-constructor')
  18. },
  19. messages: {
  20. stateInitConstructor: 'State initialization should be in a constructor',
  21. stateInitClassProp: 'State initialization should be in a class property'
  22. },
  23. schema: [{
  24. enum: ['always', 'never']
  25. }]
  26. },
  27. create: Components.detect((context, components, utils) => {
  28. const option = context.options[0] || 'always';
  29. return {
  30. ClassProperty(node) {
  31. if (
  32. option === 'always'
  33. && !node.static
  34. && node.key.name === 'state'
  35. && utils.getParentES6Component()
  36. ) {
  37. context.report({
  38. node,
  39. messageId: 'stateInitConstructor'
  40. });
  41. }
  42. },
  43. AssignmentExpression(node) {
  44. if (
  45. option === 'never'
  46. && utils.isStateMemberExpression(node.left)
  47. && utils.inConstructor()
  48. && utils.getParentES6Component()
  49. ) {
  50. context.report({
  51. node,
  52. messageId: 'stateInitClassProp'
  53. });
  54. }
  55. }
  56. };
  57. })
  58. };