displayNameHandler.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import getMemberValuePath from '../utils/getMemberValuePath.js';
  2. import getNameOrValue from '../utils/getNameOrValue.js';
  3. import isReactForwardRefCall from '../utils/isReactForwardRefCall.js';
  4. import resolveToValue from '../utils/resolveToValue.js';
  5. import resolveFunctionDefinitionToReturnValue from '../utils/resolveFunctionDefinitionToReturnValue.js';
  6. const displayNameHandler = function (documentation, componentDefinition) {
  7. let displayNamePath = getMemberValuePath(componentDefinition, 'displayName');
  8. if (!displayNamePath) {
  9. // Function and class declarations need special treatment. The name of the
  10. // function / class is the displayName
  11. if ((componentDefinition.isClassDeclaration() ||
  12. componentDefinition.isFunctionDeclaration()) &&
  13. componentDefinition.has('id')) {
  14. documentation.set('displayName', getNameOrValue(componentDefinition.get('id')));
  15. }
  16. else if (componentDefinition.isArrowFunctionExpression() ||
  17. componentDefinition.isFunctionExpression() ||
  18. isReactForwardRefCall(componentDefinition)) {
  19. let currentPath = componentDefinition;
  20. while (currentPath.parentPath) {
  21. if (currentPath.parentPath.isVariableDeclarator()) {
  22. documentation.set('displayName', getNameOrValue(currentPath.parentPath.get('id')));
  23. return;
  24. }
  25. else if (currentPath.parentPath.isAssignmentExpression()) {
  26. const leftPath = currentPath.parentPath.get('left');
  27. if (leftPath.isIdentifier() || leftPath.isLiteral()) {
  28. documentation.set('displayName', getNameOrValue(leftPath));
  29. return;
  30. }
  31. }
  32. currentPath = currentPath.parentPath;
  33. }
  34. }
  35. return;
  36. }
  37. displayNamePath = resolveToValue(displayNamePath);
  38. // If display name is defined as function somehow (getter, property with function)
  39. // we resolve the return value of the function
  40. if (displayNamePath.isFunction()) {
  41. displayNamePath = resolveFunctionDefinitionToReturnValue(displayNamePath);
  42. }
  43. if (!displayNamePath ||
  44. (!displayNamePath.isStringLiteral() && !displayNamePath.isNumericLiteral())) {
  45. return;
  46. }
  47. documentation.set('displayName', displayNamePath.node.value);
  48. };
  49. export default displayNameHandler;