<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * Generates the PhET-iO API Type documentation which will be shown at https://phet-io.colorado.edu/devguide/
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
/* eslint-env node */
'use strict';

var requirejs = require( '../../../chipper/node_modules/requirejs/bin/r.js' ); // eslint-disable-line require-statement-match
var fs = require( 'fs' );

// Mock up window globals for running in node mode

global.assert = require( 'assert' );
global._ = require( '../../../sherpa/lib/lodash-4.17.4.js' );
global.phet = {
  chipper: {
    queryParameters: {},
    brand: 'phet-io'
  },
  phetio: {
    queryParameters: {
      phetioExpressions: '[]'
    }
  }
};

// This is a hack because we are now loading scenery.js as a namespace.
global.document = { createElement: function() {return { getContext: function() {} };} };

global.window = global; // eslint-disable-line no-native-reassign

var assert = global.assert;

var paths = {
  text: '../../../sherpa/lib/text-2.0.12',
  ifphetio: '../../../chipper/js/requirejs-plugins/ifphetio',

  AXON: '../../../axon/js',
  DOT: '../../../dot/js',
  JOIST: '../../../joist/js',
  KITE: '../../../kite/js',
  PHETCOMMON: '../../../phetcommon/js',
  REPOSITORY: '../..',
  PHET_CORE: '../../../phet-core/js',
  PHET_IO: '../../../phet-io/js',
  SHRED: '../../../shred/js',
  SCENERY: '../../../scenery/js',
  SCENERY_PHET: '../../../scenery-phet/js',
  SUN: '../../../sun/js',
  TANDEM: '../../../tandem/js',
  VEGAS: '../../../vegas/js',
  VIBE: '../../../vibe/js'

};

requirejs.config( {
  paths: paths
} );

var TObject = requirejs( 'PHET_IO/types/TObject' );

// Get a list of all of the types in the 'types' directory
function walkSync( dir, filelist ) {
  var files = fs.readdirSync( dir );
  filelist = filelist || [];
  files.forEach( function( file ) {
    if ( fs.statSync( dir + '/' + file ).isDirectory() ) {
      filelist = walkSync( dir + '/' + file, filelist );
    }
    else {
      if ( file.match( /^T[A-Z].*\.js/ ) ) {
        filelist.push( dir + '/' + file.replace( '.js', '' ) );
      }
    }
  } );
  return filelist;
}

function getCommonCodeTTypes() {
  var activeRepos = fs.readFileSync( '../../../chipper/data/active-repos' ).toString();
  activeRepos = activeRepos.split( /\r?\n/ );
  var activeSims = fs.readFileSync( '../../../chipper/data/active-sims' ).toString();
  activeSims = activeSims.split( /\r?\n/ );

  // Repos that we don't want to search because they have no js/ directories, and won't have TTypes
  var blackList = [ 'babel', 'exemplar', 'function-basics', 'phet-info', 'phet-io-website', 'phet-ios-app',
    'phet-android-app', 'phet-cafepress', 'sherpa', 'slater', 'tambo', 'tasks', 'yotta' ];

  blackList.forEach( function( repo ) {
    activeRepos.splice( activeRepos.indexOf( repo ), 1 );
  } );

  activeSims.forEach( function( repo ) {
    activeRepos.splice( activeRepos.indexOf( repo ), 1 );
  } );

  var commonRepos = activeRepos;

  var files = [];
  commonRepos.forEach( function( repoName ) {
    walkSync( '../../../' + repoName + '/js', files );
  } );
  return files;
}

function toHTML( json ) {
  var html = '';
  var types = _.sortBy( _.keys( json ), function( key ) {
    return key;
  } );
  for ( var i = 0; i < types.length; i++ ) {

    var typeName = types[ i ];
    var wrapperType = json[ typeName ];
    var methods = '';
    var sortedMethodNames = _.sortBy( _.keys( wrapperType.methods ), function( key ) {
      return key;
    } );
    for ( var k = 0; k < sortedMethodNames.length; k++ ) {
      var methodName = sortedMethodNames[ k ];
      var method = wrapperType.methods[ methodName ];
      var params = method.parameterTypes.map( function( p ) {
        assert && assert( p.typeName, 'Parameter was not a type in toHTML: ' + typeName + '.' + methodName );
        return p.typeName;
      } );
      methods += '
' + methodName + ': (' + params + ') ➞ ' + method.returnType.typeName + '
' +
                 '
' + method.documentation + '
';
    }
    var eventsString = wrapperType.events ? 'events: ' + ( wrapperType.events || '' ) + '' : '';

    var supertype = wrapperType.supertype;
    html = html + '
' + typeName + ' ' +
           (supertype.typeName ? '(extends ' + supertype.typeName + ')' : '') +
           '
' +
           '
' +
           '' + wrapperType.documentation + '
' +
           eventsString +
           '
' + methods + '

';
  }
  return html;
}

/**
 * Given as list of types files, return a json that holds the necessary information for the type documentation.
 * It will have a structure like this: {
 *    typeName: TType from the requirejs call,
 *    nextTypeName: . . . ,
 *    }
 *
 * Parameterized types like TTandemEmitter and TFunctionWrapper are hard coded because they have different constructors.
 * @param ttypeFiles
 */
function getTypeJSON( ttypeFiles ) {

  var result = {};

  // Load the dependencies one at a time. This is a hack workaround that somehow allows requirejs to proceed.  Batching them
  // (that is, loading them with an array) failed for unknown reasons.  See https://github.com/phetsims/phet-io/issues/972
  for ( var i = 0; i < ttypeFiles.length; i++ ) {
    var filename = ttypeFiles[ i ];

    var TType = requirejs( filename );

    // See phetioInherit for more details
    if ( TType.typeName ) {
      result[ TType.typeName ] = TType;
    }
    else {

      // Hack around the parametrized nature of TFunctionWrapper
      if ( filename.indexOf( 'TFunctionWrapper' ) >= 0 ) {
        var returnType = TObject;
        var parameterTypes = [ TObject ];
        var instantiatedType = TType( returnType, parameterTypes );
        result[ instantiatedType.typeName ] = instantiatedType;
      }

      // Hack around the parametrized nature of TTandemEmitter
      else if ( filename.indexOf( 'TTandemEmitter' ) >= 0 ) {
        var tandemEmitterType = TType( [ TObject ] );
        result[ tandemEmitterType.typeName ] = tandemEmitterType;
      }

      else {
        var otherType = TType( TObject );
        result[ otherType.typeName ] = otherType;
      }
    }

    // Hack to clear namespaces so duplicate registration doesn't throw an assertion error.
    for ( var v in global.phet ) {
      if ( global.phet.hasOwnProperty( v ) ) {
        if ( global.phet[ v ].constructor.name === 'Namespace' ) {
          var myObject = global.phet[ v ];

          // Manually clear the namespace so it doesn't complain when getting repopulated in the next run
          for ( var member in myObject ) {
            if ( myObject.hasOwnProperty( member ) ) {
              delete myObject[ member ];
            }
          }
        }
      }
    }
  }
  return result;
}

function getCommonCodeTypeDocs() {
  var commonCodeTTypeFiles = getCommonCodeTTypes();
  var typeJSON = getTypeJSON( commonCodeTTypeFiles );

  return toHTML( typeJSON );
}

function getSimSpecificTypeDocs( simRepoName, simFormalName, simCapsForRequire ) {
  var simHTMLHeader = '
Specific Types for ' + simFormalName + '
';
  var ttypeFiles = [];

  // Get the list of TTypes
  walkSync( '../../../' + simRepoName + '/js', ttypeFiles );

  paths[ simCapsForRequire ] = '../../../' + simRepoName + '/js';
  requirejs.config( {
    paths: paths
  } );
  var typeJSON = getTypeJSON( ttypeFiles );
  var typeHTML = toHTML( typeJSON );
  return typeHTML ? simHTMLHeader + typeHTML : simHTMLHeader + '
There are no specific types for this sim
';
}

// Called from the command line, and not required, option support for both modules, used by the grunt build process. This
// can also be used to update the devGuide in the phet-io-website.
if ( require.main === module ) {
  var args = process.argv;

  // Common code docs
  if ( args.length === 3 && args[ 2 ] === '--common' ) {
    console.log( getCommonCodeTypeDocs() );
  }

  // Sim specific docs
  else if ( args.length === 6 && args[ 2 ] === '--sim' ) {
    var repoName = args[ 3 ];
    var simFormalName = args[ 4 ];
    var requirejsName = args[ 5 ];
    console.log( getSimSpecificTypeDocs( repoName, simFormalName, requirejsName ) );
  }
  else {
    console.error( 'Incorrect usage, given args: ', args );
    console.error( 'Usage for common code \'node ../../createTypeDocumentation.js --common\'\n' +
                   'Usage for a specific sim\'s docs \'node createTypeDocumention.js --sim [repo-name] [\"Sim Formal Name\"] [REQUIRE_JS_REPO_NAME]\'' );
    process.exit();
  }
}
<commit_msg>require module not file, https://github.com/phetsims/phet-io/issues/972<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * Generates the PhET-iO API Type documentation which will be shown at https://phet-io.colorado.edu/devguide/
 *
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 */
/* eslint-env node */
'use strict';

