index.js.flow 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import isSimpleType from './isSimpleType';
  2. import needWrap from './needWrap';
  3. const schema = [
  4. {
  5. enum: ['verbose', 'shorthand'],
  6. type: 'string',
  7. },
  8. ];
  9. const inlineType = (type) => {
  10. const inlined = type.replace(/\s+/ug, ' ');
  11. if (inlined.length <= 50) {
  12. return inlined;
  13. }
  14. return 'Type';
  15. };
  16. export default (defaultConfig, simpleType) => {
  17. const create = (context) => {
  18. const verbose = (context.options[0] || defaultConfig) === 'verbose';
  19. return {
  20. // shorthand
  21. ArrayTypeAnnotation(node) {
  22. const rawElementType = context.getSourceCode().getText(node.elementType);
  23. const inlinedType = inlineType(rawElementType);
  24. const wrappedInlinedType = needWrap(node.elementType) ? `(${inlinedType})` : inlinedType;
  25. if (isSimpleType(node.elementType) === simpleType && verbose) {
  26. context.report({
  27. data: {
  28. type: inlinedType,
  29. wrappedType: wrappedInlinedType,
  30. },
  31. fix(fixer) {
  32. return fixer.replaceText(node, `Array<${rawElementType}>`);
  33. },
  34. message: 'Use "Array<{{ type }}>", not "{{ wrappedType }}[]"',
  35. node,
  36. });
  37. }
  38. },
  39. // verbose
  40. GenericTypeAnnotation(node) {
  41. // Don't report on un-parameterized Array annotations. There are valid cases for this,
  42. // but regardless, we must NOT crash when encountering them.
  43. if (node.id.name === 'Array'
  44. && node.typeParameters && node.typeParameters.params.length === 1) {
  45. const elementTypeNode = node.typeParameters.params[0];
  46. const rawElementType = context.getSourceCode().getText(elementTypeNode);
  47. const inlinedType = inlineType(rawElementType);
  48. const wrappedInlinedType = needWrap(elementTypeNode) ? `(${inlinedType})` : inlinedType;
  49. if (isSimpleType(elementTypeNode) === simpleType && !verbose) {
  50. context.report({
  51. data: {
  52. type: inlinedType,
  53. wrappedType: wrappedInlinedType,
  54. },
  55. fix(fixer) {
  56. if (needWrap(elementTypeNode)) {
  57. return fixer.replaceText(node, `(${rawElementType})[]`);
  58. }
  59. return fixer.replaceText(node, `${rawElementType}[]`);
  60. },
  61. message: 'Use "{{ wrappedType }}[]", not "Array<{{ type }}>"',
  62. node,
  63. });
  64. }
  65. }
  66. },
  67. };
  68. };
  69. return {
  70. create,
  71. meta: {
  72. fixable: 'code',
  73. },
  74. schema,
  75. };
  76. };