<commit_before>'use strict';

var app = angular.module('myApp.controllers', [

  'myApp.authentications.controller',
  'myApp.boxes.controller',
  'myApp.events.controller',
  'myApp.heartbeats.controller',
  'myApp.jobs.controller',
  'myApp.invoices.controller',
  'myApp.locations.controller',
  'myApp.port_forwards.controller',
  'myApp.reports.controller',
  'myApp.speedtests.controller',
  'myApp.splash_pages.controller',
  'myApp.registrations.controller',
  'myApp.zones.controller',
  'myApp.users.controller',
  'myApp.vouchers.controller'
]);

app.controller('MainCtrl', ['$rootScope', '$scope', '$localStorage', '$window', '$location', '$routeParams', 'AccessToken', 'RefreshToken', 'Auth', 'API_END_POINT', '$pusher', '$route', 'onlineStatus', '$cookies', 'Brand', 'locationHelper', 'BrandName', 'CTLogin', 'User', 'Me', 'AUTH_URL', 'menu', 'designer', '$mdSidenav', 'docs', '$mdMedia', '$q', 'INTERCOM', 'PUSHER', 'gettextCatalog', 'Translate', 'COMMITHASH',

  function ($rootScope, $scope, $localStorage, $window, $location, $routeParams, AccessToken, RefreshToken, Auth, API, $pusher, $route, onlineStatus, $cookies, Brand, locationHelper, BrandName, CTLogin, User, Me, AUTH_URL, menu, designer, $mdSidenav, docs, $mdMedia, $q, INTERCOM, PUSHER, gettextCatalog, Translate, COMMITHASH) {

    $scope.commit = COMMITHASH;
    console.log('COMMIT: #', $scope.commit);
    $scope.ct_login = CTLogin;

    // Zak Moonman - bonjour move these into something separate
    docs.url['find-mac'] = 'http://docs.cucumberwifi.io/article/112-finding-your-mac-address';
    docs.url['getting-started'] = 'http://docs.cucumberwifi.io/category/403-getting-started';
    docs.url['firmware'] = 'http://docs.cucumberwifi.io/category/403-getting-started';
    docs.url['walled-gardens'] = 'http://docs.cucumberwifi.io/article/91-walled-gardens';
    docs.url['branding'] = 'http://docs.cucumberwifi.io/article/229-branding-your-dashboard-login';
    // Zak Moonman - bonjour move these into something separate

    function isOpen(section) {
      return (menu.isSectionSelected(section) && menu.isOpen());
    }

    $scope.toggle = function(section){
      $mdSidenav(section || 'left').toggle();
    };

    var toggleOpen = function(){
      if ($mdMedia('gt-sm')) {
        vm.menu.isOpenLeft = false;
        menu.isOpen = !menu.isOpen;
        vm._ctm = !vm._ctm;
        $cookies.put('_ctm', !menu.isOpen);
      } else {
        vm.menu.isOpenLeft = !vm.menu.isOpenLeft;
      }
      $(window).trigger('resize');
    };

    function toggle(section) {
      menu.toggleSelectSection(section);
    }

    var vm = this;

    vm._ctm = $cookies.get('_ctm');
    vm.menu = menu;

    vm.designer = designer;
    vm.toggle = toggle;

    if ($cookies.get('_ctm') === 'true') {
      vm.menu.isOpenLeft = false;
      vm.menu.isOpen = false;
    }

    vm.menu.main = [{
      title: gettextCatalog.getString('Home'),
      link: '/#/',
      type: 'link',
      icon: 'home'
    }];

    vm.menu.main.push({
      title: gettextCatalog.getString('Locations'),
      type: 'link',
      link: '/#/locations',
      icon: 'business'
    });

    vm.menu.main.push({
      title: gettextCatalog.getString('Reports'),
      type: 'link',
      link: '/#/reports',
      icon: 'timeline'
    });

    vm.menu.main.push({
      title: gettextCatalog.getString('Audit'),
      type: 'link',
      link: '/#/audit',
      icon: 'assignment'
    });

    vm.menu.main.push({
      title: gettextCatalog.getString('Events'),
      type: 'link',
      link: '/#/events',
      icon: 'warning'
    });

    vm.status = {
      isFirstOpen: true,
      isFirstDisabled: false
    };

    vm.settingsMenu = [];

    vm.menuRight = [];

    vm.menuRight.push({
      name: gettextCatalog.getString('Home'),
      link: '/#/',
      type: 'link',
      icon: 'home'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Locations'),
      link: '/#/locations',
      type: 'link',
      icon: 'business'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Reports'),
      link: '/#/reports',
      type: 'link',
      icon: 'timeline'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Audit'),
      link: '/#/audit',
      type: 'link',
      icon: 'assignment'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Developer'),
      link: '/#/apps',
      type: 'link',
      icon: 'android'
    });

    // Permissions //
    vm.menuRight.push({
      name: gettextCatalog.getString('Documentation'),
      link: 'http://docs.cucumberwifi.io',
      type: 'link',
      target: '_blank',
      icon: 'account_balance'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Discussions'),
      link: 'https://discuss.cucumberwifi.io',
      target: '_blank',
      type: 'link',
      icon: 'forum'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Support'),
      icon: 'get_app',
      id: 'intercom'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Downloads'),
      link: '/#/downloads',
      type: 'link',
      icon: 'get_app'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Profile'),
      link: '/#/me',
      type: 'link',
      icon: 'face'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    // vm.menuRight.push({
    //   name: gettextCatalog.getString('Logout'),
    //   type: 'link',
    //   icon: 'exit_to_app'
    // });

    $scope.toggleOpen = toggleOpen;

    $scope.$on('logout', function(args) {
      logout().then(function(response) {
        $route.reload();
        console.log('Refreshing Token.');
      }, function() {
        Auth.fullLogin();
      });
    });

    var logout = function(args) {
      var deferred = $q.defer();
      var user = $localStorage.user;
      var path = $location.path();
      AccessToken.del();
      if ( user && user.refresh ) {
        var host  = locationHelper.domain();
        $cookies.put('_ctp', JSON.stringify(path) );
        RefreshToken.refresh(user.refresh, path).then(function(response) {
          Auth.refresh(response).then(function(a){
            deferred.resolve();
          });
        }, function(er) {
          deferred.reject();
        });
      } else {
        deferred.reject();
      }
      return deferred.promise;
    };

    $scope.$on('login', function(args,event) {

      console.log('Logging in...');
      var cname = event.data.cname;
      if ((cname === null || cname === '') && event.data.url !== 'default') {
        var sub   = locationHelper.subdomain();
        var host  = locationHelper.domain();
        // put back when on public //
        // if (event.data.url && (sub !== event.data.url)) {
        //   var newUrl = locationHelper.reconstructed(event.data.url);
        //   var reconstructed = newUrl + '/#/switch?return_to=' + event.path;
        //   $cookies.put('event', JSON.stringify(event), {'domain': host});
        //   window.location = reconstructed;
        // } else {
          doLogin(event);
        // }
      } else {
        doLogin(event);
      }
    });

    function doLogin(event) {
      Auth.login(event.data).then(function(a) {
        var path;
        $scope.loggedIn = true;
        if (event.path) {
          path = event.path;
        } else {
          var raw = $cookies.get('_ctp');
          if (raw) {
            try{
              path = JSON.parse(raw);
            }catch(e){
              console.log('Couldn\'t parse JSON to redirect');
            }
          }
        }
        $location.path(path || '/').search(event.search || {});
        if (event !== undefined && event.rdir !== undefined) {
          $location.search({rdir: event.rdir});
        }
        $cookies.remove('_ctp');
        $scope.ct_login = undefined;
        Translate.load();
      });
    }

    $scope.$on('intercom', function(args,event) {
      if (Auth.currentUser() && (Auth.currentUser().chat_enabled !== false && Auth.currentUser().user_hash !== undefined)) {
        vm.menu.Intercom = true;
        var settings = {
            app_id: INTERCOM,
            user_id: Auth.currentUser().accountId,
            email: Auth.currentUser().email,
            name: Auth.currentUser().username,
            created_at: Auth.currentUser().created_at,
            user_hash: Auth.currentUser().user_hash,
            brand_name: Auth.currentUser().url,
            cname: Auth.currentUser().cname,
            sense_active: Auth.currentUser().sense_active,
            plan_name: Auth.currentUser().plan_name,
            paid_plan: Auth.currentUser().paid_plan,
            locs: Auth.currentUser().locs,
            version: '2'
        };
        settings.widget = {
          activator: '#intercom'
        };
        window.Intercom('boot', settings);
      }
    });

    $rootScope.$on('$routeChangeStart', function (event, next, current) {
      var pusher;
      if (Auth.currentUser() && Auth.currentUser().key !== null) {
        $scope.$broadcast('intercom', {hi: 'simon'});
        window.client = new Pusher(PUSHER, {
          authEndpoint: API + '/pusherAuth?token=' + Auth.currentUser().key
        });
        pusher = $pusher(client);
      }

      $scope.brandName = BrandName;
      function getSubdomain () {
        var sub   = locationHelper.subdomain();
        var host  = locationHelper.domain();
        var parts = $location.host().split('.');
        var cname;
        if (host !== 'ctapp.io' && host !== 'ctapp.dev') {
          getBrand(host, true);
        }
        else if (parts.length === 3) {
          sub = parts[0];
          getBrand(sub);
        } else {
          console.log('Domain error occured');
        }
      }

      function getBrand(sub, cname) {
        if (Auth.currentUser() && Auth.currentUser().url !== null) {
          sub = Auth.currentUser().url;
        }

        Brand.query({
          id: sub,
          cname: cname,
          type: 'showcase'
        }).$promise.then(function(results) {
          // Decide to switch the brand here
          // Can we turn Cucumber into a variable so we don't just set
          // Maybe use the config files - Simon TBD //
          $scope.brandName.name  = results.brand_name || 'Cucumber';
          // Maybe use the config files - Simon TBD //
          $scope.brandName.admin = results.admin;
          $scope.brandName.url   = results.url;
          $scope.brandName.id    = results.id;
        }, function() {
          setDefaultImages(sub);
        });
      }

      function getMe() {
        Me.get({}).$promise.then(function(res) {
          Auth.login(res).then(function(a) {
            $scope.user = Auth.currentUser();
            $scope.loggedIn = true;
          });
        });
      }

      var setDefaultImages = function(sub) {
        $scope.brandName.name = 'Cucumber';
      };

      var firstName = function() {
        if (Auth.currentUser() && Auth.currentUser().username) {
          $scope.user = { gravatar: Auth.currentUser().gravatar, lucky_dip: Auth.currentUser().lucky_dip };
        }
      };

      var a = AccessToken.get();
      if ( (!Auth.currentUser() && a ) || Auth.currentUser() && (Auth.currentUser().url !== 'default' )) {
        getMe();
      }
      firstName();
      getSubdomain();

      var domain = 'ctapp.io';
      var addDistro = function() {
        $cookies.put('_ct', $location.search().dst, {'domain': domain});
        $location.search({});
      };

      if ($location.search().dst) {
        addDistro();
      }

      var removeCtCookie = function() {
        $cookies.remove('_ct', { domain: domain } );
      };

      var cookie = $cookies.get('_ct', {'domain': domain});
      if (cookie && Auth.currentUser() && Auth.currentUser().id) {
        User.distro({dst: cookie}).$promise.then(function(result) {
          removeCtCookie();
        }, function() {
          removeCtCookie();
        });
      }
      Translate.load();
    });

    var setLoggedIn = function(isLoggedIn) {
      $scope.loggedIn = isLoggedIn;
      return isLoggedIn;
    };

    setLoggedIn(AccessToken.get() !== undefined);

    $scope.logout = function() {
      Auth.logout();
    };

    // $scope.onlineStatus = onlineStatus;
    // if ( $scope.loggedIn ) {
      // $scope.$watch('onlineStatus.isOnline()', function(online) {
      //   $scope.online_status_string = online ? 'online' : 'offline';
      //   if ($scope.online_status_string === 'offline') {
      //     $scope.open('md');
      //   } else if ($scope.online_status_string === 'online' ){
      //     // if ($scope.modalInstance !== undefined) {
      //     //   $scope.modalInstance.close();
      //     // }
      //   }
      // });
    // }

    // $scope.open = function (size) {
    // };

    // $scope.close = function() {
    // };

}]);

app.controller( 'ParentCtrl', function ParentCtrl($scope, onlineStatus) {

  // $scope.items = [];
  // $scope.linkItems = {
  // };

  // $scope.onlineStatus = onlineStatus;
  // $scope.$watch('onlineStatus.isOnline()', function(online) {
  //   $scope.online_status_string = online ? 'online' : 'offline';
  //   if ($scope.online_status_string === 'offline') {
  //     $scope.open('md');
  //   } else if ($scope.online_status_string === 'online' ){
  //   }
  // });

  // $scope.open = function (size) {
  // };

});
<commit_msg>Intercom, you are a menace<commit_after>'use strict';

var app = angular.module('myApp.controllers', [

  'myApp.authentications.controller',
  'myApp.boxes.controller',
  'myApp.events.controller',
  'myApp.heartbeats.controller',
  'myApp.jobs.controller',
  'myApp.invoices.controller',
  'myApp.locations.controller',
  'myApp.port_forwards.controller',
  'myApp.reports.controller',
  'myApp.speedtests.controller',
  'myApp.splash_pages.controller',
  'myApp.registrations.controller',
  'myApp.zones.controller',
  'myApp.users.controller',
  'myApp.vouchers.controller'
]);

app.controller('MainCtrl', ['$rootScope', '$scope', '$localStorage', '$window', '$location', '$routeParams', 'AccessToken', 'RefreshToken', 'Auth', 'API_END_POINT', '$pusher', '$route', 'onlineStatus', '$cookies', 'Brand', 'locationHelper', 'BrandName', 'CTLogin', 'User', 'Me', 'AUTH_URL', 'menu', 'designer', '$mdSidenav', 'docs', '$mdMedia', '$q', 'INTERCOM', 'PUSHER', 'gettextCatalog', 'Translate', 'COMMITHASH',

  function ($rootScope, $scope, $localStorage, $window, $location, $routeParams, AccessToken, RefreshToken, Auth, API, $pusher, $route, onlineStatus, $cookies, Brand, locationHelper, BrandName, CTLogin, User, Me, AUTH_URL, menu, designer, $mdSidenav, docs, $mdMedia, $q, INTERCOM, PUSHER, gettextCatalog, Translate, COMMITHASH) {

    $scope.commit = COMMITHASH;
    console.log('COMMIT: #', $scope.commit);
    $scope.ct_login = CTLogin;

    // Zak Moonman - bonjour move these into something separate
    docs.url['find-mac'] = 'http://docs.cucumberwifi.io/article/112-finding-your-mac-address';
    docs.url['getting-started'] = 'http://docs.cucumberwifi.io/category/403-getting-started';
    docs.url['firmware'] = 'http://docs.cucumberwifi.io/category/403-getting-started';
    docs.url['walled-gardens'] = 'http://docs.cucumberwifi.io/article/91-walled-gardens';
    docs.url['branding'] = 'http://docs.cucumberwifi.io/article/229-branding-your-dashboard-login';
    // Zak Moonman - bonjour move these into something separate

    function isOpen(section) {
      return (menu.isSectionSelected(section) && menu.isOpen());
    }

    $scope.toggle = function(section){
      $mdSidenav(section || 'left').toggle();
    };

    var toggleOpen = function(){
      if ($mdMedia('gt-sm')) {
        vm.menu.isOpenLeft = false;
        menu.isOpen = !menu.isOpen;
        vm._ctm = !vm._ctm;
        $cookies.put('_ctm', !menu.isOpen);
      } else {
        vm.menu.isOpenLeft = !vm.menu.isOpenLeft;
      }
      $(window).trigger('resize');
    };

    function toggle(section) {
      menu.toggleSelectSection(section);
    }

    var vm = this;

    vm._ctm = $cookies.get('_ctm');
    vm.menu = menu;

    vm.designer = designer;
    vm.toggle = toggle;

    if ($cookies.get('_ctm') === 'true') {
      vm.menu.isOpenLeft = false;
      vm.menu.isOpen = false;
    }

    vm.menu.main = [{
      title: gettextCatalog.getString('Home'),
      link: '/#/',
      type: 'link',
      icon: 'home'
    }];

    vm.menu.main.push({
      title: gettextCatalog.getString('Locations'),
      type: 'link',
      link: '/#/locations',
      icon: 'business'
    });

    vm.menu.main.push({
      title: gettextCatalog.getString('Reports'),
      type: 'link',
      link: '/#/reports',
      icon: 'timeline'
    });

    vm.menu.main.push({
      title: gettextCatalog.getString('Audit'),
      type: 'link',
      link: '/#/audit',
      icon: 'assignment'
    });

    vm.menu.main.push({
      title: gettextCatalog.getString('Events'),
      type: 'link',
      link: '/#/events',
      icon: 'warning'
    });

    vm.status = {
      isFirstOpen: true,
      isFirstDisabled: false
    };

    vm.settingsMenu = [];

    vm.menuRight = [];

    vm.menuRight.push({
      name: gettextCatalog.getString('Home'),
      link: '/#/',
      type: 'link',
      icon: 'home'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Locations'),
      link: '/#/locations',
      type: 'link',
      icon: 'business'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Reports'),
      link: '/#/reports',
      type: 'link',
      icon: 'timeline'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Audit'),
      link: '/#/audit',
      type: 'link',
      icon: 'assignment'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Developer'),
      link: '/#/apps',
      type: 'link',
      icon: 'android'
    });

    // Permissions //
    vm.menuRight.push({
      name: gettextCatalog.getString('Documentation'),
      link: 'http://docs.cucumberwifi.io',
      type: 'link',
      target: '_blank',
      icon: 'account_balance'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Discussions'),
      link: 'https://discuss.cucumberwifi.io',
      target: '_blank',
      type: 'link',
      icon: 'forum'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Support'),
      icon: 'get_app',
      id: 'intercom'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Downloads'),
      link: '/#/downloads',
      type: 'link',
      icon: 'get_app'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Profile'),
      link: '/#/me',
      type: 'link',
      icon: 'face'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    // vm.menuRight.push({
    //   name: gettextCatalog.getString('Logout'),
    //   type: 'link',
    //   icon: 'exit_to_app'
    // });

    $scope.toggleOpen = toggleOpen;

    $scope.$on('logout', function(args) {
      logout().then(function(response) {
        $route.reload();
        console.log('Refreshing Token.');
      }, function() {
        Auth.fullLogin();
      });
    });

    var logout = function(args) {
      var deferred = $q.defer();
      var user = $localStorage.user;
      var path = $location.path();
      AccessToken.del();
      if ( user && user.refresh ) {
        var host  = locationHelper.domain();
        $cookies.put('_ctp', JSON.stringify(path) );
        RefreshToken.refresh(user.refresh, path).then(function(response) {
          Auth.refresh(response).then(function(a){
            deferred.resolve();
          });
        }, function(er) {
          deferred.reject();
        });
      } else {
        deferred.reject();
      }
      return deferred.promise;
    };

    $scope.$on('login', function(args,event) {

      console.log('Logging in...');
      var cname = event.data.cname;
      if ((cname === null || cname === '') && event.data.url !== 'default') {
        var sub   = locationHelper.subdomain();
        var host  = locationHelper.domain();
        // put back when on public //
        // if (event.data.url && (sub !== event.data.url)) {
        //   var newUrl = locationHelper.reconstructed(event.data.url);
        //   var reconstructed = newUrl + '/#/switch?return_to=' + event.path;
        //   $cookies.put('event', JSON.stringify(event), {'domain': host});
        //   window.location = reconstructed;
        // } else {
          doLogin(event);
        // }
      } else {
        doLogin(event);
      }
    });

    function doLogin(event) {
      Auth.login(event.data).then(function(a) {
        var path;
        $scope.loggedIn = true;
        if (event.path) {
          path = event.path;
        } else {
          var raw = $cookies.get('_ctp');
          if (raw) {
            try{
              path = JSON.parse(raw);
            }catch(e){
              console.log('Couldn\'t parse JSON to redirect');
            }
          }
        }
        $location.path(path || '/').search(event.search || {});
        if (event !== undefined && event.rdir !== undefined) {
          $location.search({rdir: event.rdir});
        }
        $cookies.remove('_ctp');
        $scope.ct_login = undefined;
        Translate.load();
      });
    }

    $scope.$on('intercom', function(args,event) {
      if (Auth.currentUser() && (Auth.currentUser().chat_enabled !== false && Auth.currentUser().user_hash !== undefined)) {
        // vm.menu.Intercom = true;
        var settings = {
            app_id: INTERCOM,
            user_id: Auth.currentUser().accountId,
            email: Auth.currentUser().email,
            name: Auth.currentUser().username,
            created_at: Auth.currentUser().created_at,
            user_hash: Auth.currentUser().user_hash,
            brand_name: Auth.currentUser().url,
            cname: Auth.currentUser().cname,
            sense_active: Auth.currentUser().sense_active,
            plan_name: Auth.currentUser().plan_name,
            paid_plan: Auth.currentUser().paid_plan,
            locs: Auth.currentUser().locs,
            version: '2'
        };
        // settings.widget = {
        //   activator: '#intercom'
        // };
        window.Intercom('boot', settings);
      }
    });

    $rootScope.$on('$routeChangeStart', function (event, next, current) {
      var pusher;
      if (Auth.currentUser() && Auth.currentUser().key !== null) {
        $scope.$broadcast('intercom', {hi: 'simon'});
        window.client = new Pusher(PUSHER, {
          authEndpoint: API + '/pusherAuth?token=' + Auth.currentUser().key
        });
        pusher = $pusher(client);
      }

      $scope.brandName = BrandName;
      function getSubdomain () {
        var sub   = locationHelper.subdomain();
        var host  = locationHelper.domain();
        var parts = $location.host().split('.');
        var cname;
        if (host !== 'ctapp.io' && host !== 'ctapp.dev') {
          getBrand(host, true);
        }
        else if (parts.length === 3) {
          sub = parts[0];
          getBrand(sub);
        } else {
          console.log('Domain error occured');
        }
      }

      function getBrand(sub, cname) {
        if (Auth.currentUser() && Auth.currentUser().url !== null) {
          sub = Auth.currentUser().url;
        }

        Brand.query({
          id: sub,
          cname: cname,
          type: 'showcase'
        }).$promise.then(function(results) {
          // Decide to switch the brand here
          // Can we turn Cucumber into a variable so we don't just set
          // Maybe use the config files - Simon TBD //
          $scope.brandName.name  = results.brand_name || 'Cucumber';
          // Maybe use the config files - Simon TBD //
          $scope.brandName.admin = results.admin;
          $scope.brandName.url   = results.url;
          $scope.brandName.id    = results.id;
        }, function() {
          setDefaultImages(sub);
        });
      }

      function getMe() {
        Me.get({}).$promise.then(function(res) {
          Auth.login(res).then(function(a) {
            $scope.user = Auth.currentUser();
            $scope.loggedIn = true;
          });
        });
      }

      var setDefaultImages = function(sub) {
        $scope.brandName.name = 'Cucumber';
      };

      var firstName = function() {
        if (Auth.currentUser() && Auth.currentUser().username) {
          $scope.user = { gravatar: Auth.currentUser().gravatar, lucky_dip: Auth.currentUser().lucky_dip };
        }
      };

      var a = AccessToken.get();
      if ( (!Auth.currentUser() && a ) || Auth.currentUser() && (Auth.currentUser().url !== 'default' )) {
        getMe();
      }
      firstName();
      getSubdomain();

      var domain = 'ctapp.io';
      var addDistro = function() {
        $cookies.put('_ct', $location.search().dst, {'domain': domain});
        $location.search({});
      };

      if ($location.search().dst) {
        addDistro();
      }

      var removeCtCookie = function() {
        $cookies.remove('_ct', { domain: domain } );
      };

      var cookie = $cookies.get('_ct', {'domain': domain});
      if (cookie && Auth.currentUser() && Auth.currentUser().id) {
        User.distro({dst: cookie}).$promise.then(function(result) {
          removeCtCookie();
        }, function() {
          removeCtCookie();
        });
      }
      Translate.load();
    });

    var setLoggedIn = function(isLoggedIn) {
      $scope.loggedIn = isLoggedIn;
      return isLoggedIn;
    };

    setLoggedIn(AccessToken.get() !== undefined);

    $scope.logout = function() {
      Auth.logout();
    };

    // $scope.onlineStatus = onlineStatus;
    // if ( $scope.loggedIn ) {
      // $scope.$watch('onlineStatus.isOnline()', function(online) {
      //   $scope.online_status_string = online ? 'online' : 'offline';
      //   if ($scope.online_status_string === 'offline') {
      //     $scope.open('md');
      //   } else if ($scope.online_status_string === 'online' ){
      //     // if ($scope.modalInstance !== undefined) {
      //     //   $scope.modalInstance.close();
      //     // }
      //   }
      // });
    // }

    // $scope.open = function (size) {
    // };

    // $scope.close = function() {
    // };

}]);

app.controller( 'ParentCtrl', function ParentCtrl($scope, onlineStatus) {

  // $scope.items = [];
  // $scope.linkItems = {
  // };

  // $scope.onlineStatus = onlineStatus;
  // $scope.$watch('onlineStatus.isOnline()', function(online) {
  //   $scope.online_status_string = online ? 'online' : 'offline';
  //   if ($scope.online_status_string === 'offline') {
  //     $scope.open('md');
  //   } else if ($scope.online_status_string === 'online' ){
  //   }
  // });

  // $scope.open = function (size) {
  // };

});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Restaurant from './Restaurant';

class RestaurantList extends Component {
 	constructor(props) {
 		super(props);
    this.onInputChange = this.onInputChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
 		this.state = {
      searchInput: ''
    };
 	}

 	onInputChange(event) {
 		this.setState({ searchInput: event.target.value });
 	}

 	onFormSubmit(event) {
 		event.preventDefault();
    const { fetchRestaurants } = this.props.searchActions;

 		fetchRestaurants(this.state.searchInput);

 		this.setState({ searchInput: '' });
 	}

 	render() {
 		let restaurant = this.props.restaurants.map((restaurant, index) => {
 			return (
 				<Restaurant
          name={restaurant.name}
          key={index} />
 			)
 		})

    let searchError = this.props.searchErrorMsg ? (

        No Restaurants Found!

) : null;

 		return (

		 		<form onSubmit={this.onFormSubmit} className='input-group'>
		 			<input
		 				placeholder="Find a restaurant in your favorite city"
		 				className="form-control"
		 				value={this.state.searchInput}
		 				onChange={this.onInputChange}/>

		 				<button type="submit" className="btn btn-secondary">Submit</button>

		 		</form>
        {searchError}
		 		{restaurant}

 		)
 	}
 }

 export default RestaurantList;
<commit_msg>[fix] fixes logout and searchbar bug<commit_after>import React, { Component } from 'react';
import Restaurant from './Restaurant';

class RestaurantList extends Component {
 	constructor(props) {
 		super(props);
    this.onInputChange = this.onInputChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
 		this.state = {
      searchInput: ''
    };
 	}

 	onInputChange(event) {
 		this.setState({ searchInput: event.target.value });
 	}

 	onFormSubmit(event) {
 		event.preventDefault();
    const { fetchRestaurants } = this.props.searchActions;

 		fetchRestaurants(this.state.searchInput);

 		this.setState({ searchInput: '' });
 	}

 	render() {
 		let restaurant = this.props.restaurant ? this.props.restaurant.map((restaurant, index) => {
 			return (
 				<Restaurant
          name={restaurant.name}
          key={index} />
 			)
 		}) : null;

    let searchError = this.props.searchErrorMsg ? (

        No Restaurants Found!

) : null;

 		return (

		 		<form onSubmit={this.onFormSubmit} className='input-group'>
		 			<input
		 				placeholder="Find a restaurant in your favorite city"
		 				className="form-control"
		 				value={this.state.searchInput}
		 				onChange={this.onInputChange}/>

		 				<button type="submit" className="btn btn-secondary">Submit</button>

		 		</form>
        {searchError}
		 		{restaurant}

 		)
 	}
 }

 export default RestaurantList;
<|endoftext|>


<commit_before>/* @flow */

import * as Sunshine from 'sunshine/react'
import React         from 'react'
import moment        from 'moment'
import repa          from 'repa'
import marked        from 'marked'
import { mailtoUri } from '../../../lib/activity'
import * as Ev       from '../event'
import * as State    from '../state'
import { EditNote }  from '../../../lib/components/compose'
import { ActivityOptsMenu } from '../../../lib/components/activityMenu'
import { actorAvatar } from '../../../lib/components/avatar'
import { activityId
       , actor
       , edited
       , lastEdited
       , likes
       , likeCount
       , objectContent
       , objectType
       , published
       , verb
       } from '../../../lib/derivedActivity'
import { Card
       , CardHeader
       , FlatButton
       , Paper
       } from 'material-ui'

import type { DerivedActivity } from '../../../lib/derivedActivity'
import type { Conversation }    from '../../../lib/conversation'

export type ActivityProps = {
  activity:     DerivedActivity,
  conversation: Conversation,
  editing:      ?DerivedActivity,
  loading:      boolean,
  username:     string,
  useremail:    string,
}

var styles = {
  body: {
    padding: '16px',
    paddingTop: 0,
  },
  activityCard: {
    paddingTop: '0.6em'
  },
  inlineNotice: {
    padding: '16px',
    paddingBottom: 0,
  },
  inlineNoticeUnderHeader: {
    padding: '16px',
    paddingBottom: 0,
    paddingTop: 0,
  },
  menu: {
    float: 'right',
  },
}

export class ActivityView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var activity = this.props.activity
    var v = verb(activity)
    if (v === 'conflict') {
      return <ConflictView {...this.props} />
    }
    else if (v === 'join') {
      return <JoinView {...this.props} />
    }
    else if (objectType(activity) === 'note') {
      return this.editingThis() ?
        <EditNote {...this.props} /> :
        <NoteView {...this.props} />
    }
    else {
      return (
        <UnknownView {...this.props} />
      )
    }
  }

  unknown(): React.Element {
    return (
      <Paper>
        {displayUnknown()}
      </Paper>
    )
  }

  editingThis(): boolean {
    var { activity, editing } = this.props
    return editing && activityId(editing) === activityId(activity)
  }
}

class NoteView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var { activity, useremail } = this.props
    var fromStr = actor(activity).displayName || '[unknown sender]'
    var dateStr = published(activity).fromNow()
    return (

      <Paper>
        <CardHeader
          title={fromStr}
          subtitle={dateStr}
          avatar={actorAvatar(actor(activity))}
          >
          <LikeButton style={{ float:'right' }} {...this.props} />
          <ActivityOptsMenu style={styles.menu} {...this.props} />
        </CardHeader>
        {edited(activity) ?

            Last edited {lastEdited(activity).fromNow()}

 : ''}
        {displayContent(activity)}
      </Paper>

    )
  }
}

