Skip to content

Commit

Permalink
Add function to add indents in newline
Browse files Browse the repository at this point in the history
Utilised getNodeIndent helper from jsx-indent-props as base-code
  • Loading branch information
snowypowers committed Nov 2, 2016
1 parent e441aae commit 9182124
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion lib/rules/jsx-first-prop-new-line.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,50 @@ module.exports = {
schema: [{
enum: ['always', 'never', 'multiline', 'multiline-multiprop']
}]

},

create: function (context) {
var configuration = context.options[0];
var extraColumnStart = 0;
var indentType = 'space';
var indentSize = 2;
var sourceCode = context.getSourceCode();

if (context.options.length > 1) {
if (context.options[1] === 'tab') {
indentSize = 1;
indentType = 'tab';
} else if (typeof context.options[1] === 'number') {
indentSize = context.options[1];
indentType = 'space';
}
}

function getNodeIndent(node, byLastLine, excludeCommas) {
byLastLine = byLastLine || false;
excludeCommas = excludeCommas || false;

var src = sourceCode.getText(node, node.loc.start.column + extraColumnStart);
var lines = src.split('\n');
if (byLastLine) {
src = lines[lines.length - 1];
} else {
src = lines[0];
}

var skip = excludeCommas ? ',' : '';

var regExp;
if (indentType === 'space') {
regExp = new RegExp('^[ ' + skip + ']+');
} else {
regExp = new RegExp('^[\t' + skip + ']+');
}

var indent = regExp.exec(src);
return indent ? indent[0].length : 0;
}

function isMultilineJSX(jsxNode) {
return jsxNode.loc.start.line < jsxNode.loc.end.line;
Expand All @@ -42,7 +82,10 @@ module.exports = {
node: decl,
message: 'Property should be placed on a new line',
fix: function(fixer) {
return fixer.insertTextAfter(node.name, '\n');
var nodeIndent = getNodeIndent(node, false, false);
var neededIndent = nodeIndent + indentSize;
var insert = '\n' + Array(neededIndent + 1).join(indentType === 'space' ? ' ' : '\t');
return fixer.replaceTextRange([node.name.end, decl.start], insert);
}
});
}
Expand Down

0 comments on commit 9182124

Please sign in to comment.