jsx-indent.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /**
  2. * @fileoverview Validate JSX indentation
  3. * @author Yannick Croissant
  4. * This rule has been ported and modified from eslint and nodeca.
  5. * @author Vitaly Puzrin
  6. * @author Gyandeep Singh
  7. * @copyright 2015 Vitaly Puzrin. All rights reserved.
  8. * @copyright 2015 Gyandeep Singh. All rights reserved.
  9. Copyright (C) 2014 by Vitaly Puzrin
  10. Permission is hereby granted, free of charge, to any person obtaining a copy
  11. of this software and associated documentation files (the 'Software'), to deal
  12. in the Software without restriction, including without limitation the rights
  13. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. copies of the Software, and to permit persons to whom the Software is
  15. furnished to do so, subject to the following conditions:
  16. The above copyright notice and this permission notice shall be included in
  17. all copies or substantial portions of the Software.
  18. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. THE SOFTWARE.
  25. */
  26. 'use strict';
  27. const astUtil = require('../util/ast');
  28. const docsUrl = require('../util/docsUrl');
  29. // ------------------------------------------------------------------------------
  30. // Rule Definition
  31. // ------------------------------------------------------------------------------
  32. module.exports = {
  33. meta: {
  34. docs: {
  35. description: 'Validate JSX indentation',
  36. category: 'Stylistic Issues',
  37. recommended: false,
  38. url: docsUrl('jsx-indent')
  39. },
  40. fixable: 'whitespace',
  41. schema: [{
  42. oneOf: [{
  43. enum: ['tab']
  44. }, {
  45. type: 'integer'
  46. }]
  47. }]
  48. },
  49. create: function(context) {
  50. const MESSAGE = 'Expected indentation of {{needed}} {{type}} {{characters}} but found {{gotten}}.';
  51. const extraColumnStart = 0;
  52. let indentType = 'space';
  53. let indentSize = 4;
  54. const sourceCode = context.getSourceCode();
  55. if (context.options.length) {
  56. if (context.options[0] === 'tab') {
  57. indentSize = 1;
  58. indentType = 'tab';
  59. } else if (typeof context.options[0] === 'number') {
  60. indentSize = context.options[0];
  61. indentType = 'space';
  62. }
  63. }
  64. const indentChar = indentType === 'space' ? ' ' : '\t';
  65. /**
  66. * Responsible for fixing the indentation issue fix
  67. * @param {ASTNode} node Node violating the indent rule
  68. * @param {Number} needed Expected indentation character count
  69. * @returns {Function} function to be executed by the fixer
  70. * @private
  71. */
  72. function getFixerFunction(node, needed) {
  73. return function(fixer) {
  74. const indent = Array(needed + 1).join(indentChar);
  75. return fixer.replaceTextRange(
  76. [node.range[0] - node.loc.start.column, node.range[0]],
  77. indent
  78. );
  79. };
  80. }
  81. /**
  82. * Reports a given indent violation and properly pluralizes the message
  83. * @param {ASTNode} node Node violating the indent rule
  84. * @param {Number} needed Expected indentation character count
  85. * @param {Number} gotten Indentation character count in the actual node/code
  86. * @param {Object} loc Error line and column location
  87. */
  88. function report(node, needed, gotten, loc) {
  89. const msgContext = {
  90. needed: needed,
  91. type: indentType,
  92. characters: needed === 1 ? 'character' : 'characters',
  93. gotten: gotten
  94. };
  95. if (loc) {
  96. context.report({
  97. node: node,
  98. loc: loc,
  99. message: MESSAGE,
  100. data: msgContext,
  101. fix: getFixerFunction(node, needed)
  102. });
  103. } else {
  104. context.report({
  105. node: node,
  106. message: MESSAGE,
  107. data: msgContext,
  108. fix: getFixerFunction(node, needed)
  109. });
  110. }
  111. }
  112. /**
  113. * Get node indent
  114. * @param {ASTNode} node Node to examine
  115. * @param {Boolean} byLastLine get indent of node's last line
  116. * @param {Boolean} excludeCommas skip comma on start of line
  117. * @return {Number} Indent
  118. */
  119. function getNodeIndent(node, byLastLine, excludeCommas) {
  120. byLastLine = byLastLine || false;
  121. excludeCommas = excludeCommas || false;
  122. let src = sourceCode.getText(node, node.loc.start.column + extraColumnStart);
  123. const lines = src.split('\n');
  124. if (byLastLine) {
  125. src = lines[lines.length - 1];
  126. } else {
  127. src = lines[0];
  128. }
  129. const skip = excludeCommas ? ',' : '';
  130. let regExp;
  131. if (indentType === 'space') {
  132. regExp = new RegExp(`^[ ${skip}]+`);
  133. } else {
  134. regExp = new RegExp(`^[\t${skip}]+`);
  135. }
  136. const indent = regExp.exec(src);
  137. return indent ? indent[0].length : 0;
  138. }
  139. /**
  140. * Check if the node is the right member of a logical expression
  141. * @param {ASTNode} node The node to check
  142. * @return {Boolean} true if its the case, false if not
  143. */
  144. function isRightInLogicalExp(node) {
  145. return (
  146. node.parent &&
  147. node.parent.parent &&
  148. node.parent.parent.type === 'LogicalExpression' &&
  149. node.parent.parent.right === node.parent
  150. );
  151. }
  152. /**
  153. * Check if the node is the alternate member of a conditional expression
  154. * @param {ASTNode} node The node to check
  155. * @return {Boolean} true if its the case, false if not
  156. */
  157. function isAlternateInConditionalExp(node) {
  158. return (
  159. node.parent &&
  160. node.parent.parent &&
  161. node.parent.parent.type === 'ConditionalExpression' &&
  162. node.parent.parent.alternate === node.parent &&
  163. sourceCode.getTokenBefore(node).value !== '('
  164. );
  165. }
  166. /**
  167. * Check indent for nodes list
  168. * @param {ASTNode} node The node to check
  169. * @param {Number} indent needed indent
  170. * @param {Boolean} excludeCommas skip comma on start of line
  171. */
  172. function checkNodesIndent(node, indent, excludeCommas) {
  173. const nodeIndent = getNodeIndent(node, false, excludeCommas);
  174. const isCorrectRightInLogicalExp = isRightInLogicalExp(node) && (nodeIndent - indent) === indentSize;
  175. const isCorrectAlternateInCondExp = isAlternateInConditionalExp(node) && (nodeIndent - indent) === 0;
  176. if (
  177. nodeIndent !== indent &&
  178. astUtil.isNodeFirstInLine(context, node) &&
  179. !isCorrectRightInLogicalExp &&
  180. !isCorrectAlternateInCondExp
  181. ) {
  182. report(node, indent, nodeIndent);
  183. }
  184. }
  185. return {
  186. JSXOpeningElement: function(node) {
  187. let prevToken = sourceCode.getTokenBefore(node);
  188. if (!prevToken) {
  189. return;
  190. }
  191. // Use the parent in a list or an array
  192. if (prevToken.type === 'JSXText' || prevToken.type === 'Punctuator' && prevToken.value === ',') {
  193. prevToken = sourceCode.getNodeByRangeIndex(prevToken.range[0]);
  194. prevToken = prevToken.type === 'Literal' || prevToken.type === 'JSXText' ? prevToken.parent : prevToken;
  195. // Use the first non-punctuator token in a conditional expression
  196. } else if (prevToken.type === 'Punctuator' && prevToken.value === ':') {
  197. do {
  198. prevToken = sourceCode.getTokenBefore(prevToken);
  199. } while (prevToken.type === 'Punctuator');
  200. prevToken = sourceCode.getNodeByRangeIndex(prevToken.range[0]);
  201. while (prevToken.parent && prevToken.parent.type !== 'ConditionalExpression') {
  202. prevToken = prevToken.parent;
  203. }
  204. }
  205. prevToken = prevToken.type === 'JSXExpressionContainer' ? prevToken.expression : prevToken;
  206. const parentElementIndent = getNodeIndent(prevToken);
  207. const indent = (
  208. prevToken.loc.start.line === node.loc.start.line ||
  209. isRightInLogicalExp(node) ||
  210. isAlternateInConditionalExp(node)
  211. ) ? 0 : indentSize;
  212. checkNodesIndent(node, parentElementIndent + indent);
  213. },
  214. JSXClosingElement: function(node) {
  215. if (!node.parent) {
  216. return;
  217. }
  218. const peerElementIndent = getNodeIndent(node.parent.openingElement);
  219. checkNodesIndent(node, peerElementIndent);
  220. },
  221. JSXExpressionContainer: function(node) {
  222. if (!node.parent) {
  223. return;
  224. }
  225. const parentNodeIndent = getNodeIndent(node.parent);
  226. checkNodesIndent(node, parentNodeIndent + indentSize);
  227. }
  228. };
  229. }
  230. };