jsx-indent.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 matchAll = require('string.prototype.matchall');
  28. const astUtil = require('../util/ast');
  29. const docsUrl = require('../util/docsUrl');
  30. // ------------------------------------------------------------------------------
  31. // Rule Definition
  32. // ------------------------------------------------------------------------------
  33. module.exports = {
  34. meta: {
  35. docs: {
  36. description: 'Validate JSX indentation',
  37. category: 'Stylistic Issues',
  38. recommended: false,
  39. url: docsUrl('jsx-indent')
  40. },
  41. fixable: 'whitespace',
  42. messages: {
  43. wrongIndent: 'Expected indentation of {{needed}} {{type}} {{characters}} but found {{gotten}}.'
  44. },
  45. schema: [{
  46. oneOf: [{
  47. enum: ['tab']
  48. }, {
  49. type: 'integer'
  50. }]
  51. }, {
  52. type: 'object',
  53. properties: {
  54. checkAttributes: {
  55. type: 'boolean'
  56. },
  57. indentLogicalExpressions: {
  58. type: 'boolean'
  59. }
  60. },
  61. additionalProperties: false
  62. }]
  63. },
  64. create(context) {
  65. const extraColumnStart = 0;
  66. let indentType = 'space';
  67. let indentSize = 4;
  68. if (context.options.length) {
  69. if (context.options[0] === 'tab') {
  70. indentSize = 1;
  71. indentType = 'tab';
  72. } else if (typeof context.options[0] === 'number') {
  73. indentSize = context.options[0];
  74. indentType = 'space';
  75. }
  76. }
  77. const indentChar = indentType === 'space' ? ' ' : '\t';
  78. const options = context.options[1] || {};
  79. const checkAttributes = options.checkAttributes || false;
  80. const indentLogicalExpressions = options.indentLogicalExpressions || false;
  81. /**
  82. * Responsible for fixing the indentation issue fix
  83. * @param {ASTNode} node Node violating the indent rule
  84. * @param {Number} needed Expected indentation character count
  85. * @returns {Function} function to be executed by the fixer
  86. * @private
  87. */
  88. function getFixerFunction(node, needed) {
  89. return function fix(fixer) {
  90. const indent = Array(needed + 1).join(indentChar);
  91. if (node.type === 'JSXText' || node.type === 'Literal') {
  92. const regExp = /\n[\t ]*(\S)/g;
  93. const fixedText = node.raw.replace(regExp, (match, p1) => `\n${indent}${p1}`);
  94. return fixer.replaceText(node, fixedText);
  95. }
  96. return fixer.replaceTextRange(
  97. [node.range[0] - node.loc.start.column, node.range[0]],
  98. indent
  99. );
  100. };
  101. }
  102. /**
  103. * Reports a given indent violation and properly pluralizes the message
  104. * @param {ASTNode} node Node violating the indent rule
  105. * @param {Number} needed Expected indentation character count
  106. * @param {Number} gotten Indentation character count in the actual node/code
  107. * @param {Object} [loc] Error line and column location
  108. */
  109. function report(node, needed, gotten, loc) {
  110. const msgContext = {
  111. needed,
  112. type: indentType,
  113. characters: needed === 1 ? 'character' : 'characters',
  114. gotten
  115. };
  116. context.report(Object.assign({
  117. node,
  118. messageId: 'wrongIndent',
  119. data: msgContext,
  120. fix: getFixerFunction(node, needed)
  121. }, loc && {loc}));
  122. }
  123. /**
  124. * Get node indent
  125. * @param {ASTNode} node Node to examine
  126. * @param {Boolean} [byLastLine] get indent of node's last line
  127. * @param {Boolean} [excludeCommas] skip comma on start of line
  128. * @return {Number} Indent
  129. */
  130. function getNodeIndent(node, byLastLine, excludeCommas) {
  131. byLastLine = byLastLine || false;
  132. excludeCommas = excludeCommas || false;
  133. let src = context.getSourceCode().getText(node, node.loc.start.column + extraColumnStart);
  134. const lines = src.split('\n');
  135. if (byLastLine) {
  136. src = lines[lines.length - 1];
  137. } else {
  138. src = lines[0];
  139. }
  140. const skip = excludeCommas ? ',' : '';
  141. let regExp;
  142. if (indentType === 'space') {
  143. regExp = new RegExp(`^[ ${skip}]+`);
  144. } else {
  145. regExp = new RegExp(`^[\t${skip}]+`);
  146. }
  147. const indent = regExp.exec(src);
  148. return indent ? indent[0].length : 0;
  149. }
  150. /**
  151. * Check if the node is the right member of a logical expression
  152. * @param {ASTNode} node The node to check
  153. * @return {Boolean} true if its the case, false if not
  154. */
  155. function isRightInLogicalExp(node) {
  156. return (
  157. node.parent
  158. && node.parent.parent
  159. && node.parent.parent.type === 'LogicalExpression'
  160. && node.parent.parent.right === node.parent
  161. && !indentLogicalExpressions
  162. );
  163. }
  164. /**
  165. * Check if the node is the alternate member of a conditional expression
  166. * @param {ASTNode} node The node to check
  167. * @return {Boolean} true if its the case, false if not
  168. */
  169. function isAlternateInConditionalExp(node) {
  170. return (
  171. node.parent
  172. && node.parent.parent
  173. && node.parent.parent.type === 'ConditionalExpression'
  174. && node.parent.parent.alternate === node.parent
  175. && context.getSourceCode().getTokenBefore(node).value !== '('
  176. );
  177. }
  178. /**
  179. * Check if the node is within a DoExpression block but not the first expression (which need to be indented)
  180. * @param {ASTNode} node The node to check
  181. * @return {Boolean} true if its the case, false if not
  182. */
  183. function isSecondOrSubsequentExpWithinDoExp(node) {
  184. /*
  185. It returns true when node.parent.parent.parent.parent matches:
  186. DoExpression({
  187. ...,
  188. body: BlockStatement({
  189. ...,
  190. body: [
  191. ..., // 1-n times
  192. ExpressionStatement({
  193. ...,
  194. expression: JSXElement({
  195. ...,
  196. openingElement: JSXOpeningElement() // the node
  197. })
  198. }),
  199. ... // 0-n times
  200. ]
  201. })
  202. })
  203. except:
  204. DoExpression({
  205. ...,
  206. body: BlockStatement({
  207. ...,
  208. body: [
  209. ExpressionStatement({
  210. ...,
  211. expression: JSXElement({
  212. ...,
  213. openingElement: JSXOpeningElement() // the node
  214. })
  215. }),
  216. ... // 0-n times
  217. ]
  218. })
  219. })
  220. */
  221. const isInExpStmt = (
  222. node.parent
  223. && node.parent.parent
  224. && node.parent.parent.type === 'ExpressionStatement'
  225. );
  226. if (!isInExpStmt) {
  227. return false;
  228. }
  229. const expStmt = node.parent.parent;
  230. const isInBlockStmtWithinDoExp = (
  231. expStmt.parent
  232. && expStmt.parent.type === 'BlockStatement'
  233. && expStmt.parent.parent
  234. && expStmt.parent.parent.type === 'DoExpression'
  235. );
  236. if (!isInBlockStmtWithinDoExp) {
  237. return false;
  238. }
  239. const blockStmt = expStmt.parent;
  240. const blockStmtFirstExp = blockStmt.body[0];
  241. return !(blockStmtFirstExp === expStmt);
  242. }
  243. /**
  244. * Check indent for nodes list
  245. * @param {ASTNode} node The node to check
  246. * @param {Number} indent needed indent
  247. * @param {Boolean} [excludeCommas] skip comma on start of line
  248. */
  249. function checkNodesIndent(node, indent, excludeCommas) {
  250. const nodeIndent = getNodeIndent(node, false, excludeCommas);
  251. const isCorrectRightInLogicalExp = isRightInLogicalExp(node) && (nodeIndent - indent) === indentSize;
  252. const isCorrectAlternateInCondExp = isAlternateInConditionalExp(node) && (nodeIndent - indent) === 0;
  253. if (
  254. nodeIndent !== indent
  255. && astUtil.isNodeFirstInLine(context, node)
  256. && !isCorrectRightInLogicalExp
  257. && !isCorrectAlternateInCondExp
  258. ) {
  259. report(node, indent, nodeIndent);
  260. }
  261. }
  262. /**
  263. * Check indent for Literal Node or JSXText Node
  264. * @param {ASTNode} node The node to check
  265. * @param {Number} indent needed indent
  266. */
  267. function checkLiteralNodeIndent(node, indent) {
  268. const value = node.value;
  269. const regExp = indentType === 'space' ? /\n( *)[\t ]*\S/g : /\n(\t*)[\t ]*\S/g;
  270. const nodeIndentsPerLine = Array.from(
  271. matchAll(String(value), regExp),
  272. (match) => (match[1] ? match[1].length : 0)
  273. );
  274. const hasFirstInLineNode = nodeIndentsPerLine.length > 0;
  275. if (
  276. hasFirstInLineNode
  277. && !nodeIndentsPerLine.every((actualIndent) => actualIndent === indent)
  278. ) {
  279. nodeIndentsPerLine.forEach((nodeIndent) => {
  280. report(node, indent, nodeIndent);
  281. });
  282. }
  283. }
  284. function handleOpeningElement(node) {
  285. const sourceCode = context.getSourceCode();
  286. let prevToken = sourceCode.getTokenBefore(node);
  287. if (!prevToken) {
  288. return;
  289. }
  290. // Use the parent in a list or an array
  291. if (prevToken.type === 'JSXText' || ((prevToken.type === 'Punctuator') && prevToken.value === ',')) {
  292. prevToken = sourceCode.getNodeByRangeIndex(prevToken.range[0]);
  293. prevToken = prevToken.type === 'Literal' || prevToken.type === 'JSXText' ? prevToken.parent : prevToken;
  294. // Use the first non-punctuator token in a conditional expression
  295. } else if (prevToken.type === 'Punctuator' && prevToken.value === ':') {
  296. do {
  297. prevToken = sourceCode.getTokenBefore(prevToken);
  298. } while (prevToken.type === 'Punctuator' && prevToken.value !== '/');
  299. prevToken = sourceCode.getNodeByRangeIndex(prevToken.range[0]);
  300. while (prevToken.parent && prevToken.parent.type !== 'ConditionalExpression') {
  301. prevToken = prevToken.parent;
  302. }
  303. }
  304. prevToken = prevToken.type === 'JSXExpressionContainer' ? prevToken.expression : prevToken;
  305. const parentElementIndent = getNodeIndent(prevToken);
  306. const indent = (
  307. prevToken.loc.start.line === node.loc.start.line
  308. || isRightInLogicalExp(node)
  309. || isAlternateInConditionalExp(node)
  310. || isSecondOrSubsequentExpWithinDoExp(node)
  311. ) ? 0 : indentSize;
  312. checkNodesIndent(node, parentElementIndent + indent);
  313. }
  314. function handleClosingElement(node) {
  315. if (!node.parent) {
  316. return;
  317. }
  318. const peerElementIndent = getNodeIndent(node.parent.openingElement || node.parent.openingFragment);
  319. checkNodesIndent(node, peerElementIndent);
  320. }
  321. function handleAttribute(node) {
  322. if (!checkAttributes || (!node.value || node.value.type !== 'JSXExpressionContainer')) {
  323. return;
  324. }
  325. const nameIndent = getNodeIndent(node.name);
  326. const lastToken = context.getSourceCode().getLastToken(node.value);
  327. const firstInLine = astUtil.getFirstNodeInLine(context, lastToken);
  328. const indent = node.name.loc.start.line === firstInLine.loc.start.line ? 0 : nameIndent;
  329. checkNodesIndent(firstInLine, indent);
  330. }
  331. function handleLiteral(node) {
  332. if (!node.parent) {
  333. return;
  334. }
  335. if (node.parent.type !== 'JSXElement' && node.parent.type !== 'JSXFragment') {
  336. return;
  337. }
  338. const parentNodeIndent = getNodeIndent(node.parent);
  339. checkLiteralNodeIndent(node, parentNodeIndent + indentSize);
  340. }
  341. return {
  342. JSXOpeningElement: handleOpeningElement,
  343. JSXOpeningFragment: handleOpeningElement,
  344. JSXClosingElement: handleClosingElement,
  345. JSXClosingFragment: handleClosingElement,
  346. JSXAttribute: handleAttribute,
  347. JSXExpressionContainer(node) {
  348. if (!node.parent) {
  349. return;
  350. }
  351. const parentNodeIndent = getNodeIndent(node.parent);
  352. checkNodesIndent(node, parentNodeIndent + indentSize);
  353. },
  354. Literal: handleLiteral,
  355. JSXText: handleLiteral
  356. };
  357. }
  358. };