UNPKG

react-docgen

Version:

A CLI and toolkit to extract information from React components for documentation generation.

77 lines (59 loc) 2.82 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = displayNameHandler; var _getMemberValuePath = _interopRequireDefault(require("../utils/getMemberValuePath")); var _getNameOrValue = _interopRequireDefault(require("../utils/getNameOrValue")); var _recast = _interopRequireDefault(require("recast")); var _resolveToValue = _interopRequireDefault(require("../utils/resolveToValue")); var _resolveFunctionDefinitionToReturnValue = _interopRequireDefault(require("../utils/resolveFunctionDefinitionToReturnValue")); /* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * */ const types = _recast.default.types.namedTypes; function displayNameHandler(documentation, path) { let displayNamePath = (0, _getMemberValuePath.default)(path, 'displayName'); if (!displayNamePath) { // Function and class declarations need special treatment. The name of the // function / class is the displayName if (types.ClassDeclaration.check(path.node) || types.FunctionDeclaration.check(path.node)) { documentation.set('displayName', (0, _getNameOrValue.default)(path.get('id'))); } else if (types.ArrowFunctionExpression.check(path.node) || types.FunctionExpression.check(path.node)) { let currentPath = path; while (currentPath.parent) { if (types.VariableDeclarator.check(currentPath.parent.node)) { documentation.set('displayName', (0, _getNameOrValue.default)(currentPath.parent.get('id'))); return; } else if (types.AssignmentExpression.check(currentPath.parent.node)) { const leftPath = currentPath.parent.get('left'); if (types.Identifier.check(leftPath.node) || types.Literal.check(leftPath.node)) { documentation.set('displayName', (0, _getNameOrValue.default)(leftPath)); return; } } currentPath = currentPath.parent; } } return; } displayNamePath = (0, _resolveToValue.default)(displayNamePath); // If display name is defined as a getter we get a function expression as // value. In that case we try to determine the value from the return // statement. if (types.FunctionExpression.check(displayNamePath.node)) { displayNamePath = (0, _resolveFunctionDefinitionToReturnValue.default)(displayNamePath); } if (!displayNamePath || !types.Literal.check(displayNamePath.node)) { return; } documentation.set('displayName', displayNamePath.node.value); }