jsx-curly-spacing.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /**
  2. * @fileoverview Enforce or disallow spaces inside of curly braces in JSX attributes.
  3. * @author Jamund Ferguson
  4. * @author Brandyn Bennett
  5. * @author Michael Ficarra
  6. * @author Vignesh Anand
  7. * @author Jamund Ferguson
  8. * @author Yannick Croissant
  9. * @author Erik Wendel
  10. */
  11. 'use strict';
  12. const has = require('has');
  13. const docsUrl = require('../util/docsUrl');
  14. // ------------------------------------------------------------------------------
  15. // Rule Definition
  16. // ------------------------------------------------------------------------------
  17. const SPACING = {
  18. always: 'always',
  19. never: 'never'
  20. };
  21. const SPACING_VALUES = [SPACING.always, SPACING.never];
  22. module.exports = {
  23. meta: {
  24. docs: {
  25. description: 'Enforce or disallow spaces inside of curly braces in JSX attributes',
  26. category: 'Stylistic Issues',
  27. recommended: false,
  28. url: docsUrl('jsx-curly-spacing')
  29. },
  30. fixable: 'code',
  31. messages: {
  32. noNewlineAfter: 'There should be no newline after \'{{token}}\'',
  33. noNewlineBefore: 'There should be no newline before \'{{token}}\'',
  34. noSpaceAfter: 'There should be no space after \'{{token}}\'',
  35. noSpaceBefore: 'There should be no space before \'{{token}}\'',
  36. spaceNeededAfter: 'A space is required after \'{{token}}\'',
  37. spaceNeededBefore: 'A space is required before \'{{token}}\''
  38. },
  39. schema: {
  40. definitions: {
  41. basicConfig: {
  42. type: 'object',
  43. properties: {
  44. when: {
  45. enum: SPACING_VALUES
  46. },
  47. allowMultiline: {
  48. type: 'boolean'
  49. },
  50. spacing: {
  51. type: 'object',
  52. properties: {
  53. objectLiterals: {
  54. enum: SPACING_VALUES
  55. }
  56. }
  57. }
  58. }
  59. },
  60. basicConfigOrBoolean: {
  61. oneOf: [{
  62. $ref: '#/definitions/basicConfig'
  63. }, {
  64. type: 'boolean'
  65. }]
  66. }
  67. },
  68. type: 'array',
  69. items: [{
  70. oneOf: [{
  71. allOf: [{
  72. $ref: '#/definitions/basicConfig'
  73. }, {
  74. type: 'object',
  75. properties: {
  76. attributes: {
  77. $ref: '#/definitions/basicConfigOrBoolean'
  78. },
  79. children: {
  80. $ref: '#/definitions/basicConfigOrBoolean'
  81. }
  82. }
  83. }]
  84. }, {
  85. enum: SPACING_VALUES
  86. }]
  87. }, {
  88. type: 'object',
  89. properties: {
  90. allowMultiline: {
  91. type: 'boolean'
  92. },
  93. spacing: {
  94. type: 'object',
  95. properties: {
  96. objectLiterals: {
  97. enum: SPACING_VALUES
  98. }
  99. }
  100. }
  101. },
  102. additionalProperties: false
  103. }]
  104. }
  105. },
  106. create(context) {
  107. function normalizeConfig(configOrTrue, defaults, lastPass) {
  108. const config = configOrTrue === true ? {} : configOrTrue;
  109. const when = config.when || defaults.when;
  110. const allowMultiline = has(config, 'allowMultiline') ? config.allowMultiline : defaults.allowMultiline;
  111. const spacing = config.spacing || {};
  112. let objectLiteralSpaces = spacing.objectLiterals || defaults.objectLiteralSpaces;
  113. if (lastPass) {
  114. // On the final pass assign the values that should be derived from others if they are still undefined
  115. objectLiteralSpaces = objectLiteralSpaces || when;
  116. }
  117. return {
  118. when,
  119. allowMultiline,
  120. objectLiteralSpaces
  121. };
  122. }
  123. const DEFAULT_WHEN = SPACING.never;
  124. const DEFAULT_ALLOW_MULTILINE = true;
  125. const DEFAULT_ATTRIBUTES = true;
  126. const DEFAULT_CHILDREN = false;
  127. let originalConfig = context.options[0] || {};
  128. if (SPACING_VALUES.indexOf(originalConfig) !== -1) {
  129. originalConfig = Object.assign({when: context.options[0]}, context.options[1]);
  130. }
  131. const defaultConfig = normalizeConfig(originalConfig, {
  132. when: DEFAULT_WHEN,
  133. allowMultiline: DEFAULT_ALLOW_MULTILINE
  134. });
  135. const attributes = has(originalConfig, 'attributes') ? originalConfig.attributes : DEFAULT_ATTRIBUTES;
  136. const attributesConfig = attributes ? normalizeConfig(attributes, defaultConfig, true) : null;
  137. const children = has(originalConfig, 'children') ? originalConfig.children : DEFAULT_CHILDREN;
  138. const childrenConfig = children ? normalizeConfig(children, defaultConfig, true) : null;
  139. // --------------------------------------------------------------------------
  140. // Helpers
  141. // --------------------------------------------------------------------------
  142. /**
  143. * Determines whether two adjacent tokens have a newline between them.
  144. * @param {Object} left - The left token object.
  145. * @param {Object} right - The right token object.
  146. * @returns {boolean} Whether or not there is a newline between the tokens.
  147. */
  148. function isMultiline(left, right) {
  149. return left.loc.end.line !== right.loc.start.line;
  150. }
  151. /**
  152. * Trims text of whitespace between two ranges
  153. * @param {Fixer} fixer - the eslint fixer object
  154. * @param {number} fromLoc - the start location
  155. * @param {number} toLoc - the end location
  156. * @param {string} mode - either 'start' or 'end'
  157. * @param {string=} spacing - a spacing value that will optionally add a space to the removed text
  158. * @returns {Object|*|{range, text}}
  159. */
  160. function fixByTrimmingWhitespace(fixer, fromLoc, toLoc, mode, spacing) {
  161. let replacementText = context.getSourceCode().text.slice(fromLoc, toLoc);
  162. if (mode === 'start') {
  163. replacementText = replacementText.replace(/^\s+/gm, '');
  164. } else {
  165. replacementText = replacementText.replace(/\s+$/gm, '');
  166. }
  167. if (spacing === SPACING.always) {
  168. if (mode === 'start') {
  169. replacementText += ' ';
  170. } else {
  171. replacementText = ` ${replacementText}`;
  172. }
  173. }
  174. return fixer.replaceTextRange([fromLoc, toLoc], replacementText);
  175. }
  176. /**
  177. * Reports that there shouldn't be a newline after the first token
  178. * @param {ASTNode} node - The node to report in the event of an error.
  179. * @param {Token} token - The token to use for the report.
  180. * @param {string} spacing
  181. * @returns {void}
  182. */
  183. function reportNoBeginningNewline(node, token, spacing) {
  184. context.report({
  185. node,
  186. loc: token.loc.start,
  187. messageId: 'noNewlineAfter',
  188. data: {
  189. token: token.value
  190. },
  191. fix(fixer) {
  192. const nextToken = context.getSourceCode().getTokenAfter(token);
  193. return fixByTrimmingWhitespace(fixer, token.range[1], nextToken.range[0], 'start', spacing);
  194. }
  195. });
  196. }
  197. /**
  198. * Reports that there shouldn't be a newline before the last token
  199. * @param {ASTNode} node - The node to report in the event of an error.
  200. * @param {Token} token - The token to use for the report.
  201. * @param {string} spacing
  202. * @returns {void}
  203. */
  204. function reportNoEndingNewline(node, token, spacing) {
  205. context.report({
  206. node,
  207. loc: token.loc.start,
  208. messageId: 'noNewlineBefore',
  209. data: {
  210. token: token.value
  211. },
  212. fix(fixer) {
  213. const previousToken = context.getSourceCode().getTokenBefore(token);
  214. return fixByTrimmingWhitespace(fixer, previousToken.range[1], token.range[0], 'end', spacing);
  215. }
  216. });
  217. }
  218. /**
  219. * Reports that there shouldn't be a space after the first token
  220. * @param {ASTNode} node - The node to report in the event of an error.
  221. * @param {Token} token - The token to use for the report.
  222. * @returns {void}
  223. */
  224. function reportNoBeginningSpace(node, token) {
  225. context.report({
  226. node,
  227. loc: token.loc.start,
  228. messageId: 'noSpaceAfter',
  229. data: {
  230. token: token.value
  231. },
  232. fix(fixer) {
  233. const sourceCode = context.getSourceCode();
  234. const nextToken = sourceCode.getTokenAfter(token);
  235. let nextComment;
  236. // ESLint >=4.x
  237. if (sourceCode.getCommentsAfter) {
  238. nextComment = sourceCode.getCommentsAfter(token);
  239. // ESLint 3.x
  240. } else {
  241. const potentialComment = sourceCode.getTokenAfter(token, {includeComments: true});
  242. nextComment = nextToken === potentialComment ? [] : [potentialComment];
  243. }
  244. // Take comments into consideration to narrow the fix range to what is actually affected. (See #1414)
  245. if (nextComment.length > 0) {
  246. return fixByTrimmingWhitespace(fixer, token.range[1], Math.min(nextToken.range[0], nextComment[0].range[0]), 'start');
  247. }
  248. return fixByTrimmingWhitespace(fixer, token.range[1], nextToken.range[0], 'start');
  249. }
  250. });
  251. }
  252. /**
  253. * Reports that there shouldn't be a space before the last token
  254. * @param {ASTNode} node - The node to report in the event of an error.
  255. * @param {Token} token - The token to use for the report.
  256. * @returns {void}
  257. */
  258. function reportNoEndingSpace(node, token) {
  259. context.report({
  260. node,
  261. loc: token.loc.start,
  262. messageId: 'noSpaceBefore',
  263. data: {
  264. token: token.value
  265. },
  266. fix(fixer) {
  267. const sourceCode = context.getSourceCode();
  268. const previousToken = sourceCode.getTokenBefore(token);
  269. let previousComment;
  270. // ESLint >=4.x
  271. if (sourceCode.getCommentsBefore) {
  272. previousComment = sourceCode.getCommentsBefore(token);
  273. // ESLint 3.x
  274. } else {
  275. const potentialComment = sourceCode.getTokenBefore(token, {includeComments: true});
  276. previousComment = previousToken === potentialComment ? [] : [potentialComment];
  277. }
  278. // Take comments into consideration to narrow the fix range to what is actually affected. (See #1414)
  279. if (previousComment.length > 0) {
  280. return fixByTrimmingWhitespace(fixer, Math.max(previousToken.range[1], previousComment[0].range[1]), token.range[0], 'end');
  281. }
  282. return fixByTrimmingWhitespace(fixer, previousToken.range[1], token.range[0], 'end');
  283. }
  284. });
  285. }
  286. /**
  287. * Reports that there should be a space after the first token
  288. * @param {ASTNode} node - The node to report in the event of an error.
  289. * @param {Token} token - The token to use for the report.
  290. * @returns {void}
  291. */
  292. function reportRequiredBeginningSpace(node, token) {
  293. context.report({
  294. node,
  295. loc: token.loc.start,
  296. messageId: 'spaceNeededAfter',
  297. data: {
  298. token: token.value
  299. },
  300. fix(fixer) {
  301. return fixer.insertTextAfter(token, ' ');
  302. }
  303. });
  304. }
  305. /**
  306. * Reports that there should be a space before the last token
  307. * @param {ASTNode} node - The node to report in the event of an error.
  308. * @param {Token} token - The token to use for the report.
  309. * @returns {void}
  310. */
  311. function reportRequiredEndingSpace(node, token) {
  312. context.report({
  313. node,
  314. loc: token.loc.start,
  315. messageId: 'spaceNeededBefore',
  316. data: {
  317. token: token.value
  318. },
  319. fix(fixer) {
  320. return fixer.insertTextBefore(token, ' ');
  321. }
  322. });
  323. }
  324. /**
  325. * Determines if spacing in curly braces is valid.
  326. * @param {ASTNode} node The AST node to check.
  327. * @returns {void}
  328. */
  329. function validateBraceSpacing(node) {
  330. let config;
  331. switch (node.parent.type) {
  332. case 'JSXAttribute':
  333. case 'JSXOpeningElement':
  334. config = attributesConfig;
  335. break;
  336. case 'JSXElement':
  337. case 'JSXFragment':
  338. config = childrenConfig;
  339. break;
  340. default:
  341. return;
  342. }
  343. if (config === null) {
  344. return;
  345. }
  346. const sourceCode = context.getSourceCode();
  347. const first = context.getFirstToken(node);
  348. const last = sourceCode.getLastToken(node);
  349. let second = context.getTokenAfter(first, {includeComments: true});
  350. let penultimate = sourceCode.getTokenBefore(last, {includeComments: true});
  351. if (!second) {
  352. second = context.getTokenAfter(first);
  353. const leadingComments = sourceCode.getNodeByRangeIndex(second.range[0]).leadingComments;
  354. second = leadingComments ? leadingComments[0] : second;
  355. }
  356. if (!penultimate) {
  357. penultimate = sourceCode.getTokenBefore(last);
  358. const trailingComments = sourceCode.getNodeByRangeIndex(penultimate.range[0]).trailingComments;
  359. penultimate = trailingComments ? trailingComments[trailingComments.length - 1] : penultimate;
  360. }
  361. const isObjectLiteral = first.value === second.value;
  362. const spacing = isObjectLiteral ? config.objectLiteralSpaces : config.when;
  363. if (spacing === SPACING.always) {
  364. if (!sourceCode.isSpaceBetweenTokens(first, second)) {
  365. reportRequiredBeginningSpace(node, first);
  366. } else if (!config.allowMultiline && isMultiline(first, second)) {
  367. reportNoBeginningNewline(node, first, spacing);
  368. }
  369. if (!sourceCode.isSpaceBetweenTokens(penultimate, last)) {
  370. reportRequiredEndingSpace(node, last);
  371. } else if (!config.allowMultiline && isMultiline(penultimate, last)) {
  372. reportNoEndingNewline(node, last, spacing);
  373. }
  374. } else if (spacing === SPACING.never) {
  375. if (isMultiline(first, second)) {
  376. if (!config.allowMultiline) {
  377. reportNoBeginningNewline(node, first, spacing);
  378. }
  379. } else if (sourceCode.isSpaceBetweenTokens(first, second)) {
  380. reportNoBeginningSpace(node, first);
  381. }
  382. if (isMultiline(penultimate, last)) {
  383. if (!config.allowMultiline) {
  384. reportNoEndingNewline(node, last, spacing);
  385. }
  386. } else if (sourceCode.isSpaceBetweenTokens(penultimate, last)) {
  387. reportNoEndingSpace(node, last);
  388. }
  389. }
  390. }
  391. // --------------------------------------------------------------------------
  392. // Public
  393. // --------------------------------------------------------------------------
  394. return {
  395. JSXExpressionContainer: validateBraceSpacing,
  396. JSXSpreadAttribute: validateBraceSpacing
  397. };
  398. }
  399. };