All files / src/resolver findAllComponentDefinitions.js

100% Statements 17/17
87.5% Branches 7/8
100% Functions 4/4
100% Lines 17/17
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                                                    12x 12x     7x 5x 5x   7x       10x 8x   10x     12x             14x 7x   7x 7x 7x   7x       12x    
/*
 * 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 isReactComponentClass from '../utils/isReactComponentClass';
import isReactCreateClassCall from '../utils/isReactCreateClassCall';
import isStatelessComponent from '../utils/isStatelessComponent';
import normalizeClassDefinition from '../utils/normalizeClassDefinition';
import resolveToValue from '../utils/resolveToValue';
 
/**
 * Given an AST, this function tries to find all object expressions that are
 * passed to `React.createClass` calls, by resolving all references properly.
 */
export default function findAllReactCreateClassCalls(
  ast: ASTNode,
  recast: Object
): Array<NodePath> {
  var types = recast.types.namedTypes;
  var definitions = [];
 
  function classVisitor(path) {
    if (isReactComponentClass(path)) {
      normalizeClassDefinition(path);
      definitions.push(path);
    }
    return false;
  }
 
  function statelessVisitor(path) {
    if (isStatelessComponent(path)) {
      definitions.push(path);
    }
    return false;
  }
 
  recast.visit(ast, {
    visitFunctionDeclaration: statelessVisitor,
    visitFunctionExpression: statelessVisitor,
    visitArrowFunctionExpression: statelessVisitor,
    visitClassExpression: classVisitor,
    visitClassDeclaration: classVisitor,
    visitCallExpression: function(path) {
      if (!isReactCreateClassCall(path)) {
        return false;
      }
      var resolvedPath = resolveToValue(path.get('arguments', 0));
      Eif (types.ObjectExpression.check(resolvedPath.node)) {
        definitions.push(resolvedPath);
      }
      return false;
    },
  });
 
  return definitions;
}