<commit_before>
'use strict';

/**
 * @ngdoc function
 * @name Teem.controller:ProjectsCtrl
 * @description
 * # ProjectsCtrl
 * Controller of the Teem
 */

angular.module('Teem')
  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider
      .when('/teems/featured', {
        templateUrl: 'projects/index.html',
        // We need this route here to take precendence on /teems/:id
        // but note we are using the projects (plural) controller
        controller: 'ProjectsCtrl'
      })
      // Transition from old paths
      .when('/projects/:id/:new?', {
        redirectTo: function(params) {
          return '/teems/' + params.id;
        }
      })
      .when('/teems/new', {
        templateUrl: 'projects/project.html',
        // We need this route here to take precendence on /teems/:id
        // but note we are using the projects (plural) controller
        controller: 'ProjectsCtrl'
      })
      .when('/teems/:id', {
        templateUrl: 'projects/project.html',
        controller: 'ProjectCtrl',
        // Change between tabs without re-rendering the view
        reloadOnSearch: false
      })
      // Getting a project from projects widget
      .when('/communities/:communityId/teems/fetch/:id', {
        controller: 'FetchProject',
        template: ''
      })
      // Old stuff
      .when('/communities/:communityId/teems/:id', {
        redirectTo: function(params) {
          return '/teems/' + params.id;
        }
      })
      .when('/communities/:communityId/teems/:id/:tab', {
        redirectTo: function(params) {
          return '/teems/' + params.id + '?tab=' + params.tab;
        }
      });
  }])
  .controller('FetchProject', [
  'ProjectsSvc', 'Url', '$route', '$location', 'SessionSvc',
  function(ProjectsSvc, Url, $route, $location, SessionSvc) {

    var communityId = Url.decode($route.current.params.communityId),
        localId     = $route.current.params.id;

    SessionSvc.onLoad(() => {

      ProjectsSvc.all({
        community: communityId,
        localId: localId
      }).then(function(projects) {

        var project = projects[0];

        if (project) {
          $location.path(project.path());
          return;
        }

        ProjectsSvc.create({
          communityId:  communityId
        }).then(function(project) {
          project.localId = localId;

          $location.path(project.path());
        });
      });
    });
  }])
  .controller('ProjectCtrl', [
  'SessionSvc', '$scope', '$rootScope', '$location', '$route', '$timeout', 'swellRT', '$filter',
  'SharedState', 'ProjectsSvc', 'Loading', '$window', 'CommunitiesSvc', 'User', 'Selector',
  function (SessionSvc, $scope, $rootScope, $location, $route, $timeout, swellRT, $filter,
  SharedState, ProjectsSvc, Loading, $window, CommunitiesSvc, User, Selector) {

    // Prevent users from forging the form parameter
    // and set the form order
    const Forms = [ 'image', 'details', 'share', 'congrats' ];

    // Use them in steps template
    $scope.formSteps = Forms;

    // Hack to hide the navbar
    // We should be using the class .has-navbar-top automatically added by
    // mobile-angular-ui, it should be removed when the navbar is removed
    // by ui-content-for, but it is not happening
    $rootScope.noNavbarTop = true;
    $scope.$on('$destroy', () => {
      $rootScope.noNavbarTop = false;
    });

    var editingTitle = false;

    // FIXME Defined here instead of inside pad because when pad scope is destroyed,
    // `editing` variable can't be accessed, and it is used outside pad.
    $scope.pad = {
      editing: false,
      saving: false,
      outline: []
    };
    $scope.pic = {};

    $scope.editOff = function() {
      angular.element(document.querySelector('pad')).scope().editOff();
    };

    $scope.invite = {
      list : [],
      selected : []
    };

    var initialize = function(){
      Loading.show(ProjectsSvc.findByUrlId($route.current.params.id)).
        then(function(project) {
          $scope.project = project;
          Selector.populateUserSelector($scope.invite.list, $scope.project.communities);

          $rootScope.og = {
            title: project.title,
            description: project.pad.text().substring(0, 200),
            url: project.url(),
            image: project.logoUrl()
          };

          if($location.search().tab === 'chat' && !$scope.project.isParticipant()){
            SharedState.setOne('projectTab', 'pad');
          }

          CommunitiesSvc.all({ ids: project.communities }).then(function (communities) {
            $timeout(function() {
              $scope.communities = communities;
            });
          });
          $timeout();
        });
    };

    SessionSvc.onLoad(initialize);

    function currentTab() {
      return $location.search().tab || 'pad';
    }

    SharedState.initialize($scope, 'projectTab', {
      defaultValue: currentTab()
    });

    function swipeToProjectTab(tab) {
      return function(event) {
        if (event.pointerType === 'touch') {
          SharedState.set('projectTab', tab);
        }
      };
    }

    $scope.swipeToPad = swipeToProjectTab('pad');
    $scope.swipeToNeeds = swipeToProjectTab('needs');
    $scope.swipeToChat = swipeToProjectTab('chat');

    $scope.hmManagerOpt = '{"cssProps": {"userSelect": true}}';
    $scope.hmRecognizerOpt = '{"threshold": 200}';

    SharedState.initialize($scope, 'hiddenTabs');
    $scope.areTabsHidden = function() {
      return SharedState.isActive('hiddenTabs') && $window.innerHeight < 400;
    };

    $scope.form = function () {
      var f = $route.current.params.form;

      if (f && Forms.indexOf(f) >= 0) {
        return f;
      }
    };

    $scope.formStep = function() {
      return Forms.indexOf($route.current.params.form) + 1;
    };

    $scope.nextForm = function () {
      var index = Forms.indexOf($route.current.params.form) + 1;

      if (index > 0 && index < Forms.length) {
        return Forms[index];
      }

      return null;
    };

    $scope.goToNextForm = function () {
      if ($scope.form() === 'image' && $scope.pic.croppedPicture) {
        $scope.uploadProjectPhoto($filter('dataUriToBlob')($scope.pic.croppedPicture));
      }
      $location.search('form', $scope.nextForm());
    };

    $scope.uploadProjectPhoto = function(file) {
      $scope.project.image = new swellRT.FileObject(file);
    };

    $scope.editingTitle = function() {
      return editingTitle || $scope.isNew();
    };

    $scope.infoTip = function(close) {
      if (close) {
        localStorage.setItem('clickToTap', true);
      }
      return !localStorage.getItem('clickToTap');
    };

    $scope.showEditTitle = function() {
      editingTitle = true;
    };

    $scope.hideEditTitle = function() {
      editingTitle = false;
    };

    $scope.createProject = function() {
      let params = {};

      ProjectsSvc.create(params, function(p) {
        $location.path(p.path()).search('form', 'image');
      });
    };

    $scope.$on('mobile-angular-ui.state.changed.projectTab', function(e, newVal, oldVal) {
      $scope.project.setTimestampAccess(oldVal);
      $scope.project.setTimestampAccess(newVal);

      $location.search({ tab: newVal});

      $scope.pad.editing = false;
    });

      $scope.$on('$routeChangeStart', function(event, next, current) {
      if (current.params.tab !== undefined && $scope.project!== undefined) {
        $scope.project.setTimestampAccess(current.params.tab);
      }
    });

    $scope.cancelProject = function() {
      SharedState.turnOff('modal.confirm');

      $scope.project.delete();

      if ($location.search('form')) {
        $location.search('form', null);

        $location.path('/teems');
      } else {
        $location.path('/home/teems');
      }
    };

    $scope.hasChanged = function(section){

      if(!$scope.project || ! $scope.project.lastChange(section) ||
        !$scope.project.isParticipant()){
        return false;
      }

      var lastChange = $scope.project.lastChange(section);
      var lastAccess;
          if ($scope.project.getTimestampAccess() &&
            $scope.project.getTimestampAccess()[section]) {
            lastAccess = new Date(($scope.project.getTimestampAccess()[section]).last);
          } else {
            lastAccess = new Date(0);
          }
      return lastChange > lastAccess;
    };

    $scope.communitySelector = {
      options: [],
      config: {
        create: function(input, callback) {
          CommunitiesSvc.create({ name: input }, (community) => {
            callback(community);
          });
        },
        load: function(query, callback) {
          CommunitiesSvc.all({ nameLike: query }, (communities) => {
            callback(communities);
          });
        },
        valueField: 'id',
        labelField: 'name',
        searchField: 'name',
        maxOptions: 10,
        onChange: function(ids) {
          $scope.communities = $scope.communitySelector.options.filter(community => ids.includes(community.id));
          Selector.populateUserSelector($scope.invite.list, $scope.project.communities);
        },
        plugins: ['remove_button'],
        onDropdownOpen(dropdown){
          dropdown[0].scrollIntoView();
        },
        closeAfterSelect: true
      }
    };
    $scope.locationSelector = {
      options: [],
      config: {
        mode: 'single',
        openOnFocus: false,
        delimiter: null,
        plugins: {
          'placecomplete': {
            placeholder: '',
            //selectDetails: (placeResult) => {
              // placeResult.displayText contains something like "Madrid, Spain"
            //}
          }
        }
      }
    };

    SessionSvc.onLoad(function() {
      CommunitiesSvc.participating({ projectCount: true }).then(function(communities){
        $scope.communitySelector.options = angular.extend([], $scope.communities, communities);
      });
    });

    $scope.userSelectorConfig = Selector.config.users;

    $scope.inviteUsers = function(){
      Selector.invite($scope.invite.selected, $scope.project);
      $scope.invite.selected = [];
      SharedState.turnOff('modal.share');
    };

    $scope.cancelInvite = function(){
      $scope.invite.selected = [];
      SharedState.turnOff('modal.share');
    };

    $scope.focusTitleInput = function() {
      $('.title-input').focus();
    };

    $scope.createProjectFormInvalid = function() {
      // There should be a better way to implement this
      try {
        let form = angular.element('[name="createProjectForm"]');

        return form.scope().createProjectForm.$invalid;
      } catch(e) {
        return false;
      }

    };

    $scope.archiveProject = function() {
      // TODO
    };

  }])
  .directive(
    'hideTabs',
    function (SharedState, $timeout) {
      return {
        restrict: 'A',
        link: function(scope, element) {
          element.on('focus', function() {
            SharedState.turnOn('hiddenTabs');
            $timeout();
          });
          element.on('blur', function() {
            SharedState.turnOff('hiddenTabs');
            $timeout();
          });
          scope.$on('$destroy', function() {
            element.off('focus');
            element.off('blur');
          });
        }
      };
    });
