UNPKG

3.41 kBJavaScriptView Raw
1/**
2 * @fileoverview Disallow or enforce spaces around equal signs in JSX attributes.
3 * @author ryym
4 */
5
6'use strict';
7
8const docsUrl = require('../util/docsUrl');
9
10// ------------------------------------------------------------------------------
11// Rule Definition
12// ------------------------------------------------------------------------------
13
14module.exports = {
15 meta: {
16 docs: {
17 description: 'Disallow or enforce spaces around equal signs in JSX attributes',
18 category: 'Stylistic Issues',
19 recommended: false,
20 url: docsUrl('jsx-equals-spacing')
21 },
22 fixable: 'code',
23
24 schema: [{
25 enum: ['always', 'never']
26 }]
27 },
28
29 create(context) {
30 const config = context.options[0];
31
32 /**
33 * Determines a given attribute node has an equal sign.
34 * @param {ASTNode} attrNode - The attribute node.
35 * @returns {boolean} Whether or not the attriute node has an equal sign.
36 */
37 function hasEqual(attrNode) {
38 return attrNode.type !== 'JSXSpreadAttribute' && attrNode.value !== null;
39 }
40
41 // --------------------------------------------------------------------------
42 // Public
43 // --------------------------------------------------------------------------
44
45 return {
46 JSXOpeningElement(node) {
47 node.attributes.forEach((attrNode) => {
48 if (!hasEqual(attrNode)) {
49 return;
50 }
51
52 const sourceCode = context.getSourceCode();
53 const equalToken = sourceCode.getTokenAfter(attrNode.name);
54 const spacedBefore = sourceCode.isSpaceBetweenTokens(attrNode.name, equalToken);
55 const spacedAfter = sourceCode.isSpaceBetweenTokens(equalToken, attrNode.value);
56
57 switch (config) {
58 default:
59 case 'never':
60 if (spacedBefore) {
61 context.report({
62 node: attrNode,
63 loc: equalToken.loc.start,
64 message: 'There should be no space before \'=\'',
65 fix(fixer) {
66 return fixer.removeRange([attrNode.name.range[1], equalToken.range[0]]);
67 }
68 });
69 }
70 if (spacedAfter) {
71 context.report({
72 node: attrNode,
73 loc: equalToken.loc.start,
74 message: 'There should be no space after \'=\'',
75 fix(fixer) {
76 return fixer.removeRange([equalToken.range[1], attrNode.value.range[0]]);
77 }
78 });
79 }
80 break;
81 case 'always':
82 if (!spacedBefore) {
83 context.report({
84 node: attrNode,
85 loc: equalToken.loc.start,
86 message: 'A space is required before \'=\'',
87 fix(fixer) {
88 return fixer.insertTextBefore(equalToken, ' ');
89 }
90 });
91 }
92 if (!spacedAfter) {
93 context.report({
94 node: attrNode,
95 loc: equalToken.loc.start,
96 message: 'A space is required after \'=\'',
97 fix(fixer) {
98 return fixer.insertTextAfter(equalToken, ' ');
99 }
100 });
101 }
102 break;
103 }
104 });
105 }
106 };
107 }
108};