var requirejs = require( 'requirejs' ); // eslint-disable-line require-statement-match
var fs = require( 'fs' );

// Mock up window globals for running in node mode

global.assert = require( 'assert' );
global._ = require( '../../../sherpa/lib/lodash-4.17.4.js' );
global.phet = {
  chipper: {
    queryParameters: {},
    brand: 'phet-io'
  },
  phetio: {
    queryParameters: {
      phetioExpressions: '[]'
    }
  }
};

// This is a hack because we are now loading scenery.js as a namespace.
global.document = { createElement: function() {return { getContext: function() {} };} };

global.window = global; // eslint-disable-line no-native-reassign

var assert = global.assert;

var paths = {
  text: '../../../sherpa/lib/text-2.0.12',
  ifphetio: '../../../chipper/js/requirejs-plugins/ifphetio',

  AXON: '../../../axon/js',
  DOT: '../../../dot/js',
  JOIST: '../../../joist/js',
  KITE: '../../../kite/js',
  PHETCOMMON: '../../../phetcommon/js',
  REPOSITORY: '../..',
  PHET_CORE: '../../../phet-core/js',
  PHET_IO: '../../../phet-io/js',
  SHRED: '../../../shred/js',
  SCENERY: '../../../scenery/js',
  SCENERY_PHET: '../../../scenery-phet/js',
  SUN: '../../../sun/js',
  TANDEM: '../../../tandem/js',
  VEGAS: '../../../vegas/js',
  VIBE: '../../../vibe/js'

};

requirejs.config( {
  paths: paths
} );

var TObject = requirejs( 'PHET_IO/types/TObject' );

// Get a list of all of the types in the 'types' directory
function walkSync( dir, filelist ) {
  var files = fs.readdirSync( dir );
  filelist = filelist || [];
  files.forEach( function( file ) {
    if ( fs.statSync( dir + '/' + file ).isDirectory() ) {
      filelist = walkSync( dir + '/' + file, filelist );
    }
    else {
      if ( file.match( /^T[A-Z].*\.js/ ) ) {
        filelist.push( dir + '/' + file.replace( '.js', '' ) );
      }
    }
  } );
  return filelist;
}

function getCommonCodeTTypes() {
  var activeRepos = fs.readFileSync( '../../../chipper/data/active-repos' ).toString();
  activeRepos = activeRepos.split( /\r?\n/ );
  var activeSims = fs.readFileSync( '../../../chipper/data/active-sims' ).toString();
  activeSims = activeSims.split( /\r?\n/ );

  // Repos that we don't want to search because they have no js/ directories, and won't have TTypes
  var blackList = [ 'babel', 'exemplar', 'function-basics', 'phet-info', 'phet-io-website', 'phet-ios-app',
    'phet-android-app', 'phet-cafepress', 'sherpa', 'slater', 'tambo', 'tasks', 'yotta' ];

  blackList.forEach( function( repo ) {
    activeRepos.splice( activeRepos.indexOf( repo ), 1 );
  } );

  activeSims.forEach( function( repo ) {
    activeRepos.splice( activeRepos.indexOf( repo ), 1 );
  } );

  var commonRepos = activeRepos;

  var files = [];
  commonRepos.forEach( function( repoName ) {
    walkSync( '../../../' + repoName + '/js', files );
  } );
  return files;
}

function toHTML( json ) {
  var html = '';
  var types = _.sortBy( _.keys( json ), function( key ) {
    return key;
  } );
  for ( var i = 0; i < types.length; i++ ) {

    var typeName = types[ i ];
    var wrapperType = json[ typeName ];
    var methods = '';
    var sortedMethodNames = _.sortBy( _.keys( wrapperType.methods ), function( key ) {
      return key;
    } );
    for ( var k = 0; k < sortedMethodNames.length; k++ ) {
      var methodName = sortedMethodNames[ k ];
      var method = wrapperType.methods[ methodName ];
      var params = method.parameterTypes.map( function( p ) {
        assert && assert( p.typeName, 'Parameter was not a type in toHTML: ' + typeName + '.' + methodName );
        return p.typeName;
      } );
      methods += '
' + methodName + ': (' + params + ') ➞ ' + method.returnType.typeName + '
' +
                 '
' + method.documentation + '
';
    }
    var eventsString = wrapperType.events ? 'events: ' + ( wrapperType.events || '' ) + '' : '';

    var supertype = wrapperType.supertype;
    html = html + '
' + typeName + ' ' +
           (supertype.typeName ? '(extends ' + supertype.typeName + ')' : '') +
           '
' +
           '
' +
           '' + wrapperType.documentation + '
' +
           eventsString +
           '
' + methods + '

';
  }
  return html;
}

/**
 * Given as list of types files, return a json that holds the necessary information for the type documentation.
 * It will have a structure like this: {
 *    typeName: TType from the requirejs call,
 *    nextTypeName: . . . ,
 *    }
 *
 * Parameterized types like TTandemEmitter and TFunctionWrapper are hard coded because they have different constructors.
 * @param ttypeFiles
 */
function getTypeJSON( ttypeFiles ) {

  var result = {};

  // Load the dependencies one at a time. This is a hack workaround that somehow allows requirejs to proceed.  Batching them
  // (that is, loading them with an array) failed for unknown reasons.  See https://github.com/phetsims/phet-io/issues/972
  for ( var i = 0; i < ttypeFiles.length; i++ ) {
    var filename = ttypeFiles[ i ];

    var TType = requirejs( filename );

    // See phetioInherit for more details
    if ( TType.typeName ) {
      result[ TType.typeName ] = TType;
    }
    else {

      // Hack around the parametrized nature of TFunctionWrapper
      if ( filename.indexOf( 'TFunctionWrapper' ) >= 0 ) {
        var returnType = TObject;
        var parameterTypes = [ TObject ];
        var instantiatedType = TType( returnType, parameterTypes );
        result[ instantiatedType.typeName ] = instantiatedType;
      }

      // Hack around the parametrized nature of TTandemEmitter
      else if ( filename.indexOf( 'TTandemEmitter' ) >= 0 ) {
        var tandemEmitterType = TType( [ TObject ] );
        result[ tandemEmitterType.typeName ] = tandemEmitterType;
      }

      else {
        var otherType = TType( TObject );
        result[ otherType.typeName ] = otherType;
      }
    }

    // Hack to clear namespaces so duplicate registration doesn't throw an assertion error.
    for ( var v in global.phet ) {
      if ( global.phet.hasOwnProperty( v ) ) {
        if ( global.phet[ v ].constructor.name === 'Namespace' ) {
          var myObject = global.phet[ v ];

          // Manually clear the namespace so it doesn't complain when getting repopulated in the next run
          for ( var member in myObject ) {
            if ( myObject.hasOwnProperty( member ) ) {
              delete myObject[ member ];
            }
          }
        }
      }
    }
  }
  return result;
}

function getCommonCodeTypeDocs() {
  var commonCodeTTypeFiles = getCommonCodeTTypes();
  var typeJSON = getTypeJSON( commonCodeTTypeFiles );

  return toHTML( typeJSON );
}

function getSimSpecificTypeDocs( simRepoName, simFormalName, simCapsForRequire ) {
  var simHTMLHeader = '
Specific Types for ' + simFormalName + '
';
  var ttypeFiles = [];

  // Get the list of TTypes
  walkSync( '../../../' + simRepoName + '/js', ttypeFiles );

  paths[ simCapsForRequire ] = '../../../' + simRepoName + '/js';
  requirejs.config( {
    paths: paths
  } );
  var typeJSON = getTypeJSON( ttypeFiles );
  var typeHTML = toHTML( typeJSON );
  return typeHTML ? simHTMLHeader + typeHTML : simHTMLHeader + '
There are no specific types for this sim
';
}

// Called from the command line, and not required, option support for both modules, used by the grunt build process. This
// can also be used to update the devGuide in the phet-io-website.
if ( require.main === module ) {
  var args = process.argv;

  // Common code docs
  if ( args.length === 3 && args[ 2 ] === '--common' ) {
    console.log( getCommonCodeTypeDocs() );
  }

  // Sim specific docs
  else if ( args.length === 6 && args[ 2 ] === '--sim' ) {
    var repoName = args[ 3 ];
    var simFormalName = args[ 4 ];
    var requirejsName = args[ 5 ];
    console.log( getSimSpecificTypeDocs( repoName, simFormalName, requirejsName ) );
  }
  else {
    console.error( 'Incorrect usage, given args: ', args );
    console.error( 'Usage for common code \'node ../../createTypeDocumentation.js --common\'\n' +
                   'Usage for a specific sim\'s docs \'node createTypeDocumention.js --sim [repo-name] [\"Sim Formal Name\"] [REQUIRE_JS_REPO_NAME]\'' );
    process.exit();
  }
}
<|endoftext|>