class ConflictView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var { activity, useremail } = this.props
    var fromStr = actor(activity).displayName || '[unknown sender]'
    var dateStr = published(activity).fromNow()
    return (

      <Paper>

          Edit failed due to a conflict with another edit.

        {displayContent(activity)}
      </Paper>

    )
  }
}

class JoinView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var { activity } = this.props
    var fromStr = actor(activity).displayName
    return (

      <Paper>
        <CardHeader
          title={fromStr}
          subtitle='joined the discussion'
          avatar={actorAvatar(actor(activity))}
          >
        </CardHeader>
      </Paper>

    )
  }
}

class UnknownView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var activity = this.props.activity
    var fromStr  = actor(activity).displayName || '[unknown sender]'
    var dateStr  = published(activity).fromNow()
    return (
      <Paper>
        <CardHeader
          title={fromStr}
          subtitle={dateStr}
          avatar={actorAvatar(actor(activity))}
          />
        {displayContent(activity)}
      </Paper>
    )
  }
}

type LikeButtonProps = ActivityProps & {
  style?: Object
}

class LikeButton extends Sunshine.Component<{},LikeButtonProps,{}> {
  render(): React.Element {
    var { activity, loading, useremail, style } = this.props
    var me           = mailtoUri(useremail)
    var alreadyLiked = likes(activity).some(l => l.uri === me)
    var mine         = myContent(activity, useremail)
    return (
      <FlatButton
        style={style || {}}
        label={`+${likeCount(activity)+1}`}
        onTouchTap={this.like.bind(this)}
        disabled={mine || alreadyLiked || loading}
        />
    )
  }

