jsx-indent-props.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /**
  2. * @fileoverview Validate props indentation in JSX
  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. const reportC = require('../util/report');
  30. // ------------------------------------------------------------------------------
  31. // Rule Definition
  32. // ------------------------------------------------------------------------------
  33. const messages = {
  34. wrongIndent: 'Expected indentation of {{needed}} {{type}} {{characters}} but found {{gotten}}.',
  35. };
  36. module.exports = {
  37. meta: {
  38. docs: {
  39. description: 'Enforce props indentation in JSX',
  40. category: 'Stylistic Issues',
  41. recommended: false,
  42. url: docsUrl('jsx-indent-props'),
  43. },
  44. fixable: 'code',
  45. messages,
  46. schema: [{
  47. anyOf: [{
  48. enum: ['tab', 'first'],
  49. }, {
  50. type: 'integer',
  51. }, {
  52. type: 'object',
  53. properties: {
  54. indentMode: {
  55. anyOf: [{
  56. enum: ['tab', 'first'],
  57. }, {
  58. type: 'integer',
  59. }],
  60. },
  61. ignoreTernaryOperator: {
  62. type: 'boolean',
  63. },
  64. },
  65. }],
  66. }],
  67. },
  68. create(context) {
  69. const extraColumnStart = 0;
  70. let indentType = 'space';
  71. /** @type {number|'first'} */
  72. let indentSize = 4;
  73. const line = {
  74. isUsingOperator: false,
  75. currentOperator: false,
  76. };
  77. let ignoreTernaryOperator = false;
  78. if (context.options.length) {
  79. const isConfigObject = typeof context.options[0] === 'object';
  80. const indentMode = isConfigObject
  81. ? context.options[0].indentMode
  82. : context.options[0];
  83. if (indentMode === 'first') {
  84. indentSize = 'first';
  85. indentType = 'space';
  86. } else if (indentMode === 'tab') {
  87. indentSize = 1;
  88. indentType = 'tab';
  89. } else if (typeof indentMode === 'number') {
  90. indentSize = indentMode;
  91. indentType = 'space';
  92. }
  93. if (isConfigObject && context.options[0].ignoreTernaryOperator) {
  94. ignoreTernaryOperator = true;
  95. }
  96. }
  97. /**
  98. * Reports a given indent violation and properly pluralizes the message
  99. * @param {ASTNode} node Node violating the indent rule
  100. * @param {Number} needed Expected indentation character count
  101. * @param {Number} gotten Indentation character count in the actual node/code
  102. */
  103. function report(node, needed, gotten) {
  104. const msgContext = {
  105. needed,
  106. type: indentType,
  107. characters: needed === 1 ? 'character' : 'characters',
  108. gotten,
  109. };
  110. reportC(context, messages.wrongIndent, 'wrongIndent', {
  111. node,
  112. data: msgContext,
  113. fix(fixer) {
  114. return fixer.replaceTextRange([node.range[0] - node.loc.start.column, node.range[0]],
  115. Array(needed + 1).join(indentType === 'space' ? ' ' : '\t'));
  116. },
  117. });
  118. }
  119. /**
  120. * Get node indent
  121. * @param {ASTNode} node Node to examine
  122. * @return {Number} Indent
  123. */
  124. function getNodeIndent(node) {
  125. let src = context.getSourceCode().getText(node, node.loc.start.column + extraColumnStart);
  126. const lines = src.split('\n');
  127. src = lines[0];
  128. let regExp;
  129. if (indentType === 'space') {
  130. regExp = /^[ ]+/;
  131. } else {
  132. regExp = /^[\t]+/;
  133. }
  134. const indent = regExp.exec(src);
  135. const useOperator = /^([ ]|[\t])*[:]/.test(src) || /^([ ]|[\t])*[?]/.test(src);
  136. const useBracket = /[<]/.test(src);
  137. line.currentOperator = false;
  138. if (useOperator) {
  139. line.isUsingOperator = true;
  140. line.currentOperator = true;
  141. } else if (useBracket) {
  142. line.isUsingOperator = false;
  143. }
  144. return indent ? indent[0].length : 0;
  145. }
  146. /**
  147. * Check indent for nodes list
  148. * @param {ASTNode[]} nodes list of node objects
  149. * @param {Number} indent needed indent
  150. */
  151. function checkNodesIndent(nodes, indent) {
  152. let nestedIndent = indent;
  153. nodes.forEach((node) => {
  154. const nodeIndent = getNodeIndent(node);
  155. if (
  156. line.isUsingOperator
  157. && !line.currentOperator
  158. && indentSize !== 'first'
  159. && !ignoreTernaryOperator
  160. ) {
  161. nestedIndent += indentSize;
  162. line.isUsingOperator = false;
  163. }
  164. if (
  165. node.type !== 'ArrayExpression' && node.type !== 'ObjectExpression'
  166. && nodeIndent !== nestedIndent && astUtil.isNodeFirstInLine(context, node)
  167. ) {
  168. report(node, nestedIndent, nodeIndent);
  169. }
  170. });
  171. }
  172. return {
  173. JSXOpeningElement(node) {
  174. if (!node.attributes.length) {
  175. return;
  176. }
  177. let propIndent;
  178. if (indentSize === 'first') {
  179. const firstPropNode = node.attributes[0];
  180. propIndent = firstPropNode.loc.start.column;
  181. } else {
  182. const elementIndent = getNodeIndent(node);
  183. propIndent = elementIndent + indentSize;
  184. }
  185. checkNodesIndent(node.attributes, propIndent);
  186. },
  187. };
  188. },
  189. };