unionIntersectionSpacing.js.flow 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {
  2. spacingFixers, getTokenAfterParens,
  3. } from '../utilities';
  4. const schema = [
  5. {
  6. enum: ['always', 'never'],
  7. type: 'string',
  8. },
  9. ];
  10. const create = (context) => {
  11. const sourceCode = context.getSourceCode();
  12. const always = (context.options[0] || 'always') === 'always';
  13. const check = (node) => {
  14. for (const [index, type] of node.types.entries()) {
  15. if (index + 1 === node.types.length) {
  16. continue;
  17. }
  18. const separator = getTokenAfterParens(sourceCode, type);
  19. const endOfType = sourceCode.getTokenBefore(separator);
  20. const nextType = sourceCode.getTokenAfter(separator);
  21. const spaceBefore = separator.range[0] - endOfType.range[1];
  22. const spaceAfter = nextType.range[0] - separator.range[1];
  23. const data = { type: node.type === 'UnionTypeAnnotation' ? 'union' : 'intersection' };
  24. if (always) {
  25. if (!spaceBefore) {
  26. context.report({
  27. data,
  28. fix: spacingFixers.addSpaceAfter(endOfType),
  29. message: 'There must be a space before {{type}} type annotation separator',
  30. node,
  31. });
  32. }
  33. if (!spaceAfter) {
  34. context.report({
  35. data,
  36. fix: spacingFixers.addSpaceAfter(separator),
  37. message: 'There must be a space after {{type}} type annotation separator',
  38. node,
  39. });
  40. }
  41. } else {
  42. if (spaceBefore) {
  43. context.report({
  44. data,
  45. fix: spacingFixers.stripSpacesAfter(endOfType, spaceBefore),
  46. message: 'There must be no space before {{type}} type annotation separator',
  47. node,
  48. });
  49. }
  50. if (spaceAfter) {
  51. context.report({
  52. data,
  53. fix: spacingFixers.stripSpacesAfter(separator, spaceAfter),
  54. message: 'There must be no space after {{type}} type annotation separator',
  55. node,
  56. });
  57. }
  58. }
  59. }
  60. };
  61. return {
  62. IntersectionTypeAnnotation: check,
  63. UnionTypeAnnotation: check,
  64. };
  65. };
  66. export default {
  67. create,
  68. meta: {
  69. fixable: 'code',
  70. },
  71. schema,
  72. };