  like() {
    this.emit(new Ev.Like(this.props.activity, this.props.conversation))
  }
}

function displayContent(activity: DerivedActivity): React.Element {
  var content = objectContent(activity)
  .sort((a,b) => {
    // prefer text/plain
    if (a.contentType === 'text/plain' && b.contentType !== 'text/plain') {
      return -1
    }
    else if (a.contentType !== 'text/plain' && b.contentType === 'text/plain') {
      return 1
    }
    else {
      return 0
    }
  })
  .filter(({ contentType }) => contentType === 'text/plain' || contentType === 'text/html')  // TODO: support other content types
  [0]
  if (content && content.contentType === 'text/plain') {
    return displayText(content.content)
  }
  else if (content && content.contentType === 'text/html') {
    return displayHtml(content.content)
  }
  else {
    return displayUnknown()
  }
}

function displayText(content: Buffer): React.Element {
  var content = repa(content.toString('utf8'))
  var out = {
    __html: marked(content, { sanitized: true })
  }
  return

}

function displayHtml(content: Buffer): React.Element {
  return (

TODO: display HTML

  )
}

function displayUnknown(): React.Element {
  return

[no content]

}

function myContent(activity: DerivedActivity, email: string): boolean {
  var me = mailtoUri(email)
  return actor(activity).uri === me
}
<commit_msg>Another whitespace tweak<commit_after>/* @flow */

