All files / src/handlers componentMethodsHandler.js

100% Statements 22/22
91.67% Branches 11/12
100% Functions 6/6
100% Lines 22/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                        2x     10x   10x 9x 5x     4x     10x       11x                       10x 10x 2x   8x 8x 4x     4x 4x 1x 1x 1x 1x           10x 10x    
/*
 * 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.
 *
 * @flow
 */
 
import recast from 'recast';
 
import getMemberValuePath from '../utils/getMemberValuePath';
import getMethodDocumentation from '../utils/getMethodDocumentation';
import isReactComponentClass from '../utils/isReactComponentClass';
import isReactComponentMethod from '../utils/isReactComponentMethod';
 
import type Documentation from '../Documentation';
 
const {types: {namedTypes: types}} = recast;
 
function getMethodsDoc(methodPaths) {
  const methods = [];
 
  methodPaths.forEach((methodPath) => {
    if (isReactComponentMethod(methodPath)) {
      return;
    }
 
    methods.push(getMethodDocumentation(methodPath));
  });
 
  return methods;
}
 
function isFunctionExpression(path) {
  return types.FunctionExpression.check(path.get('value').node)
}
 
/**
 * Extract all flow types for the methods of a react component. Doesn't
 * return any react specific lifecycle methods.
 */
export default function componentMethodsHandler(
  documentation: Documentation,
  path: NodePath
) {
  // Extract all methods from the class or object.
  let methodPaths = [];
  if (isReactComponentClass(path)) {
    methodPaths = path
      .get('body', 'body')
      .filter(p => types.MethodDefinition.check(p.node) && p.node.kind !== 'constructor');
  } else if (types.ObjectExpression.check(path.node)) {
    methodPaths = path.get('properties').filter(isFunctionExpression);
 
    // Add the statics object properties.
    const statics = getMemberValuePath(path, 'statics');
    if (statics) {
      statics.get('properties').each(p => {
        Eif (isFunctionExpression(p)) {
          p.node.static = true;
          methodPaths.push(p);
        }
      });
    }
  }
 
  const methods = getMethodsDoc(methodPaths);
  documentation.set('methods', methods);
}