jsx-curly-spacing.js 14 KB

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