UNPKG

react-docgen

Version:

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

72 lines (57 loc) 2.53 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = componentMethodsHandler; var _recast = _interopRequireDefault(require("recast")); var _getMemberValuePath = _interopRequireDefault(require("../utils/getMemberValuePath")); var _getMethodDocumentation = _interopRequireDefault(require("../utils/getMethodDocumentation")); var _isReactComponentClass = _interopRequireDefault(require("../utils/isReactComponentClass")); var _isReactComponentMethod = _interopRequireDefault(require("../utils/isReactComponentMethod")); /* * 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; /** * The following values/constructs are considered methods: * * - Method declarations in classes (except "constructor" and React lifecycle * methods * - Public class fields in classes whose value are a functions * - Object properties whose values are functions */ function isMethod(path) { const isProbablyMethod = types.MethodDefinition.check(path.node) && path.node.kind !== 'constructor' || types.ClassProperty.check(path.node) && types.Function.check(path.get('value').node) || types.Property.check(path.node) && types.Function.check(path.get('value').node); return isProbablyMethod && !(0, _isReactComponentMethod.default)(path); } /** * Extract all flow types for the methods of a react component. Doesn't * return any react specific lifecycle methods. */ function componentMethodsHandler(documentation, path) { // Extract all methods from the class or object. let methodPaths = []; if ((0, _isReactComponentClass.default)(path)) { methodPaths = path.get('body', 'body').filter(isMethod); } else if (types.ObjectExpression.check(path.node)) { methodPaths = path.get('properties').filter(isMethod); // Add the statics object properties. const statics = (0, _getMemberValuePath.default)(path, 'statics'); if (statics) { statics.get('properties').each(p => { if (isMethod(p)) { p.node.static = true; methodPaths.push(p); } }); } } documentation.set('methods', methodPaths.map(_getMethodDocumentation.default)); }