<commit_before>"use strict";

window.name = "NG_DEFER_BOOTSTRAP!";

require.config({
    "baseUrl": "scripts",
    "paths": {
        "config": "config",
        "jQuery": "../lib/jquery.min",
        "bootstrap": "../lib/bootstrap.min",
        "angular": "../lib/angular/angular.min",

        "angular-scenario": "../lib/angular/angular-scenario.min",
        "angular-sanitize": "../lib/angular/angular-sanitize.min",
        "angular-route": "../lib/angular/angular-route.min",
        "angular-resource": "../lib/angular/angular-resource.min",
        "angular-cookies": "../lib/angular/angular-cookies.min",
        "angular-mocks": "../lib/angular/angular-mocks"
    },
    "shim": {
        "jQuery": {exports: "jQuery"},
        "config": {deps: ["jQuery"], exports: "config"},
        "bootstrap": { deps: ["jQuery"], exports: "jQuery"},
        "angular": {deps: ["config", "bootstrap"], exports: "angular"},

        "angular-route": ["angular"],
        "angular-cookies": ["angular"],
        "angular-sanitize": ["angular"],
        "angular-resource": ["angular"],
        "angular-mocks": { deps: ["angular"], exports: "angular.mock"}
    },
    "priority": ["config", "angular"]
});

require(['angular'], function (angular) {
    if (typeof require.iniConfig === "undefined") {
        require.iniConfig = {};
    }

    angular.appConfig = {};
    angular.appConfigValue = function (valueName) {
        if (typeof angular.appConfig[valueName] !== "undefined") {
            return angular.appConfig[valueName];
        } else {
            if (typeof require.iniConfig[valueName] !== "undefined") {
                return require.iniConfig[valueName];
            }
        }
        return "";
    };
});

require([
        "jQuery",
        "angular",

        "design/module",
        "common/module",

        "visitor/module",
        "category/module",
        "pdp/module",
        "cart/module",
        "checkout/module",
        "cms/module"
    ],
    function ($, angular) {
        /**
         * Page loader
         */
        $('#loader .progress-bar').animate({width: '60%'}, 800, function () {
            setTimeout(function () {
                $('#loader .progress-bar').animate({width: '100%'}, 200, function () {
                    $('#loader').animate({opacity: 0}, 400, function () {
                        $(this).css('display', 'none');
                        setTimeout(function () {
                            $('#content').removeClass('ng-hide');
                        }, 100);
                    });
                });
            }, 500);
        });

        angular.element(document).ready(function () {
            angular.referrer = document.referrer;

            //TODO: not sure why we do it this way
            var runApp = function () {

                require(["../theme/scripts/init"], function () {
                    var modules = Object.keys(angular.module);
                    angular.resumeBootstrap(modules);
                });

            };

            runApp();

            /**
             * increase count of visits
             */
            $.ajax({
                url: angular.REST_SERVER_URI + "/rts/visit",
                type: "POST",
                xhrFields: {
                    withCredentials: true
                },
                headers: {
                    "X-Referer": angular.referrer
                }
            });
        });
    }
);

<commit_msg>improve todo comment<commit_after>"use strict";

window.name = "NG_DEFER_BOOTSTRAP!";

require.config({
    "baseUrl": "scripts",
    "paths": {
        "config": "config",
        "jQuery": "../lib/jquery.min",
        "bootstrap": "../lib/bootstrap.min",
        "angular": "../lib/angular/angular.min",

        "angular-scenario": "../lib/angular/angular-scenario.min",
        "angular-sanitize": "../lib/angular/angular-sanitize.min",
        "angular-route": "../lib/angular/angular-route.min",
        "angular-resource": "../lib/angular/angular-resource.min",
        "angular-cookies": "../lib/angular/angular-cookies.min",
        "angular-mocks": "../lib/angular/angular-mocks"
    },
    "shim": {
        "jQuery": {exports: "jQuery"},
        "config": {deps: ["jQuery"], exports: "config"},
        "bootstrap": { deps: ["jQuery"], exports: "jQuery"},
        "angular": {deps: ["config", "bootstrap"], exports: "angular"},

        "angular-route": ["angular"],
        "angular-cookies": ["angular"],
        "angular-sanitize": ["angular"],
        "angular-resource": ["angular"],
        "angular-mocks": { deps: ["angular"], exports: "angular.mock"}
    },
    "priority": ["config", "angular"]
});

require(['angular'], function (angular) {
    if (typeof require.iniConfig === "undefined") {
        require.iniConfig = {};
    }

    angular.appConfig = {};
    angular.appConfigValue = function (valueName) {
        if (typeof angular.appConfig[valueName] !== "undefined") {
            return angular.appConfig[valueName];
        } else {
            if (typeof require.iniConfig[valueName] !== "undefined") {
                return require.iniConfig[valueName];
            }
        }
        return "";
    };
});

require([
        "jQuery",
        "angular",

        "design/module",
        "common/module",

        "visitor/module",
        "category/module",
        "pdp/module",
        "cart/module",
        "checkout/module",
        "cms/module"
    ],
    function ($, angular) {
        /**
         * Page loader
         */
        $('#loader .progress-bar').animate({width: '60%'}, 800, function () {
            setTimeout(function () {
                $('#loader .progress-bar').animate({width: '100%'}, 200, function () {
                    $('#loader').animate({opacity: 0}, 400, function () {
                        $(this).css('display', 'none');
                        setTimeout(function () {
                            $('#content').removeClass('ng-hide');
                        }, 100);
                    });
                });
            }, 500);
        });

        angular.element(document).ready(function () {
            angular.referrer = document.referrer;

            //TODO: We should find a better way to do this
            // instead of loading in theme files here
            var runApp = function () {

                require(["../theme/scripts/init"], function () {
                    var modules = Object.keys(angular.module);
                    angular.resumeBootstrap(modules);
                });

            };

            runApp();

            /**
             * increase count of visits
             */
            $.ajax({
                url: angular.REST_SERVER_URI + "/rts/visit",
                type: "POST",
                xhrFields: {
                    withCredentials: true
                },
                headers: {
                    "X-Referer": angular.referrer
                }
            });
        });
    }
);

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
    Header,
} from "semantic-ui-react";

import './App.css';

class App extends Component {
    render() {
        return (

                    Project Mini-Mek

        );
    }
}

export default App;
<commit_msg>Render initial hardcoded tab bar<commit_after>import React, { Component } from 'react';
import {
    Header,
    Container,
    Menu,
} from "semantic-ui-react";

import './App.css';

class App extends Component {
    render() {
        return (

                    Project Mini-Mek

                <Container>
                    <Menu tabular size="massive">
                        <Menu.Item name="unitInfo" active={true}>Unit Info</Menu.Item>
                        <Menu.Item name="pilots" active={false}>Pilots</Menu.Item>
                        <Menu.Item name="mechs" active={false}>Mechs</Menu.Item>
                        <Menu.Item name="unitOrganization" active={false}>Unit Organization</Menu.Item>
                    </Menu>
                </Container>

        );
    }
}

export default App;
<|endoftext|>