import * as Sunshine from 'sunshine/react'
import React         from 'react'
import moment        from 'moment'
import repa          from 'repa'
import marked        from 'marked'
import { mailtoUri } from '../../../lib/activity'
import * as Ev       from '../event'
import * as State    from '../state'
import { EditNote }  from '../../../lib/components/compose'
import { ActivityOptsMenu } from '../../../lib/components/activityMenu'
import { actorAvatar } from '../../../lib/components/avatar'
import { activityId
       , actor
       , edited
       , lastEdited
       , likes
       , likeCount
       , objectContent
       , objectType
       , published
       , verb
       } from '../../../lib/derivedActivity'
import { Card
       , CardHeader
       , FlatButton
       , Paper
       } from 'material-ui'

import type { DerivedActivity } from '../../../lib/derivedActivity'
import type { Conversation }    from '../../../lib/conversation'

export type ActivityProps = {
  activity:     DerivedActivity,
  conversation: Conversation,
  editing:      ?DerivedActivity,
  loading:      boolean,
  username:     string,
  useremail:    string,
}

var styles = {
  body: {
    padding: '16px',
    paddingTop: 0,
  },
  activityCard: {
    paddingTop: '0.6em'
  },
  inlineNotice: {
    padding: '16px',
    paddingBottom: 0,
  },
  inlineNoticeUnderHeader: {
    padding: '16px',
    paddingBottom: 0,
    paddingTop: 0,
  },
  menu: {
    float: 'right',
  },
}

export class ActivityView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var activity = this.props.activity
    var v = verb(activity)
    if (v === 'conflict') {
      return <ConflictView {...this.props} />
    }
    else if (v === 'join') {
      return <JoinView {...this.props} />
    }
    else if (objectType(activity) === 'note') {
      return this.editingThis() ?
        <EditNote {...this.props} /> :
        <NoteView {...this.props} />
    }
    else {
      return (
        <UnknownView {...this.props} />
      )
    }
  }

  unknown(): React.Element {
    return (
      <Paper>
        {displayUnknown()}
      </Paper>
    )
  }

  editingThis(): boolean {
    var { activity, editing } = this.props
    return editing && activityId(editing) === activityId(activity)
  }
}

class NoteView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var { activity, useremail } = this.props
    var fromStr = actor(activity).displayName || '[unknown sender]'
    var dateStr = published(activity).fromNow()
    return (

      <Paper>
        <CardHeader
          title={fromStr}
          subtitle={dateStr}
          avatar={actorAvatar(actor(activity))}
          >
          <LikeButton style={{ float:'right' }} {...this.props} />
          <ActivityOptsMenu style={styles.menu} {...this.props} />
        </CardHeader>
        {edited(activity) ?

            Last edited {lastEdited(activity).fromNow()}

 : ''}
        {displayContent(activity)}
      </Paper>

    )
  }
}

class ConflictView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var { activity, useremail } = this.props
    var fromStr = actor(activity).displayName || '[unknown sender]'
    var dateStr = published(activity).fromNow()
    return (

      <Paper>

          Edit failed due to a conflict with another edit.

        {displayContent(activity)}
      </Paper>

    )
  }
}

class JoinView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var { activity } = this.props
    var fromStr = actor(activity).displayName
    return (

      <Paper>
        <CardHeader
          title={fromStr}
          subtitle='joined the discussion'
          avatar={actorAvatar(actor(activity))}
          >
        </CardHeader>
      </Paper>

    )
  }
}

class UnknownView extends Sunshine.Component<{},ActivityProps,{}> {
  render(): React.Element {
    var activity = this.props.activity
    var fromStr  = actor(activity).displayName || '[unknown sender]'
    var dateStr  = published(activity).fromNow()
    return (
      <Paper>
        <CardHeader
          title={fromStr}
          subtitle={dateStr}
          avatar={actorAvatar(actor(activity))}
          />
        {displayContent(activity)}
      </Paper>
    )
  }
}

type LikeButtonProps = ActivityProps & {
  style?: Object
}

class LikeButton extends Sunshine.Component<{},LikeButtonProps,{}> {
  render(): React.Element {
    var { activity, loading, useremail, style } = this.props
    var me           = mailtoUri(useremail)
    var alreadyLiked = likes(activity).some(l => l.uri === me)
    var mine         = myContent(activity, useremail)
    return (
      <FlatButton
        style={style || {}}
        label={`+${likeCount(activity)+1}`}
        onTouchTap={this.like.bind(this)}
        disabled={mine || alreadyLiked || loading}
        />
    )
  }

  like() {
    this.emit(new Ev.Like(this.props.activity, this.props.conversation))
  }
}

function displayContent(activity: DerivedActivity): React.Element {
  var content = objectContent(activity)
  .sort((a,b) => {
    // prefer text/plain
    if (a.contentType === 'text/plain' && b.contentType !== 'text/plain') {
      return -1
    }
    else if (a.contentType !== 'text/plain' && b.contentType === 'text/plain') {
      return 1
    }
    else {
      return 0
    }
  })
  .filter(({ contentType }) => contentType === 'text/plain' || contentType === 'text/html')  // TODO: support other content types
  [0]
  if (content && content.contentType === 'text/plain') {
    return displayText(content.content)
  }
  else if (content && content.contentType === 'text/html') {
    return displayHtml(content.content)
  }
  else {
    return displayUnknown()
  }
}

function displayText(content: Buffer): React.Element {
  var content = repa(content.toString('utf8'))
  var out = {
    __html: marked(content, { sanitized: true })
  }
  return

}

function displayHtml(content: Buffer): React.Element {
  return (

TODO: display HTML

  )
}

function displayUnknown(): React.Element {
  return

[no content]

}

