jsx-indent.js 14 KB

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