<commit_before>(function ynabEnhancedInjectCollapseBudgetInitializer() {
  if (typeof Em !== 'undefined' && typeof Ember !== 'undefined') {

    $(document).on('click', '.undo-redo-container', function(e) {
      var container = $('.undo-redo-container');
      var min = container.offset().left + container.outerWidth() - 2;
      var max = min + 28;

      if (e.pageX >= min && e.pageX <= max) {
        collapseGroups();
      }
    });

    function collapseGroups() {
      var collapsed = false;
      var rows = $('.budget-content').find('.is-master-category');

      if (rows.length) {
        collapsed = $(rows[0]).hasClass('is-collapsed');

        handleGroups(collapsed);
        handleItems(collapsed);
      }
    }

    function handleGroups(collapsed) {
      var rows = $('.budget-content').find('.is-master-category');

      for (i = 0; i < rows.length; i++) {
        if (collapsed) {
          $(rows[i]).removeClass('is-collapsed');
          $(rows[i]).find('.budget-table-cell-name-static-width')
            .find('.button').removeClass('right').addClass('down');
        } else {
          $(rows[i]).addClass('is-collapsed');
          $(rows[i]).find('.budget-table-cell-name-static-width')
            .find('.button').removeClass('down').addClass('right');
        }
      }
    }

    function handleItems(collapsed) {
      var rows = $('.budget-content').find('.is-sub-category');

      for (i = 0; i < rows.length; i++) {
        if (collapsed) {
          $(rows[i]).show();
        } else {
          $(rows[i]).hide();
        }
      }
    }
  } else {
    setTimeout(ynabEnhancedInjectCollapseBudgetInitializer, 250);
  }
})();
<commit_msg>Moved feature to collapse budget rows into ynabToolKit object<commit_after>(function poll() {
  if ( typeof ynabToolKit !== "undefined"  && ynabToolKit.pageReady === true ) {

    ynabToolKit.featureOptions.collapseBudget = true;
    ynabToolKit.collapseBudget = function ()  {

     $(document).on('click', '.undo-redo-container', function(e) {
        var container = $('.undo-redo-container');
        var min = container.offset().left + container.outerWidth() - 2;
        var max = min + 28;

        if (e.pageX >= min && e.pageX <= max) {
          collapseGroups();
        }
      });

      function collapseGroups() {
        var collapsed = false;
        var rows = $('.budget-content').find('.is-master-category');

        if (rows.length) {
          collapsed = $(rows[0]).hasClass('is-collapsed');

          handleGroups(collapsed);
          handleItems(collapsed);
        }
      }

      function handleGroups(collapsed) {
        var rows = $('.budget-content').find('.is-master-category');

        for (i = 0; i < rows.length; i++) {
          if (collapsed) {
            $(rows[i]).removeClass('is-collapsed');
            $(rows[i]).find('.budget-table-cell-name-static-width')
              .find('.button').removeClass('right').addClass('down');
          } else {
            $(rows[i]).addClass('is-collapsed');
            $(rows[i]).find('.budget-table-cell-name-static-width')
              .find('.button').removeClass('down').addClass('right');
          }
        }
      }

      function handleItems(collapsed) {
        var rows = $('.budget-content').find('.is-sub-category');

        for (i = 0; i < rows.length; i++) {
          if (collapsed) {
            $(rows[i]).show();
          } else {
            $(rows[i]).hide();
          }
        }
      }

    };

    setTimeout(ynabToolKit.collapseBudget, 250);
  } else {
    setTimeout(poll, 250);
  }
})();

<|endoftext|>


<commit_before>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.021'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var i = 0;
var IdleStatus = 0;
var incoming_ONG = 0;
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var NinjaAutoClickStatus = 1;
var RKAutoClickStatus = 0;
var RKAlertFrequency = 8;
var Time_to_ONG = 1800000;
var RKType = 'abc123';

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function RedundaKitty() {
	i = Molpy.redactedToggle - Molpy.redactedCountup;

	if (Molpy.redactedVisible > 0) {
		//Border CSS change works on RK and LC.
		g(redacteditem).css("border","2px solid red");
		//var content = $('#redacteditem').innerHTML;
		//Clicks if RedundaKitty AutoClicker Enabled and Not a Logicat
		if (RKAutoClickStatus == 1 && Molpy.redactedPuzzleTarget == undefined) {
			Molpy.ClickRedacted();
			//$(":button").click();
		}
		//else if (LCAutoClickStatus == 1 && Molpy.redactedPuzzleTarget != undefined) {
			//Logicat();
		//}
		else {
			//Redundakitty Notifications (Title Bar and Audio)
			document.title = "! kitten !";
			if (Math.floor(i % RKAlertFrequency) == 0 && (AudioAlertsStatus == 1 || AudioAlertsStatus == 3)) {
				audio_Bell.play();
			}
		}
	}
	else {
		document.title = Molpy.redactedToggle-Molpy.redactedCountup;
		if (i != 0) { i = 0; }
	}
}

function Logicat() {
	i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);
	Molpy.redactedPuzzleTarget = undefined;

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 1) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'RKAutoClick' || option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error',1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only';}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG';}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status,1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1)

//Main Loop
setInterval(function() {
	//Molpy.Notify(Molpy.redactedToggle, 0);
	Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
    RedundaKitty();
    Ninja();
}, 1800);
<commit_msg>Continuing testing RK vs LC<commit_after>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.021'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var i = 0;
var IdleStatus = 0;
var incoming_ONG = 0;
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var NinjaAutoClickStatus = 1;
var RKAutoClickStatus = 0;
var RKAlertFrequency = 8;
var Time_to_ONG = 1800000;
var RKType = 'abc123';

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function RedundaKitty() {
	i = Molpy.redactedToggle - Molpy.redactedCountup;

	if (Molpy.redactedVisible > 0) {
		//Border CSS change works on RK and LC.
		$('#redacteditem').css("border","2px solid red");
		var content = $('#redacteditem').html();
		if (content.indexOf("statement") !== -1) {
			Molpy.Notify("Redundakitty Found",0);
		}
		//Clicks if RedundaKitty AutoClicker Enabled and Not a Logicat
		if (RKAutoClickStatus == 1 && Molpy.redactedPuzzleTarget == undefined) {
			Molpy.ClickRedacted();
			//$(":button").click();
		}
		//else if (LCAutoClickStatus == 1 && Molpy.redactedPuzzleTarget != undefined) {
			//Logicat();
		//}
		else {
			//Redundakitty Notifications (Title Bar and Audio)
			document.title = "! kitten !";
			if (Math.floor(i % RKAlertFrequency) == 0 && (AudioAlertsStatus == 1 || AudioAlertsStatus == 3)) {
				audio_Bell.play();
			}
		}
	}
	else {
		document.title = Molpy.redactedToggle-Molpy.redactedCountup;
		if (i != 0) { i = 0; }
	}
}

function Logicat() {
	i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);
	Molpy.redactedPuzzleTarget = undefined;

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 1) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'RKAutoClick' || option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error',1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only';}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG';}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status,1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1)

//Main Loop
setInterval(function() {
	//Molpy.Notify(Molpy.redactedToggle, 0);
	Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
    RedundaKitty();
    Ninja();
}, 1800);
<|endoftext|>