function myContent(activity: DerivedActivity, email: string): boolean {
  var me = mailtoUri(email)
  return actor(activity).uri === me
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import {
  Container,
  Segment,
  Grid,
  Form,
  Image,
  Label,
  Card,
  Divider,
  Button
} from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import { uniqBy, union } from 'lodash'
import Zooming from 'zooming'

import { upload } from '../actions/user'
import { search } from '../actions/entities'
import { resetErrorMessageIfNeeded } from '../actions/common'

const propTypes = {
  dispatch: PropTypes.func.isRequired,
  isUploading: PropTypes.bool.isRequired
}

class UploadPage extends Component {
  state = {
    files: [],
    tagSuggestions: [],
    tags: [],
    nsfw: false,
    zooming: new Zooming({
      bgColor: '#000'
    })
  }

  handleInputChange = (event, { value }) => {
    this.setState({
      tags: value
    })
  }

  handleSearchChange = (event, value) => {
    const { dispatch } = this.props

    dispatch(search({ query: value })).then(res => {
      const { value } = res
      const { data } = value
      const newSuggestions = data.map(({ name }) => {
        return { text: name, value: name }
      })

      this.setState({
        tagSuggestions: uniqBy(
          union(this.state.tagSuggestions, newSuggestions),
          'text'
        )
      })
    })
  }

  handleAddTag = (event, { value }) => {
    this.setState({
      tagSuggestions: uniqBy(
        [{ text: value, value }, ...this.state.tagSuggestions],
        'text'
      )
    })
  }

  handleImageChange = e => {
    e.preventDefault()
    const { dispatch } = this.props
    dispatch(resetErrorMessageIfNeeded())

    this.setState({ files: [] })
    const files = e.target.files

    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      let reader = new FileReader()

      reader.onloadend = () => {
        file.preview = reader.result

        this.setState({
          files: [...this.state.files, file]
        })

        this.state.zooming.listen('.img-preview')
      }

      reader.readAsDataURL(file)
    }
  }

  handleRemoveImage = index => {
    this.setState(
      {
        files: this.state.files.filter((_, i) => i !== index)
      },
      () => {
        this.refs.files.length = this.state.files.length
        if (this.state.files.length === 0) {
          this.handleReset()
        }
      }
    )
  }

  handleReset = () => {
    const { dispatch } = this.props
    dispatch(resetErrorMessageIfNeeded())
    this.setState({
      files: [],
      tagSuggestions: [],
      tags: [],
      nsfw: false
    })
  }

  handleInputToggle = (event, data) => {
    const { name, checked } = data

    this.setState({
      [name]: checked
    })
  }

  handleSubmit = event => {
    event.preventDefault()

    const { dispatch } = this.props
    const { files, tags, nsfw } = this.state

    const data = new FormData()
    files.forEach(file => data.append('file[]', file))
    data.append('tags', JSON.stringify(tags))
    data.append('nsfw', nsfw)

    dispatch(upload(data)).then(() => browserHistory.push('/'))
  }

  renderPreview = () => {
    const { files } = this.state
    if (files.length === 0) return
    let itemsPerRow

    switch (files.length) {
      case 1:
        itemsPerRow = 1
        break
      case 2:
      case 4:
        itemsPerRow = 2
        break
      default:
        itemsPerRow = 3
        break
    }

    return (
      <Container text={files.length <= 1}>
        <Card.Group itemsPerRow={itemsPerRow} stackable>
          {files.map((file, index) => (
            <Card key={index}>
              <Image src={file.preview} className="img-preview" />

              <Card.Content extra>
                <Card.Meta>{file.name}</Card.Meta>
              </Card.Content>
              <Card.Content extra>
                <Button
                  icon="remove"
                  onClick={() => this.handleRemoveImage(index)}
                  basic
                  fluid
                />
              </Card.Content>
            </Card>
          ))}
        </Card.Group>
        <Divider horizontal />
      </Container>
    )
  }

  renderForm = () => {
    const { isUploading } = this.props
    const size = 'large'

    return (
      <Form onSubmit={this.handleSubmit} loading={isUploading} size={size}>
        {this.renderInputFile()}
        {this.renderInputTags()}
        {this.renderCheckboxNSFW()}
        {this.renderButtonSubmit()}
      </Form>
    )
  }

  renderInputFile = () => {
    const { files } = this.state
    if (files.length > 0) return null

    return (
      <Form.Field>
        <input
          type="file"
          accept="image/png,image/jpeg"
          onChange={this.handleImageChange}
          ref="files"
          multiple
          required
        />
      </Form.Field>
    )
  }

  renderInputTags = () => {
    const { files, tags, tagSuggestions } = this.state
    if (files.length === 0) return null

    return (
      <Form.Dropdown
        options={tagSuggestions}
        placeholder="Enter tags"
        additionLabel=""
        icon={null}
        search
        selection
        fluid
        multiple
        allowAdditions
        noResultsMessage={'Type to show suggestions...'}
        name="tags"
        value={tags}
        onAddItem={this.handleAddTag}
        onChange={this.handleInputChange}
        onSearchChange={this.handleSearchChange}
      />
    )
  }

  renderCheckboxNSFW = () => {
    const { files } = this.state
    if (files.length === 0) return null

    return (
      <Form.Checkbox
        label="NSFW (Not Safe For Work)"
        name="nsfw"
        onChange={this.handleInputToggle}
      />
    )
  }

  renderButtonSubmit = () => {
    const { files } = this.state
    if (files.length === 0) return null
    return (
      <Form.Field>
        <Button.Group fluid>
          <Button content="Reset" onClick={this.handleReset} />
          <Button.Or />
          <Button type="submit" primary>Submit</Button>
        </Button.Group>
      </Form.Field>
    )
  }

  renderTagLabels = () => {
    const { tags } = this.state

    return (

        {tags.map((tag, index) => (

            {tag}

        ))}

    )
  }

  renderInstructions = () => {
    return (
      <Segment color="pink" padded vertical inverted>
        <Grid columns="equal" stackable divided>
          <Grid.Row textAlign="center">
            <Grid.Column>

No Character, No Game

Make sure to have character(s) in your screenshot.

            </Grid.Column>
            <Grid.Column>

Hi-Res Image Only

                Image quality below 1080p is not accepted.

            </Grid.Column>
            <Grid.Column>

Multiple Uploads

                You may submit up to 9 files at one time.

            </Grid.Column>
          </Grid.Row>
        </Grid>
      </Segment>
    )
  }

  render() {
    return (

        {this.renderInstructions()}

        <Divider section horizontal>Screenshot Upload</Divider>

        {this.renderPreview()}

        <Container text>
          {this.renderForm()}
        </Container>

    )
  }
}

UploadPage.propTypes = propTypes

export default UploadPage
<commit_msg>Improve upload page UI<commit_after>import React, { Component, PropTypes } from 'react'
import {
  Container,
  Segment,
  Grid,
  Form,
  Image,
  Label,
  Card,
  Divider,
  Button
} from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import { uniqBy, union } from 'lodash'
import Zooming from 'zooming'

import { upload } from '../actions/user'
import { search } from '../actions/entities'
import { resetErrorMessageIfNeeded } from '../actions/common'

const propTypes = {
  dispatch: PropTypes.func.isRequired,
  isUploading: PropTypes.bool.isRequired
}

class UploadPage extends Component {
  state = {
    files: [],
    tagSuggestions: [],
    tags: [],
    nsfw: false,
    zooming: new Zooming({
      bgColor: '#000'
    })
  }

  handleInputChange = (event, { value }) => {
    this.setState({
      tags: value
    })
  }

  handleSearchChange = (event, value) => {
    const { dispatch } = this.props

    dispatch(search({ query: value })).then(res => {
      const { value } = res
      const { data } = value
      const newSuggestions = data.map(({ name }) => {
        return { text: name, value: name }
      })

      this.setState({
        tagSuggestions: uniqBy(
          union(this.state.tagSuggestions, newSuggestions),
          'text'
        )
      })
    })
  }

  handleAddTag = (event, { value }) => {
    this.setState({
      tagSuggestions: uniqBy(
        [{ text: value, value }, ...this.state.tagSuggestions],
        'text'
      )
    })
  }

