Esempio n. 1
0
    return this.forEach(path => {
      let items = null;
      path.node.properties.forEach(prop => {
        if (j.Property.check(prop) && prop.key.name === itemsKey) {
          assert(
            j.ObjectExpression.check(prop.value),
            `_addModelItem: ${itemsKey} should be ObjectExpression, but got ${prop.value.type}`
          );
          items = prop;
        }
      });

      if (!items) {
        items = j.property(
          'init',
          j.identifier(itemsKey),
          j.objectExpression([])
        );
        path.node.properties.push(items);
      }

      const item = j.property(
        'init',
        j.identifier(name),
        utils.getExpression(source || defaultSource)
      );
      items.value.properties.push(item);
    });
Esempio n. 2
0
export function createAssertion(assertionNameOrProperty, args) {
  const assertionName = (assertionNameOrProperty.name == null)
    ? assertionNameOrProperty
    : assertionNameOrProperty.name;

  return j.callExpression(
    j.memberExpression(j.identifier('assert'), j.identifier(assertionName), false),
    args
  );
}
function generateDirectEventInfo(event) {
  return j.property(
    'init',
    j.identifier(event.name),
    j.objectExpression([
      j.property(
        'init',
        j.identifier('registrationName'),
        j.literal(event.name),
      ),
    ]),
  );
}
Esempio n. 4
0
export default function convertToBeDefined (node) {
  let expectExpression = node.value.object
  let to
  if (isNegated(node)) {
    to = j.memberExpression(expectExpression.object, j.identifier('to'))
  } else {
    to = j.memberExpression(expectExpression, j.identifier('to'))
    to = j.memberExpression(to, j.identifier('not'))
  }
  const be = j.memberExpression(to, j.identifier('be'))
  const _undefined = j.memberExpression(be, j.identifier('undefined'))
  return _undefined
}
 ...componentProps.map(schemaProp => {
   return j.property(
     'init',
     j.identifier(schemaProp.name),
     getReactDiffProcessValue(schemaProp),
   );
 }),
Esempio n. 6
0
  root.findRouteComponents().forEach(path => {
    if (path.node.type === 'ClassDeclaration') {
      // add method
      const methodName = `["${payload.actionType}"]`;
      const callMethod = `this${methodName}()`;
      const renderMethod = j(path).find(j.MethodDefinition, {
        key: {
          type: 'Identifier',
          name: 'render',
        },
      }).at(0);

      renderMethod.insertBefore(
        j.methodDefinition(
          'method',
          j.identifier(methodName),
          getExpression(`\nfunction() {\n  this.props.dispatch({ type: '${payload.actionType}', payload: {} });\n}`)
        )
      );

      // add button & callback to render
      addDispatchButton(path, payload.actionType, callMethod);
    } else if(path.node.type === 'FunctionDeclaration') {
      const callFunction = `props.dispatch({ type: '${payload.actionType}', payload: {} })`;
      addDispatchButton(path, payload.actionType, callFunction);
    }

  });
function generateBubblingEventInfo(event) {
  return j.property(
    'init',
    j.identifier(event.name),
    j.objectExpression([
      j.property(
        'init',
        j.identifier('phasedRegistrationNames'),
        j.objectExpression([
          j.property(
            'init',
            j.identifier('captured'),
            j.literal(`${event.name}Capture`),
          ),
          j.property('init', j.identifier('bubbled'), j.literal(event.name)),
        ]),
      ),
    ]),
  );
}
 component.extendsProps.forEach(extendProps => {
   switch (extendProps.type) {
     case 'ReactNativeBuiltInType':
       switch (extendProps.knownTypeName) {
         case 'ReactNativeCoreViewProps':
           imports.add(
             "const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');",
           );
           styleAttribute = j.property(
             'init',
             j.identifier('style'),
             j.identifier('ReactNativeStyleAttributes'),
           );
           return;
         default:
           (extendProps.knownTypeName: empty);
           throw new Error('Invalid knownTypeName');
       }
     default:
       (extendProps.type: empty);
       throw new Error('Invalid extended type');
   }
 });