<commit_msg>Clean call to removed function<commit_after>
'use strict';

/**
 * @ngdoc function
 * @name Teem.controller:ProjectsCtrl
 * @description
 * # ProjectsCtrl
 * Controller of the Teem
 */

angular.module('Teem')
  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider
      .when('/teems/featured', {
        templateUrl: 'projects/index.html',
        // We need this route here to take precendence on /teems/:id
        // but note we are using the projects (plural) controller
        controller: 'ProjectsCtrl'
      })
      // Transition from old paths
      .when('/projects/:id/:new?', {
        redirectTo: function(params) {
          return '/teems/' + params.id;
        }
      })
      .when('/teems/new', {
        templateUrl: 'projects/project.html',
        // We need this route here to take precendence on /teems/:id
        // but note we are using the projects (plural) controller
        controller: 'ProjectsCtrl'
      })
      .when('/teems/:id', {
        templateUrl: 'projects/project.html',
        controller: 'ProjectCtrl',
        // Change between tabs without re-rendering the view
        reloadOnSearch: false
      })
      // Getting a project from projects widget
      .when('/communities/:communityId/teems/fetch/:id', {
        controller: 'FetchProject',
        template: ''
      })
      // Old stuff
      .when('/communities/:communityId/teems/:id', {
        redirectTo: function(params) {
          return '/teems/' + params.id;
        }
      })
      .when('/communities/:communityId/teems/:id/:tab', {
        redirectTo: function(params) {
          return '/teems/' + params.id + '?tab=' + params.tab;
        }
      });
  }])
  .controller('FetchProject', [
  'ProjectsSvc', 'Url', '$route', '$location', 'SessionSvc',
  function(ProjectsSvc, Url, $route, $location, SessionSvc) {

    var communityId = Url.decode($route.current.params.communityId),
        localId     = $route.current.params.id;

    SessionSvc.onLoad(() => {

      ProjectsSvc.all({
        community: communityId,
        localId: localId
      }).then(function(projects) {

        var project = projects[0];

        if (project) {
          $location.path(project.path());
          return;
        }

        ProjectsSvc.create({
          communityId:  communityId
        }).then(function(project) {
          project.localId = localId;

          $location.path(project.path());
        });
      });
    });
  }])
  .controller('ProjectCtrl', [
  'SessionSvc', '$scope', '$rootScope', '$location', '$route', '$timeout', 'swellRT', '$filter',
  'SharedState', 'ProjectsSvc', 'Loading', '$window', 'CommunitiesSvc', 'User', 'Selector',
  function (SessionSvc, $scope, $rootScope, $location, $route, $timeout, swellRT, $filter,
  SharedState, ProjectsSvc, Loading, $window, CommunitiesSvc, User, Selector) {

    // Prevent users from forging the form parameter
    // and set the form order
    const Forms = [ 'image', 'details', 'share', 'congrats' ];

    // Use them in steps template
    $scope.formSteps = Forms;

    // Hack to hide the navbar
    // We should be using the class .has-navbar-top automatically added by
    // mobile-angular-ui, it should be removed when the navbar is removed
    // by ui-content-for, but it is not happening
    $rootScope.noNavbarTop = true;
    $scope.$on('$destroy', () => {
      $rootScope.noNavbarTop = false;
    });

    var editingTitle = false;

    // FIXME Defined here instead of inside pad because when pad scope is destroyed,
    // `editing` variable can't be accessed, and it is used outside pad.
    $scope.pad = {
      editing: false,
      saving: false,
      outline: []
    };
    $scope.pic = {};

    $scope.editOff = function() {
      angular.element(document.querySelector('pad')).scope().editOff();
    };

    $scope.invite = {
      list : [],
      selected : []
    };

    var initialize = function(){
      Loading.show(ProjectsSvc.findByUrlId($route.current.params.id)).
        then(function(project) {
          $scope.project = project;
          Selector.populateUserSelector($scope.invite.list, $scope.project.communities);

          $rootScope.og = {
            title: project.title,
            description: project.pad.text().substring(0, 200),
            url: project.url(),
            image: project.logoUrl()
          };

          if($location.search().tab === 'chat' && !$scope.project.isParticipant()){
            SharedState.setOne('projectTab', 'pad');
          }

          CommunitiesSvc.all({ ids: project.communities }).then(function (communities) {
            $timeout(function() {
              $scope.communities = communities;
            });
          });
          $timeout();
        });
    };

    SessionSvc.onLoad(initialize);

    function currentTab() {
      return $location.search().tab || 'pad';
    }

    SharedState.initialize($scope, 'projectTab', {
      defaultValue: currentTab()
    });

    function swipeToProjectTab(tab) {
      return function(event) {
        if (event.pointerType === 'touch') {
          SharedState.set('projectTab', tab);
        }
      };
    }

    $scope.swipeToPad = swipeToProjectTab('pad');
    $scope.swipeToNeeds = swipeToProjectTab('needs');
    $scope.swipeToChat = swipeToProjectTab('chat');

    $scope.hmManagerOpt = '{"cssProps": {"userSelect": true}}';
    $scope.hmRecognizerOpt = '{"threshold": 200}';

    SharedState.initialize($scope, 'hiddenTabs');
    $scope.areTabsHidden = function() {
      return SharedState.isActive('hiddenTabs') && $window.innerHeight < 400;
    };

    $scope.form = function () {
      var f = $route.current.params.form;

      if (f && Forms.indexOf(f) >= 0) {
        return f;
      }
    };

    $scope.formStep = function() {
      return Forms.indexOf($route.current.params.form) + 1;
    };

    $scope.nextForm = function () {
      var index = Forms.indexOf($route.current.params.form) + 1;

      if (index > 0 && index < Forms.length) {
        return Forms[index];
      }

      return null;
    };

    $scope.goToNextForm = function () {
      if ($scope.form() === 'image' && $scope.pic.croppedPicture) {
        $scope.uploadProjectPhoto($filter('dataUriToBlob')($scope.pic.croppedPicture));
      }
      $location.search('form', $scope.nextForm());
    };

    $scope.uploadProjectPhoto = function(file) {
      $scope.project.image = new swellRT.FileObject(file);
    };

    $scope.editingTitle = function() {
      return editingTitle;
    };

    $scope.infoTip = function(close) {
      if (close) {
        localStorage.setItem('clickToTap', true);
      }
      return !localStorage.getItem('clickToTap');
    };

    $scope.showEditTitle = function() {
      editingTitle = true;
    };

    $scope.hideEditTitle = function() {
      editingTitle = false;
    };

    $scope.createProject = function() {
      let params = {};

      ProjectsSvc.create(params, function(p) {
        $location.path(p.path()).search('form', 'image');
      });
    };

    $scope.$on('mobile-angular-ui.state.changed.projectTab', function(e, newVal, oldVal) {
      $scope.project.setTimestampAccess(oldVal);
      $scope.project.setTimestampAccess(newVal);

      $location.search({ tab: newVal});

      $scope.pad.editing = false;
    });

      $scope.$on('$routeChangeStart', function(event, next, current) {
      if (current.params.tab !== undefined && $scope.project!== undefined) {
        $scope.project.setTimestampAccess(current.params.tab);
      }
    });

    $scope.cancelProject = function() {
      SharedState.turnOff('modal.confirm');

      $scope.project.delete();

      if ($location.search('form')) {
        $location.search('form', null);

        $location.path('/teems');
      } else {
        $location.path('/home/teems');
      }
    };

    $scope.hasChanged = function(section){

      if(!$scope.project || ! $scope.project.lastChange(section) ||
        !$scope.project.isParticipant()){
        return false;
      }

      var lastChange = $scope.project.lastChange(section);
      var lastAccess;
          if ($scope.project.getTimestampAccess() &&
            $scope.project.getTimestampAccess()[section]) {
            lastAccess = new Date(($scope.project.getTimestampAccess()[section]).last);
          } else {
            lastAccess = new Date(0);
          }
      return lastChange > lastAccess;
    };

    $scope.communitySelector = {
      options: [],
      config: {
        create: function(input, callback) {
          CommunitiesSvc.create({ name: input }, (community) => {
            callback(community);
          });
        },
        load: function(query, callback) {
          CommunitiesSvc.all({ nameLike: query }, (communities) => {
            callback(communities);
          });
        },
        valueField: 'id',
        labelField: 'name',
        searchField: 'name',
        maxOptions: 10,
        onChange: function(ids) {
          $scope.communities = $scope.communitySelector.options.filter(community => ids.includes(community.id));
          Selector.populateUserSelector($scope.invite.list, $scope.project.communities);
        },
        plugins: ['remove_button'],
        onDropdownOpen(dropdown){
          dropdown[0].scrollIntoView();
        },
        closeAfterSelect: true
      }
    };
    $scope.locationSelector = {
      options: [],
      config: {
        mode: 'single',
        openOnFocus: false,
        delimiter: null,
        plugins: {
          'placecomplete': {
            placeholder: '',
            //selectDetails: (placeResult) => {
              // placeResult.displayText contains something like "Madrid, Spain"
            //}
          }
        }
      }
    };

    SessionSvc.onLoad(function() {
      CommunitiesSvc.participating({ projectCount: true }).then(function(communities){
        $scope.communitySelector.options = angular.extend([], $scope.communities, communities);
      });
    });

    $scope.userSelectorConfig = Selector.config.users;

    $scope.inviteUsers = function(){
      Selector.invite($scope.invite.selected, $scope.project);
      $scope.invite.selected = [];
      SharedState.turnOff('modal.share');
    };

    $scope.cancelInvite = function(){
      $scope.invite.selected = [];
      SharedState.turnOff('modal.share');
    };

    $scope.focusTitleInput = function() {
      $('.title-input').focus();
    };

    $scope.createProjectFormInvalid = function() {
      // There should be a better way to implement this
      try {
        let form = angular.element('[name="createProjectForm"]');

        return form.scope().createProjectForm.$invalid;
      } catch(e) {
        return false;
      }

    };

    $scope.archiveProject = function() {
      // TODO
    };

  }])
  .directive(
    'hideTabs',
    function (SharedState, $timeout) {
      return {
        restrict: 'A',
        link: function(scope, element) {
          element.on('focus', function() {
            SharedState.turnOn('hiddenTabs');
            $timeout();
          });
          element.on('blur', function() {
            SharedState.turnOff('hiddenTabs');
            $timeout();
          });
          scope.$on('$destroy', function() {
            element.off('focus');
            element.off('blur');
          });
        }
      };
    });