  handleImageChange = e => {
    e.preventDefault()
    const { dispatch } = this.props
    dispatch(resetErrorMessageIfNeeded())

    this.setState({ files: [] })
    const files = e.target.files

    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      let reader = new FileReader()

      reader.onloadend = () => {
        file.preview = reader.result

        this.setState({
          files: [...this.state.files, file]
        })

        this.state.zooming.listen('.img-preview')
      }

      reader.readAsDataURL(file)
    }
  }

  handleRemoveImage = index => {
    this.setState(
      {
        files: this.state.files.filter((_, i) => i !== index)
      },
      () => {
        this.refs.files.length = this.state.files.length
        if (this.state.files.length === 0) {
          this.handleReset()
        }
      }
    )
  }

  handleReset = () => {
    const { dispatch } = this.props
    dispatch(resetErrorMessageIfNeeded())
    this.setState({
      files: [],
      tagSuggestions: [],
      tags: [],
      nsfw: false
    })
  }

  handleInputToggle = (event, data) => {
    const { name, checked } = data

    this.setState({
      [name]: checked
    })
  }

  handleSubmit = event => {
    event.preventDefault()

    const { dispatch } = this.props
    const { files, tags, nsfw } = this.state

    const data = new FormData()
    files.forEach(file => data.append('file[]', file))
    data.append('tags', JSON.stringify(tags))
    data.append('nsfw', nsfw)

    dispatch(upload(data)).then(() => browserHistory.push('/'))
  }

  renderPreview = () => {
    const { files } = this.state
    if (files.length === 0) return
    let itemsPerRow

    switch (files.length) {
      case 1:
        itemsPerRow = 1
        break
      case 2:
      case 4:
        itemsPerRow = 2
        break
      default:
        itemsPerRow = 3
        break
    }

    return (
      <Container text={files.length === 1 || files.length % 2 === 0}>
        <Card.Group itemsPerRow={itemsPerRow} stackable>
          {files.map((file, index) => (
            <Card key={index}>
              <Image src={file.preview} className="img-preview" />

              <Card.Content extra>
                <Card.Meta>{file.name}</Card.Meta>
              </Card.Content>
              <Card.Content extra>
                <Button
                  icon="remove"
                  onClick={() => this.handleRemoveImage(index)}
                  basic
                  fluid
                />
              </Card.Content>
            </Card>
          ))}
        </Card.Group>
        <Divider horizontal />
      </Container>
    )
  }

  renderForm = () => {
    const { isUploading } = this.props
    const size = 'large'

    return (
      <Form onSubmit={this.handleSubmit} loading={isUploading} size={size}>
        {this.renderInputFile()}
        {this.renderInputTags()}
        {this.renderCheckboxNSFW()}
        {this.renderButtonSubmit()}
      </Form>
    )
  }

  renderInputFile = () => {
    const { files } = this.state
    if (files.length > 0) return null

    return (
      <Form.Field>
        <input
          type="file"
          accept="image/png,image/jpeg"
          onChange={this.handleImageChange}
          ref="files"
          multiple
          required
        />
      </Form.Field>
    )
  }

  renderInputTags = () => {
    const { files, tags, tagSuggestions } = this.state
    if (files.length === 0) return null

    return (
      <Form.Dropdown
        options={tagSuggestions}
        placeholder="Enter tags"
        additionLabel=""
        icon={null}
        search
        selection
        fluid
        multiple
        allowAdditions
        noResultsMessage={'Type to show suggestions...'}
        name="tags"
        value={tags}
        onAddItem={this.handleAddTag}
        onChange={this.handleInputChange}
        onSearchChange={this.handleSearchChange}
      />
    )
  }

  renderCheckboxNSFW = () => {
    const { files } = this.state
    if (files.length === 0) return null

    return (
      <Form.Checkbox
        label="NSFW (Not Safe For Work)"
        name="nsfw"
        onChange={this.handleInputToggle}
      />
    )
  }

  renderButtonSubmit = () => {
    const { files } = this.state
    if (files.length === 0) return null
    return (
      <Form.Field>
        <Button.Group fluid>
          <Button content="Reset" onClick={this.handleReset} />
          <Button.Or />
          <Button type="submit" primary>Submit</Button>
        </Button.Group>
      </Form.Field>
    )
  }

  renderTagLabels = () => {
    const { tags } = this.state

    return (

        {tags.map((tag, index) => (

            {tag}

        ))}

    )
  }

  renderInstructions = () => {
    const { files } = this.state
    if (files.length > 0) return null

    return (
      <Segment color="pink" padded vertical inverted>
        <Grid columns="equal" stackable divided>
          <Grid.Row textAlign="center">
            <Grid.Column>

No Character, No Game

Make sure to have character(s) in your screenshot.

            </Grid.Column>
            <Grid.Column>

Hi-Res Image Only

                Image quality below 1080p is not accepted.

            </Grid.Column>
            <Grid.Column>

Multiple Uploads

                You may submit up to 9 files at one time.

            </Grid.Column>
          </Grid.Row>
        </Grid>
      </Segment>
    )
  }

  render() {
    return (

        {this.renderInstructions()}

        <Divider section horizontal>Upload</Divider>

        {this.renderPreview()}

        <Container text>
          <Segment>{this.renderForm()}</Segment>

        </Container>

    )
  }
}

UploadPage.propTypes = propTypes

export default UploadPage
<|endoftext|>


<commit_before>import React from "react";
import { startsWith } from "lodash-es";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import { LinkContainer } from "react-router-bootstrap";
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from "react-bootstrap";
import NotificationIcon from "./Icon";
import { logout } from "../../account/actions";
import { Icon, AutoProgressBar } from "../../base";

const isHomeActive = (match, location) => location.pathname === "/" || startsWith(location.pathname, "/home");

const Bar = (props) => {

    const dropdownTitle = (

            <Icon name="user" /> {props.id}

    );

    return (

            <Navbar fixedTop>
                <Navbar.Header>
                    <Navbar.Brand>
                        <Icon name="vtlogo" className="vtlogo" />
                    </Navbar.Brand>

                    <Navbar.Toggle />
                </Navbar.Header>

                <Navbar.Collapse>

                        <LinkContainer to="/home" isActive={isHomeActive}>
                            <NavItem>
                                Home
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/jobs">
                            <NavItem>
                                Jobs
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/samples">
                            <NavItem>
                                Samples
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/refs">
                            <NavItem>
                                References
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/hmm">
                            <NavItem>
                                HMM
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/subtraction">
                            <NavItem>
                                Subtraction
                            </NavItem>
                        </LinkContainer>

                        <NavItem>
                            <NotificationIcon />
                        </NavItem>

                        <NavItem
                            target="_blank"
                            href="https://github.com/virtool/virtool"
                            rel="noopener noreferrer"
                        >
                            <Icon name="github" />
                        </NavItem>

                        <NavItem target="_blank" href="https://docs.virtool.ca" rel="noopener noreferrer">
                            <Icon name="book" />
                        </NavItem>

                        <NavDropdown id="account-dropdown" title={dropdownTitle}>
                            <LinkContainer to="/account" activeClassName="">
                                <MenuItem>Account</MenuItem>
                            </LinkContainer>
                            <LinkContainer to="/administration">
                                <MenuItem>Administration</MenuItem>
                            </LinkContainer>
                            <MenuItem href="https://gitreports.com/issue/virtool/virtool" target="_blank">
                                Report Issue
                            </MenuItem>
                            <MenuItem onClick={props.logout}>Logout</MenuItem>
                        </NavDropdown>

                </Navbar.Collapse>
            </Navbar>

            <AutoProgressBar step={50} interval={80} active={props.pending} affixed />

    );
};

const mapStateToProps = (state) => ({
    ...state.account,
    pending: state.app.pending
});

const mapDispatchToProps = (dispatch) => ({

    logout: () => {
        dispatch(logout());
    }
});

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Bar));
<commit_msg>Update docs nav bar link<commit_after>import React from "react";
import { startsWith } from "lodash-es";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import { LinkContainer } from "react-router-bootstrap";
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from "react-bootstrap";
import NotificationIcon from "./Icon";
import { logout } from "../../account/actions";
import { Icon, AutoProgressBar } from "../../base";

const isHomeActive = (match, location) => location.pathname === "/" || startsWith(location.pathname, "/home");

const Bar = (props) => {

    const dropdownTitle = (

            <Icon name="user" /> {props.id}

    );

    return (

            <Navbar fixedTop>
                <Navbar.Header>
                    <Navbar.Brand>
                        <Icon name="vtlogo" className="vtlogo" />
                    </Navbar.Brand>

                    <Navbar.Toggle />
                </Navbar.Header>

                <Navbar.Collapse>

                        <LinkContainer to="/home" isActive={isHomeActive}>
                            <NavItem>
                                Home
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/jobs">
                            <NavItem>
                                Jobs
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/samples">
                            <NavItem>
                                Samples
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/refs">
                            <NavItem>
                                References
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/hmm">
                            <NavItem>
                                HMM
                            </NavItem>
                        </LinkContainer>

                        <LinkContainer to="/subtraction">
                            <NavItem>
                                Subtraction
                            </NavItem>
                        </LinkContainer>

                        <NavItem>
                            <NotificationIcon />
                        </NavItem>

                        <NavItem
                            target="_blank"
                            href="https://github.com/virtool/virtool"
                            rel="noopener noreferrer"
                        >
                            <Icon name="github" />
                        </NavItem>

                        <NavItem target="_blank" href="https://www.virtool.ca/docs/manual" rel="noopener noreferrer">
                            <Icon name="book" />
                        </NavItem>

                        <NavDropdown id="account-dropdown" title={dropdownTitle}>
                            <LinkContainer to="/account" activeClassName="">
                                <MenuItem>Account</MenuItem>
                            </LinkContainer>
                            <LinkContainer to="/administration">
                                <MenuItem>Administration</MenuItem>
                            </LinkContainer>
                            <MenuItem href="https://gitreports.com/issue/virtool/virtool" target="_blank">
                                Report Issue
                            </MenuItem>
                            <MenuItem onClick={props.logout}>Logout</MenuItem>
                        </NavDropdown>

                </Navbar.Collapse>
            </Navbar>

            <AutoProgressBar step={50} interval={80} active={props.pending} affixed />

    );
};

const mapStateToProps = (state) => ({
    ...state.account,
    pending: state.app.pending
});

const mapDispatchToProps = (dispatch) => ({

    logout: () => {
        dispatch(logout());
    }
});

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Bar));
<|endoftext|>


