jsx-indent.js 14 KB

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