<|endoftext|>


<commit_before>// Copyright 2011 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

suite('Loader.js', function() {

  var MutedErrorReporter =
      $traceurRuntime.ModuleStore.getForTesting('src/util/MutedErrorReporter').MutedErrorReporter;

  var reporter, baseURL;

  setup(function() {
    reporter = new traceur.util.ErrorReporter();
    baseURL = System.baseURL;
  });

  teardown(function() {
    assert.isFalse(reporter.hadError());
    System.baseURL = baseURL;
  });

  var url;
  var fileLoader;
  if (typeof __filename !== 'undefined') {
    // TOD(arv): Make the system work better with file paths, especially
    // Windows file paths.
    url = __filename.replace(/\\/g, '/');
    fileLoader = require('../../../src/node/nodeLoader.js');
  } else {
    url = traceur.util.resolveUrl(window.location.href,
                                  'unit/runtime/modules.js');
  }

  function getLoaderHooks(opt_reporter) {
    var LoaderHooks = traceur.runtime.LoaderHooks;
    opt_reporter = opt_reporter || reporter;
    return new LoaderHooks(opt_reporter, url, fileLoader);
  }

  function getLoader(opt_reporter) {
    return new traceur.runtime.TraceurLoader(getLoaderHooks(opt_reporter));
  }

  test('LoaderHooks.locate', function() {
    var loaderHooks = getLoaderHooks();
    var load = {
      metadata: {
        baseURL: 'http://example.org/a/'
      },
      data: {}
    }
    load.normalizedName = '@abc/def';
    assert.equal(loaderHooks.locate(load), 'http://example.org/a/@abc/def.js');
    load.normalizedName = 'abc/def';
    assert.equal(loaderHooks.locate(load), 'http://example.org/a/abc/def.js');
    load.normalizedName = 'abc/def.js';
    assert.notEqual(loaderHooks.locate(load), 'http://example.org/a/abc/def.js');
  });

  test('traceur@', function() {
    var traceur = System.get('traceur@');
    var optionsModule = $traceurRuntime.ModuleStore.getForTesting('src/options');
    assert.equal(traceur.options, optionsModule.options);
  });

  test('Loader.PreCompiledModule', function(done) {
    var traceur = System.get('traceur@');
    System.import('traceur@', {}).then(function(module) {
      assert.equal(traceur.options, module.options);
      done();
    });
  });

  test('LoaderEval', function(done) {
    getLoader().script('(function(x = 42) { return x; })()', {}).then(
      function(result) {
        assert.equal(42, result);
        done();
      });
  });

  test('Loader.Script.Fail', function(done) {
    var reporter = new MutedErrorReporter();
    getLoader(reporter).script('export var x = 5;', {}).then(
      function(result) {
        fail('should not have succeeded');
        done();
      }, function(ex) {
        assert(ex);
        done();
      });
  });

  test('LoaderModule', function(done) {
    var code =
        'module a from "./test_a";\n' +
        'module b from "./test_b";\n' +
        'module c from "./test_c";\n' +
        '\n' +
        'export var arr = [\'test\', a.name, b.name, c.name];\n';

    var result = getLoader().module(code, {}).then(
      function(module) {
        assert.equal('test', module.arr[0]);
        assert.equal('A', module.arr[1]);
        assert.equal('B', module.arr[2]);
        assert.equal('C', module.arr[3]);
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('LoaderModuleWithSubdir', function(done) {
    var code =
        'module d from "./subdir/test_d";\n' +
        '\n' +
        'export var arr = [d.name, d.e.name];\n';

    var result = getLoader().module(code, {}).then(
      function(module) {
        assert.equal('D', module.arr[0]);
        assert.equal('E', module.arr[1]);
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('LoaderModuleFail', function(done) {
    var code =
        'module a from "./test_a";\n' +
        'module b from "./test_b";\n' +
        'module c from "./test_c";\n' +
        '\n' +
        '[\'test\', SYNTAX ERROR a.name, b.name, c.name];\n';

    var reporter = new MutedErrorReporter();

    var result = getLoader(reporter).module(code, {}).then(
      function(value) {
        fail('Should not have succeeded');
        done();
      }, function(error) {
        // We should probably get some meaningful error here.

        //assert.isTrue(reporter.hadError());
        assert.isTrue(true);
        done();
      });
  });

  test('LoaderLoad', function(done) {
    getLoader().loadAsScript('./test_script.js', {}).then(function(result) {
      assert.equal('A', result[0]);
      assert.equal('B', result[1]);
      assert.equal('C', result[2]);
      done();
    }, function(error) {
      fail(error);
      done();
    });
  });

  test('LoaderLoad.Fail', function(done) {
    var reporter = new MutedErrorReporter();
    getLoader(reporter).loadAsScript('./non_existing.js', {}).then(function(result) {
      fail('should not have succeeded');
      done();
    }, function(error) {
      assert(error);
      done();
    });
  });

  test('LoaderLoadWithReferrer', function(done) {
    getLoader().loadAsScript('../test_script.js',
      {referrerName: 'traceur@0.0.1/bin'}).then(
      function(result) {
        assert.equal('A', result[0]);
        assert.equal('B', result[1]);
        assert.equal('C', result[2]);
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('LoaderImport', function(done) {
    getLoader().import('./test_module', {}).then(function(mod) {
      assert.equal('test', mod.name);
      assert.equal('A', mod.a);
      assert.equal('B', mod.b);
      assert.equal('C', mod.c);
      done();
    }, function(error) {
      fail(error);
      done();
    });
  });

  test('LoaderImport.Fail', function(done) {
    var reporter = new MutedErrorReporter();
    getLoader(reporter).import('./non_existing', {}).then(function(mod) {
      fail('should not have succeeded')
      done();
    }, function(error) {
      assert(error);
      done();
    });
  });

  test('LoaderImportWithReferrer', function(done) {
    getLoader().import('../test_module',
      {referrerName: 'traceur@0.0.1/bin'}).then(function(mod) {
        assert.equal('test', mod.name);
        assert.equal('A', mod.a);
        assert.equal('B', mod.b);
        assert.equal('C', mod.c);
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('Loader.define', function(done) {
    var name = System.normalize('./test_define');
    getLoader().import('./side-effect', {}).then(function(mod) {
      assert.equal(6, mod.currentSideEffect());  // starting value.
      var src = 'export {name as a} from \'./test_a\';\n' +
        'export var d = 4;\n' + 'this.sideEffect++;';
      getLoader().define(name, src, {}).then(function() {
          assert.equal(6, mod.currentSideEffect());  // no change
          var definedModule = System.get(name);
          assert.equal(7, mod.currentSideEffect());  // module body evaluated
          assert.equal(4, definedModule.d);  // define does exports
          assert.equal('A', definedModule.a);  // define does imports
          done();
        }, function(error) {
          fail(error);
          done();
        });
    });
  });

  test('Loader.define.Fail', function(done) {
    var name = System.normalize('./test_define');
    var reporter = new MutedErrorReporter();
    getLoader(reporter).import('./side-effect', {}).then(function(mod) {
      var src = 'syntax error';
      getLoader(reporter).define(name, src, {}).then(function() {
          fail('should not have succeeded');
          done();
        }, function(error) {
          assert(error);
          done();
        });
    });
  });

  test('Loader.defineWithSourceMap', function(done) {
    var normalizedName = System.normalize('./test_define_with_source_map');
    var loader = getLoader();
    loader.options.sourceMaps = true;
    var src = 'export {name as a} from \'./test_a\';\nexport var d = 4;\n';
    loader.define(normalizedName, src, {}).then(function() {
        var sourceMap = loader.sourceMap(normalizedName, 'module');
        assert(sourceMap);
        var SourceMapConsumer = traceur.outputgeneration.SourceMapConsumer;
        var consumer = new SourceMapConsumer(sourceMap);
        var sourceContent = consumer.sourceContentFor(normalizedName);
        assert.equal(sourceContent, src);
        done();
      }, function(error) {
        fail(error);
        done();
      }
    );
  });

  test('System.semverMap', function() {
    var semVerRegExp = System.semVerRegExp_();
    var m = semVerRegExp.exec('1.2.3-a.b.c.5.d.100');
    assert.equal(1, m[1]);
    assert.equal(2, m[2]);
    m = semVerRegExp.exec('1.2.X');
    assert(!m);
    m = semVerRegExp.exec('Any');
    assert(!m);

    var version = System.map['traceur'];
    assert(version);
    // This test must be updated if the major or minor version number changes.
    // If the change is intended, this is a reminder to update the documentation.
    assert.equal(version, System.map['traceur@0']);
    assert.equal(version, System.map['traceur@0.0']);
  });

  test('System.map', function() {
    System.map = System.semverMap('traceur@0.0.13/src/runtime/System');
    var version = System.map['traceur'];
    var remapped = System.normalize('traceur@0.0/src/runtime/System');
    var versionSegment = remapped.split('/')[0];
    assert.equal(version, versionSegment);
  });

  test('System.applyMap', function() {
    var originalMap = System.map;
    System.map['tests/contextual'] = {
      maptest: 'tests/contextual-map-dep'
    };
    var contexualRemap = System.normalize('maptest', 'tests/contextual');
    assert.equal('tests/contextual-map-dep', contexualRemap);
    // prefix must match up to segment delimiter '/'
    System.map = {
      jquery: 'jquery@2.0.0'
    };
    var remap = System.normalize('jquery-ui');
    assert.equal('jquery-ui', remap);
    System.map = originalMap;
  });

  test('AnonModuleSourceMap', function() {
    var src = "  import {name} from './test_a';";

    var loader = getLoader();
    loader.options.sourceMap = true;

    loader.module(src, {}, function (mod) {
      assert(mod);
    }, function(err) {
      throw new Error('AnonModuleSourceMap FAILED ');
    });

  });

});
<commit_msg>Verify that Object.getPrototypeOf(module) is null<commit_after>// Copyright 2011 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

suite('Loader.js', function() {

  var MutedErrorReporter =
      $traceurRuntime.ModuleStore.getForTesting('src/util/MutedErrorReporter').MutedErrorReporter;

  var reporter, baseURL;

  setup(function() {
    reporter = new traceur.util.ErrorReporter();
    baseURL = System.baseURL;
  });

  teardown(function() {
    assert.isFalse(reporter.hadError());
    System.baseURL = baseURL;
  });

  var url;
  var fileLoader;
  if (typeof __filename !== 'undefined') {
    // TOD(arv): Make the system work better with file paths, especially
    // Windows file paths.
    url = __filename.replace(/\\/g, '/');
    fileLoader = require('../../../src/node/nodeLoader.js');
  } else {
    url = traceur.util.resolveUrl(window.location.href,
                                  'unit/runtime/modules.js');
  }

  function getLoaderHooks(opt_reporter) {
    var LoaderHooks = traceur.runtime.LoaderHooks;
    opt_reporter = opt_reporter || reporter;
    return new LoaderHooks(opt_reporter, url, fileLoader);
  }

  function getLoader(opt_reporter) {
    return new traceur.runtime.TraceurLoader(getLoaderHooks(opt_reporter));
  }

  test('LoaderHooks.locate', function() {
    var loaderHooks = getLoaderHooks();
    var load = {
      metadata: {
        baseURL: 'http://example.org/a/'
      },
      data: {}
    }
    load.normalizedName = '@abc/def';
    assert.equal(loaderHooks.locate(load), 'http://example.org/a/@abc/def.js');
    load.normalizedName = 'abc/def';
    assert.equal(loaderHooks.locate(load), 'http://example.org/a/abc/def.js');
    load.normalizedName = 'abc/def.js';
    assert.notEqual(loaderHooks.locate(load), 'http://example.org/a/abc/def.js');
  });

  test('traceur@', function() {
    var traceur = System.get('traceur@');
    var optionsModule = $traceurRuntime.ModuleStore.getForTesting('src/options');
    assert.equal(traceur.options, optionsModule.options);
  });

  test('Loader.PreCompiledModule', function(done) {
    var traceur = System.get('traceur@');
    System.import('traceur@', {}).then(function(module) {
      assert.equal(traceur.options, module.options);
      done();
    });
  });

  test('LoaderEval', function(done) {
    getLoader().script('(function(x = 42) { return x; })()', {}).then(
      function(result) {
        assert.equal(42, result);
        done();
      });
  });

  test('Loader.Script.Fail', function(done) {
    var reporter = new MutedErrorReporter();
    getLoader(reporter).script('export var x = 5;', {}).then(
      function(result) {
        fail('should not have succeeded');
        done();
      }, function(ex) {
        assert(ex);
        done();
      });
  });

  test('LoaderModule', function(done) {
    var code =
        'module a from "./test_a";\n' +
        'module b from "./test_b";\n' +
        'module c from "./test_c";\n' +
        '\n' +
        'export var arr = [\'test\', a.name, b.name, c.name];\n';

    var result = getLoader().module(code, {}).then(
      function(module) {
        assert.equal('test', module.arr[0]);
        assert.equal('A', module.arr[1]);
        assert.equal('B', module.arr[2]);
        assert.equal('C', module.arr[3]);
        assert.isNull(Object.getPrototypeOf(module));
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('LoaderModuleWithSubdir', function(done) {
    var code =
        'module d from "./subdir/test_d";\n' +
        '\n' +
        'export var arr = [d.name, d.e.name];\n';

    var result = getLoader().module(code, {}).then(
      function(module) {
        assert.equal('D', module.arr[0]);
        assert.equal('E', module.arr[1]);
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('LoaderModuleFail', function(done) {
    var code =
        'module a from "./test_a";\n' +
        'module b from "./test_b";\n' +
        'module c from "./test_c";\n' +
        '\n' +
        '[\'test\', SYNTAX ERROR a.name, b.name, c.name];\n';

    var reporter = new MutedErrorReporter();

    var result = getLoader(reporter).module(code, {}).then(
      function(value) {
        fail('Should not have succeeded');
        done();
      }, function(error) {
        // We should probably get some meaningful error here.

        //assert.isTrue(reporter.hadError());
        assert.isTrue(true);
        done();
      });
  });

  test('LoaderLoad', function(done) {
    getLoader().loadAsScript('./test_script.js', {}).then(function(result) {
      assert.equal('A', result[0]);
      assert.equal('B', result[1]);
      assert.equal('C', result[2]);
      done();
    }, function(error) {
      fail(error);
      done();
    });
  });

  test('LoaderLoad.Fail', function(done) {
    var reporter = new MutedErrorReporter();
    getLoader(reporter).loadAsScript('./non_existing.js', {}).then(function(result) {
      fail('should not have succeeded');
      done();
    }, function(error) {
      assert(error);
      done();
    });
  });

  test('LoaderLoadWithReferrer', function(done) {
    getLoader().loadAsScript('../test_script.js',
      {referrerName: 'traceur@0.0.1/bin'}).then(
      function(result) {
        assert.equal('A', result[0]);
        assert.equal('B', result[1]);
        assert.equal('C', result[2]);
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('LoaderImport', function(done) {
    getLoader().import('./test_module', {}).then(function(mod) {
      assert.equal('test', mod.name);
      assert.equal('A', mod.a);
      assert.equal('B', mod.b);
      assert.equal('C', mod.c);
      done();
    }, function(error) {
      fail(error);
      done();
    });
  });

  test('LoaderImport.Fail', function(done) {
    var reporter = new MutedErrorReporter();
    getLoader(reporter).import('./non_existing', {}).then(function(mod) {
      fail('should not have succeeded')
      done();
    }, function(error) {
      assert(error);
      done();
    });
  });

  test('LoaderImportWithReferrer', function(done) {
    getLoader().import('../test_module',
      {referrerName: 'traceur@0.0.1/bin'}).then(function(mod) {
        assert.equal('test', mod.name);
        assert.equal('A', mod.a);
        assert.equal('B', mod.b);
        assert.equal('C', mod.c);
        done();
      }, function(error) {
        fail(error);
        done();
      });
  });

  test('Loader.define', function(done) {
    var name = System.normalize('./test_define');
    getLoader().import('./side-effect', {}).then(function(mod) {
      assert.equal(6, mod.currentSideEffect());  // starting value.
      var src = 'export {name as a} from \'./test_a\';\n' +
        'export var d = 4;\n' + 'this.sideEffect++;';
      getLoader().define(name, src, {}).then(function() {
          assert.equal(6, mod.currentSideEffect());  // no change
          var definedModule = System.get(name);
          assert.equal(7, mod.currentSideEffect());  // module body evaluated
          assert.equal(4, definedModule.d);  // define does exports
          assert.equal('A', definedModule.a);  // define does imports
          done();
        }, function(error) {
          fail(error);
          done();
        });
    });
  });

  test('Loader.define.Fail', function(done) {
    var name = System.normalize('./test_define');
    var reporter = new MutedErrorReporter();
    getLoader(reporter).import('./side-effect', {}).then(function(mod) {
      var src = 'syntax error';
      getLoader(reporter).define(name, src, {}).then(function() {
          fail('should not have succeeded');
          done();
        }, function(error) {
          assert(error);
          done();
        });
    });
  });

  test('Loader.defineWithSourceMap', function(done) {
    var normalizedName = System.normalize('./test_define_with_source_map');
    var loader = getLoader();
    loader.options.sourceMaps = true;
    var src = 'export {name as a} from \'./test_a\';\nexport var d = 4;\n';
    loader.define(normalizedName, src, {}).then(function() {
        var sourceMap = loader.sourceMap(normalizedName, 'module');
        assert(sourceMap);
        var SourceMapConsumer = traceur.outputgeneration.SourceMapConsumer;
        var consumer = new SourceMapConsumer(sourceMap);
        var sourceContent = consumer.sourceContentFor(normalizedName);
        assert.equal(sourceContent, src);
        done();
      }, function(error) {
        fail(error);
        done();
      }
    );
  });

  test('System.semverMap', function() {
    var semVerRegExp = System.semVerRegExp_();
    var m = semVerRegExp.exec('1.2.3-a.b.c.5.d.100');
    assert.equal(1, m[1]);
    assert.equal(2, m[2]);
    m = semVerRegExp.exec('1.2.X');
    assert(!m);
    m = semVerRegExp.exec('Any');
    assert(!m);

    var version = System.map['traceur'];
    assert(version);
    // This test must be updated if the major or minor version number changes.
    // If the change is intended, this is a reminder to update the documentation.
    assert.equal(version, System.map['traceur@0']);
    assert.equal(version, System.map['traceur@0.0']);
  });

  test('System.map', function() {
    System.map = System.semverMap('traceur@0.0.13/src/runtime/System');
    var version = System.map['traceur'];
    var remapped = System.normalize('traceur@0.0/src/runtime/System');
    var versionSegment = remapped.split('/')[0];
    assert.equal(version, versionSegment);
  });

  test('System.applyMap', function() {
    var originalMap = System.map;
    System.map['tests/contextual'] = {
      maptest: 'tests/contextual-map-dep'
    };
    var contexualRemap = System.normalize('maptest', 'tests/contextual');
    assert.equal('tests/contextual-map-dep', contexualRemap);
    // prefix must match up to segment delimiter '/'
    System.map = {
      jquery: 'jquery@2.0.0'
    };
    var remap = System.normalize('jquery-ui');
    assert.equal('jquery-ui', remap);
    System.map = originalMap;
  });

  test('AnonModuleSourceMap', function() {
    var src = "  import {name} from './test_a';";

    var loader = getLoader();
    loader.options.sourceMap = true;

    loader.module(src, {}, function (mod) {
      assert(mod);
    }, function(err) {
      throw new Error('AnonModuleSourceMap FAILED ');
    });

  });

});
<|endoftext|>


<commit_before>import { readDataByYear, writeToDB, clearCollection } from '../service/dbService.js'
import R from 'ramda'
import * as calculate from '../utils/calculate'

readDataByYear('2016', 'aggregatedData', (res) => {
  const result = aggregateOverallInstructor(res)
  console.log(result)
  clearCollection('OverallInstructor')
  writeToDB(result, 'OverallInstructor')
})

const sumCount = (umi, val, tuple) =>
  R.reduce((acc, record) => (acc + record[umi].count[val]), 0, tuple[1])

const sumGender = (gen, tuple) =>
  R.reduce((acc, record) => (acc + record.gender[gen]), 0, tuple[1])

const sumEnrolment = (tuple) =>
  R.reduce((acc, record) => (acc + record.enrolment), 0, tuple[1])

const sumResponded = (tuple) =>
  R.reduce((acc, record) => (acc + (record.responseRate * record.enrolment)), 0, tuple[1])

const sumCourseCount = (tuple) =>
  R.reduce((acc, record) => (acc + 1), 0, tuple[1])

const concatenateDept = (tuple) => {
  const deptList = []
  R.map(x => {
    if (!deptList.includes(x.dept)) { deptList.push(x.dept) }
  }, tuple[1])
  return deptList
}

const aggregateOverallInstructor = (data) => {
  const byInstructor = R.groupBy((course) => course.PUID)

  const result = R.reduce((acc, tuple) => {
    const instructorObj = {
      instructorName: tuple[1][0].instructorName,
      gender: {
        Female: sumGender('Female', tuple),
        Male: sumGender('Male', tuple)
      },
      numCoursesTaught: tuple[1].length,
      numStudentsTaught: sumEnrolment(tuple),
      responseRate: sumResponded(tuple) / sumEnrolment(tuple),
      dept: concatenateDept(tuple).join(', ')
    }

    for (let i = 1; i <= 6; i++) {
      instructorObj['UMI' + i] = {
        count: {
          '1': sumCount('UMI' + i, '1', tuple),
          '2': sumCount('UMI' + i, '2', tuple),
          '3': sumCount('UMI' + i, '3', tuple),
          '4': sumCount('UMI' + i, '4', tuple),
          '5': sumCount('UMI' + i, '5', tuple)
        }
      }
      instructorObj['UMI' + i]['dispersionIndex'] = calculate.dispersionIndex(instructorObj['UMI' + i].count)
      instructorObj['UMI' + i]['average'] = calculate.umiAvg(instructorObj['UMI' + i].count)
      instructorObj['UMI' + i]['percentFavourable'] = calculate.percentFavourable(instructorObj['UMI' + i].count)
    }
    acc.push(instructorObj)
    return acc
  }, [], R.toPairs(byInstructor(data)))
  return result
}

export {
  aggregateOverallInstructor
}
<commit_msg>Moved db connection to bottom<commit_after>import { readDataByYear, writeToDB, clearCollection } from '../service/dbService.js'
import R from 'ramda'
import * as calculate from '../utils/calculate'

const sumCount = (umi, val, tuple) =>
  R.reduce((acc, record) => (acc + record[umi].count[val]), 0, tuple[1])

const sumGender = (gen, tuple) =>
  R.reduce((acc, record) => (acc + record.gender[gen]), 0, tuple[1])

const sumEnrolment = (tuple) =>
  R.reduce((acc, record) => (acc + record.enrolment), 0, tuple[1])

const sumResponded = (tuple) =>
  R.reduce((acc, record) => (acc + (record.responseRate * record.enrolment)), 0, tuple[1])

const sumCourseCount = (tuple) =>
  R.reduce((acc, record) => (acc + 1), 0, tuple[1])

const concatenateDept = (tuple) => {
  const deptList = []
  R.map(x => {
    if (!deptList.includes(x.dept)) { deptList.push(x.dept) }
  }, tuple[1])
  return deptList
}

const aggregateOverallInstructor = (data) => {
  const byInstructor = R.groupBy((course) => course.PUID)

  const result = R.reduce((acc, tuple) => {
    const instructorObj = {
      instructorName: tuple[1][0].instructorName,
      gender: {
        Female: sumGender('Female', tuple),
        Male: sumGender('Male', tuple)
      },
      numCoursesTaught: tuple[1].length,
      numStudentsTaught: sumEnrolment(tuple),
      responseRate: sumResponded(tuple) / sumEnrolment(tuple),
      dept: concatenateDept(tuple).join(', ')
    }

    for (let i = 1; i <= 6; i++) {
      instructorObj['UMI' + i] = {
        count: {
          '1': sumCount('UMI' + i, '1', tuple),
          '2': sumCount('UMI' + i, '2', tuple),
          '3': sumCount('UMI' + i, '3', tuple),
          '4': sumCount('UMI' + i, '4', tuple),
          '5': sumCount('UMI' + i, '5', tuple)
        }
      }
      instructorObj['UMI' + i]['dispersionIndex'] = calculate.dispersionIndex(instructorObj['UMI' + i].count)
      instructorObj['UMI' + i]['average'] = calculate.umiAvg(instructorObj['UMI' + i].count)
      instructorObj['UMI' + i]['percentFavourable'] = calculate.percentFavourable(instructorObj['UMI' + i].count)
    }
    acc.push(instructorObj)
    return acc
  }, [], R.toPairs(byInstructor(data)))
  return result
}

readDataByYear('2016', 'aggregatedData', (res) => {
  const result = aggregateOverallInstructor(res)
  console.log(result)
  clearCollection('OverallInstructor')
  writeToDB(result, 'OverallInstructor')
})

export {
  aggregateOverallInstructor
}
<|endoftext|>


<commit_before>
"use strict";

import {RootController} from './src/controllers/RootController';
import {HomeController} from './src/controllers/HomeController';
import {LoginController} from './src/controllers/LoginController';
import {Navigation} from './src/services/Navigation';
import {default as normalizePost} from './src/helpers/post';
import {default as listHeader} from './src/directives/list/header/directive';
import {default as listTable} from './src/directives/list/table/directive';
import {default as Path} from './src/directives/path/directive';

let ngModule = 'monad.core';

function config($translateProvider, $translatePartialLoaderProvider, $routeProvider, $locationProvider) {
    $locationProvider.html5Mode(false);
    $routeProvider.
        when('/', {
            controller: 'moController'
        }).
        when('/:language/', {
            controller: 'moHomeController',
            controllerAs: 'home',
            templateUrl: 'monad/src/template/home.html'
        }).
        when('/:language/login/', {
            controller: LoginController,
            controllerAs: 'login',
            templateUrl: 'monad/src/template/login.html'
        });
    $translateProvider.useLoader('$translatePartialLoader', {
        urlTemplate: '{part}/i18n/{lang}.json'
    });
    $translateProvider.preferredLanguage('en');
};

angular.module(ngModule, ['ng', 'ngRoute', 'pascalprecht.translate', 'ngCkeditor', 'ngSanitize', 'ngFileUpload', 'ui.bootstrap',])
    .config(['$translateProvider', '$translatePartialLoaderProvider', '$routeProvider', '$locationProvider', config])
    .run(['$http', normalizePost])
    .controller('moController', RootController)
    .controller('moHomeController', HomeController)
    .service('moNavigation', Navigation)
    .directive('moListHeader', listHeader)
    .directive('moListTable', listTable)
    .directive('moPath', Path)
;

export default ngModule;

<commit_msg>plural<commit_after>
"use strict";

import {RootController} from './src/controllers/RootController';
import {HomeController} from './src/controllers/HomeController';
import {LoginController} from './src/controllers/LoginController';
import {Navigation} from './src/services/Navigation';
import {default as normalizePost} from './src/helpers/post';
import {default as listHeader} from './src/directives/list/header/directive';
import {default as listTable} from './src/directives/list/table/directive';
import {default as Path} from './src/directives/path/directive';

let ngModule = 'monad.core';

function config($translateProvider, $translatePartialLoaderProvider, $routeProvider, $locationProvider) {
    $locationProvider.html5Mode(false);
    $routeProvider.
        when('/', {
            controller: 'moController'
        }).
        when('/:language/', {
            controller: 'moHomeController',
            controllerAs: 'home',
            templateUrl: 'monad/src/templates/home.html'
        }).
        when('/:language/login/', {
            controller: LoginController,
            controllerAs: 'login',
            templateUrl: 'monad/src/templates/login.html'
        });
    $translateProvider.useLoader('$translatePartialLoader', {
        urlTemplate: '{part}/i18n/{lang}.json'
    });
    $translateProvider.preferredLanguage('en');
};

angular.module(ngModule, ['ng', 'ngRoute', 'pascalprecht.translate', 'ngCkeditor', 'ngSanitize', 'ngFileUpload', 'ui.bootstrap',])
    .config(['$translateProvider', '$translatePartialLoaderProvider', '$routeProvider', '$locationProvider', config])
    .run(['$http', normalizePost])
    .controller('moController', RootController)
    .controller('moHomeController', HomeController)
    .service('moNavigation', Navigation)
    .directive('moListHeader', listHeader)
    .directive('moListTable', listTable)
    .directive('moPath', Path)
;

export default ngModule;

<|endoftext|>


<commit_before>import React from 'react';
import { mount, shallow } from 'enzyme';
import DetailPageHeader from '../DetailPageHeader';
import Icon from '../Icon';

describe('DetailPageHeader', () => {
  describe('component is rendered correctly when no child is passed', () => {
    const wrapper = shallow(
      <DetailPageHeader
        title="test"
        onBackLinkClick={() => {}}
      />
    );

    it('should render wrapper with the correct class', () => {
      expect(wrapper.hasClass('bx--detail-page-header--no-tabs')).toEqual(true);
    });

    it('should render a link with the correct class', () => {
      const link = wrapper.find('a');
      const hasLinkWrapperClass = link.hasClass('bx--detail-page-header--no-tabs__link-wrapper');

      expect(hasLinkWrapperClass).toEqual(true);
    });

    it('should render an icon with the correct class', () => {
      const link = wrapper.find('a');
      const icon = link.find(Icon);
      const hasIcon = icon.length === 1;
      const hasIconClass = hasIcon && icon.props().className === 'bx--detail-page-header--no-tabs__arrow';

      expect(hasIcon).toEqual(true);
      expect(hasIconClass).toEqual(true);
    });

    it('should render correct icon', () => {
      expect(wrapper.find(Icon).at(0).props().name).toEqual('arrow--left');
    });

    it('should render an element with a link text class', () => {
      const link = wrapper.find('a');
      const hasLinkText = link.find('.bx--detail-page-header--no-tabs__link-text').length === 1;

      expect(hasLinkText).toEqual(true);
    });

    it('should render an element with a title class', () => {
      const hasTitle = wrapper.find('.bx--detail-page-header--no-tabs__info-title').length === 1;
      expect(hasTitle).toEqual(true);
    });
  });

  describe('component is rendered correctly when a child is passed', () => {
    const wrapper = shallow(
      <DetailPageHeader
        title="test"
        onBackLinkClick={() => {}}
      >

      </DetailPageHeader>
    );

    it('should render a wrapper with the correct class', () => {
      expect(wrapper.hasClass('bx--detail-page-header--with-tabs')).toEqual(true);
    });

    it('should render an element with a container class', () => {
      expect(wrapper.find('.bx--detail-page-header--with-tabs__container').length).toEqual(1);
    });

    it('should render a tabs container with a child element within it', () => {
      const tabsContainer = wrapper.find('.bx--detail-page-header--with-tabs__tabs-container');

      expect(tabsContainer.length).toEqual(1);
      expect(tabsContainer.find('.child').length).toEqual(1);
    });

    it('should render an element with the breadcrumb class and expected child elements', () => {
      const breadcrumb = wrapper.find('.bx--detail-page-header--with-tabs__breadcrumb');
      const link = breadcrumb.find('a');
      const icon = breadcrumb.find(Icon);

      expect(breadcrumb.length).toEqual(1);
      expect(link.hasClass('bx--detail-page-header--with-tabs__link-wrapper')).toEqual(true);
      expect(icon.props().className).toEqual('bx--detail-page-header--with-tabs__arrow');
      expect(link.find('.bx--detail-page-header--with-tabs__breadcrumb-title').length).toEqual(1);
    });

    it('should be able to hide the breadcrumb', () => {
      const nobreadcrumbWrapper = shallow(
        <DetailPageHeader
          title="test"
          hideBreadcrumb
          onBackLinkClick={() => {}}
        >

        </DetailPageHeader>
      );
      const breadcrumb = nobreadcrumbWrapper.find('.bx--detail-page-header--with-tabs__breadcrumb');
      expect(breadcrumb.hasClass('bx--visually-hidden')).toBe(true);
    });
  });

  describe('props with no child passed', () => {
    const onBackLinkClick = jest.fn();
    const wrapper = mount(
      <DetailPageHeader
        title="test"
        onBackLinkClick={onBackLinkClick}
      />
    );

    it('should invoke onBackLinkClick when link is clicked', () => {
      wrapper.find('a').simulate('click');
      expect(onBackLinkClick).toBeCalled();
    });

    it('should display title when one is passed as props', () => {
      const title = wrapper.find('.bx--detail-page-header--no-tabs__info-title');
      expect(title.text()).toEqual('test');
    });

    it('should set breadcrumbTitle when one is passed as props', () => {
      const link = wrapper.find('.bx--detail-page-header--no-tabs__link-text');
      const icon = wrapper.find(Icon);

      expect(link.text()).toEqual('back');
      expect(icon.props().description).toEqual('back');

      wrapper.setProps({ breadcrumbTitle: 'test breadcrumb' });
      expect(link.text()).toEqual('test breadcrumb');
      expect(icon.props().description).toEqual('test breadcrumb');
    });
  });

  describe('props when a child is passed', () => {
    const onBackLinkClick = jest.fn();
    const wrapper = mount(
      <DetailPageHeader
        title="test title"
        onBackLinkClick={onBackLinkClick}
      >

      </DetailPageHeader>
    );

    it('should invoke onBackLinkClick when link is clicked', () => {
      wrapper.find('a').simulate('click');
      expect(onBackLinkClick).toBeCalled();
    });

    it('should set breadcrumbTitle when one is passed as props', () => {
      const breadcrumb = wrapper.find('.bx--detail-page-header--with-tabs__breadcrumb-title');
      const icon = wrapper.find(Icon);

      expect(breadcrumb.text()).toEqual('back');
      expect(icon.props().description).toEqual('back');

      wrapper.setProps({ breadcrumbTitle: 'test breadcrumb' });
      expect(breadcrumb.text()).toEqual('test breadcrumb');
      expect(icon.props().description).toEqual('test breadcrumb');
    });

    it('should display title when one is passed as props', () => {
      const title = wrapper.find('.bx--detail-page-header--with-tabs__info-title');
      expect(title.text()).toEqual('test title');
    });
  });
});
<commit_msg>resolve error message from DetailPageHeader test (#356)<commit_after>import React from 'react';
import { mount, shallow } from 'enzyme';
import DetailPageHeader from '../DetailPageHeader';
import Icon from '../Icon';

describe('DetailPageHeader', () => {
  describe('component is rendered correctly when no child is passed', () => {
    const wrapper = shallow(
      <DetailPageHeader
        title="test"
        onBackLinkClick={() => {}}
      />
    );

    it('should render wrapper with the correct class', () => {
      expect(wrapper.hasClass('bx--detail-page-header--no-tabs')).toEqual(true);
    });

    it('should render a link with the correct class', () => {
      const link = wrapper.find('a');
      const hasLinkWrapperClass = link.hasClass('bx--detail-page-header--no-tabs__link-wrapper');

      expect(hasLinkWrapperClass).toEqual(true);
    });

    it('should render an icon with the correct class', () => {
      const link = wrapper.find('a');
      const icon = link.find(Icon);
      const hasIcon = icon.length === 1;
      const hasIconClass = hasIcon && icon.props().className === 'bx--detail-page-header--no-tabs__arrow';

      expect(hasIcon).toEqual(true);
      expect(hasIconClass).toEqual(true);
    });

    it('should render correct icon', () => {
      expect(wrapper.find(Icon).at(0).props().name).toEqual('arrow--left');
    });

    it('should render an element with a link text class', () => {
      const link = wrapper.find('a');
      const hasLinkText = link.find('.bx--detail-page-header--no-tabs__link-text').length === 1;

      expect(hasLinkText).toEqual(true);
    });

    it('should render an element with a title class', () => {
      const hasTitle = wrapper.find('.bx--detail-page-header--no-tabs__info-title').length === 1;
      expect(hasTitle).toEqual(true);
    });
  });

  describe('component is rendered correctly when a child is passed', () => {
    const wrapper = shallow(
      <DetailPageHeader
        title="test"
        onBackLinkClick={() => {}}
      >

      </DetailPageHeader>
    );

    it('should render a wrapper with the correct class', () => {
      expect(wrapper.hasClass('bx--detail-page-header--with-tabs')).toEqual(true);
    });

    it('should render an element with a container class', () => {
      expect(wrapper.find('.bx--detail-page-header--with-tabs__container').length).toEqual(1);
    });

    it('should render a tabs container with a child element within it', () => {
      const tabsContainer = wrapper.find('.bx--detail-page-header--with-tabs__tabs-container');

      expect(tabsContainer.length).toEqual(1);
      expect(tabsContainer.find('.child').length).toEqual(1);
    });

    it('should render an element with the breadcrumb class and expected child elements', () => {
      const breadcrumb = wrapper.find('.bx--detail-page-header--with-tabs__breadcrumb');
      const link = breadcrumb.find('a');
      const icon = breadcrumb.find(Icon);

      expect(breadcrumb.length).toEqual(1);
      expect(link.hasClass('bx--detail-page-header--with-tabs__link-wrapper')).toEqual(true);
      expect(icon.props().className).toEqual('bx--detail-page-header--with-tabs__arrow');
      expect(link.find('.bx--detail-page-header--with-tabs__breadcrumb-title').length).toEqual(1);
    });

    it('should be able to hide the breadcrumb', () => {
      wrapper.setProps({ hideBreadcrumb: true });
      const breadcrumb = wrapper.find('.bx--detail-page-header--with-tabs__breadcrumb');
      expect(breadcrumb.hasClass('bx--visually-hidden')).toBe(true);
    });
  });

  describe('props with no child passed', () => {
    const onBackLinkClick = jest.fn();
    const wrapper = mount(
      <DetailPageHeader
        title="test"
        onBackLinkClick={onBackLinkClick}
      />
    );

    it('should invoke onBackLinkClick when link is clicked', () => {
      wrapper.find('a').simulate('click');
      expect(onBackLinkClick).toBeCalled();
    });

    it('should display title when one is passed as props', () => {
      const title = wrapper.find('.bx--detail-page-header--no-tabs__info-title');
      expect(title.text()).toEqual('test');
    });

    it('should set breadcrumbTitle when one is passed as props', () => {
      const link = wrapper.find('.bx--detail-page-header--no-tabs__link-text');
      const icon = wrapper.find(Icon);

      expect(link.text()).toEqual('back');
      expect(icon.props().description).toEqual('back');

      wrapper.setProps({ breadcrumbTitle: 'test breadcrumb' });
      expect(link.text()).toEqual('test breadcrumb');
      expect(icon.props().description).toEqual('test breadcrumb');
    });
  });

  describe('props when a child is passed', () => {
    const onBackLinkClick = jest.fn();
    const wrapper = mount(
      <DetailPageHeader
        title="test title"
        onBackLinkClick={onBackLinkClick}
      >

      </DetailPageHeader>
    );

    it('should invoke onBackLinkClick when link is clicked', () => {
      wrapper.find('a').simulate('click');
      expect(onBackLinkClick).toBeCalled();
    });

    it('should set breadcrumbTitle when one is passed as props', () => {
      const breadcrumb = wrapper.find('.bx--detail-page-header--with-tabs__breadcrumb-title');
      const icon = wrapper.find(Icon);

      expect(breadcrumb.text()).toEqual('back');
      expect(icon.props().description).toEqual('back');

      wrapper.setProps({ breadcrumbTitle: 'test breadcrumb' });
      expect(breadcrumb.text()).toEqual('test breadcrumb');
      expect(icon.props().description).toEqual('test breadcrumb');
    });

    it('should display title when one is passed as props', () => {
      const title = wrapper.find('.bx--detail-page-header--with-tabs__info-title');
      expect(title.text()).toEqual('test title');
    });
  });
});
<|endoftext|>


<commit_before>var fs       = require('fs'),
    path     = require('path'),
    spawn    = require('child_process').spawn,
    through2 = require('through2');

var section = ['\\section{', '\\subsection{', '\\subsubsection{'];
var extensions = ['.cc', '.cpp', '.c', '.java', '.py', '.tex'];

function walk(_path, depth) {
  var ans = "";
  depth = Math.min(depth, section.length - 1);
  fs.readdirSync(_path).forEach(function (file) {
    var f = path.resolve(_path, file);
    var stat = fs.lstatSync(f);
    if (stat.isDirectory())
      ans += '\n' + section[depth] + file + '}\n' + walk(f, depth + 1);
    else if (extensions.indexOf(path.extname(f)) != -1) {
      ans += '\n' + section[depth] + file.split('.')[0] + '}\n';
      if (path.extname(f) != '.tex')
        ans += '\\begin{lstlisting}\n' + fs.readFileSync(f) + '\\end{lstlisting}\n';
      else
        ans += fs.readFileSync(f);
    }
  });
  return ans;
}

/**
 * pdf must be generated twice in order to generate the table of contents.
 * */
function genpdf(ans, tex_path, iter) {
  var tex = spawn('pdflatex', [
      '-interaction=nonstopmode',
      tex_path
  ], {
    cwd: '/tmp',
    env: process.env
  });

  tex.on('error', function(err) {
    console.error(err);
  });

  tex.on('exit', function(code, signal) {
    var output_file = tex_path.split('.')[0] + '.pdf';
    fs.exists(output_file, function(exists) {
      if (exists) {
        if (iter == 1) {
          var s = fs.createReadStream(output_file);
          s.pipe(ans);
        } else {
          genpdf(ans, tex_path, iter + 1);
        }
      } else {
        console.error('Not generated ' + code + ' : ' + signal);
      }
    });
  });
}

function pdflatex(doc, iter) {
  var tex_path = '/tmp/_notebook.tex';

  var ans   = through2();
  ans.readable = true;
  var input = fs.createWriteStream(tex_path);
  input.end(doc);
  input.on('close', function() {
    genpdf(ans, tex_path, 0)
  });

  return ans;
}

module.exports =  function(path, output, author, initials) {
  var template = fs.readFileSync(__dirname + '/template_header.tex').toString();
  template = template
    .replace('${author}', author)
    .replace('${initials}', initials)

  template += walk(path, 0);
  template += '\\end{document}';
  output = output || './notebook.pdf';
  pdflatex(template).pipe(fs.createWriteStream(output));
}
<commit_msg>fix bug about skip hidden directories<commit_after>var fs       = require('fs'),
    path     = require('path'),
    spawn    = require('child_process').spawn,
    through2 = require('through2');

var section = ['\\section{', '\\subsection{', '\\subsubsection{'];
var extensions = ['.cc', '.cpp', '.c', '.java', '.py', '.tex'];

function walk(_path, depth) {
  var ans = "";
  depth = Math.min(depth, section.length - 1);
  fs.readdirSync(_path).forEach(function (file) {
    if (file.startsWith(".")) {
      return; // hidden directory
    }
    var f = path.resolve(_path, file);
    var stat = fs.lstatSync(f);
    if (stat.isDirectory())
      ans += '\n' + section[depth] + file + '}\n' + walk(f, depth + 1);
    else if (extensions.indexOf(path.extname(f)) != -1) {
      ans += '\n' + section[depth] + file.split('.')[0] + '}\n';
      if (path.extname(f) != '.tex')
        ans += '\\begin{lstlisting}\n' + fs.readFileSync(f) + '\\end{lstlisting}\n';
      else
        ans += fs.readFileSync(f);
    }
  });
  return ans;
}

/**
 * pdf must be generated twice in order to generate the table of contents.
 * */
function genpdf(ans, tex_path, iter) {
  var tex = spawn('pdflatex', [
      '-interaction=nonstopmode',
      tex_path
  ], {
    cwd: '/tmp',
    env: process.env
  });

  tex.on('error', function(err) {
    console.error(err);
  });

  tex.on('exit', function(code, signal) {
    var output_file = tex_path.split('.')[0] + '.pdf';
    fs.exists(output_file, function(exists) {
      if (exists) {
        if (iter == 1) {
          var s = fs.createReadStream(output_file);
          s.pipe(ans);
        } else {
          genpdf(ans, tex_path, iter + 1);
        }
      } else {
        console.error('Not generated ' + code + ' : ' + signal);
      }
    });
  });
}

function pdflatex(doc, iter) {
  var tex_path = '/tmp/_notebook.tex';

  var ans   = through2();
  ans.readable = true;
  var input = fs.createWriteStream(tex_path);
  input.end(doc);
  input.on('close', function() {
    genpdf(ans, tex_path, 0)
  });

  return ans;
}

module.exports =  function(path, output, author, initials) {
  var template = fs.readFileSync(__dirname + '/template_header.tex').toString();
  template = template
    .replace('${author}', author)
    .replace('${initials}', initials)

  template += walk(path, 0);
  template += '\\end{document}';
  output = output || './notebook.pdf';
  pdflatex(template).pipe(fs.createWriteStream(output));
}
<|endoftext|>


<commit_before>import fs from 'fs';
import interpret from 'interpret';

// const boost = ['.js', '.jsx', '.ts', '.tsx'];

function getPossibleExtensions() {
  return Object.keys(interpret.extensions).sort((a, b) => {
    if (a === '.js') {
      return -1;
    }

    if (b === '.js') {
      return 1;
    }

    return a.length - b.length;
  });
}

const possibleExtensions = getPossibleExtensions();

export function getInterpretedFile(pathToFile) {
  const candidates = possibleExtensions.map(ext => `${pathToFile}${ext}`);

  return candidates.find(candidate => {
    if (fs.existsSync(candidate)) {
      return candidate;
    }

    return null;
  });
}
<commit_msg>Enable extensions boosting<commit_after>import fs from 'fs';
import { extensions } from 'interpret';

const boost = new Set(['.js', '.jsx', '.ts', '.tsx']);

function sortExtensions() {
  return [
    ...Array.from(boost),
    ...Object.keys(extensions)
      .filter(ext => !boost.has(ext))
      .sort((a, b) => a.length - b.length),
  ];
}

const possibleExtensions = sortExtensions();

export function getInterpretedFile(pathToFile) {
  const candidates = possibleExtensions.map(ext => `${pathToFile}${ext}`);

  return candidates.find(candidate => {
    if (fs.existsSync(candidate)) {
      return candidate;
    }

    return null;
  });
}
<|endoftext|>


<commit_before>// External Dependencies
const React           = require('react');
const classNames      = require('classnames');

/**
 * A container component for configurable modals
 * @class ModalContainer
 *
 * @memberOf GlobalComponents
 * @see {@link GlobalComponents}
 *
 * @type {*|Function}
 */
const ModalContainer = React.createClass({
	propTypes: {
		openWhen         : React.PropTypes.bool.isRequired,
		width            : React.PropTypes.string,
		title            : React.PropTypes.string.isRequired,
		closeText        : React.PropTypes.string,
		confirmText      : React.PropTypes.string,
		modalBodyClasses : React.PropTypes.string,
		beforeOpen       : React.PropTypes.func,
		afterOpen        : React.PropTypes.func,
		beforeClose      : React.PropTypes.func,
		afterClose       : React.PropTypes.func,
		beforeConfirm    : React.PropTypes.func,
		afterConfirm     : React.PropTypes.func,
		disableConfirm   : React.PropTypes.bool,
		children         : React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.object]),
		options          : React.PropTypes.shape({
			keepOpen: React.PropTypes.bool // If this is true, clicking outside of a modal will not close the modal
		})
	},

	/**
	 * getInitialState
	 *
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {object}
	 */
	getInitialState: function () {
		return {
			isOpen: false
		};
	},

	unitRegExp  : new RegExp(/^\d+(px|em|\%|cm|mm|in|pt|pc|ch|vh|vw|vmin|vmax)$/),
	digitRegExp : new RegExp(/\d+/),

	/**
	 * When the component mounts, an event listener is attached to the window
	 * to track keyup events, and filter them into this component's handleKeyUp function.
	 *
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	componentDidMount: function() {
		window.addEventListener('keyup', this.handleKeyUp);
	},

	/**
	 * When the component is unmounted, the window's KeyUp listener is removed
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	componentWillUnmount: function() {
		window.removeEventListener('keyup', this.handleKeyUp);
	},

	/**
	 * Invoked when a component is receiving new props. This method is not called for the initial render.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param  {object} newProps Incoming props from parent component
	 *
	 * @return {null}
	 */
	componentWillReceiveProps: function(newProps) {
		newProps.openWhen && this.openModal();
	},

	/**
	 * Open the modal and fire appropriate user functions
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	openModal: function () {
		this._modalLifeCycleEvent('open', true);
	},

	/**
	 * Close the modal and fire appropriate user functions
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	closeModal: function () {
		this._modalLifeCycleEvent('close', false);
	},

	/**
	 * Save modal and fire the appropriate user functions
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	confirmModal: function () {
		this._modalLifeCycleEvent('confirm', false);
	},

	/**
	 * Fire the before and after lifecycle hooks for the modal component.
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param  {string} action         Modal lifecycle action
	 * @param  {bool}   nextModalState The next value for the modal `isOpen` prop
	 *
	 * @return {null}
	 */
	_modalLifeCycleEvent: function(action, nextModalState) {
		action = action.charAt(0).toUpperCase() + action.slice(1);

		this._callUserFunc(`before${action}`);

		this.setState({
			isOpen: nextModalState
		});

		this._callUserFunc(`after${action}`);
	},

	/**
	 * Determine whether the modal is open and we should render the overlay
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx|null}
	 */
	_shouldRenderOverlay: function () {
		return this.state.isOpen &&

;
	},

	/**
	 * Fire the selected user function, if it's provided
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param {string} propName Lifecycle event for modal
	 *
	 * @return {null}
	 */
	_callUserFunc: function (propName) {
		if (this.props[propName]) {
			this.props[propName]();
		}
	},

	/**
	 * Return save button jsx
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx}
	 */
	confirmButton: function () {
		return <button type="button" className={"btn btn-primary"} disabled={this.props.disableConfirm} onClick={this.confirmModal}>{this.props.confirmText || 'Confirm'}</button>;
	},

	/**
	 * Return cancel button jsx
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx}
	 */
	cancelButton: function () {
		return <button type="button" className="btn btn-default" onClick={this.closeModal}>{this.props.closeText || 'Cancel'}</button>;
	},

	/**
	 * A click listener attached to the modal.
	 * Every time a click happens, this function checks to see if the click was on the modal dialog,
	 * or outside of it.
	 *
	 * If the click is outside of the dialog, we close the modal without saving.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param {Event} event The click event
	 *
	 * @return {null}
	 */
	handleClick: function(event) {
		let clickArea = this.refs.dialog,
			options   = this.props.options || {};
		if (! options.keepOpen && ! clickArea.contains(event.target)) {
			this.closeModal();
		}
	},

	/**
	 * A keyup listener attached to the modal.
	 * Every time a key is released, this function checks to see if it was the 'ESC' key.
	 * If the 'ESC' was released, we close the modal.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param {Event} event The keyup event
	 *
	 * @return {null}
	 */
	handleKeyUp: function(event) {
		if (event.keyCode === 27) {
			this.closeModal();
		}
	},

	/**
	 * Determine which, if any, buttons to display
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx}
	 */
	_buildButtons: function () {
		return (

				{this.cancelButton()}
				{this.confirmButton()}

		);
	},

	/**
	 * Set up a modal's class names
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {object} CSS classes for the entire modal component
	 */
	_modalClassnames: function() {
		return classNames({
			'mortar-modal' : true,
			fade           : true,
			in             : this.state.isOpen
		});
	},

	/**
	 * Prepares the CSS classes for the modal body
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {string} CSS classes for the modal body
	 */
	_modalBodyClasses: function() {
		return this.props.modalBodyClasses ? `mortar-modal-body ${this.props.modalBodyClasses}` : 'mortar-modal-body';
	},

	/**
	 * Sets the width of the modal component. The default modal size is 600px.
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {object} Width of modal in pixels
	 */
	_modalWidth: function() {
		let width = this.props.width;
		try {
			if (! this.unitRegExp.test(width)) {
				let newWidth = width.match(this.digitRegExp)[0] + 'px';

				console.warn(`The value provided for width: "${width}" was not valid.  Adjusting to ${newWidth}. Please note that valid css units are required: https://developer.mozilla.org/en-US/docs/Web/CSS/length`);
				width = newWidth;
			}

		} catch (e) {
			console.warn(`A digit is required when specifying width.  Your input: "${width}".  Falling back to 600px.`);
			width = "600px";
		}

		return {
			width: width
		};
	},

	/**
	 * Render the active modal
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {jsx}
	 */
	_renderModal: function() {
		return (

								<button type="button" className="close" onClick={this.closeModal}>×</button>

{this.props.title}

								{this.props.children}

							{this._buildButtons()}

				{this._shouldRenderOverlay()}

		);
	},

	/**
	 * Renders the complete Modal component.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {jsx}
	 */
	render: function () {
		return (

				{this.state.isOpen && this._renderModal()}

		);
	}
});

module.exports = ModalContainer;
<commit_msg>Allowing the CSS to define a default modal width<commit_after>// External Dependencies
const React           = require('react');
const classNames      = require('classnames');

/**
 * A container component for configurable modals
 * @class ModalContainer
 *
 * @memberOf GlobalComponents
 * @see {@link GlobalComponents}
 *
 * @type {*|Function}
 */
const ModalContainer = React.createClass({
	propTypes: {
		openWhen         : React.PropTypes.bool.isRequired,
		width            : React.PropTypes.string,
		title            : React.PropTypes.string.isRequired,
		closeText        : React.PropTypes.string,
		confirmText      : React.PropTypes.string,
		modalBodyClasses : React.PropTypes.string,
		beforeOpen       : React.PropTypes.func,
		afterOpen        : React.PropTypes.func,
		beforeClose      : React.PropTypes.func,
		afterClose       : React.PropTypes.func,
		beforeConfirm    : React.PropTypes.func,
		afterConfirm     : React.PropTypes.func,
		disableConfirm   : React.PropTypes.bool,
		children         : React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.object]),
		options          : React.PropTypes.shape({
			keepOpen: React.PropTypes.bool // If this is true, clicking outside of a modal will not close the modal
		})
	},

	/**
	 * getInitialState
	 *
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {object}
	 */
	getInitialState: function () {
		return {
			isOpen: false
		};
	},

	unitRegExp  : new RegExp(/^\d+(px|em|\%|cm|mm|in|pt|pc|ch|vh|vw|vmin|vmax)$/),
	digitRegExp : new RegExp(/\d+/),

	/**
	 * When the component mounts, an event listener is attached to the window
	 * to track keyup events, and filter them into this component's handleKeyUp function.
	 *
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	componentDidMount: function() {
		window.addEventListener('keyup', this.handleKeyUp);
	},

	/**
	 * When the component is unmounted, the window's KeyUp listener is removed
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	componentWillUnmount: function() {
		window.removeEventListener('keyup', this.handleKeyUp);
	},

	/**
	 * Invoked when a component is receiving new props. This method is not called for the initial render.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param  {object} newProps Incoming props from parent component
	 *
	 * @return {null}
	 */
	componentWillReceiveProps: function(newProps) {
		newProps.openWhen && this.openModal();
	},

	/**
	 * Open the modal and fire appropriate user functions
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	openModal: function () {
		this._modalLifeCycleEvent('open', true);
	},

	/**
	 * Close the modal and fire appropriate user functions
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	closeModal: function () {
		this._modalLifeCycleEvent('close', false);
	},

	/**
	 * Save modal and fire the appropriate user functions
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {null}
	 */
	confirmModal: function () {
		this._modalLifeCycleEvent('confirm', false);
	},

	/**
	 * Fire the before and after lifecycle hooks for the modal component.
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param  {string} action         Modal lifecycle action
	 * @param  {bool}   nextModalState The next value for the modal `isOpen` prop
	 *
	 * @return {null}
	 */
	_modalLifeCycleEvent: function(action, nextModalState) {
		action = action.charAt(0).toUpperCase() + action.slice(1);

		this._callUserFunc(`before${action}`);

		this.setState({
			isOpen: nextModalState
		});

		this._callUserFunc(`after${action}`);
	},

	/**
	 * Determine whether the modal is open and we should render the overlay
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx|null}
	 */
	_shouldRenderOverlay: function () {
		return this.state.isOpen &&

;
	},

	/**
	 * Fire the selected user function, if it's provided
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param {string} propName Lifecycle event for modal
	 *
	 * @return {null}
	 */
	_callUserFunc: function (propName) {
		if (this.props[propName]) {
			this.props[propName]();
		}
	},

	/**
	 * Return save button jsx
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx}
	 */
	confirmButton: function () {
		return <button type="button" className={"btn btn-primary"} disabled={this.props.disableConfirm} onClick={this.confirmModal}>{this.props.confirmText || 'Confirm'}</button>;
	},

	/**
	 * Return cancel button jsx
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx}
	 */
	cancelButton: function () {
		return <button type="button" className="btn btn-default" onClick={this.closeModal}>{this.props.closeText || 'Cancel'}</button>;
	},

	/**
	 * A click listener attached to the modal.
	 * Every time a click happens, this function checks to see if the click was on the modal dialog,
	 * or outside of it.
	 *
	 * If the click is outside of the dialog, we close the modal without saving.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param {Event} event The click event
	 *
	 * @return {null}
	 */
	handleClick: function(event) {
		let clickArea = this.refs.dialog,
			options   = this.props.options || {};
		if (! options.keepOpen && ! clickArea.contains(event.target)) {
			this.closeModal();
		}
	},

	/**
	 * A keyup listener attached to the modal.
	 * Every time a key is released, this function checks to see if it was the 'ESC' key.
	 * If the 'ESC' was released, we close the modal.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @param {Event} event The keyup event
	 *
	 * @return {null}
	 */
	handleKeyUp: function(event) {
		if (event.keyCode === 27) {
			this.closeModal();
		}
	},

	/**
	 * Determine which, if any, buttons to display
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @returns {jsx}
	 */
	_buildButtons: function () {
		return (

				{this.cancelButton()}
				{this.confirmButton()}

		);
	},

	/**
	 * Set up a modal's class names
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {object} CSS classes for the entire modal component
	 */
	_modalClassnames: function() {
		return classNames({
			'mortar-modal' : true,
			fade           : true,
			in             : this.state.isOpen
		});
	},

	/**
	 * Prepares the CSS classes for the modal body
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {string} CSS classes for the modal body
	 */
	_modalBodyClasses: function() {
		return this.props.modalBodyClasses ? `mortar-modal-body ${this.props.modalBodyClasses}` : 'mortar-modal-body';
	},

	/**
	 * Sets the width of the modal component. The default modal size is 600px.
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {object | boolean} Width of modal in pixels or false if one is not provided
	 */
	_modalWidth: function() {
		let width = this.props.width;

		try {
			if (! this.unitRegExp.test(width)) {
				let newWidth = width.match(this.digitRegExp)[0] + 'px';

				console.warn(`The value provided for width: "${width}" was not valid.  Adjusting to ${newWidth}. Please note that valid css units are required: https://developer.mozilla.org/en-US/docs/Web/CSS/length`);
				width = newWidth;

				return {
					width: width
				};
			}

		} catch (e) {
			console.warn(`A digit is required when specifying width.  Your input: "${width}".  Falling back to 600px.`);
			return false;
		}
	},

	/**
	 * Render the active modal
	 *
	 * @private
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {jsx}
	 */
	_renderModal: function() {
		return (

								<button type="button" className="close" onClick={this.closeModal}>×</button>

{this.props.title}

								{this.props.children}

							{this._buildButtons()}

				{this._shouldRenderOverlay()}

		);
	},

	/**
	 * Renders the complete Modal component.
	 * @memberOf GlobalComponents.ModalContainer
	 *
	 * @return {jsx}
	 */
	render: function () {
		return (

				{this.state.isOpen && this._renderModal()}

		);
	}
});

module.exports = ModalContainer;
<|endoftext|>


<commit_before>/**@jsx React.DOM */

var React = require('react');
var Addons = require('react-addons');

var RequiredTextbox = React.createClass({displayName: 'RequiredTextbox',

    getInitialState: function(){
        return {value : this.props.value ,valid: this.props.value && this.props.value.length};
    },
    getDefaultProps:function(){
        return {type:"text", pattern:null};
    },
    onChange:function(e){
        this.setState({value:e.target.value, valid:e.target.value.length});
    },
    render: function () {

        var controlClass = Addons.classSet({
            "ng-invalid-required":!this.state.valid,
            "ng-valid-required":this.state.valid
        });

        return this.transferPropsTo(React.DOM.input( {type:"password", onChange:this.onChange, className:controlClass, value:this.state.value}   ));
}

});

module.exports = RequiredTextbox;

<commit_msg>Delete RequiredPassword.js<commit_after><|endoftext|>