<commit_before>(function(angular) {
    'use strict';

    // Ensure FH module is defined
    try {
        angular.module('FH')
    } catch (e) {
        angular.module('FH', []);
    }

    angular.module('FH').service('FH.Act', function($rootScope, $window) {
        var FH_ERRORS = {
            UNKNOWN_ACT: 'no such function',
            INTERNAL_ERROR: 'internal error in',
            TIMEOUT: 'timeout'
        };

        // Controls whether debug logging is enabled
        var printLogs = true;

        /**
         * Log debug output for this module.
         * @param {String}  str
         */
        function debug(str) {
            if(printLogs === true) {
                console.debug('$fh.act ' + new Date().toISOString() + ': ' + str);
            }
        }

        /**
         * Called on a successful act call (when main.js callback is called with a null error param)
         * It is assumed if a request could not be fulfilled res.errors will be defined.
         * @param {String}      actname
         * @param {Object}      res
         * @param {Function}    callback
         */
        function onSuccess(actname, res, callback) {
            // No response body maybe returned.
            // For example "return callback(null, null)" in the cloud
            if(res && res.errors) {
                debug('Called "' + actname + '" successfully but some errors were generated:', JSON.stringify(res.errors, null, 2));
                return callback(res.errors, res);
            }

            debug('Called "' + actname + '" successfully with no errors.');

            return callback(null, res);
        }

        /**
         * Called when an act call has failed.
         * Tries to create a meaningful error string.
         * @param {String}      actname
         * @param {String}      err
         * @param {Object}      details
         * @param {Function}    callback
         */
        function onFail(actname, err, details, callback) {
            // TODO: More investigation into errors Act calls can return
            // Results from "console.log(err, msg)" below:
            // err              |           details
            // -------------------------------------
            // error_ajaxfail   | Object {status: 500, message: "error", error: "what you sent to main.js callback err param goes here!"}
            // error_ajaxfail   | Object {status: 0, message: "timeout", error: ""}

            debug('"' + actname + '" failed with errors:', details);

            // Not sure of other error types thrown
            if(err !== 'error_ajaxfail') {
                console.error('An unknown act call error occrued: ' + err, details);
                return callback('An unknown error occured during a request ( "' + err + '" ).');
            }

            else if(details.error.toLowerCase().indexOf(FH_ERRORS.UNKNOWN_ACT) >= 0) {
                return callback('Unknown cloud action "' + actname+ '" was called. (404)', null);
            }

            else if(details.message.toLowerCase().indexOf(FH_ERRORS.TIMEOUT) >= 0) {
                return callback('Request timed out.', null);
            }

            // Return error that cloud code sent to it's callback
            else {
                return callback(details, null);
            }
        }

        /**
         * Call an action on the cloud.
         * @param {String}      actname
         * @param {Object}      params
         * @param {Function}    callback
         */
        this.callFn = function(actname, params, callback) {
            if(typeof params === 'function') {
                callback = params;
                params = {};
            }

            // Check are we online before trying the request
            if($window.navigator.onLine === true) {
                $fh.act(opts, function(res) {
                    return onSuccess(actname, res, callback);
                }, function(err, msg) {
                    return onFail(actname, err, msg, callback);
                });
            } else {
                debug('Could not call "' + actname + '". No network connection.');
                return callback('You have no network connection. Please enable 3G / Wifi and try again.', null);
            }
        };

        // Disable internal logging by this service.
        this.disableLogging = function() {
            printLogs = false;
        };

        // Disable internal logging by this service.
        this.enableLogging = function() {
            printLogs = true;
        };
    });

})(window.angular);
<commit_msg>Update to assume user doesn't use error prop in success responses. Change logging to support multiple args<commit_after>(function(angular) {
    'use strict';

    // Ensure FH module is defined
    try {
        angular.module('FH')
    } catch (e) {
        angular.module('FH', []);
    }

    angular.module('FH').service('FH.Act', function($rootScope, $window) {
        // Error strings used for error type detection
        var ACT_ERRORS = {
            UNKNOWN_ACT: 'no such function',
            INTERNAL_ERROR: 'internal error in',
            TIMEOUT: 'timeout'
        };

        // Expose error types for checks by user
        var ERRORS = this.ERRORS = {
            UNKNOWN_ACT: 'UNKNOWN_ACT',
            INTERNAL_ERROR: 'INTERNAL_ERROR',
            TIMEOUT: 'TIMEOUT',
            NETWORK: 'NETWORK'
        };

        // Controls whether debug logging is enabled
        var printLogs = true;

        /**
         * Log debug output for this module.
         * @param {String}  str
         */
        function debug() {
            if(printLogs === true) {
                args = Array.prototype.slice.call(arguments);
                args.unshift('$fh.act ' + new Date().toISOString() + ': ');

                console.debug.apply(console, args);
            }
        }

        /**
         * Called on a successful act call (when main.js callback is called with a null error param)
         * It is assumed if a request could not be fulfilled res.errors will be defined.
         * @param {String}      actname
         * @param {Object}      res
         * @param {Function}    callback
         */
        function onSuccess(actname, res, callback) {
            // No response body maybe returned.
            // For example "return callback(null, null)" in the cloud
            debug('Called "' + actname + '" successfully.');

            return callback(null, res);
        }

        /**
         * Called when an act call has failed.
         * Tries to create a meaningful error string.
         * @param {String}      actname
         * @param {String}      err
         * @param {Object}      details
         * @param {Function}    callback
         */
        function onFail(actname, err, details, callback) {
            // TODO: More investigation into errors Act calls can return
            // Results from "console.log(err, msg)" below:
            // err              |           details
            // -------------------------------------
            // error_ajaxfail   | Object {status: 500, message: "error", error: "what you sent to main.js callback err param goes here!"}
            // error_ajaxfail   | Object {status: 0, message: "timeout", error: ""}

            debug('"' + actname + '" failed with errors:', details);

            // Not sure of other error types thrown
            if(err !== 'error_ajaxfail') {
                console.error('An unknown act call error occrued: ' + err, details);
                return callback('An unknown error occured during a request ( "' + err + '" ).');
            }

            else if(details.error.toLowerCase().indexOf(ACT_ERRORS.UNKNOWN_ACT) >= 0) {
                return callback(ERRORS.UNKNOWN_ACT, null);
            }

            else if(details.message.toLowerCase().indexOf(ACT_ERRORS.TIMEOUT) >= 0) {
                debug('Timeout occured calling ')
                return callback(ERRORS.TIMEOUT, null);
            }

            // Return error that cloud code sent to it's callback
            else {
                return callback(details, null);
            }
        }

        /**
         * Call an action on the cloud.
         * @param {String}      actname
         * @param {Object}      params
         * @param {Function}    callback
         */
        this.callFn = function(actname, params, callback) {
            if(typeof params === 'function') {
                callback = params;
                params = {};
            }

            // Check are we online before trying the request
            if($window.navigator.onLine === true) {
                debug('Calling "' + actname + '" cloud side function.');
                $fh.act(opts, function(res) {
                    return onSuccess(actname, res, callback);
                }, function(err, msg) {
                    return onFail(actname, err, msg, callback);
                });
            } else {
                debug('Could not call "' + actname + '". No network connection.');
                return callback(ERRORS.NETWORK, null);
            }
        };

        // Disable internal logging by this service.
        this.disableLogging = function() {
            printLogs = false;
        };

        // Disable internal logging by this service.
        this.enableLogging = function() {
            printLogs = true;
        };
    });

})(window.angular);
<|endoftext|>


<commit_before>import React from 'react'
import { ReservedTokensInputBlock } from './ReservedTokensInputBlock'
import { VALIDATION_TYPES } from '../../utils/constants'
import renderer from 'react-test-renderer'
import Adapter from 'enzyme-adapter-react-15'
import { configure, mount } from 'enzyme'

const { VALID, INVALID } = VALIDATION_TYPES

configure({ adapter: new Adapter() })