<commit_before>module.exports = {
  run: function(creep) {
    if (creep.spawning === false) {
      var numEnergySources = 2;
      if (creep.memory.sourcenum == undefined || creep.memory.sourcenum > 1) {
        // var numEnergySources = creep.room.lookForAtArea(LOOK_SOURCES, 0, 0, 49, 49, true).length;
        creep.memory.sourcenum = Math.floor(Math.random() * (numEnergySources + 1));
      }
      if (creep.memory.working === true) {
        if (creep.carry.energy === 0) {
          creep.memory.working = false;
        }
        if (creep.upgradeController(creep.room.controller) === ERR_NOT_IN_RANGE) {
          creep.moveTo(creep.room.controller);
        }
      } else {
        if (creep.carry.energy === creep.carryCapacity) {
          creep.memory.working = true;
        }
        var targets = creep.room.find(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType === STRUCTURE_CONTAINER ||
              structure.structureType === STRUCTURE_STORAGE) &&
              structure.store.energy > creep.carryCapacity;
          }
        });
        if (targets.length > 0) {
          var source = targets[0];
          if (creep.withdraw(source, RESOURCE_ENERGY, creep.carryCapacity - creep.carry) === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          }
        } else {
          var source = creep.room.find(FIND_SOURCES)[creep.memory.sourcenum];
          if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          }
        }
      }
    }
  }
};
<commit_msg>Check if full after all else fails<commit_after>module.exports = {
  run: function(creep) {
    if (creep.spawning === false) {
      var numEnergySources = 2;
      if (creep.memory.sourcenum == undefined || creep.memory.sourcenum > 1) {
        // var numEnergySources = creep.room.lookForAtArea(LOOK_SOURCES, 0, 0, 49, 49, true).length;
        creep.memory.sourcenum = Math.floor(Math.random() * (numEnergySources + 1));
      }
      if (creep.memory.working === true) {
        if (creep.carry.energy === 0) {
          creep.memory.working = false;
        }
        if (creep.upgradeController(creep.room.controller) === ERR_NOT_IN_RANGE) {
          creep.moveTo(creep.room.controller);
        }
      } else {
        if (creep.carry.energy === creep.carryCapacity) {
          creep.memory.working = true;
        }
        var targets = creep.room.find(FIND_STRUCTURES, {
          filter: (structure) => {
            return (structure.structureType === STRUCTURE_CONTAINER ||
              structure.structureType === STRUCTURE_STORAGE) &&
              structure.store.energy > creep.carryCapacity;
          }
        });
        if (targets.length > 0) {
          var source = targets[0];
          if (creep.withdraw(source, RESOURCE_ENERGY, creep.carryCapacity - creep.carry) === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          }
        } else {
          var source = creep.room.find(FIND_SOURCES)[creep.memory.sourcenum];
          var tryHarvest = creep.harvest(source);
          if (tryHarvest === ERR_NOT_IN_RANGE) {
            creep.moveTo(source);
          } else if (tryHarvest === ERR_FULL) {
            creep.say("Full");
          }
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>import nodeResolve from '@rollup/plugin-node-resolve';

const pkg = require('./package.json');
const external = Object.keys(pkg.dependencies);

export default {
  input: 'src/index.js',
  output: [
    {file: pkg.exports.require, format: 'cjs', exports: 'default'},
    {file: pkg.exports.import, format: 'es'},
  ],
  plugins: [nodeResolve()],
  external: external,
};
<commit_msg>minor improvements<commit_after>import nodeResolve from '@rollup/plugin-node-resolve';

const pkg = require('./package.json');
const external = Object.keys(pkg.dependencies);

export default {
  input: 'src/index.js',
  output: [
    {file: pkg.exports.require, format: 'cjs', exports: 'auto'},
    {file: pkg.exports.import, format: 'es'},
  ],
  plugins: [nodeResolve()],
  external: external,
};
<|endoftext|>


<commit_before>import typescript from 'rollup-plugin-typescript2';
import { terser } from 'rollup-plugin-terser';
import rollupReplace from 'rollup-plugin-replace';
import fileSize from 'rollup-plugin-filesize';

const createConfig = ({ input, output, target = undefined }) => ({
  input,
  output,
  plugins: [
    rollupReplace({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    typescript({
      clean: true,
      tsconfigOverride: {
        compilerOptions: {
          declaration: false,
          ...(target ? { target } : {})
        }
      }
    }),
    terser({
      toplevel: true
    }),
    fileSize()
  ]
});

export default [
  createConfig({
    input: 'src/index.ts',
    output: {
      file: 'dist/xstate.js',
      format: 'umd',
      name: 'XState'
    }
  }),
  createConfig({
    input: 'src/graph.ts',
    output: {
      file: 'dist/xstate.graph.js',
      format: 'umd',
      name: 'XStateGraph'
    }
  }),
  createConfig({
    input: 'src/interpreter.ts',
    output: {
      file: 'dist/xstate.interpreter.js',
      format: 'umd',
      name: 'XStateInterpreter'
    }
  }),
  createConfig({
    input: 'src/index.ts',
    output: {
      file: 'dist/xstate.web.js',
      format: 'esm'
    },
    target: 'ES2015'
  })
];
<commit_msg>chore: remove xstate.graph.js (@xstate/graph package to be used instead)<commit_after>import typescript from 'rollup-plugin-typescript2';
import { terser } from 'rollup-plugin-terser';
import rollupReplace from 'rollup-plugin-replace';
import fileSize from 'rollup-plugin-filesize';

const createConfig = ({ input, output, target = undefined }) => ({
  input,
  output,
  plugins: [
    rollupReplace({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    typescript({
      clean: true,
      tsconfigOverride: {
        compilerOptions: {
          declaration: false,
          ...(target ? { target } : {})
        }
      }
    }),
    terser({
      toplevel: true
    }),
    fileSize()
  ]
});

export default [
  createConfig({
    input: 'src/index.ts',
    output: {
      file: 'dist/xstate.js',
      format: 'umd',
      name: 'XState'
    }
  }),
  createConfig({
    input: 'src/interpreter.ts',
    output: {
      file: 'dist/xstate.interpreter.js',
      format: 'umd',
      name: 'XStateInterpreter'
    }
  }),
  createConfig({
    input: 'src/index.ts',
    output: {
      file: 'dist/xstate.web.js',
      format: 'esm'
    },
    target: 'ES2015'
  })
];
<|endoftext|>


<commit_before>// Libs
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import gzip from 'rollup-plugin-gzip';
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import path from 'path';
import uglify from 'rollup-plugin-uglify';

// Read package config
const pkgConfig = require('./package.json');

// Constants
const DIST = process.env.DIST || false;
const MIN = process.env.MIN || false;

var banner = `/* Inspire Tree DOM
 * @version ${pkgConfig.version}
 * ${pkgConfig.repository}
 * @copyright Copyright 2015 Helion3, and other contributors
 * @license Licensed under MIT
 *          see ${pkgConfig.repository}/blob/master/LICENSE
 */`;

let plugins = [
    replace({
        'process.env.NODE_ENV': JSON.stringify(DIST ? 'production' : 'development')
    }),
    babel({
        exclude: [
            'node_modules/**',
            'src/scss/**'
        ]
    }),
    nodeResolve({
        jsnext: true
    }),
    commonjs({
        sourceMap: false,
        namedExports: {
            'node_modules/inferno/index.js': ['render']
        }
    })
];

if (MIN) {
    plugins.push(uglify({
        output: {
            comments: /@license/
        }
    }));
    plugins.push(gzip());
}

export default {
    input: path.join('src', 'dom.js'),
    output: {
        file: path.join(DIST ? 'dist' : 'build', 'inspire-tree-dom' + (MIN ? '.min' : '') + '.js'),
        format: 'umd'
    },
    name: 'InspireTreeDOM',
    external: ['lodash', 'InspireTree', 'inspire-tree'],
    banner: banner,
    globals: {
        'inspire-tree': 'InspireTree',
        lodash: '_'
    },
    plugins: plugins
};
<commit_msg>Updates rollup config<commit_after>// Libs
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import gzip from 'rollup-plugin-gzip';
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import path from 'path';
import uglify from 'rollup-plugin-uglify';

// Read package config
const pkgConfig = require('./package.json');

// Constants
const DIST = process.env.DIST || false;
const MIN = process.env.MIN || false;

var banner = `/* Inspire Tree DOM
 * @version ${pkgConfig.version}
 * ${pkgConfig.repository}
 * @copyright Copyright 2015 Helion3, and other contributors
 * @license Licensed under MIT
 *          see ${pkgConfig.repository}/blob/master/LICENSE
 */`;

let plugins = [
    replace({
        'process.env.NODE_ENV': JSON.stringify(DIST ? 'production' : 'development')
    }),
    babel({
        exclude: [
            'node_modules/**',
            'src/scss/**'
        ]
    }),
    nodeResolve({
        jsnext: true
    }),
    commonjs({
        sourceMap: false,
        namedExports: {
            'node_modules/inferno/index.js': ['render']
        }
    })
];

if (MIN) {
    plugins.push(uglify({
        output: {
            comments: /@license/
        }
    }));
    plugins.push(gzip());
}

export default {
    input: path.join('src', 'dom.js'),
    external: ['lodash', 'InspireTree', 'inspire-tree'],
    output: {
        file: path.join(DIST ? 'dist' : 'build', 'inspire-tree-dom' + (MIN ? '.min' : '') + '.js'),
        format: 'umd',
        banner: banner,
        name: 'InspireTreeDOM',
        globals: {
            'inspire-tree': 'InspireTree',
            lodash: '_'
        }
    },
    plugins: plugins
};
<|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';

const production = process.env.NODE_ENV === 'production';
const config = {};

config.ponyfill = {
  input: 'fetch-browser-polyfill.js',
  output: {
    file: 'dist/fetch-browser.js',
    format: 'cjs',
    strict: false
  },
  plugins: [
    resolve({
      browser: true
    }),
    commonjs(),
    production && uglify(),
  ],
  context: 'this',
  banner: 'var self = {};',
  footer: 'module.exports = self;'
};

config.polyfill = {
  input: 'fetch-browser-polyfill.js',
  output: {
    file: 'dist/fetch-browser-polyfill.js',
    format: 'cjs',
    strict: false
  },
  plugins: [
    resolve({
      browser: true
    }),
    commonjs(),
    production && uglify(),
  ],
  context: 'this'
};

module.exports = [
  config.ponyfill,
  config.polyfill
];
<commit_msg>cdn support.<commit_after>import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';

const production = process.env.NODE_ENV === 'production';
const config = {};

config.ponyfill = {
  input: 'fetch-browser-polyfill.js',
  output: {
    file: 'dist/fetch-browser.js',
    format: 'cjs',
    strict: false
  },
  plugins: [
    resolve({
      browser: true
    }),
    commonjs(),
    production && uglify(),
  ],
  context: 'this',
  banner: 'var self = {};',
  footer: 'module.exports = self;'
};

config.polyfill = {
  input: 'fetch-browser-polyfill.js',
  output: [{
    file: 'dist/fetch-browser-polyfill.js',
    format: 'cjs',
    strict: false
  },{
    file: 'dist/cross-fetch.js',
    format: 'cjs',
    sourcemap: true,
    strict: false
  }],
  plugins: [
    resolve({
      browser: true
    }),
    commonjs(),
    production && uglify(),
  ],
  context: 'this'
};

module.exports = [
  config.ponyfill,
  config.polyfill
];
<|endoftext|>


<commit_before>import babel from 'rollup-plugin-babel';
import babelrc from 'babelrc-rollup';

const babelConfig = {
  'presets': [
    ['env', {
      'targets': {
        'browsers': ['last 2 versions']
      },
      'modules': false,
      'loose': true
    }]
  ]
};

export default {
  entry: 'src/alpha.js',
  format: 'umd',
  moduleName: 'Alpha',
  plugins: [
    babel(babelrc({
      addExternalHelpersPlugin: false,
      config: babelConfig,
      exclude: 'node_modules/**'
    }))
  ],
  dest: 'dist/bundle.js'
};
<commit_msg>Removed 'modules: false' as babelrc adds it automatically<commit_after>import babel from 'rollup-plugin-babel';
import babelrc from 'babelrc-rollup';

const babelConfig = {
  'presets': [
    ['env', {
      'targets': {
        'browsers': ['last 2 versions']
      },
      'loose': true
    }]
  ]
};

export default {
  entry: 'src/alpha.js',
  format: 'umd',
  moduleName: 'Alpha',
  plugins: [
    babel(babelrc({
      addExternalHelpersPlugin: false,
      config: babelConfig,
      exclude: 'node_modules/**'
    }))
  ],
  dest: 'dist/bundle.js'
};
<|endoftext|>


<commit_before>import typescript from 'rollup-plugin-typescript2';

export default {
  input: './src/aurelia-dialog.ts',
  external: [
    'aurelia-framework',
    'aurelia-binding',
    'aurelia-templating',
    'aurelia-dependency-injection',
    'aurelia-pal'
  ],
  output: [
    {
      file: 'dist/umd/aurelia-dialog.js',
      format: 'umd',
      name: 'au.dialog',
      globals: {
        'aurelia-framework': 'au',
        'aurelia-binding': 'au',
        'aurelia-templating': 'au',
        'aurelia-dependency-injection': 'au',
        'aurelia-pal': 'au'
      },
      esModule: false
    }
  ],
  inlineDynamicImports: true,
  plugins: [
    typescript({
      tsconfigOverride: {
        compilerOptions: {
          module: 'esnext',
          outDir: undefined,
          target: 'es2015',
          declaration: false,
          removeComments: true
        },
        include: [
          'src'
        ]
      },
      cacheRoot: '.rollupcache'
    })
  ]
}
<commit_msg>fix(build): adjust umd build, add umd-es2015<commit_after>import typescript from 'rollup-plugin-typescript2';

export default [
  {
    input: './src/aurelia-dialog.ts',
    external: [
      'aurelia-framework',
      'aurelia-binding',
      'aurelia-templating',
      'aurelia-dependency-injection',
      'aurelia-pal'
    ],
    output: [
      {
        file: 'dist/umd/aurelia-dialog.js',
        format: 'umd',
        name: 'au.dialog',
        globals: {
          'aurelia-framework': 'au',
          'aurelia-binding': 'au',
          'aurelia-templating': 'au',
          'aurelia-dependency-injection': 'au',
          'aurelia-pal': 'au'
        },
        esModule: false
      }
    ],
    inlineDynamicImports: true,
    plugins: [
      typescript({
        tsconfigOverride: {
          compilerOptions: {
            module: 'esnext',
            outDir: undefined,
            target: 'es5',
            declaration: false,
            removeComments: true
          },
          include: [
            'src'
          ]
        },
        cacheRoot: '.rollupcache'
      })
    ]
  },
  {
    input: './src/aurelia-dialog.ts',
    external: [
      'aurelia-framework',
      'aurelia-binding',
      'aurelia-templating',
      'aurelia-dependency-injection',
      'aurelia-pal'
    ],
    output: [
      {
        file: 'dist/umd-es2015/aurelia-dialog.js',
        format: 'umd',
        name: 'au.dialog',
        globals: {
          'aurelia-framework': 'au',
          'aurelia-binding': 'au',
          'aurelia-templating': 'au',
          'aurelia-dependency-injection': 'au',
          'aurelia-pal': 'au'
        },
        esModule: false
      }
    ],
    inlineDynamicImports: true,
    plugins: [
      typescript({
        tsconfigOverride: {
          compilerOptions: {
            module: 'esnext',
            outDir: undefined,
            target: 'es2015',
            declaration: false,
            removeComments: true
          },
          include: [
            'src'
          ]
        },
        cacheRoot: '.rollupcache'
      })
    ]
  }
]
<|endoftext|>


<commit_before>import pluginNodeResolve from "@rollup/plugin-node-resolve"
import pluginCommonjs from "@rollup/plugin-commonjs"
import pluginTypescript from "@rollup/plugin-typescript"
import { babel as pluginBabel } from "@rollup/plugin-babel"
import { terser as pluginTerser } from "rollup-plugin-terser"
import multi from '@rollup/plugin-multi-entry'
import replace from '@rollup/plugin-replace'

const moduleName = 'ReduxPersist'

import * as path from 'path'

import pkg from "./package.json"

const banner = `/*!
  ${moduleName}.js v${pkg.version}
  ${pkg.homepage}
  Released under the ${pkg.license} License.
*/`;

const config = [
  // browser
  {
    // entry point
    input: 'src/**/*.ts',
    output: [
      // no minify
      {
        name: moduleName,
        file: pkg.browser,
        format: 'iife',
        sourcemap: 'inline',
        // copyright
        banner,
      },
      // minify
      {
        name: moduleName,
        file: pkg.browser.replace('.js', '.min.js'),
        format: 'iife',
        banner,
        plugins: [
          pluginTerser(),
        ],
      }
    ],
    external: [
      'react'
    ],
    plugins: [
      multi(),
      pluginTypescript({
        module: "esnext"
      }),
      pluginCommonjs({
        extensions: [".js", ".ts"]
      }),
      pluginBabel({
        babelHelpers: "bundled",
        configFile: path.resolve(__dirname, ".babelrc.js")
      }),
      pluginNodeResolve({
        browser: true
      }),
      replace({
        'process.env.NODE_ENV': JSON.stringify('production')
      }),
    ]
  },
  // es module
  {
    // entry point
    input: 'src/**/*.ts',
    output: [
      {
        file: pkg.main,
        format: "es",
        sourcemap: "inline",
        banner,
        exports: "named"
      },
    ],
    external: [
      ...Object.keys(pkg.devDependencies || {}),
      'react'
    ],
    plugins: [
      multi(),
      pluginTypescript({
        module: "esnext"
      }),
      pluginBabel({
        babelHelpers: "bundled",
        configFile: path.resolve(__dirname, ".babelrc.js")
      }),
      replace({
        'process.env.NODE_ENV': JSON.stringify('production')
      }),
    ]
  },
];

export default config

<commit_msg>set globals<commit_after>import pluginNodeResolve from "@rollup/plugin-node-resolve"
import pluginCommonjs from "@rollup/plugin-commonjs"
import pluginTypescript from "@rollup/plugin-typescript"
import { babel as pluginBabel } from "@rollup/plugin-babel"
import { terser as pluginTerser } from "rollup-plugin-terser"
import multi from '@rollup/plugin-multi-entry'

const moduleName = 'ReduxPersist'

import * as path from 'path'

import pkg from "./package.json"

const banner = `/*!
  ${moduleName}.js v${pkg.version}
  ${pkg.homepage}
  Released under the ${pkg.license} License.
*/`;

const config = [
  // browser
  {
    // entry point
    input: 'src/**/*.ts',
    output: [
      // no minify
      {
        name: moduleName,
        file: pkg.browser,
        format: 'iife',
        sourcemap: 'inline',
        // copyright
        banner,
        globals: {
          react: 'react'
        }
      },
      // minify
      {
        name: moduleName,
        file: pkg.browser.replace('.js', '.min.js'),
        format: 'iife',
        banner,
        globals: {
          react: 'react'
        },
        plugins: [
          pluginTerser(),
        ],
      }
    ],
    external: [
      'react'
    ],
    plugins: [
      multi(),
      pluginTypescript({
        module: "esnext"
      }),
      pluginCommonjs({
        extensions: [".js", ".ts"]
      }),
      pluginBabel({
        babelHelpers: "bundled",
        configFile: path.resolve(__dirname, ".babelrc.js")
      }),
      pluginNodeResolve({
        browser: true
      }),
    ]
  },
  // es module
  {
    // entry point
    input: 'src/**/*.ts',
    output: [
      {
        file: pkg.main,
        format: "es",
        sourcemap: "inline",
        banner,
        exports: "named"
      },
    ],
    external: [
      ...Object.keys(pkg.devDependencies || {}),
      'react'
    ],
    plugins: [
      multi(),
      pluginTypescript({
        module: "esnext"
      }),
      pluginBabel({
        babelHelpers: "bundled",
        configFile: path.resolve(__dirname, ".babelrc.js")
      }),
    ]
  },
];

export default config

<|endoftext|>


<commit_before>import babel  from 'rollup-plugin-babel';
import eslint from 'rollup-plugin-eslint';
import uglify from 'rollup-plugin-uglify';

export default {
	entry: 'src/game.js',
	dest: 'build/invaders.min.js',
	format: 'iife',
	sourceMap: 'inline',
	plugins: [
		eslint( {
			exclude: ['src/lib/Three.js', 'src/node_modules/**']
		} ),
		babel( {
			exclude: ['src/node_modules/**']
		} ),
		(process.env.NODE_ENV === 'production' && uglify())
	]
};
<commit_msg>Remove unnecessary excludes of src/node_modules<commit_after>import babel  from 'rollup-plugin-babel';
import eslint from 'rollup-plugin-eslint';
import uglify from 'rollup-plugin-uglify';

export default {
	entry: 'src/game.js',
	dest: 'build/invaders.min.js',
	format: 'iife',
	sourceMap: 'inline',
	plugins: [
		eslint( {
			exclude: ['src/lib/Three.js']
		} ),
		babel(),
		(process.env.NODE_ENV === 'production' && uglify())
	]
};
<|endoftext|>