jsx-space-before-closing.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @fileoverview Validate spacing before closing bracket in JSX.
  3. * @author ryym
  4. * @deprecated
  5. */
  6. 'use strict';
  7. const getTokenBeforeClosingBracket = require('../util/getTokenBeforeClosingBracket');
  8. const docsUrl = require('../util/docsUrl');
  9. const log = require('../util/log');
  10. let isWarnedForDeprecation = false;
  11. // ------------------------------------------------------------------------------
  12. // Rule Definition
  13. // ------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. deprecated: true,
  17. docs: {
  18. description: 'Validate spacing before closing bracket in JSX',
  19. category: 'Stylistic Issues',
  20. recommended: false,
  21. url: docsUrl('jsx-space-before-closing')
  22. },
  23. fixable: 'code',
  24. messages: {
  25. noSpaceBeforeClose: 'A space is forbidden before closing bracket',
  26. needSpaceBeforeClose: 'A space is required before closing bracket'
  27. },
  28. schema: [{
  29. enum: ['always', 'never']
  30. }]
  31. },
  32. create(context) {
  33. const configuration = context.options[0] || 'always';
  34. // --------------------------------------------------------------------------
  35. // Public
  36. // --------------------------------------------------------------------------
  37. return {
  38. JSXOpeningElement(node) {
  39. if (!node.selfClosing) {
  40. return;
  41. }
  42. const sourceCode = context.getSourceCode();
  43. const leftToken = getTokenBeforeClosingBracket(node);
  44. const closingSlash = sourceCode.getTokenAfter(leftToken);
  45. if (leftToken.loc.end.line !== closingSlash.loc.start.line) {
  46. return;
  47. }
  48. if (configuration === 'always' && !sourceCode.isSpaceBetweenTokens(leftToken, closingSlash)) {
  49. context.report({
  50. loc: closingSlash.loc.start,
  51. messageId: 'needSpaceBeforeClose',
  52. fix(fixer) {
  53. return fixer.insertTextBefore(closingSlash, ' ');
  54. }
  55. });
  56. } else if (configuration === 'never' && sourceCode.isSpaceBetweenTokens(leftToken, closingSlash)) {
  57. context.report({
  58. loc: closingSlash.loc.start,
  59. messageId: 'noSpaceBeforeClose',
  60. fix(fixer) {
  61. const previousToken = sourceCode.getTokenBefore(closingSlash);
  62. return fixer.removeRange([previousToken.range[1], closingSlash.range[0]]);
  63. }
  64. });
  65. }
  66. },
  67. Program() {
  68. if (isWarnedForDeprecation) {
  69. return;
  70. }
  71. log('The react/jsx-space-before-closing rule is deprecated. '
  72. + 'Please use the react/jsx-tag-spacing rule with the '
  73. + '"beforeSelfClosing" option instead.');
  74. isWarnedForDeprecation = true;
  75. }
  76. };
  77. }
  78. };