describe('ReservedTokensInputBlock', () => {
  let tokenList
  let addCallback
  let removeCallback
  let decimals
  let wrapperMemo, wrapper
  let addressInputMemo, addressInput
  let valueInputMemo, valueInput
  let addressStateMemo, addressState
  let valueStateMemo, valueState

  beforeEach(() => {
    tokenList = [
      {
        addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
        dim: 'tokens',
        value: '120'
      },
      {
        addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
        dim: 'percentage',
        value: '105'
      },
      {
        addr: '0xffcf8fdee72ac11b5c542428b35eef5769c409f0',
        dim: 'percentage',
        value: '100'
      },
      {
        addr: '0x22d491bde2303f2f43325b2108d26f1eaba1e32b',
        dim: 'tokens',
        value: '20'
      }
    ]
    addCallback = jest.fn()
    removeCallback = jest.fn()
    decimals = 3

    wrapperMemo = undefined
    wrapper = () => wrapperMemo || (wrapperMemo = mount(
      <ReservedTokensInputBlock
        tokens={tokenList}
        decimals={decimals}
        addReservedTokensItem={addCallback}
        removeReservedToken={removeCallback}
      />
    ))

    addressInputMemo = undefined
    addressInput = () => addressInputMemo || (addressInputMemo = wrapper().find('input[type="text"]').at(0))

    valueInputMemo = undefined
    valueInput = () => valueInputMemo || (valueInputMemo = wrapper().find('input[type="number"]').at(0))

    addressStateMemo = undefined
    addressState = () => addressStateMemo || (addressStateMemo = wrapper().state('validation').address)

    valueStateMemo = undefined
    valueState = () => valueStateMemo || (valueStateMemo = wrapper().state('validation').value)
  })

  describe('render', () => {
    let componentMemo, component
    beforeEach(() => {
      componentMemo = undefined
      component = () => componentMemo || (componentMemo = renderer.create(
        <ReservedTokensInputBlock
          tokens={tokenList}
          decimals={decimals}
          addReservedTokensItem={addCallback}
          removeReservedToken={removeCallback}
        />
      ))
    })

    it('Should render the component for tokens', () => {
      expect(component().toJSON()).toMatchSnapshot('tokens')
    })

    it('Should render the component for percentage', () => {
      wrapper().find('input[type="radio"]').at(1).simulate('change')
      expect(component().toJSON()).toMatchSnapshot('percentage')
    })

    it('Should render all the tokens passed', () => {
      expect(wrapper().find('.reserved-tokens-item-container')).toHaveLength(tokenList.length)
    })
  })

  describe('Address field', () => {
    [
      { value: '0x123', expected: false },
      { value: '0x90F8bF6A479f320EAD074411A4B0E7944EA8C9C1', expected: false },
      { value: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1', expected: true },
      { value: '0X90f8bf6a479f320ead074411a4b0e7944ea8c9c1', expected: true },
      { value: '0x90F8BF6A479F320EAD074411A4B0E7944EA8C9C1', expected: true },
      { value: '0X90F8BF6A479F320EAD074411A4B0E7944EA8C9C1', expected: true },
    ].forEach(testCase => {
      const action = testCase.expected ? 'pass' : 'fail'
      const validity = testCase.expected ? VALID : INVALID

      it(`Should ${action} for '${testCase.value}'`, () => {
        const handleAddressChange = jest.spyOn(wrapper().instance(), 'handleAddressChange')

        wrapper().update()

        addressInput().simulate('change', { target: { value: testCase.value } })
        expect(handleAddressChange).toHaveBeenCalledTimes(1)
        expect(handleAddressChange).toHaveBeenCalledWith(testCase.value)
        expect(addressState().pristine).toBeFalsy()
        expect(addressState().valid).toBe(validity)
      })
    })
  })

  describe('Dimension selection', () => {
    it('Should set "tokens" as selected dimension', () => {
      const updateReservedTokenInput = jest.spyOn(wrapper().instance(), 'updateReservedTokenInput')

      wrapper().update()

      wrapper().find('input[type="radio"]').at(0).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('tokens', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(1)
      expect(wrapper().state('dim')).toBe('tokens')
    })
    it('Should set "percentage" as selected dimension', () => {
      const updateReservedTokenInput = jest.spyOn(wrapper().instance(), 'updateReservedTokenInput')

      wrapper().update()

      wrapper().find('input[type="radio"]').at(1).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('percentage', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(1)
      expect(wrapper().state('dim')).toBe('percentage')
    })
    it('Should set "tokens" as selected dimension after selecting percentage', () => {
      const updateReservedTokenInput = jest.spyOn(wrapper().instance(), 'updateReservedTokenInput')

      wrapper().update()

      wrapper().find('input[type="radio"]').at(1).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('percentage', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(1)
      expect(wrapper().state('dim')).toBe('percentage')

      wrapper().find('input[type="radio"]').at(0).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('tokens', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(2)
      expect(wrapper().state('dim')).toBe('tokens')
    })
    it('Should fail if state.dim is not "percentage" or "tokens"', () => {
      wrapper().setState({dim: 'height'})
      const radio = wrapper().find('input[type="radio"]')
      const tokens = radio.at(0)
      const percentage = radio.at(1)

      expect(tokens.props().checked).toBeFalsy()
      expect(percentage.props().checked).toBeFalsy()
    })
  })

  describe('Value field', () => {
    describe('tokens', () => {
      [
        { value: '0', expected: false },
        { value: '-10', expected: false },
        { value: -10, expected: false },
        { value: 123.1234, expected: false },
        { value: '10', expected: true },
        { value: 10, expected: true },
        { value: '0.1', expected: true },
        { value: '1e-3', expected: true },
        { value: '1.3', expected: true },
      ].forEach(testCase => {
        const action = testCase.expected ? 'pass' : 'fail'
        const validity = testCase.expected ? VALID : INVALID
        const calledWith = {
          value: testCase.value === '' ? '' : parseFloat(testCase.value),
          pristine: false,
          valid: validity
        }

        it(`Should ${action} for '${testCase.value}' with ${decimals} decimals`, () => {
          const handleValueChange = jest.spyOn(wrapper().instance(), 'handleValueChange')

          wrapper().update()
          wrapper().find('input[type="radio"]').at(0).simulate('change')
          valueInput().simulate('change', { target: { value: testCase.value } })

          expect(handleValueChange).toHaveBeenCalledTimes(1)
          expect(handleValueChange).toHaveBeenCalledWith(calledWith)
        })
      })
    })

    describe('percentage', () => {
      [
        { value: '0', expected: false },
        { value: '-10', expected: false },
        { value: -10, expected: false },
        { value: '10', expected: true },
        { value: 10, expected: true },
        { value: '0.1', expected: true },
        { value: '1e-3', expected: true },
        { value: '1.3', expected: true },
        { value: 123.1234, expected: true },
      ].forEach(testCase => {
        const action = testCase.expected ? 'pass' : 'fail'
        const validity = testCase.expected ? VALID : INVALID
        const calledWith = {
          value: testCase.value === '' ? '' : parseFloat(testCase.value),
          pristine: false,
          valid: validity
        }

        it(`Should ${action} for '${testCase.value}'`, () => {
          const handleValueChange = jest.spyOn(wrapper().instance(), 'handleValueChange')

          wrapper().update()
          wrapper().find('input[type="radio"]').at(1).simulate('change')
          valueInput().simulate('change', { target: { value: testCase.value } })

          expect(handleValueChange).toHaveBeenCalledTimes(2)
          expect(handleValueChange).toHaveBeenCalledWith({
            value: '',
            pristine: true,
            valid: INVALID
          })
          expect(handleValueChange).toHaveBeenCalledWith(calledWith)
        })
      })
    })
  })

  describe('Callbacks', () => {
    describe('addReservedTokensItem', () => {
      [
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '120'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '0.001'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: ''
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '0'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '120.1234'
          },
          expected: false
        },
        {
          value: {
            addr: '',
            dim: 'tokens',
            val: '120'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a4',
            dim: 'tokens',
            val: '120'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c10x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '120'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: '120'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: '120.123'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: ''
          },
          expected: false
        },
        {
          value: {
            addr: '',
            dim: 'percentage',
            val: '120.123'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: '0'
          },
          expected: false
        },
      ].forEach(testCase => {
        const radioIndex = testCase.value.dim === 'tokens' ? 0 : 1
        const action = testCase.expected ? 'call' : 'not call'
        const callTimes = testCase.expected ? 1 : 0

        it(`Should ${action} addReservedTokensItem callback for: ${JSON.stringify(testCase.value)}`, () => {
          wrapper().find('input[type="radio"]').at(radioIndex).simulate('change')

          addressInput().simulate('change', { target: { value: testCase.value.addr } })
          valueInput().simulate('change', { target: { value: testCase.value.val } })

          wrapper().find('.plus-button-container').childAt(0).simulate('click')

          const { value } = testCase
          value.val = testCase.value.val === '' ? '' : parseFloat(testCase.value.val)

          if (testCase.expect) {
            expect(addCallback).toHaveBeenCalledWith(value)
          }
          expect(addCallback).toHaveBeenCalledTimes(callTimes)
        })

      })
    })

    describe('removeReservedToken', () => {
      it('Should call removeReservedToken callback', () => {
        wrapper().find('.reserved-tokens-item-empty').children('a').at(0).simulate('click')
        expect(removeCallback).toHaveBeenCalledTimes(1)
      })
    })
  })

  // it('Should reset state after adding a new address', () => {
  //   const newReserved = {
  //     addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
  //     dim: 'percentage',
  //     val: '120'
  //   }
  //   const addressEvent = { target: { value: newReserved.addr } }
  //   const valueEvent = { target: { value: newReserved.val } }
  //
  //   const handleAddressChange = jest.spyOn(wrapper().instance(), 'handleAddressChange')
  //   const handleValueChange = jest.spyOn(wrapper().instance(), 'handleValueChange')
  //
  //   wrapper().update()
  //
  //   expect(addressState().pristine).toBeTruthy()
  //   expect(addressState().valid).toBe(INVALID)
  //   expect(valueState().pristine).toBeTruthy()
  //   expect(valueState().valid).toBe(INVALID)
  //   expect(wrapper().state('addr')).toBe('')
  //   expect(wrapper().state('dim')).toBe('tokens')
  //   expect(wrapper().state('val')).toBe('')
  //
  //   addressInput().simulate('change', addressEvent)
  //   valueInput().simulate('change', valueEvent)
  //   wrapper().find('input[type="radio"]').at(1).simulate('change')
  //
  //   expect(addressState().pristine).toBeFalsy()
  //   expect(addressState().valid).toBe(VALID)
  //   expect(wrapper().state('addr')).toBe(newReserved.addr)
  //   expect(handleAddressChange).toHaveBeenCalledTimes(1)
  //   expect(handleAddressChange).toHaveBeenCalledWith(newReserved.addr)
  //
  //   expect(valueState().pristine).toBeFalsy()
  //   expect(valueState().valid).toBe(VALID)
  //   expect(wrapper().state('val')).toBe(newReserved.val)
  //   expect(handleValueChange).toHaveBeenCalledTimes(1)
  //   expect(handleValueChange).toHaveBeenCalledWith(newReserved.val)
  //
  //   expect(wrapper().state('dim')).toBe(newReserved.dim)
  //
  //   wrapper().find('.plus-button-container').childAt(0).simulate('click')
  //
  //   expect(addressState().pristine).toBeTruthy()
  //   expect(addressState().valid).toBe(INVALID)
  //   expect(valueState().pristine).toBeTruthy()
  //   expect(valueState().valid).toBe(INVALID)
  //   expect(wrapper().state('addr')).toBe('')
  //   expect(wrapper().state('dim')).toBe('tokens')
  //   expect(wrapper().state('val')).toBe('')
  // })

})
<commit_msg>Remove commented code<commit_after>import React from 'react'
import { ReservedTokensInputBlock } from './ReservedTokensInputBlock'
import { VALIDATION_TYPES } from '../../utils/constants'
import renderer from 'react-test-renderer'
import Adapter from 'enzyme-adapter-react-15'
import { configure, mount } from 'enzyme'

const { VALID, INVALID } = VALIDATION_TYPES

configure({ adapter: new Adapter() })

describe('ReservedTokensInputBlock', () => {
  let tokenList
  let addCallback
  let removeCallback
  let decimals
  let wrapperMemo, wrapper
  let addressInputMemo, addressInput
  let valueInputMemo, valueInput
  let addressStateMemo, addressState
  let valueStateMemo, valueState

  beforeEach(() => {
    tokenList = [
      {
        addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
        dim: 'tokens',
        value: '120'
      },
      {
        addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
        dim: 'percentage',
        value: '105'
      },
      {
        addr: '0xffcf8fdee72ac11b5c542428b35eef5769c409f0',
        dim: 'percentage',
        value: '100'
      },
      {
        addr: '0x22d491bde2303f2f43325b2108d26f1eaba1e32b',
        dim: 'tokens',
        value: '20'
      }
    ]
    addCallback = jest.fn()
    removeCallback = jest.fn()
    decimals = 3

    wrapperMemo = undefined
    wrapper = () => wrapperMemo || (wrapperMemo = mount(
      <ReservedTokensInputBlock
        tokens={tokenList}
        decimals={decimals}
        addReservedTokensItem={addCallback}
        removeReservedToken={removeCallback}
      />
    ))

    addressInputMemo = undefined
    addressInput = () => addressInputMemo || (addressInputMemo = wrapper().find('input[type="text"]').at(0))

    valueInputMemo = undefined
    valueInput = () => valueInputMemo || (valueInputMemo = wrapper().find('input[type="number"]').at(0))

    addressStateMemo = undefined
    addressState = () => addressStateMemo || (addressStateMemo = wrapper().state('validation').address)

    valueStateMemo = undefined
    valueState = () => valueStateMemo || (valueStateMemo = wrapper().state('validation').value)
  })

  describe('render', () => {
    let componentMemo, component
    beforeEach(() => {
      componentMemo = undefined
      component = () => componentMemo || (componentMemo = renderer.create(
        <ReservedTokensInputBlock
          tokens={tokenList}
          decimals={decimals}
          addReservedTokensItem={addCallback}
          removeReservedToken={removeCallback}
        />
      ))
    })

    it('Should render the component for tokens', () => {
      expect(component().toJSON()).toMatchSnapshot('tokens')
    })

    it('Should render the component for percentage', () => {
      wrapper().find('input[type="radio"]').at(1).simulate('change')
      expect(component().toJSON()).toMatchSnapshot('percentage')
    })

    it('Should render all the tokens passed', () => {
      expect(wrapper().find('.reserved-tokens-item-container')).toHaveLength(tokenList.length)
    })
  })

  describe('Address field', () => {
    [
      { value: '0x123', expected: false },
      { value: '0x90F8bF6A479f320EAD074411A4B0E7944EA8C9C1', expected: false },
      { value: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1', expected: true },
      { value: '0X90f8bf6a479f320ead074411a4b0e7944ea8c9c1', expected: true },
      { value: '0x90F8BF6A479F320EAD074411A4B0E7944EA8C9C1', expected: true },
      { value: '0X90F8BF6A479F320EAD074411A4B0E7944EA8C9C1', expected: true },
    ].forEach(testCase => {
      const action = testCase.expected ? 'pass' : 'fail'
      const validity = testCase.expected ? VALID : INVALID

      it(`Should ${action} for '${testCase.value}'`, () => {
        const handleAddressChange = jest.spyOn(wrapper().instance(), 'handleAddressChange')

        wrapper().update()

        addressInput().simulate('change', { target: { value: testCase.value } })
        expect(handleAddressChange).toHaveBeenCalledTimes(1)
        expect(handleAddressChange).toHaveBeenCalledWith(testCase.value)
        expect(addressState().pristine).toBeFalsy()
        expect(addressState().valid).toBe(validity)
      })
    })
  })

  describe('Dimension selection', () => {
    it('Should set "tokens" as selected dimension', () => {
      const updateReservedTokenInput = jest.spyOn(wrapper().instance(), 'updateReservedTokenInput')

      wrapper().update()

      wrapper().find('input[type="radio"]').at(0).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('tokens', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(1)
      expect(wrapper().state('dim')).toBe('tokens')
    })
    it('Should set "percentage" as selected dimension', () => {
      const updateReservedTokenInput = jest.spyOn(wrapper().instance(), 'updateReservedTokenInput')

      wrapper().update()

      wrapper().find('input[type="radio"]').at(1).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('percentage', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(1)
      expect(wrapper().state('dim')).toBe('percentage')
    })
    it('Should set "tokens" as selected dimension after selecting percentage', () => {
      const updateReservedTokenInput = jest.spyOn(wrapper().instance(), 'updateReservedTokenInput')

      wrapper().update()

      wrapper().find('input[type="radio"]').at(1).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('percentage', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(1)
      expect(wrapper().state('dim')).toBe('percentage')

      wrapper().find('input[type="radio"]').at(0).simulate('change')
      expect(updateReservedTokenInput).toHaveBeenCalledWith('tokens', 'dim')
      expect(updateReservedTokenInput).toHaveBeenCalledTimes(2)
      expect(wrapper().state('dim')).toBe('tokens')
    })
    it('Should fail if state.dim is not "percentage" or "tokens"', () => {
      wrapper().setState({dim: 'height'})
      const radio = wrapper().find('input[type="radio"]')
      const tokens = radio.at(0)
      const percentage = radio.at(1)

      expect(tokens.props().checked).toBeFalsy()
      expect(percentage.props().checked).toBeFalsy()
    })
  })

  describe('Value field', () => {
    describe('tokens', () => {
      [
        { value: '0', expected: false },
        { value: '-10', expected: false },
        { value: -10, expected: false },
        { value: 123.1234, expected: false },
        { value: '10', expected: true },
        { value: 10, expected: true },
        { value: '0.1', expected: true },
        { value: '1e-3', expected: true },
        { value: '1.3', expected: true },
      ].forEach(testCase => {
        const action = testCase.expected ? 'pass' : 'fail'
        const validity = testCase.expected ? VALID : INVALID
        const calledWith = {
          value: testCase.value === '' ? '' : parseFloat(testCase.value),
          pristine: false,
          valid: validity
        }

        it(`Should ${action} for '${testCase.value}' with ${decimals} decimals`, () => {
          const handleValueChange = jest.spyOn(wrapper().instance(), 'handleValueChange')

          wrapper().update()
          wrapper().find('input[type="radio"]').at(0).simulate('change')
          valueInput().simulate('change', { target: { value: testCase.value } })

          expect(handleValueChange).toHaveBeenCalledTimes(1)
          expect(handleValueChange).toHaveBeenCalledWith(calledWith)
        })
      })
    })

    describe('percentage', () => {
      [
        { value: '0', expected: false },
        { value: '-10', expected: false },
        { value: -10, expected: false },
        { value: '10', expected: true },
        { value: 10, expected: true },
        { value: '0.1', expected: true },
        { value: '1e-3', expected: true },
        { value: '1.3', expected: true },
        { value: 123.1234, expected: true },
      ].forEach(testCase => {
        const action = testCase.expected ? 'pass' : 'fail'
        const validity = testCase.expected ? VALID : INVALID
        const calledWith = {
          value: testCase.value === '' ? '' : parseFloat(testCase.value),
          pristine: false,
          valid: validity
        }

        it(`Should ${action} for '${testCase.value}'`, () => {
          const handleValueChange = jest.spyOn(wrapper().instance(), 'handleValueChange')

          wrapper().update()
          wrapper().find('input[type="radio"]').at(1).simulate('change')
          valueInput().simulate('change', { target: { value: testCase.value } })

          expect(handleValueChange).toHaveBeenCalledTimes(2)
          expect(handleValueChange).toHaveBeenCalledWith({
            value: '',
            pristine: true,
            valid: INVALID
          })
          expect(handleValueChange).toHaveBeenCalledWith(calledWith)
        })
      })
    })
  })

  describe('Callbacks', () => {
    describe('addReservedTokensItem', () => {
      [
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '120'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '0.001'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: ''
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '0'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '120.1234'
          },
          expected: false
        },
        {
          value: {
            addr: '',
            dim: 'tokens',
            val: '120'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a4',
            dim: 'tokens',
            val: '120'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c10x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'tokens',
            val: '120'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: '120'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: '120.123'
          },
          expected: true
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: ''
          },
          expected: false
        },
        {
          value: {
            addr: '',
            dim: 'percentage',
            val: '120.123'
          },
          expected: false
        },
        {
          value: {
            addr: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
            dim: 'percentage',
            val: '0'
          },
          expected: false
        },
      ].forEach(testCase => {
        const radioIndex = testCase.value.dim === 'tokens' ? 0 : 1
        const action = testCase.expected ? 'call' : 'not call'
        const callTimes = testCase.expected ? 1 : 0

        it(`Should ${action} addReservedTokensItem callback for: ${JSON.stringify(testCase.value)}`, () => {
          wrapper().find('input[type="radio"]').at(radioIndex).simulate('change')

          addressInput().simulate('change', { target: { value: testCase.value.addr } })
          valueInput().simulate('change', { target: { value: testCase.value.val } })

          wrapper().find('.plus-button-container').childAt(0).simulate('click')

          const { value } = testCase
          value.val = testCase.value.val === '' ? '' : parseFloat(testCase.value.val)

          if (testCase.expect) {
            expect(addCallback).toHaveBeenCalledWith(value)
          }
          expect(addCallback).toHaveBeenCalledTimes(callTimes)
        })

      })
    })

    describe('removeReservedToken', () => {
      it('Should call removeReservedToken callback', () => {
        wrapper().find('.reserved-tokens-item-empty').children('a').at(0).simulate('click')
        expect(removeCallback).toHaveBeenCalledTimes(1)
      })
    })
  })
})
<|endoftext|>


<commit_before>angular.module('exceptionless', [])
    .constant('$ExceptionlessClient', Exceptionless.ExceptionlessClient.default)
    .factory('exceptionlessHttpInterceptor', ['$q', '$ExceptionlessClient', function ($q, $ExceptionlessClient) {
        return {
            responseError: function responseError(rejection) {
                if (rejection.status === 404) {
                    $ExceptionlessClient.submitNotFound(rejection.config.url);
                }
                else {
                    $ExceptionlessClient.createUnhandledException(new Error('HTTP response error'), 'errorHttpInterceptor')
                        .setSource(rejection.config.url)
                        .setProperty('status', rejection.status)
                        .setProperty('config', rejection.config)
                        .submit();
                }
                return $q.reject(rejection);
            }
        };
    }])
    .config(['$httpProvider', '$provide', '$ExceptionlessClient', function ($httpProvider, $provide, $ExceptionlessClient) {
        $httpProvider.interceptors.push('exceptionlessHttpInterceptor');
        $provide.decorator('$exceptionHandler', ['$delegate', function ($delegate) {
                return function (exception, cause) {
                    $delegate(exception, cause);
                    $ExceptionlessClient.createUnhandledException(exception, '$exceptionHandler').setMessage(cause).submit();
                };
            }]);
        $provide.decorator('$log', ['$delegate', function ($delegate) {
                function decorateRegularCall(property, logLevel) {
                    var previousFn = $delegate[property];
                    return $delegate[property] = function () {
                        previousFn.call(null, arguments);
                        $ExceptionlessClient.submitLog(null, arguments[0], logLevel);
                    };
                }
                $delegate.log = decorateRegularCall('log', 'Trace');
                $delegate.info = decorateRegularCall('info', 'Info');
                $delegate.warn = decorateRegularCall('warn', 'Warn');
                $delegate.debug = decorateRegularCall('debug', 'Debug');
                $delegate.error = decorateRegularCall('error', 'Error');
                return $delegate;
            }]);
    }])
    .run(['$rootScope', '$ExceptionlessClient', function ($rootScope, $ExceptionlessClient) {
        $rootScope.$on('$routeChangeSuccess', function (event, next, current) {
            $ExceptionlessClient.createFeatureUsage(current.name)
                .setProperty('next', next)
                .setProperty('current', current)
                .submit();
        });
        $rootScope.$on('$routeChangeError', function (event, current, previous, rejection) {
            $ExceptionlessClient.createUnhandledException(new Error(rejection), '$routeChangeError')
                .setProperty('current', current)
                .setProperty('previous', previous)
                .submit();
        });
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (toState.name === 'otherwise') {
                return;
            }
            $ExceptionlessClient.createFeatureUsage(toState.controller || toState.name)
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$stateNotFound', function (event, unfoundState, fromState, fromParams) {
            $ExceptionlessClient.createNotFound(unfoundState.to)
                .setProperty('unfoundState', unfoundState)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
            if (!error) {
                return;
            }
            $ExceptionlessClient.createUnhandledException(error, '$stateChangeError')
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$destroy', function () {
            $ExceptionlessClient.config.queue.process();
        });
    }]);
<commit_msg>ignore 401 errors<commit_after>angular.module('exceptionless', [])
    .constant('$ExceptionlessClient', Exceptionless.ExceptionlessClient.default)
    .factory('exceptionlessHttpInterceptor', ['$q', '$ExceptionlessClient', function ($q, $ExceptionlessClient) {
        return {
            responseError: function responseError(rejection) {
                if (rejection.status === 404) {
                    $ExceptionlessClient.submitNotFound(rejection.config.url);
                }
                else if (rejection.status !== 401) {
                    $ExceptionlessClient.createUnhandledException(new Error('HTTP response error'), 'errorHttpInterceptor')
                        .setSource(rejection.config.url)
                        .setProperty('status', rejection.status)
                        .setProperty('config', rejection.config)
                        .submit();
                }
                return $q.reject(rejection);
            }
        };
    }])
    .config(['$httpProvider', '$provide', '$ExceptionlessClient', function ($httpProvider, $provide, $ExceptionlessClient) {
        $httpProvider.interceptors.push('exceptionlessHttpInterceptor');
        $provide.decorator('$exceptionHandler', ['$delegate', function ($delegate) {
                return function (exception, cause) {
                    $delegate(exception, cause);
                    $ExceptionlessClient.createUnhandledException(exception, '$exceptionHandler').setMessage(cause).submit();
                };
            }]);
        $provide.decorator('$log', ['$delegate', function ($delegate) {
                function decorateRegularCall(property, logLevel) {
                    var previousFn = $delegate[property];
                    return $delegate[property] = function () {
                        previousFn.call(null, arguments);
                        $ExceptionlessClient.submitLog(null, arguments[0], logLevel);
                    };
                }
                $delegate.log = decorateRegularCall('log', 'Trace');
                $delegate.info = decorateRegularCall('info', 'Info');
                $delegate.warn = decorateRegularCall('warn', 'Warn');
                $delegate.debug = decorateRegularCall('debug', 'Debug');
                $delegate.error = decorateRegularCall('error', 'Error');
                return $delegate;
            }]);
    }])
    .run(['$rootScope', '$ExceptionlessClient', function ($rootScope, $ExceptionlessClient) {
        $rootScope.$on('$routeChangeSuccess', function (event, next, current) {
            $ExceptionlessClient.createFeatureUsage(current.name)
                .setProperty('next', next)
                .setProperty('current', current)
                .submit();
        });
        $rootScope.$on('$routeChangeError', function (event, current, previous, rejection) {
            $ExceptionlessClient.createUnhandledException(new Error(rejection), '$routeChangeError')
                .setProperty('current', current)
                .setProperty('previous', previous)
                .submit();
        });
        $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
            if (toState.name === 'otherwise') {
                return;
            }
            $ExceptionlessClient.createFeatureUsage(toState.controller || toState.name)
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$stateNotFound', function (event, unfoundState, fromState, fromParams) {
            $ExceptionlessClient.createNotFound(unfoundState.to)
                .setProperty('unfoundState', unfoundState)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
            if (!error) {
                return;
            }
            $ExceptionlessClient.createUnhandledException(error, '$stateChangeError')
                .setProperty('toState', toState)
                .setProperty('toParams', toParams)
                .setProperty('fromState', fromState)
                .setProperty('fromParams', fromParams)
                .submit();
        });
        $rootScope.$on('$destroy', function () {
            $ExceptionlessClient.config.queue.process();
        });
    }]);
