Skip to content

Commit e83600b

Browse files
author
Kent C. Dodds
committed
[Fix] jsx-indent with tabs (fixes jsx-eslint#1057)
1 parent c97dd0f commit e83600b

File tree

2 files changed

+177
-86
lines changed

2 files changed

+177
-86
lines changed

lib/rules/jsx-indent.js

+127-60
Original file line numberDiff line numberDiff line change
@@ -73,18 +73,16 @@ module.exports = {
7373

7474
/**
7575
* Responsible for fixing the indentation issue fix
76-
* @param {ASTNode} node Node violating the indent rule
76+
* @param {Boolean} rangeToReplace is used to specify the range
77+
* to replace with the correct indentation.
7778
* @param {Number} needed Expected indentation character count
7879
* @returns {Function} function to be executed by the fixer
7980
* @private
8081
*/
81-
function getFixerFunction(node, needed) {
82+
function getFixerFunction(rangeToReplace, needed) {
8283
return function(fixer) {
8384
var indent = Array(needed + 1).join(indentChar);
84-
return fixer.replaceTextRange(
85-
[node.start - node.loc.start.column, node.start],
86-
indent
87-
);
85+
return fixer.replaceTextRange(rangeToReplace, indent);
8886
};
8987
}
9088

@@ -93,46 +91,36 @@ module.exports = {
9391
* @param {ASTNode} node Node violating the indent rule
9492
* @param {Number} needed Expected indentation character count
9593
* @param {Number} gotten Indentation character count in the actual node/code
96-
* @param {Object} loc Error line and column location
94+
* @param {Array} rangeToReplace is used in the fixer.
95+
* Defaults to the indent of the start of the node
96+
* @param {Object} loc Error line and column location (defaults to node.loc
9797
*/
98-
function report(node, needed, gotten, loc) {
98+
function report(node, needed, gotten, rangeToReplace, loc) {
9999
var msgContext = {
100100
needed: needed,
101101
type: indentType,
102102
characters: needed === 1 ? 'character' : 'characters',
103103
gotten: gotten
104104
};
105+
rangeToReplace = rangeToReplace || [node.start - node.loc.start.column, node.start];
105106

106-
if (loc) {
107-
context.report({
108-
node: node,
109-
loc: loc,
110-
message: MESSAGE,
111-
data: msgContext,
112-
fix: getFixerFunction(node, needed)
113-
});
114-
} else {
115-
context.report({
116-
node: node,
117-
message: MESSAGE,
118-
data: msgContext,
119-
fix: getFixerFunction(node, needed)
120-
});
121-
}
107+
context.report({
108+
node: node,
109+
loc: loc || node.loc,
110+
message: MESSAGE,
111+
data: msgContext,
112+
fix: getFixerFunction(rangeToReplace, needed)
113+
});
122114
}
123115

124116
/**
125-
* Get node indent
126-
* @param {ASTNode} node Node to examine
127-
* @param {Boolean} byLastLine get indent of node's last line
128-
* @param {Boolean} excludeCommas skip comma on start of line
129-
* @return {Number} Indent
117+
* Get the indentation (of the proper indentType) that exists in the source
118+
* @param {String} the source string
119+
* @param {Boolean} whether the line checked should be the last (defaults to the first line)
120+
* @param {Boolean} whether to skip commas in the check (defaults to false)
121+
* @return {Number} the indentation of the indentType that exists on the line
130122
*/
131-
function getNodeIndent(node, byLastLine, excludeCommas) {
132-
byLastLine = byLastLine || false;
133-
excludeCommas = excludeCommas || false;
134-
135-
var src = sourceCode.getText(node, node.loc.start.column + extraColumnStart);
123+
function getIndentFromString(src, byLastLine, excludeCommas) {
136124
var lines = src.split('\n');
137125
if (byLastLine) {
138126
src = lines[lines.length - 1];
@@ -154,7 +142,24 @@ module.exports = {
154142
}
155143

156144
/**
157-
* Checks node is the first in its own start line. By default it looks by start line.
145+
* Get node indent
146+
* @param {ASTNode} node Node to examine
147+
* @param {Boolean} byLastLine get indent of node's last line
148+
* @param {Boolean} excludeCommas skip comma on start of line
149+
* @return {Number} Indent
150+
*/
151+
function getNodeIndent(node, byLastLine, excludeCommas) {
152+
byLastLine = byLastLine || false;
153+
excludeCommas = excludeCommas || false;
154+
155+
var src = sourceCode.getText(node, node.loc.start.column + extraColumnStart);
156+
157+
return getIndentFromString(src, byLastLine, excludeCommas);
158+
}
159+
160+
/**
161+
* Checks if the node is the first in its own start line. By default it looks by start line.
162+
* One exception is closing tags with preceeding whitespace
158163
* @param {ASTNode} node The node to check
159164
* @return {Boolean} true if its the first in the its start line
160165
*/
@@ -165,8 +170,9 @@ module.exports = {
165170
} while (token.type === 'JSXText' && /^\s*$/.test(token.value));
166171
var startLine = node.loc.start.line;
167172
var endLine = token ? token.loc.end.line : -1;
173+
var whitespaceOnly = token ? /\n\s*$/.test(token.value) : false;
168174

169-
return startLine !== endLine;
175+
return startLine !== endLine || whitespaceOnly;
170176
}
171177

172178
/**
@@ -218,41 +224,74 @@ module.exports = {
218224
}
219225
}
220226

227+
/**
228+
* Checks the end of the tag (>) to determine whether it's on its own line
229+
* If so, it verifies the indentation is correct and reports if it is not
230+
* @param {[type]} node [description]
231+
* @param {[type]} startIndent [description]
232+
* @return {[type]} [description]
233+
*/
234+
function checkTagEndIndent(node, startIndent) {
235+
var source = sourceCode.getText(node);
236+
var isTagEndOnOwnLine = /\n\s*\/?>$/.exec(source);
237+
if (isTagEndOnOwnLine) {
238+
var endIndent = getIndentFromString(source, true, false);
239+
if (endIndent !== startIndent) {
240+
var rangeToReplace = [node.end - node.loc.end.column, node.end - 1];
241+
report(node, startIndent, endIndent, rangeToReplace);
242+
}
243+
}
244+
}
245+
246+
function getOpeningElementIndent(node) {
247+
var prevToken = sourceCode.getTokenBefore(node);
248+
if (!prevToken) {
249+
return 0;
250+
}
251+
// Use the parent in a list or an array
252+
if (prevToken.type === 'JSXText' || prevToken.type === 'Punctuator' && prevToken.value === ',') {
253+
prevToken = sourceCode.getNodeByRangeIndex(prevToken.start);
254+
prevToken = prevToken.type === 'Literal' ? prevToken.parent : prevToken;
255+
// Use the first non-punctuator token in a conditional expression
256+
} else if (prevToken.type === 'Punctuator' && prevToken.value === ':') {
257+
do {
258+
prevToken = sourceCode.getTokenBefore(prevToken);
259+
} while (prevToken.type === 'Punctuator');
260+
prevToken = sourceCode.getNodeByRangeIndex(prevToken.start);
261+
while (prevToken.parent && prevToken.parent.type !== 'ConditionalExpression') {
262+
prevToken = prevToken.parent;
263+
}
264+
}
265+
prevToken = prevToken.type === 'JSXExpressionContainer' ? prevToken.expression : prevToken;
266+
267+
var parentElementIndent = getNodeIndent(prevToken);
268+
if (prevToken.type === 'JSXElement') {
269+
parentElementIndent = getOpeningElementIndent(prevToken.openingElement);
270+
}
271+
272+
var indent = (
273+
prevToken.loc.start.line === node.loc.start.line ||
274+
isRightInLogicalExp(node) ||
275+
isAlternateInConditionalExp(node)
276+
) ? 0 : indentSize;
277+
return parentElementIndent + indent;
278+
}
279+
221280
return {
222281
JSXOpeningElement: function(node) {
223282
var prevToken = sourceCode.getTokenBefore(node);
224283
if (!prevToken) {
225284
return;
226285
}
227-
// Use the parent in a list or an array
228-
if (prevToken.type === 'JSXText' || prevToken.type === 'Punctuator' && prevToken.value === ',') {
229-
prevToken = sourceCode.getNodeByRangeIndex(prevToken.start);
230-
prevToken = prevToken.type === 'Literal' ? prevToken.parent : prevToken;
231-
// Use the first non-punctuator token in a conditional expression
232-
} else if (prevToken.type === 'Punctuator' && prevToken.value === ':') {
233-
do {
234-
prevToken = sourceCode.getTokenBefore(prevToken);
235-
} while (prevToken.type === 'Punctuator');
236-
prevToken = sourceCode.getNodeByRangeIndex(prevToken.start);
237-
while (prevToken.parent && prevToken.parent.type !== 'ConditionalExpression') {
238-
prevToken = prevToken.parent;
239-
}
240-
}
241-
prevToken = prevToken.type === 'JSXExpressionContainer' ? prevToken.expression : prevToken;
242-
243-
var parentElementIndent = getNodeIndent(prevToken);
244-
var indent = (
245-
prevToken.loc.start.line === node.loc.start.line ||
246-
isRightInLogicalExp(node) ||
247-
isAlternateInConditionalExp(node)
248-
) ? 0 : indentSize;
249-
checkNodesIndent(node, parentElementIndent + indent);
286+
var startIndent = getOpeningElementIndent(node);
287+
checkNodesIndent(node, startIndent);
288+
checkTagEndIndent(node, startIndent);
250289
},
251290
JSXClosingElement: function(node) {
252291
if (!node.parent) {
253292
return;
254293
}
255-
var peerElementIndent = getNodeIndent(node.parent.openingElement);
294+
var peerElementIndent = getOpeningElementIndent(node.parent.openingElement);
256295
checkNodesIndent(node, peerElementIndent);
257296
},
258297
JSXExpressionContainer: function(node) {
@@ -261,6 +300,34 @@ module.exports = {
261300
}
262301
var parentNodeIndent = getNodeIndent(node.parent);
263302
checkNodesIndent(node, parentNodeIndent + indentSize);
303+
},
304+
Literal: function(node) {
305+
if (!node.parent || (node.parent.type !== 'JSXElement' && node.parent.type !== 'JSXExpressionContainer')) {
306+
return;
307+
}
308+
var parentElementIndent = getOpeningElementIndent(node.parent.openingElement);
309+
var expectedIndent = parentElementIndent + indentSize;
310+
var source = sourceCode.getText(node);
311+
var lines = source.split('\n');
312+
var currentIndex = 0;
313+
lines.forEach(function(line, lineNumber) {
314+
if (line.trim()) {
315+
var lineIndent = getIndentFromString(line);
316+
if (lineIndent !== expectedIndent) {
317+
var lineStart = source.indexOf(line, currentIndex);
318+
var lineIndentStart = line.search(/\S/);
319+
var lineIndentEnd = lineStart + lineIndentStart;
320+
var rangeToReplace = [node.start + lineStart, node.start + lineIndentEnd];
321+
var locLine = lineNumber + node.loc.start.line;
322+
var loc = {
323+
start: {line: locLine, column: lineIndentStart},
324+
end: {line: locLine, column: lineIndentEnd}
325+
};
326+
report(node, expectedIndent, lineIndent, rangeToReplace, loc);
327+
}
328+
}
329+
currentIndex += line.length;
330+
});
264331
}
265332
};
266333

tests/lib/rules/jsx-indent.js

+50-26
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,16 @@ ruleTester.run('jsx-indent', rule, {
5151
].join('\n'),
5252
options: [0],
5353
parserOptions: parserOptions
54-
}, {
55-
code: [
56-
' <App>',
57-
'<Foo />',
58-
' </App>'
59-
].join('\n'),
60-
options: [-2],
61-
parserOptions: parserOptions
54+
// }, {
55+
// should we put effort in making this work?
56+
// who in their right mind would do this?
57+
// code: [
58+
// ' <App>',
59+
// '<Foo />',
60+
// ' </App>'
61+
// ].join('\n'),
62+
// options: [-2],
63+
// parserOptions: parserOptions
6264
}, {
6365
code: [
6466
'<App>',
@@ -211,17 +213,6 @@ ruleTester.run('jsx-indent', rule, {
211213
'</div>'
212214
].join('\n'),
213215
parserOptions: parserOptions
214-
}, {
215-
// Literals indentation is not touched
216-
code: [
217-
'<div>',
218-
'bar <div>',
219-
' bar',
220-
' bar {foo}',
221-
'bar </div>',
222-
'</div>'
223-
].join('\n'),
224-
parserOptions: parserOptions
225216
}, {
226217
// Multiline ternary
227218
// (colon at the end of the first expression)
@@ -459,6 +450,39 @@ ruleTester.run('jsx-indent', rule, {
459450
options: ['tab'],
460451
parserOptions: parserOptions,
461452
errors: [{message: 'Expected indentation of 1 tab character but found 0.'}]
453+
}, {
454+
code: [
455+
'function MyComponent(props) {',
456+
'\treturn (',
457+
' <div',
458+
'\t\t\tclassName="foo-bar"',
459+
'\t\t\tid="thing"',
460+
' >',
461+
' Hello world!',
462+
' </div>',
463+
'\t)',
464+
'}'
465+
].join('\n'),
466+
output: [
467+
'function MyComponent(props) {',
468+
'\treturn (',
469+
'\t\t<div',
470+
'\t\t\tclassName="foo-bar"',
471+
'\t\t\tid="thing"',
472+
'\t\t>',
473+
'\t\t\tHello world!',
474+
'\t\t</div>',
475+
'\t)',
476+
'}'
477+
].join('\n'),
478+
options: ['tab'],
479+
parserOptions: parserOptions,
480+
errors: [
481+
{message: 'Expected indentation of 2 tab characters but found 0.'},
482+
{message: 'Expected indentation of 2 tab characters but found 0.'},
483+
{message: 'Expected indentation of 3 tab characters but found 0.'},
484+
{message: 'Expected indentation of 2 tab characters but found 0.'}
485+
]
462486
}, {
463487
code: [
464488
'function App() {',
@@ -505,22 +529,22 @@ ruleTester.run('jsx-indent', rule, {
505529
' );',
506530
'}'
507531
].join('\n'),
508-
// The detection logic only thinks <App> is indented wrong, not the other
509-
// two lines following. I *think* because it incorrectly uses <App>'s indention
510-
// as the baseline for the next two, instead of the realizing the entire three
511-
// lines are wrong together. See #608
512-
/* output: [
532+
output: [
513533
'function App() {',
514534
' return (',
515535
' <App>',
516536
' <Foo />',
517537
' </App>',
518538
' );',
519539
'}'
520-
].join('\n'), */
540+
].join('\n'),
521541
options: [2],
522542
parserOptions: parserOptions,
523-
errors: [{message: 'Expected indentation of 4 space characters but found 0.'}]
543+
errors: [
544+
{message: 'Expected indentation of 4 space characters but found 0.'},
545+
{message: 'Expected indentation of 6 space characters but found 2.'},
546+
{message: 'Expected indentation of 4 space characters but found 0.'}
547+
]
524548
}, {
525549
code: [
526550
'<App>',

0 commit comments

Comments
 (0)