enforceLineBreak.js.flow 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const schema = [];
  2. const breakLineMessage = (direction) => `New line required ${direction} type declaration`;
  3. const create = (context) => ({
  4. TypeAlias(node) {
  5. const sourceCode = context.getSourceCode();
  6. if (sourceCode.lines.length === 1) {
  7. return;
  8. }
  9. const exportedType = node.parent.type === 'ExportNamedDeclaration';
  10. const leadingComments = sourceCode.getCommentsBefore(exportedType ? node.parent : node);
  11. const hasLeadingComments = leadingComments.length > 0;
  12. if (node.loc.start.line !== 1) {
  13. if (hasLeadingComments && leadingComments[0].loc.start.line !== 1) {
  14. const lineAboveComment = sourceCode.lines[leadingComments[0].loc.start.line - 2];
  15. if (lineAboveComment !== '') {
  16. context.report({
  17. fix(fixer) {
  18. return fixer.insertTextBeforeRange(leadingComments[0].range, '\n');
  19. },
  20. message: breakLineMessage('above'),
  21. node,
  22. });
  23. }
  24. } else if (!hasLeadingComments) {
  25. const isLineAbove = sourceCode.lines[node.loc.start.line - 2];
  26. if (isLineAbove !== '') {
  27. context.report({
  28. fix(fixer) {
  29. return fixer.insertTextBefore(
  30. exportedType ? node.parent : node,
  31. '\n',
  32. );
  33. },
  34. message: breakLineMessage('above'),
  35. node,
  36. });
  37. }
  38. }
  39. }
  40. if (sourceCode.lines.length !== node.loc.end.line) {
  41. const isLineBelow = sourceCode.lines[node.loc.end.line];
  42. if (isLineBelow !== '') {
  43. context.report({
  44. fix(fixer) {
  45. return fixer.insertTextAfter(node, '\n');
  46. },
  47. message: breakLineMessage('below'),
  48. node,
  49. });
  50. }
  51. }
  52. },
  53. });
  54. export default {
  55. create,
  56. meta: {
  57. fixable: 'code',
  58. },
  59. schema,
  60. };