function buildViewConfig(
  schema: SchemaType,
  componentName: string,
  component,
  imports,
) {
  const componentProps = component.props;

  let styleAttribute = null;

  component.extendsProps.forEach(extendProps => {
    switch (extendProps.type) {
      case 'ReactNativeBuiltInType':
        switch (extendProps.knownTypeName) {
          case 'ReactNativeCoreViewProps':
            imports.add(
              "const ReactNativeStyleAttributes = require('ReactNativeStyleAttributes');",
            );
            styleAttribute = j.property(
              'init',
              j.identifier('style'),
              j.identifier('ReactNativeStyleAttributes'),
            );
            return;
          default:
            (extendProps.knownTypeName: empty);
            throw new Error('Invalid knownTypeName');
        }
      default:
        (extendProps.type: empty);
        throw new Error('Invalid extended type');
    }
  });

  const validAttributes = j.objectExpression([
    ...componentProps.map(schemaProp => {
      return j.property(
        'init',
        j.identifier(schemaProp.name),
        getReactDiffProcessValue(schemaProp),
      );
    }),
    styleAttribute,
  ]);

  const bubblingEventNames = component.events
    .filter(event => event.bubblingType === 'bubble')
    .map(generateBubblingEventInfo);

  const bubblingEvents =
    bubblingEventNames.length > 0
      ? j.property(
          'init',
          j.identifier('bubblingEventTypes'),
          j.objectExpression(bubblingEventNames),
        )
      : null;

  const directEventNames = component.events
    .filter(event => event.bubblingType === 'direct')
    .map(generateDirectEventInfo);

  const directEvents =
    directEventNames.length > 0
      ? j.property(
          'init',
          j.identifier('directEventTypes'),
          j.objectExpression(directEventNames),
        )
      : null;

  const properties = [
    j.property(
      'init',
      j.identifier('uiViewClassName'),
      j.literal(componentName),
    ),
    bubblingEvents,
    directEvents,
    j.property('init', j.identifier('validAttributes'), validAttributes),
  ].filter(Boolean);

  return j.objectExpression(properties);
}
Esempio n. 10
0
  /**
   * Gets a single require, this isn't great for when you want to destructure
   * multiple things in a single statement.
   *
   * TODO: add a getRequires() that consolidates automatically, or add a
   * specific consolidate step as part of the transform.
   */
  getRequire(id: Identifier, options: RequireOptions): ?Node {
    Options.validateRequireOptions(options);

    // Don't import built ins.
    if (!options.typeImport) {
      if (this._builtIns.has(id)) {
        return null;
      }
    } else {
      if (this._builtInTypes.has(id)) {
        return null;
      }
    }

    // TODO: Use let for proper scoping.
    let literal;
    let tmp;

    if (this._aliases.has(id)) {
      literal = this._aliases.get(id);
    } else if (options.sourcePath && this._aliasesToRelativize.has(id)) {
      literal = ModuleMapUtils.relativizeForRequire(
        options.sourcePath,
        // $FlowFixMe(kad)
        this._aliasesToRelativize.get(id),
      );
    } else if (
      this._defaults.has(id) &&
      // $FlowFixMe(kad)
      this._defaults.get(id).size === 1
    ) {
      // TODO: What's the best way to get the single thing out of a one element
      // Set?
      // $FlowFixMe(kad)
      for (tmp of this._defaults.get(id)) {
        literal = tmp;
        break;
      }
    } else if (
      options.sourcePath &&
      this._defaultsToRelativize.has(id) &&
      // $FlowFixMe(kad)
      this._defaultsToRelativize.get(id).size === 1
    ) {
      const nonNullSourcePath = options.sourcePath;
      // TODO: What's the best way to get the single thing out of a one element
      // Set?
      // $FlowFixMe(kad)
      for (const filePath of this._defaultsToRelativize.get(id)) {
        literal = ModuleMapUtils.relativizeForRequire(
          nonNullSourcePath,
          filePath,
        );
        break;
      }
    } else if (options.jsxIdentifier) {
      // TODO: Make this configurable so that the suffix for JSX can be changed.
      literal = id + '.react';
    } else {
      // TODO: Make this configurable so that it's possible to only add known
      // requires and ignore unknown modules.
      literal = id;
    }

    // Create common nodes for printing.
    const idNode = jscs.identifier(id);
    const literalNode = jscs.literal(literal);

    // TODO: Support exports and destructuring.
    const destructure = false;

    if (destructure && options.typeImport) {
      // import type {foo} from 'foo';
      tmp = statement`import type {_} from '_'`;
      tmp.specifiers[0].imported = idNode;
      tmp.specifiers[0].local = idNode;
      tmp.source = literalNode;
      return tmp;
    } else if (!destructure && options.typeImport) {
      // import type foo from 'foo';
      tmp = statement`import type _ from '_'`;
      tmp.specifiers[0].id = idNode;
      tmp.specifiers[0].local = idNode;
      tmp.source = literalNode;
      return tmp;
    } else if (destructure && !options.typeImport) {
      // var {foo} = require('foo');
      const property = jscs.property('init', idNode, idNode);
      property.shorthand = true;
      return jscs.variableDeclaration(
        'const',
        [jscs.variableDeclarator(
          oneLineObjectPattern(jscs.objectPattern([property])),
          jscs.callExpression(
            jscs.identifier('require'),
            [literalNode],
          ),
        )],
      );
    } else if (!destructure && !options.typeImport) {
      // var foo = require('foo');
      return jscs.variableDeclaration(
        'const',
        [jscs.variableDeclarator(
          idNode,
          jscs.callExpression(
            jscs.identifier('require'),
            [literalNode],
          ),
        )],
      );
    }

    // Can't handle this type of require yet.
    return null;
  }
 *
 * This source code is licensed under the license found in the LICENSE file in
 * the root directory of this source tree.
 */

import type {Collection, Node, NodePath} from '../types/ast';

const getNamesFromID = require('./getNamesFromID');
const jscs = require('jscodeshift');

type ConfigEntry = {
  searchTerms: [any, Object];
  getNodes: (path: NodePath) => Array<Node>;
};

const REACT_NODE = jscs.identifier('React');

/**
 * These are the ways in which one might access an undeclared identifier. This
 * should only apply to actual code, not accessing undeclared types.
 */
const CONFIG: Array<ConfigEntry> = [
  // foo;
  {
    searchTerms: [jscs.ExpressionStatement],
    getNodes: path => [path.node.expression],
  },

  // foo(bar);
  {
    searchTerms: [jscs.CallExpression],
Esempio n. 12
0
 return events.map(eventType => {
   return j.property('init', j.identifier(eventType.name), j.literal(true));
 });