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