jsx-first-prop-new-line.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @fileoverview Ensure proper position of the first property in JSX
  3. * @author Joachim Seminck
  4. */
  5. 'use strict';
  6. const docsUrl = require('../util/docsUrl');
  7. // ------------------------------------------------------------------------------
  8. // Rule Definition
  9. // ------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description: 'Ensure proper position of the first property in JSX',
  14. category: 'Stylistic Issues',
  15. recommended: false,
  16. url: docsUrl('jsx-first-prop-new-line')
  17. },
  18. fixable: 'code',
  19. schema: [{
  20. enum: ['always', 'never', 'multiline', 'multiline-multiprop']
  21. }]
  22. },
  23. create: function (context) {
  24. const configuration = context.options[0] || 'multiline-multiprop';
  25. function isMultilineJSX(jsxNode) {
  26. return jsxNode.loc.start.line < jsxNode.loc.end.line;
  27. }
  28. return {
  29. JSXOpeningElement: function (node) {
  30. if (
  31. (configuration === 'multiline' && isMultilineJSX(node)) ||
  32. (configuration === 'multiline-multiprop' && isMultilineJSX(node) && node.attributes.length > 1) ||
  33. (configuration === 'always')
  34. ) {
  35. node.attributes.some(decl => {
  36. if (decl.loc.start.line === node.loc.start.line) {
  37. context.report({
  38. node: decl,
  39. message: 'Property should be placed on a new line',
  40. fix: function(fixer) {
  41. return fixer.replaceTextRange([node.name.end, decl.range[0]], '\n');
  42. }
  43. });
  44. }
  45. return true;
  46. });
  47. } else if (configuration === 'never' && node.attributes.length > 0) {
  48. const firstNode = node.attributes[0];
  49. if (node.loc.start.line < firstNode.loc.start.line) {
  50. context.report({
  51. node: firstNode,
  52. message: 'Property should be placed on the same line as the component declaration',
  53. fix: function(fixer) {
  54. return fixer.replaceTextRange([node.name.end, firstNode.range[0]], ' ');
  55. }
  56. });
  57. return;
  58. }
  59. }
  60. return;
  61. }
  62. };
  63. }
  64. };