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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. messages: {
  20. propOnNewLine: 'Property should be placed on a new line',
  21. propOnSameLine: 'Property should be placed on the same line as the component declaration'
  22. },
  23. schema: [{
  24. enum: ['always', 'never', 'multiline', 'multiline-multiprop']
  25. }]
  26. },
  27. create(context) {
  28. const configuration = context.options[0] || 'multiline-multiprop';
  29. function isMultilineJSX(jsxNode) {
  30. return jsxNode.loc.start.line < jsxNode.loc.end.line;
  31. }
  32. return {
  33. JSXOpeningElement(node) {
  34. if (
  35. (configuration === 'multiline' && isMultilineJSX(node))
  36. || (configuration === 'multiline-multiprop' && isMultilineJSX(node) && node.attributes.length > 1)
  37. || (configuration === 'always')
  38. ) {
  39. node.attributes.some((decl) => {
  40. if (decl.loc.start.line === node.loc.start.line) {
  41. context.report({
  42. node: decl,
  43. messageId: 'propOnNewLine',
  44. fix(fixer) {
  45. return fixer.replaceTextRange([node.name.range[1], decl.range[0]], '\n');
  46. }
  47. });
  48. }
  49. return true;
  50. });
  51. } else if (configuration === 'never' && node.attributes.length > 0) {
  52. const firstNode = node.attributes[0];
  53. if (node.loc.start.line < firstNode.loc.start.line) {
  54. context.report({
  55. node: firstNode,
  56. messageId: 'propOnSameLine',
  57. fix(fixer) {
  58. return fixer.replaceTextRange([node.name.range[1], firstNode.range[0]], ' ');
  59. }
  60. });
  61. }
  62. }
  63. }
  64. };
  65. }
  66. };