<|endoftext|>


<commit_before>/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
/* eslint-disable max-len */

import deprecatedProperty from '../../utilities/warning/deprecated-property';
import getComponentDocFn from '../../utilities/get-component-doc';

let checkProps = function() {};

if (process.env.NODE_ENV !== 'production') {
	checkProps = function(COMPONENT, props, jsonDoc) {
		const createDocUrl = getComponentDocFn(jsonDoc);
		deprecatedProperty(
			COMPONENT,
			props.closeButtonAssistiveText,
			'closeButtonAssistiveText',
			"assistiveText['closeButton']",
			createDocUrl('assistiveText')
		);
		deprecatedProperty(COMPONENT, props.title, 'title', 'heading');
	};
}

export default checkProps;
<commit_msg>Modal: Add createDocUrl to checkProps<commit_after>/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
/* eslint-disable max-len */

import deprecatedProperty from '../../utilities/warning/deprecated-property';
import getComponentDocFn from '../../utilities/get-component-doc';

let checkProps = function() {};

if (process.env.NODE_ENV !== 'production') {
	checkProps = function(COMPONENT, props, jsonDoc) {
		const createDocUrl = getComponentDocFn(jsonDoc);
		deprecatedProperty(
			COMPONENT,
			props.closeButtonAssistiveText,
			'closeButtonAssistiveText',
			"assistiveText['closeButton']",
			createDocUrl('assistiveText')
		);
		deprecatedProperty(
			COMPONENT,
			props.title,
			'title',
			'heading',
			createDocUrl('tiheadingtle')
		);
	};
}

export default checkProps;
<|endoftext|>