jsx-curly-spacing.js 14 KB

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