<commit_before>'use strict';

var j = jQuery.noConflict();

(function ($) {
  var $win = j(window),
      $doc = j(document),
      $animationElements = j('.animation-element'),
      sldExpert;

  function affixHeader() {
    j('.Header').affix({
      offset: {
        top: function () {
          return 20;
        }
      }
    });
  }

  function checkIfInView() {
    var windowHeight = $win.height();
    var windowTopPosition = $win.scrollTop();
    var windowBottomPosition = (windowTopPosition + windowHeight);

    j.each($animationElements, function(){
      var element = j(this);
      var animation = element.data('animation');
      var elementHeight = element.outerHeight();
      var elementTopPosition = element.offset().top;
      var elementBottomPosition = (elementTopPosition + elementHeight);

      if ((elementBottomPosition >= windowTopPosition) && (elementTopPosition <= windowBottomPosition)) {
        element.addClass(animation);
      } else {
        element.removeClass(animation);
      }
    });
  }

  $win.on('scroll resize', checkIfInView);

  $win.on('resize', function() {
    if (map) {
      var $map = j('#map');

      if ($map.length) {
        var lat = $map.data('lat'),
            long = $map.data('long');

        map.setCenter({lat: lat, lng: long});
      }
    }

    if (j('.Bxslider-list').length) {
      var bx = j('.Bxslider-list'),
          widthBxSlider = parseInt(bx.width()),
          widthBxSlider = $win.width() > 600 ? (widthBxSlider * 42) / 100 : 0,
          slides = $win.width() > 600 ? 3 : 1;

      sldExpert.reloadSlider({
        auto: true,
        autoHover: true,
        minSlides: slides,
        maxSlides: slides,
        slideWidth: widthBxSlider,
        slideMargin: 15,
        nextText: '',
        prevText: '',
        pager: false,
        onSliderLoad: function() {
          j('.bx-controls-direction a').on('click', function(){
            var i = $(this).attr('data-slide-index');
              sldExpert.goToSlide(i);
              sldExpert.stopAuto();
              sldExpert.startAuto();
              return false;
          });
        }
      });
    }
  });

  $win.on('scroll', function(event) {
    var arrow = j('.ArrowTop');

    if ( j(this).scrollTop() > 150) {
      arrow.fadeIn();
    } else {
      arrow.fadeOut();
    }
  });

  $doc.on('ready', function () {
    affixHeader();

    j('.ArrowTop').on('click', function(ev){
      ev.preventDefault();
      j('html, body').animate({scrollTop: 0}, 800);
    });

    j('.js-move-scroll').on('click', function(event) {
      event.preventDefault();
      var $this = j(this);
      var dest = $this.data('href');

      dest = (typeof dest === 'undefined') ? $this.attr('href') : dest;

      dest = (dest.charAt(0) === '#') ? dest : '#' + dest;

      j('html, body').stop().animate({
        scrollTop: j(dest).offset().top
      }, 2000, 'easeInOutExpo');
    });

    j('.js-menu-move-scroll a').on('click', function(event) {
      event.preventDefault();
      var $this = j(this);
      var dest = $this.attr('href');

      j('html, body').stop().animate({
        scrollTop: j(dest).offset().top
      }, 2000, 'easeInOutExpo');
    });

    j('#js-frm-contact').formValidation({
      locale: 'es_ES',
      framework: 'bootstrap',
      icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      }
    }).on('err.field.fv', function(e, data){
      var field = e.target;
      j('small.help-block[data-bv-result="INVALID"]').addClass('hide');
    }).on('success.form.fv', function(e){
      e.preventDefault();

      var $form = j(e.target),
          fv = j(e.target).data('formValidation');

      var msg     = j('#js-form-contact-msg'),
          loader  = j('#js-form-contact-loader');

      loader.removeClass('hidden').addClass('infinite animated');
      msg.text('');

      var data = $form.serialize() + '&nonce=' + TCAjax.nonce + '&action=register_contact';

      j.post(TCAjax.url, data, function(data){
        $form.data('formValidation').resetForm(true);

        if (data.result) {
          msg.text('Ya tenemos su consulta. En breve nos pondremos en contacto con usted.');
        } else {
          msg.text(data.error);
        }

        loader.addClass('hidden').removeClass('infinite animated');
        msg.fadeIn('slow');
        setTimeout(function(){
          msg.fadeOut('slow', function(){
              j(this).text('');
          });
        }, 5000);
      }, 'json').fail(function(){
        alert('No se pudo realizar la operación solicitada. Por favor vuelva a intentarlo.');
      });
    });

    j('.js-toggle-slidebar').on('click', function(ev) {
      ev.preventDefault();
      var slidebar = j('.Slidebar');

      if (slidebar.hasClass('active')) {
        slidebar.removeClass('active');
      } else {
        slidebar.addClass('active');
      }
    });

    if (j('.Bxslider-list').length) {
      var bx = j('.Bxslider-list'),
          widthBxSlider = parseInt(bx.width()),
          widthBxSlider = $win.width() > 600 ? (widthBxSlider * 42) / 100 : 0,
          slides = $win.width() > 600 ? 3 : 1;

      sldExpert = j('.bxslider').bxSlider({
        auto: true,
        autoHover: true,
        minSlides: slides,
        maxSlides: slides,
        slideWidth: widthBxSlider,
        slideMargin: 15,
        nextText: '',
        prevText: '',
        pager: false,
        onSliderLoad: function() {
          j('.bx-controls-direction a').on('click', function(){
            var i = $(this).attr('data-slide-index');
              sldExpert.goToSlide(i);
              sldExpert.stopAuto();
              sldExpert.startAuto();
              return false;
          });
        }
      });
    }
  });
})(jQuery);
<commit_msg>Bug move previous and next in bxslider<commit_after>'use strict';

var j = jQuery.noConflict();

(function ($) {
  var $win = j(window),
      $doc = j(document),
      $animationElements = j('.animation-element'),
      sldExpert;

  function affixHeader() {
    j('.Header').affix({
      offset: {
        top: function () {
          return 20;
        }
      }
    });
  }

  function checkIfInView() {
    var windowHeight = $win.height();
    var windowTopPosition = $win.scrollTop();
    var windowBottomPosition = (windowTopPosition + windowHeight);

    j.each($animationElements, function(){
      var element = j(this);
      var animation = element.data('animation');
      var elementHeight = element.outerHeight();
      var elementTopPosition = element.offset().top;
      var elementBottomPosition = (elementTopPosition + elementHeight);

      if ((elementBottomPosition >= windowTopPosition) && (elementTopPosition <= windowBottomPosition)) {
        element.addClass(animation);
      } else {
        element.removeClass(animation);
      }
    });
  }

  $win.on('scroll resize', checkIfInView);

  $win.on('resize', function() {
    if (map) {
      var $map = j('#map');

      if ($map.length) {
        var lat = $map.data('lat'),
            long = $map.data('long');

        map.setCenter({lat: lat, lng: long});
      }
    }

    if (j('.Bxslider-list').length) {
      var bx = j('.Bxslider-list'),
          widthBxSlider = parseInt(bx.width()),
          widthBxSlider = $win.width() > 600 ? (widthBxSlider * 42) / 100 : 0,
          slides = $win.width() > 600 ? 3 : 1;

      sldExpert.reloadSlider({
        auto: true,
        autoHover: true,
        minSlides: slides,
        maxSlides: slides,
        slideWidth: widthBxSlider,
        slideMargin: 15,
        nextText: '',
        prevText: '',
        pager: false,
        onSlidePrev: function($slideElement, oldIndex, newIndex) {
          sldExpert.goToSlide(newIndex);
          sldExpert.stopAuto();
          sldExpert.startAuto();
          return false;
        },
        onSlideNext: function($slideElement, oldIndex, newIndex) {
          sldExpert.goToSlide(newIndex);
          sldExpert.stopAuto();
          sldExpert.startAuto();
          return false;
        }
        /*onSliderLoad: function() {
          j('.bx-controls-direction a').on('click', function(){
            var i = $(this).attr('data-slide-index');
              sldExpert.goToSlide(i);
              sldExpert.stopAuto();
              sldExpert.startAuto();
              return false;
          });
        }*/
      });
    }
  });

  $win.on('scroll', function(event) {
    var arrow = j('.ArrowTop');

    if ( j(this).scrollTop() > 150) {
      arrow.fadeIn();
    } else {
      arrow.fadeOut();
    }
  });

  $doc.on('ready', function () {
    affixHeader();

    j('.ArrowTop').on('click', function(ev){
      ev.preventDefault();
      j('html, body').animate({scrollTop: 0}, 800);
    });

    j('.js-move-scroll').on('click', function(event) {
      event.preventDefault();
      var $this = j(this);
      var dest = $this.data('href');

      dest = (typeof dest === 'undefined') ? $this.attr('href') : dest;

      dest = (dest.charAt(0) === '#') ? dest : '#' + dest;

      j('html, body').stop().animate({
        scrollTop: j(dest).offset().top
      }, 2000, 'easeInOutExpo');
    });

    j('.js-menu-move-scroll a').on('click', function(event) {
      event.preventDefault();
      var $this = j(this);
      var dest = $this.attr('href');

      j('html, body').stop().animate({
        scrollTop: j(dest).offset().top
      }, 2000, 'easeInOutExpo');
    });

    j('#js-frm-contact').formValidation({
      locale: 'es_ES',
      framework: 'bootstrap',
      icon: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      }
    }).on('err.field.fv', function(e, data){
      var field = e.target;
      j('small.help-block[data-bv-result="INVALID"]').addClass('hide');
    }).on('success.form.fv', function(e){
      e.preventDefault();

      var $form = j(e.target),
          fv = j(e.target).data('formValidation');

      var msg     = j('#js-form-contact-msg'),
          loader  = j('#js-form-contact-loader');

      loader.removeClass('hidden').addClass('infinite animated');
      msg.text('');

      var data = $form.serialize() + '&nonce=' + TCAjax.nonce + '&action=register_contact';

      j.post(TCAjax.url, data, function(data){
        $form.data('formValidation').resetForm(true);

        if (data.result) {
          msg.text('Ya tenemos su consulta. En breve nos pondremos en contacto con usted.');
        } else {
          msg.text(data.error);
        }

        loader.addClass('hidden').removeClass('infinite animated');
        msg.fadeIn('slow');
        setTimeout(function(){
          msg.fadeOut('slow', function(){
              j(this).text('');
          });
        }, 5000);
      }, 'json').fail(function(){
        alert('No se pudo realizar la operación solicitada. Por favor vuelva a intentarlo.');
      });
    });

    j('.js-toggle-slidebar').on('click', function(ev) {
      ev.preventDefault();
      var slidebar = j('.Slidebar');

      if (slidebar.hasClass('active')) {
        slidebar.removeClass('active');
      } else {
        slidebar.addClass('active');
      }
    });

    if (j('.Bxslider-list').length) {
      var bx = j('.Bxslider-list'),
          widthBxSlider = parseInt(bx.width()),
          widthBxSlider = $win.width() > 600 ? (widthBxSlider * 42) / 100 : 0,
          slides = $win.width() > 600 ? 3 : 1;

      sldExpert = j('.bxslider').bxSlider({
        auto: true,
        autoHover: true,
        minSlides: slides,
        maxSlides: slides,
        slideWidth: widthBxSlider,
        slideMargin: 15,
        nextText: '',
        prevText: '',
        pager: false,
        onSlidePrev: function($slideElement, oldIndex, newIndex) {
          sldExpert.goToSlide(newIndex);
          sldExpert.stopAuto();
          sldExpert.startAuto();
          return false;
        },
        onSlideNext: function($slideElement, oldIndex, newIndex) {
          sldExpert.goToSlide(newIndex);
          sldExpert.stopAuto();
          sldExpert.startAuto();
          return false;
        }
        /*onSliderLoad: function() {
          j('.bx-controls-direction a').on('click', function(){
            var i = $(this).attr('data-slide-index');
              sldExpert.goToSlide(i);
              sldExpert.stopAuto();
              sldExpert.startAuto();
              return false;
          });
        }*/
      });
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>angular.module('quick-survey').run(function($rootScope, $state) {

  $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
    console.log('error is', error)
    if (error === 'SET_UP_COMPLETE')
      $state.go('index')
  });

});

angular.module("quick-survey").config(
  function ($urlRouterProvider, $stateProvider, $locationProvider) {

    $locationProvider.html5Mode(true);

    $stateProvider
      .state('index', {
        url: '/',
        templateUrl: 'client/js/surveys/views/survey.ng.html',
        controller: 'SurveyCtrl',
        resolve: {
          'surveys': ['$q', function($q) {
            var deferred = $q.defer();

            Meteor.subscribe('surveys', {
              onReady: deferred.resolve,
              onStop: deferred.reject
            });

            return deferred.promise;
          }],
        }
      })
      .state('manage', {
        url: '/manage',
        templateUrl: 'client/js/manage/views/manage.ng.html',
        controller: 'ManageCtrl',
        resolve: {
          'currentUser': ['$q', function($q){
            var deferred = $q.defer();

            Meteor.autorun(function() {
              if (!Meteor.loggingIn()){
                var user = Meteor.user();
                if (user && user.is_admin)
                  deferred.resolve();
                if (user) {
                  var sandstorm = Meteor.user().services.sandstorm;
                  if (sandstorm && sandstorm.permissions[0] === 'owner')
                    deferred.resolve();

                }
               deferred.reject('UNAUTHORIZED');
              }
            })

            return deferred.promise;
          }],
          'activeSurvey': ['$q', function($q) {
            var deferred = $q.defer();

            Meteor.subscribe('surveys', {
              onReady: function() {
                var surveys = Surveys.find({active: true}).fetch();
                if (surveys.length > 0) {
                  var survey = Surveys.findOne(surveys[0]._id);
                  deferred.resolve(survey);
                } else {
                  // let's create an active survey
                  Surveys.insert({
                    questions: [],
                    description: 'This describes my first survey',
                    name: 'My First Survey',
                    require_sign_in: false,
                    active: true
                  }, function(err, id) {
                    if (err) deferred.reject(err)
                    deferred.resolve(Surveys.findOne(id))
                  })
                }

              },
              onStop: deferred.reject
            });
            return deferred.promise;
          }],
          'responses': ['$q', function($q) {
            var deferred = $q.defer();

            Meteor.subscribe('responses', {
              onReady: function() {
                deferred.resolve(Responses.find());
              },
              onStop: deferred.reject
            });

            return deferred.promise;
          }]
        }
      });

    $urlRouterProvider.otherwise("/");
  })

.run(function($rootScope, $state, $auth) {

  $auth.waitForUser().then(function() {
    Meteor.call('isSandstorm', function(err, resp) {
      console.log('is it sandstorm', resp);
      if (resp) {
        $rootScope.on_sandstorm = true;
      }
    });

    Meteor.call('isAdmin', function(err, resp) {
      console.log('is it admin', resp);
      if (resp) $rootScope.is_admin = true
    })
    Meteor.call('isSetUp', function(err, isSetUp) {
      console.log('is site setup', isSetUp);
      if (!isSetUp) {
        $state.go('setup')
      }
    })
  })
})
<commit_msg>Better checking that user exists<commit_after>angular.module('quick-survey').run(function($rootScope, $state) {

  $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
    console.log('error is', error)
    if (error === 'SET_UP_COMPLETE')
      $state.go('index')
  });

});

angular.module("quick-survey").config(
  function ($urlRouterProvider, $stateProvider, $locationProvider) {

    $locationProvider.html5Mode(true);

    $stateProvider
      .state('index', {
        url: '/',
        templateUrl: 'client/js/surveys/views/survey.ng.html',
        controller: 'SurveyCtrl',
        resolve: {
          'surveys': ['$q', function($q) {
            var deferred = $q.defer();

            Meteor.subscribe('surveys', {
              onReady: deferred.resolve,
              onStop: deferred.reject
            });

            return deferred.promise;
          }],
        }
      })
      .state('manage', {
        url: '/manage',
        templateUrl: 'client/js/manage/views/manage.ng.html',
        controller: 'ManageCtrl',
        resolve: {
          'currentUser': ['$q', function($q){
            var deferred = $q.defer();

            Meteor.autorun(function() {
              if (!Meteor.loggingIn()){
                var user = Meteor.user();
                if (user && user.is_admin)
                  deferred.resolve();
                if (user) {
                  var sandstorm = Meteor.user().services.sandstorm;
                  if (sandstorm && sandstorm.permissions[0] === 'owner')
                    deferred.resolve();

                }
               deferred.reject('UNAUTHORIZED');
              }
            })

            return deferred.promise;
          }],
          'activeSurvey': ['$q', function($q) {
            var deferred = $q.defer();

            Meteor.subscribe('surveys', {
              onReady: function() {
                var surveys = Surveys.find({active: true}).fetch();
                if (surveys.length > 0) {
                  var survey = Surveys.findOne(surveys[0]._id);
                  deferred.resolve(survey);
                } else {
                  // let's create an active survey
                  Surveys.insert({
                    questions: [],
                    description: 'This describes my first survey',
                    name: 'My First Survey',
                    require_sign_in: false,
                    active: true
                  }, function(err, id) {
                    if (err) deferred.reject(err)
                    deferred.resolve(Surveys.findOne(id))
                  })
                }

              },
              onStop: deferred.reject
            });
            return deferred.promise;
          }],
          'responses': ['$q', function($q) {
            var deferred = $q.defer();

            Meteor.subscribe('responses', {
              onReady: function() {
                deferred.resolve(Responses.find());
              },
              onStop: deferred.reject
            });

            return deferred.promise;
          }]
        }
      });

    $urlRouterProvider.otherwise("/");
  })

.run(function($rootScope, $state, $auth) {

  $auth.waitForUser().then(function() {
    Meteor.call('isSandstorm', function(err, resp) {
      console.log('is it sandstorm', resp);
      if (resp) {
        $rootScope.on_sandstorm = true;
      }
    });
    Meteor.call('isAdmin', function(err, resp) {
      console.log('is it admin', resp, JSON.stringify(Meteor.user()));
      if (resp) $rootScope.is_admin = true
    })
    Meteor.call('isSetUp', function(err, isSetUp) {
      console.log('is site setup', isSetUp);
      if (!isSetUp) {
        $state.go('setup')
      }
    })
  })
})
<|endoftext|>


<commit_before>import { combineReducers } from 'redux'

import {
  FETCH_FILES,
  RECEIVE_FILES,
  OPEN_FOLDER,
  OPEN_FOLDER_SUCCESS,
  OPEN_FOLDER_FAILURE,
  ADD_FOLDER,
  ABORT_ADD_FOLDER,
  CREATE_FOLDER,
  CREATE_FOLDER_SUCCESS,
  CREATE_FOLDER_FAILURE_DUPLICATE,
  CREATE_FOLDER_FAILURE_GENERIC,
  UPLOAD_FILE,
  UPLOAD_FILE_SUCCESS,
  TRASH_FILE,
  TRASH_FILE_SUCCESS,
  TRASH_FILE_FAILURE,
  SHOW_SELECTION_BAR,
  HIDE_SELECTION_BAR,
  SHOW_DELETE_CONFIRMATION,
  HIDE_DELETE_CONFIRMATION,
  SELECT_FILE,
  UNSELECT_FILE,
  DOWNLOAD_SELECTION,
  SHOW_FILE_ACTIONMENU,
  HIDE_FILE_ACTIONMENU,
  DISPLAY_TOAST,
  HIDE_TOAST,
  ALERT_CLOSED
} from '../actions'

const isFetching = (state = false, action) => {
  switch (action.type) {
    case FETCH_FILES:
      return true
    case RECEIVE_FILES:
      return false
    default:
      return state
  }
}

export const currentFolderId = (state = null, action) => {
  switch (action.type) {
    case OPEN_FOLDER:
      return action.folderId
    default:
      return state
  }
}

const isWorking = (state = false, action) => {
  switch (action.type) {
    case CREATE_FOLDER:
    case UPLOAD_FILE:
    case TRASH_FILE:
      return true
    case CREATE_FOLDER_SUCCESS:
    case CREATE_FOLDER_FAILURE_DUPLICATE:
    case CREATE_FOLDER_FAILURE_GENERIC:
    case UPLOAD_FILE_SUCCESS:
    case TRASH_FILE_SUCCESS:
    case TRASH_FILE_FAILURE:
      return false
    default:
      return state
  }
}

const opening = (state = false, action) => {
  switch (action.type) {
    case OPEN_FOLDER:
      return action.folderId
    case OPEN_FOLDER_SUCCESS:
    case OPEN_FOLDER_FAILURE:
      return false
    default:
      return state
  }
}

const creating = (state = false, action) => {
  switch (action.type) {
    case CREATE_FOLDER:
      return action.id
    case CREATE_FOLDER_SUCCESS:
    case CREATE_FOLDER_FAILURE_DUPLICATE:
    case CREATE_FOLDER_FAILURE_GENERIC:
      return false
    default:
      return state
  }
}

const failedCreation = (state = null, action) => {
  switch (action.type) {
    case CREATE_FOLDER:
      return null
    case CREATE_FOLDER_FAILURE_DUPLICATE:
    case CREATE_FOLDER_FAILURE_GENERIC:
      return {
        id: action.id
      }
    default:
      return state
  }
}

const updating = (state = [], action) => {
  switch (action.type) {
    case CREATE_FOLDER:
      return [
        ...state,
        action.id
      ]
    case CREATE_FOLDER_SUCCESS:
      let idx = state.indexOf(action.tempId)
      return [
        ...state.slice(0, idx),
        ...state.slice(idx + 1)
      ]
    default:
      return state
  }
}

const disableFolderCreation = (state = false, action) => {
  switch (action.type) {
    case ADD_FOLDER:
      return true
    case ABORT_ADD_FOLDER:
    case CREATE_FOLDER_SUCCESS:
      return false
    default:
      return state
  }
}

const showSelectionBar = (state = false, action) => {
  switch (action.type) {
    case SHOW_SELECTION_BAR:
      return true
    case OPEN_FOLDER:
    case HIDE_SELECTION_BAR:
      return false
    default:
      return state
  }
}

const showDeleteConfirmation = (state = false, action) => {
  switch (action.type) {
    case SHOW_DELETE_CONFIRMATION:
      return true
    case HIDE_DELETE_CONFIRMATION:
      return false
    default:
      return state
  }
}

const selected = (state = [], action) => {
  switch (action.type) {
    case SELECT_FILE:
      return [
        ...state,
        action.id
      ]
    case UNSELECT_FILE:
      let idx = state.indexOf(action.id)
      return [
        ...state.slice(0, idx),
        ...state.slice(idx + 1)
      ]
    case OPEN_FOLDER:
    case DOWNLOAD_SELECTION:
    case HIDE_SELECTION_BAR:
      return []
    default:
      return state
  }
}

const showFileActionMenu = (state = false, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return true
    case HIDE_FILE_ACTIONMENU:
      return false
    default:
      return state
  }
}

const actionable = (state = null, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return action.id
    case HIDE_FILE_ACTIONMENU:
      return null
    default:
      return state
  }
}

const error = (state = null, action) => {
  switch (action.type) {
    case OPEN_FOLDER_FAILURE:
      return {
        message: 'error.open_folder',
        cause: action.error,
        critical: true
      }
    default:
      return state
  }
}

const toastMessage = (state = null, action) => {
  switch (action.type) {
    case DISPLAY_TOAST:
      return {
        message: action.message,
        duration: action.duration || 3000,
        criticity: action.criticity || 'critical'
      }
    case HIDE_TOAST:
      return null
    default:
      return state
  }
}

const actionMenu = (state = { openWith: false }, action) => {
  const newState = {}
  switch (action.type) {
    case 'SHOW_SPINNER':
      newState[action.menu] = true
      return Object.assign({}, state, newState)
    case 'HIDE_SPINNER':
      newState[action.menu] = false
      return Object.assign({}, state, newState)
    default:
      return state
  }
}

const alert = (state = null, action) => {
  switch (action.type) {
    case TRASH_FILE_FAILURE:
      return {
        message: 'alert.trash_file_error',
        type: 'info'
      }
    case TRASH_FILE_SUCCESS:
      return {
        message: 'alert.trash_file_success',
        type: 'info'
      }
    case ABORT_ADD_FOLDER:
      return {
        message: 'alert.folder_abort',
        type: 'info'
      }
    case CREATE_FOLDER_FAILURE_DUPLICATE:
      return {
        message: 'alert.folder_name',
        messageData: {folderName: action.name},
        type: 'info'
      }
    case CREATE_FOLDER_FAILURE_GENERIC:
      return {
        message: 'alert.folder_generic',
        type: 'info'
      }
    case ALERT_CLOSED:
      return null
    default:
      return state
  }
}

export default combineReducers({
  isFetching,
  currentFolderId,
  isWorking,
  opening,
  creating,
  failedCreation,
  updating,
  disableFolderCreation,
  showSelectionBar,
  showDeleteConfirmation,
  selected,
  showFileActionMenu,
  actionable,
  error,
  toastMessage,
  actionMenu,
  alert
})
<commit_msg>[fix] Hide the selection bar after the action on mobile<commit_after>import { combineReducers } from 'redux'

import {
  FETCH_FILES,
  RECEIVE_FILES,
  OPEN_FOLDER,
  OPEN_FOLDER_SUCCESS,
  OPEN_FOLDER_FAILURE,
  ADD_FOLDER,
  ABORT_ADD_FOLDER,
  CREATE_FOLDER,
  CREATE_FOLDER_SUCCESS,
  CREATE_FOLDER_FAILURE_DUPLICATE,
  CREATE_FOLDER_FAILURE_GENERIC,
  UPLOAD_FILE,
  UPLOAD_FILE_SUCCESS,
  TRASH_FILE,
  TRASH_FILE_SUCCESS,
  TRASH_FILE_FAILURE,
  SHOW_SELECTION_BAR,
  HIDE_SELECTION_BAR,
  SHOW_DELETE_CONFIRMATION,
  HIDE_DELETE_CONFIRMATION,
  SELECT_FILE,
  UNSELECT_FILE,
  DOWNLOAD_SELECTION,
  SHOW_FILE_ACTIONMENU,
  HIDE_FILE_ACTIONMENU,
  DISPLAY_TOAST,
  HIDE_TOAST,
  ALERT_CLOSED
} from '../actions'

const isFetching = (state = false, action) => {
  switch (action.type) {
    case FETCH_FILES:
      return true
    case RECEIVE_FILES:
      return false
    default:
      return state
  }
}

export const currentFolderId = (state = null, action) => {
  switch (action.type) {
    case OPEN_FOLDER:
      return action.folderId
    default:
      return state
  }
}

const isWorking = (state = false, action) => {
  switch (action.type) {
    case CREATE_FOLDER:
    case UPLOAD_FILE:
    case TRASH_FILE:
      return true
    case CREATE_FOLDER_SUCCESS:
    case CREATE_FOLDER_FAILURE_DUPLICATE:
    case CREATE_FOLDER_FAILURE_GENERIC:
    case UPLOAD_FILE_SUCCESS:
    case TRASH_FILE_SUCCESS:
    case TRASH_FILE_FAILURE:
      return false
    default:
      return state
  }
}

const opening = (state = false, action) => {
  switch (action.type) {
    case OPEN_FOLDER:
      return action.folderId
    case OPEN_FOLDER_SUCCESS:
    case OPEN_FOLDER_FAILURE:
      return false
    default:
      return state
  }
}

const creating = (state = false, action) => {
  switch (action.type) {
    case CREATE_FOLDER:
      return action.id
    case CREATE_FOLDER_SUCCESS:
    case CREATE_FOLDER_FAILURE_DUPLICATE:
    case CREATE_FOLDER_FAILURE_GENERIC:
      return false
    default:
      return state
  }
}

const failedCreation = (state = null, action) => {
  switch (action.type) {
    case CREATE_FOLDER:
      return null
    case CREATE_FOLDER_FAILURE_DUPLICATE:
    case CREATE_FOLDER_FAILURE_GENERIC:
      return {
        id: action.id
      }
    default:
      return state
  }
}

const updating = (state = [], action) => {
  switch (action.type) {
    case CREATE_FOLDER:
      return [
        ...state,
        action.id
      ]
    case CREATE_FOLDER_SUCCESS:
      let idx = state.indexOf(action.tempId)
      return [
        ...state.slice(0, idx),
        ...state.slice(idx + 1)
      ]
    default:
      return state
  }
}

const disableFolderCreation = (state = false, action) => {
  switch (action.type) {
    case ADD_FOLDER:
      return true
    case ABORT_ADD_FOLDER:
    case CREATE_FOLDER_SUCCESS:
      return false
    default:
      return state
  }
}

const showSelectionBar = (state = false, action) => {
  switch (action.type) {
    case SHOW_SELECTION_BAR:
      return true
    case OPEN_FOLDER:
    case DOWNLOAD_SELECTION:
    case HIDE_SELECTION_BAR:
      return false
    default:
      return state
  }
}

const showDeleteConfirmation = (state = false, action) => {
  switch (action.type) {
    case SHOW_DELETE_CONFIRMATION:
      return true
    case HIDE_DELETE_CONFIRMATION:
      return false
    default:
      return state
  }
}

const selected = (state = [], action) => {
  switch (action.type) {
    case SELECT_FILE:
      return [
        ...state,
        action.id
      ]
    case UNSELECT_FILE:
      let idx = state.indexOf(action.id)
      return [
        ...state.slice(0, idx),
        ...state.slice(idx + 1)
      ]
    case OPEN_FOLDER:
    case DOWNLOAD_SELECTION:
    case HIDE_SELECTION_BAR:
      return []
    default:
      return state
  }
}

const showFileActionMenu = (state = false, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return true
    case HIDE_FILE_ACTIONMENU:
      return false
    default:
      return state
  }
}

const actionable = (state = null, action) => {
  switch (action.type) {
    case SHOW_FILE_ACTIONMENU:
      return action.id
    case HIDE_FILE_ACTIONMENU:
      return null
    default:
      return state
  }
}

const error = (state = null, action) => {
  switch (action.type) {
    case OPEN_FOLDER_FAILURE:
      return {
        message: 'error.open_folder',
        cause: action.error,
        critical: true
      }
    default:
      return state
  }
}

const toastMessage = (state = null, action) => {
  switch (action.type) {
    case DISPLAY_TOAST:
      return {
        message: action.message,
        duration: action.duration || 3000,
        criticity: action.criticity || 'critical'
      }
    case HIDE_TOAST:
      return null
    default:
      return state
  }
}

const actionMenu = (state = { openWith: false }, action) => {
  const newState = {}
  switch (action.type) {
    case 'SHOW_SPINNER':
      newState[action.menu] = true
      return Object.assign({}, state, newState)
    case 'HIDE_SPINNER':
      newState[action.menu] = false
      return Object.assign({}, state, newState)
    default:
      return state
  }
}

const alert = (state = null, action) => {
  switch (action.type) {
    case TRASH_FILE_FAILURE:
      return {
        message: 'alert.trash_file_error',
        type: 'info'
      }
    case TRASH_FILE_SUCCESS:
      return {
        message: 'alert.trash_file_success',
        type: 'info'
      }
    case ABORT_ADD_FOLDER:
      return {
        message: 'alert.folder_abort',
        type: 'info'
      }
    case CREATE_FOLDER_FAILURE_DUPLICATE:
      return {
        message: 'alert.folder_name',
        messageData: {folderName: action.name},
        type: 'info'
      }
    case CREATE_FOLDER_FAILURE_GENERIC:
      return {
        message: 'alert.folder_generic',
        type: 'info'
      }
    case ALERT_CLOSED:
      return null
    default:
      return state
  }
}

export default combineReducers({
  isFetching,
  currentFolderId,
  isWorking,
  opening,
  creating,
  failedCreation,
  updating,
  disableFolderCreation,
  showSelectionBar,
  showDeleteConfirmation,
  selected,
  showFileActionMenu,
  actionable,
  error,
  toastMessage,
  actionMenu,
  alert
})
<|endoftext|>


<commit_before>function action(worker, on, action, selector, original_color, highlight_color, params, on_success) {
    var url = '';
    if(on) {
        url = '/cmpp/personnes/gestion/' + worker + '/holidays/' + on + '/' + action + '/';
        $(selector).attr('style', 'background: ' + highlight_color);
    } else {
        url = '/cmpp/personnes/gestion/' + worker + '/holidays/' + action;
    }
    $("#holiday-dlg").load(url,
                           function() {
                               $(this).dialog({title: params.title,
                                               width: params.width,
                                               buttons: [{text: params.button_close,
                                                          click: function() {
                                                              $(this).dialog('close');
                                                              $(selector).attr('style', original_color);
                                                          }},{text: params.button_confirm,
                                                              click: function(){
                                                                  $.ajax({url: url,
                                                                          type: 'post',
                                                                          data: $('#holiday-dlg form').serialize()
                                                                         }).done(on_success)
                                                              }}]});
                           })
};

function add_holiday(worker) {
    params = {'title': 'Ajouter une absence', 'button_close': 'Fermer',
              'button_confirm': 'Ajouter', 'width': '500px'};

    on_success = function(response, status, xhr) {
        var content_type = xhr.getResponseHeader('content-type');
      if(content_type.indexOf('html') > -1) {
            $('#holiday-dlg form').html(response);
        } else {
            if(!response.err) {
                var result = response.content;
                var id = response.id;
                var li = $("

");
                var ul = $('

');
                $.each(result, function(i, e) {
                    console.log(e);
                    var item = $('
' + e[1] + '
');
                    ul.append(item);
                });
                var button_edit = $('<button class="icon-edit" data-action="edit" data-id="' + id + '"></button>');
                var button_delete = $('<button class="icon-remove" data-action="delete" data-id="' + id + '"></button>');
                var actions = $('

');
                actions.append(button_edit, button_delete);
                ul.append(actions);
                li.append(ul);
                $("#holidays").append(li);
                $("#holiday-dlg").dialog("close");
            }
        }
    };
    action(worker, null, 'ajouter', null, null, null, params, on_success);
};

function delete_holiday(worker, holiday) {
    var selector = '#' + holiday + ' ul';
    var initial_color = $(selector).attr('style');
    var params = {'title': 'Supprimer une absence',
                  'button_close': 'Non', 'button_confirm': 'Oui',
                  'width': '450px'}

    on_success = function(response) {
        if(!response.err) {
            $('#' +  holiday).remove();
            $(selector).attr('style', initial_color);
            $("#holiday-dlg").dialog("close");
        }
    };
    action(worker, holiday, 'supprimer', selector, initial_color, '#f8b0b0', params, on_success);
};

function edit_holiday(worker, holiday) {
    var selector = '#' + holiday + ' ul';
    var initial_color = $(selector).attr('style');
    params = {'title': 'Éditer une absence',
              'button_close': 'Fermer', 'button_confirm': 'Mettre à jour',
              'width': '500px'}

    on_success = function(response, status, xhr) {
        var content_type = xhr.getResponseHeader('content-type');
        if(content_type.indexOf('html') > -1) {
            $('#holiday-dlg form').html(response);
        } else {
            if(!response.err) {
                $.each(response.content, function(i, e) {
                    $('#holidays #' + holiday + ' li.' + e[0]).html(e[1]);
                });
                $(selector).attr('style', initial_color);
                $("#holiday-dlg").dialog("close");
            }
        }}
    action(worker, holiday, 'editer', selector, initial_color,  '#af7', params, on_success);
};<commit_msg>Handling more properly json responses<commit_after>function action(worker, on, action, selector, original_color, highlight_color, params, on_success) {
    var url = '';
    if(on) {
        url = '/cmpp/personnes/gestion/' + worker + '/holidays/' + on + '/' + action + '/';
        $(selector).attr('style', 'background: ' + highlight_color);
    } else {
        url = '/cmpp/personnes/gestion/' + worker + '/holidays/' + action;
    }
    $("#holiday-dlg").load(url,
                           function() {
                               $(this).dialog({title: params.title,
                                               width: params.width,
                                               buttons: [{text: params.button_close,
                                                          click: function() {
                                                              $(this).dialog('close');
                                                              $(selector).attr('style', original_color);
                                                          }},{text: params.button_confirm,
                                                              click: function(){
                                                                  $.ajax({url: url,
                                                                          type: 'post',
                                                                          data: $('#holiday-dlg form').serialize()
                                                                         }).done(on_success)
                                                              }}]});
                           })
};

function add_holiday(worker) {
    params = {'title': 'Ajouter une absence', 'button_close': 'Fermer',
              'button_confirm': 'Ajouter', 'width': '500px'};

    on_success = function(response) {
        try {
            $.parseJSON(response);
            if(!response.err) {
                var result = response.content;
                var id = response.id;
                var li = $("

");
                var ul = $('

');
                $.each(result, function(i, e) {
                    var item = $('
' + e[1] + '
');
                    ul.append(item);
                });
                var button_edit = $('<button class="icon-edit" data-action="edit" data-id="' + id + '"></button>');
                var button_delete = $('<button class="icon-remove" data-action="delete" data-id="' + id + '"></button>');
                var actions = $('

');
                actions.append(button_edit, button_delete);
                ul.append(actions);
                li.append(ul);
                $("#holidays").append(li);
                $("#holiday-dlg").dialog("close");
            }
        } catch(e) {
            $('#holiday-dlg form').html(response);
        }

    };
    action(worker, null, 'ajouter', null, null, null, params, on_success);
};

function delete_holiday(worker, holiday) {
    var selector = '#' + holiday + ' ul';
    var initial_color = $(selector).attr('style');
    var params = {'title': 'Supprimer une absence',
                  'button_close': 'Non', 'button_confirm': 'Oui',
                  'width': '450px'}

    on_success = function(response) {
        if(!response.err) {
            $('#' +  holiday).remove();
            $(selector).attr('style', initial_color);
            $("#holiday-dlg").dialog("close");
        }
    };
    action(worker, holiday, 'supprimer', selector, initial_color, '#f8b0b0', params, on_success);
};

function edit_holiday(worker, holiday) {
    var selector = '#' + holiday + ' ul';
    var initial_color = $(selector).attr('style');
    params = {'title': 'Éditer une absence',
              'button_close': 'Fermer', 'button_confirm': 'Mettre à jour',
              'width': '500px'}

    on_success = function(response) {
        try {
            $.parseJSON(response);
            if(!response.err) {
                $.each(response.content, function(i, e) {
                    $('#holidays #' + holiday + ' li.' + e[0]).html(e[1]);
                });
                $(selector).attr('style', initial_color);
                $("#holiday-dlg").dialog("close");
            }
        } catch(e) {
            console.log(e);
            $('#holiday-dlg form').html(response);
        }

    }
    action(worker, holiday, 'editer', selector, initial_color,  '#af7', params, on_success);
};<|endoftext|>


<commit_before>define(["js/ui/View"], function (View) {

    var ratios = {
        2: [75, 25],
        3: [60, 30, 10]
    };

    var lengthCache = {};

    return View.inherit("sprd.view.AppearanceColorClass", {

        defaults: {
            appearance: null,
            componentClass: "appearance-color"
        },

        colorWidth: function (index) {
            var length = this.get("appearance.colors.length");

            var cacheKey = "" + length;
            if (lengthCache.hasOwnProperty(cacheKey)) {
                return lengthCache[cacheKey];
            }

            var ret = 0;
            if (length) {

                if (ratios.hasOwnProperty(length)) {
                    ret = ratios[length][index];
                } else {
                    ret = 100 / length;
                }

            }

            lengthCache[cacheKey] = ret;

            return ret;

        }.onChange("appearance")

    });

});
<commit_msg>DEV-53447 - add class to the colors in the modal window of the product selector<commit_after>define(["js/ui/View"], function (View) {

    var ratios = {
        2: [75, 25],
        3: [60, 30, 10]
    };

    var lengthCache = {};

    return View.inherit("sprd.view.AppearanceColorClass", {

        defaults: {
            appearance: null,
            componentClass: "appearance-color appearance-{appearance.id}"
        },

        colorWidth: function (index) {
            var length = this.get("appearance.colors.length");

            var cacheKey = "" + length;
            if (lengthCache.hasOwnProperty(cacheKey)) {
                return lengthCache[cacheKey];
            }

            var ret = 0;
            if (length) {

                if (ratios.hasOwnProperty(length)) {
                    ret = ratios[length][index];
                } else {
                    ret = 100 / length;
                }

            }

            lengthCache[cacheKey] = ret;

            return ret;

        }.onChange("appearance")

    });

});
<|endoftext|>


<commit_before>
/**
 * SAHARA Web Interface
 *
 * User interface to Sahara Remote Laboratory system.
 *
 * @license See LICENSE in the top level directory for complete license terms.
 *
 * Copyright (c) 2010, University of Technology, Sydney
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of the University of Technology, Sydney nor the names
 *    of its contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author Michael Diponio (mdiponio)
 * @date 20th September 2010
 */

function initPage()
{
	resizeFooter();
	menuSlider.init("menu", "slide");
}

var menuSlider = function() {
	var m, e, g, s, q, i;
	e = [];
	q = 8;
	i = 8;
	return {
		init : function(j, k) {
			m = document.getElementById(j);
			e = m.getElementsByTagName('li');
			var i, l, w, p;
			i = 0;
			l = e.length;
			for (i; i < l; i++) {
				var c, v;
				c = e[i];
				v = c.value;
				if (v == 1) {
					s = c;
					w = c.offsetWidth;
					p = c.offsetLeft
				}
				c.onmouseover = function() {
					menuSlider.mo(this)
				};
				c.onmouseout = function() {
					menuSlider.mo(s)
				};
			}
			g = document.getElementById(k);
			g.style.width = w + 'px';
			g.style.left = p + 'px';
		},
		mo : function(d) {
			clearInterval(m.tm);
			var el, ew;
			el = parseInt(d.offsetLeft);
			ew = parseInt(d.offsetWidth);
			m.tm = setInterval(function() {
				menuSlider.mv(el, ew);
			}, i);
		},
		mv : function(el, ew) {
			var l, w;
			l = parseInt(g.offsetLeft);
			w = parseInt(g.offsetWidth);
			if (l != el || w != ew) {
				if (l != el) {
					var ld, lr, li;
					ld = (l > el) ? -1 : 1;
					lr = Math.abs(el - l);
					li = (lr < q) ? ld * lr : ld * q;
					g.style.left = (l + li) + 'px';
				}
				if (w != ew) {
					var wd, wr, wi;
					wd = (w > ew) ? -1 : 1;
					wr = Math.abs(ew - w);
					wi = (wr < q) ? wd * wr : wd * q;
					g.style.width = (w + wi) + 'px';
				}
			} else {
				clearInterval(m.tm);
			}
		}
	};
}();

function resizeFooter()
{
	 var height;

	 if (typeof window.innerWidth != 'undefined')
	 {
	      height = window.innerHeight;
	 }
	 else
     {
		 height = document.documentElement.clientHeight;
     }

	var n = document.getElementById("wrapper");
	n.style.minHeight = height + "px";
}

function loadToolTip(pre, id, tt)
{
	if (tt[id])
	{
		$(pre + "hov" + id).fadeIn();
		$(pre + id).css('font-weight', 'bold');
	}
}

function updateLogs()
{
	$.get(
		"/logs/update",
		null,
		function (response) {
			if (response.indexOf("<li") == 0)
			{
				$("#logslist").empty().append(response);

				if (!$("#fatalcheck").is(":checked")) $(".fatallog").hide();
				if (!$("#pricheck").is(":checked")) $(".prilog").hide();
				if (!$("#errorcheck").is(":checked")) $(".errorlog").hide();
				if (!$("#warncheck").is(":checked")) $(".warnlog").hide();
				if (!$("#infocheck").is(":checked"))  $(".infolog").hide();
				if (!$("#debugcheck").is(":checked")) $(".debuglog").hide();
			}
			else if (response != "") window.location.reload();

			setTimeout(updateLogs, 5000);
		}
	);
}

function updateStatus()
{
	$.get(
		"/status/update",
		null,
		function (response) {
			if (response.indexOf("<div") == 0)
			{
				$("#statuscontents").empty().append(response);
			}
			else if (response != "")
			{
				window.location.reload();
			}

			setTimeout(updateStatus, 10000);
		}
	);
}

function updateNavStatus()
{
	$.get(
		"/status/current",
		null,
		function (response) {
			if (response.indexOf("<img") == 0)
			{
				$("#currentstatusicon").empty().append(response);
				setTimeout(updateNavStatus, 5000);
			}
		}
	);
}

function restartRigClient()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
		"

\n" +
		"Restarting rig client..."
	);

	$.post(
		"/op/restart",
		null,
		function() {
			setTimeout(checkIfRestarted, 5000);
		}
	);
}

function checkIfRestarted()
{
	$.get(
		"/status/current",
		null,
		function (response) {
			if (response != '') {
				window.location.replace("/");
			}
		}
	);
}

function shutdownRigClient()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
		"

\n" +
		"Shutting down rig client..."
	);

	$.post(
		"/op/shutdown",
		null,
		function() {
			$("#confirmationcontainer").empty().append(
				"Rig client has shutdown."
			);
		}
	);
}

function clearMaintenance()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
		"

\n" +
		"Clearing maintenance..."
	);

	$.post(
		"/op/clear",
		null,
		function() {
			window.location.replace("/");
	});
}

function cleanBackups()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
			"

\n" +
			"Cleaning backups..."
	);

	$.post(
		"/op/clean",
		null,
		function() {
			window.location.replace("/");
	});
}

function updateSelectedInfoTab()
{
	$.get(
		"/info/" + selectedTab,
		null,
		function (resp) {
			$("#contentstable").empty()
							  .append(resp);

			$("#contentstable tr:even").addClass("evenrow");
			$("#contentstable tr:odd").addClass("oddrow");

			setTimeout(updateSelectedInfoTab, 5000);
		}
	);
}

function loadInfoTab(tab)
{
	/* Change selected tab. */
	selectedTab = tab;

	$('.selectedtab').removeClass('selectedtab')
					 .addClass('notselectedtab');
	$("#" + tab + "tab").removeClass('notselectedtab')
	                    .addClass('selectedtab');

	$.get(
		"/info/" + tab,
		null,
		function (resp) {
			$("#contentstable").empty()
							  .append(resp);

			$("#contentstable tr:even").addClass("evenrow");
			$("#contentstable tr:odd").addClass("oddrow");
		}
	);
}

function loadConfStanza(stanza)
{
	$.get(
		"/config/" + stanza,
		null,
		function(data) {
			/* Content pane. */
	        $("#contentspane").empty()
	        				  .append(data);
	        $("#confform").validationEngine();
            $("#confform").jqTransform();
            $(".jqTransformInputWrapper").css("width", "305px");
            $(".jqTransformInputInner div input").css("width", "100%");
		}
	);

	$(".selectedtab").removeClass("selectedtab")
					 .addClass("notselectedtab");
	$("#" + stanza.replace(/\s/g, "") + "tab").removeClass('notselectedtab')
											.addClass('selectedtab');
}

function resizeConfPanel()
{
	var height = $(window).height() - 230;
    var tabsHeight = $('#lefttablist').height();

    if (height < tabsHeight) height = tabsHeight;
    $('#contentspane').css('height', height);
}
<commit_msg>Fixed page updates.<commit_after>
/**
 * SAHARA Web Interface
 *
 * User interface to Sahara Remote Laboratory system.
 *
 * @license See LICENSE in the top level directory for complete license terms.
 *
 * Copyright (c) 2010, University of Technology, Sydney
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of the University of Technology, Sydney nor the names
 *    of its contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author Michael Diponio (mdiponio)
 * @date 20th September 2010
 */

function initPage()
{
	resizeFooter();
	menuSlider.init("menu", "slide");
}

var menuSlider = function() {
	var m, e, g, s, q, i;
	e = [];
	q = 8;
	i = 8;
	return {
		init : function(j, k) {
			m = document.getElementById(j);
			e = m.getElementsByTagName('li');
			var i, l, w, p;
			i = 0;
			l = e.length;
			for (i; i < l; i++) {
				var c, v;
				c = e[i];
				v = c.value;
				if (v == 1) {
					s = c;
					w = c.offsetWidth;
					p = c.offsetLeft
				}
				c.onmouseover = function() {
					menuSlider.mo(this)
				};
				c.onmouseout = function() {
					menuSlider.mo(s)
				};
			}
			g = document.getElementById(k);
			g.style.width = w + 'px';
			g.style.left = p + 'px';
		},
		mo : function(d) {
			clearInterval(m.tm);
			var el, ew;
			el = parseInt(d.offsetLeft);
			ew = parseInt(d.offsetWidth);
			m.tm = setInterval(function() {
				menuSlider.mv(el, ew);
			}, i);
		},
		mv : function(el, ew) {
			var l, w;
			l = parseInt(g.offsetLeft);
			w = parseInt(g.offsetWidth);
			if (l != el || w != ew) {
				if (l != el) {
					var ld, lr, li;
					ld = (l > el) ? -1 : 1;
					lr = Math.abs(el - l);
					li = (lr < q) ? ld * lr : ld * q;
					g.style.left = (l + li) + 'px';
				}
				if (w != ew) {
					var wd, wr, wi;
					wd = (w > ew) ? -1 : 1;
					wr = Math.abs(ew - w);
					wi = (wr < q) ? wd * wr : wd * q;
					g.style.width = (w + wi) + 'px';
				}
			} else {
				clearInterval(m.tm);
			}
		}
	};
}();

function resizeFooter()
{
	 var height;

	 if (typeof window.innerWidth != 'undefined')
	 {
	      height = window.innerHeight;
	 }
	 else
     {
		 height = document.documentElement.clientHeight;
     }

	var n = document.getElementById("wrapper");
	n.style.minHeight = height + "px";
}

function loadToolTip(pre, id, tt)
{
	if (tt[id])
	{
		$(pre + "hov" + id).fadeIn();
		$(pre + id).css('font-weight', 'bold');
	}
}

function updateLogs()
{
	$.get(
		"/logs/update",
		null,
		function (response) {
			response = $.trim(response);
			if (response.indexOf("<li") == 0)
			{
				$("#logslist").empty().append(response);

				if (!$("#fatalcheck").is(":checked")) $(".fatallog").hide();
				if (!$("#pricheck").is(":checked")) $(".prilog").hide();
				if (!$("#errorcheck").is(":checked")) $(".errorlog").hide();
				if (!$("#warncheck").is(":checked")) $(".warnlog").hide();
				if (!$("#infocheck").is(":checked"))  $(".infolog").hide();
				if (!$("#debugcheck").is(":checked")) $(".debuglog").hide();
			}
			else if (response != "") window.location.reload();

			setTimeout(updateLogs, 5000);
		}
	);
}

function updateStatus()
{
	$.get(
		"/status/update",
		null,
		function (response) {
			response = $.trim(response);
			if (response.indexOf("<div") == 0)
			{
				$("#statuscontents").empty().append(response);
			}
			else if (response != "")
			{
				window.location.reload();
			}

			setTimeout(updateStatus, 10000);
		}
	);
}

function updateNavStatus()
{
	$.get(
		"/status/current",
		null,
		function (response) {
			response = $.trim(response);
			if (response.indexOf("<img") == 0)
			{
				$("#currentstatusicon").empty().append(response);
				setTimeout(updateNavStatus, 5000);
			}
		}
	);
}

function restartRigClient()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
		"

\n" +
		"Restarting rig client..."
	);

	$.post(
		"/op/restart",
		null,
		function() {
			setTimeout(checkIfRestarted, 5000);
		}
	);
}

function checkIfRestarted()
{
	$.get(
		"/status/current",
		null,
		function (response) {
			if (response != '') {
				window.location.replace("/");
			}
		}
	);
}

function shutdownRigClient()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
		"

\n" +
		"Shutting down rig client..."
	);

	$.post(
		"/op/shutdown",
		null,
		function() {
			$("#confirmationcontainer").empty().append(
				"Rig client has shutdown."
			);
		}
	);
}

function clearMaintenance()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
		"

\n" +
		"Clearing maintenance..."
	);

	$.post(
		"/op/clear",
		null,
		function() {
			window.location.replace("/");
	});
}

function cleanBackups()
{
	$("#confirmationcontainer").empty().addClass('confirminprogress').append(
			"

\n" +
			"Cleaning backups..."
	);

	$.post(
		"/op/clean",
		null,
		function() {
			window.location.replace("/");
	});
}

function updateSelectedInfoTab()
{
	$.get(
		"/info/" + selectedTab,
		null,
		function (response) {
			response = $.trim(response);
			if (response.indexOf("<tr") == 0)
			{
				$("#contentstable").empty()
								  .append(response);

				$("#contentstable tr:even").addClass("evenrow");
				$("#contentstable tr:odd").addClass("oddrow");
			}
			else if (response != "") window.location.reload();

			setTimeout(updateSelectedInfoTab, 5000);
		}
	);
}

function loadInfoTab(tab)
{
	/* Change selected tab. */
	selectedTab = tab;

	$('.selectedtab').removeClass('selectedtab')
					 .addClass('notselectedtab');
	$("#" + tab + "tab").removeClass('notselectedtab')
	                    .addClass('selectedtab');

	$.get(
		"/info/" + tab,
		null,
		function (response) {
			response = $.trim(response);
			if (response.indexOf("<tr") == 0)
			{
				$("#contentstable").empty()
								  .append(response);

				$("#contentstable tr:even").addClass("evenrow");
				$("#contentstable tr:odd").addClass("oddrow");
			}
			else window.location.reload();
		}
	);
}

function loadConfStanza(stanza)
{
	$.get(
		"/config/" + stanza,
		null,
		function(data) {
			/* Content pane. */
	        $("#contentspane").empty()
	        				  .append(data);
	        $("#confform").validationEngine();
            $("#confform").jqTransform();
            $(".jqTransformInputWrapper").css("width", "305px");
            $(".jqTransformInputInner div input").css("width", "100%");
		}
	);

	$(".selectedtab").removeClass("selectedtab")
					 .addClass("notselectedtab");
	$("#" + stanza.replace(/\s/g, "") + "tab").removeClass('notselectedtab')
											.addClass('selectedtab');
}

function resizeConfPanel()
{
	var height = $(window).height() - 230;
    var tabsHeight = $('#lefttablist').height();

    if (height < tabsHeight) height = tabsHeight;
    $('#contentspane').css('height', height);
}
<|endoftext|>


<commit_before>import { getMapClickLocation } from '../../../../src/map/ducks/click-location/map-click-location';

(function () {
    angular
        .module('dpDetail')
        .component('dpDetail', {
            bindings: {
                show: '=',
                endpoint: '@',
                reload: '=',
                isLoading: '=',
                isMapHighlight: '=',
                catalogFilters: '=',
                user: '<'
            },
            templateUrl: 'modules/detail/components/detail/detail.html',
            controller: DpDetailController,
            controllerAs: 'vm'
        });

    DpDetailController.$inject = [
        '$scope',
        'store',
        'ACTIONS',
        'api',
        'endpointParser',
        'geometry',
        'geojson',
        'crsConverter',
        'dataFormatter',
        'markdownParser'
    ];

    /* eslint-disable max-params */
    function DpDetailController (
        $scope,
        store,
        ACTIONS,
        api,
        endpointParser,
        geometry,
        geojson,
        crsConverter,
        dataFormatter,
        markdownParser
    ) {
        /* eslint-enable max-params */
        var vm = this;

        // Reload the data when the reload flag has been set (endpoint has not
        // changed)
        $scope.$watch('vm.reload', reload => {
            if (reload) {
                getData(vm.endpoint);
            }
        });

        // (Re)load the data when the endpoint is set or gets changed
        $scope.$watch('vm.endpoint', getData);

        // Ensure the catalog filters for dcatd endpoints
        $scope.$watch('vm.catalogFilters', () => {
            if (vm.catalogFilters) {
                getData(vm.endpoint);
            }
        });

        // (Re)load the data when the user logs in or out or on a change of authorization level
        $scope.$watch('vm.user.scopes', (newValue, oldValue) => {
            if (newValue !== oldValue) {
                getData(vm.endpoint);
            }
        });

        function getData (endpoint) {
            vm.location = null;

            vm.includeSrc = endpointParser.getTemplateUrl(endpoint);

            const location = getMapClickLocation(store.getState());

            vm.geosearchButton = vm.isMapHighlight ? false : [location.latitude, location.longitude];

            const [category, subject] = endpointParser.getParts(endpoint);

            if ((category === 'brk' && subject === 'subject' && !vm.user.scopes.includes('BRK/RS')) ||
                (category === 'handelsregister' && !vm.user.scopes.includes('HR/R')) ||
                (category === 'grondexploitatie' && !vm.user.scopes.includes('GREX/R'))
            ) {
                // User is not authorized to view
                //   BRK Kadastrale Subjecten, nor
                //   handelsregister, nor
                //   grondexploitatie
                // so do not fetch data
                delete vm.apiData;
                errorHandler();
            } else if (category === 'dcatd' && subject === 'datasets' && !vm.catalogFilters) {
                // The catalogFilters data is not present so do not fetch data
                delete vm.apiData;
                errorHandler();
            } else {
                const endpointVersion = category === 'grondexploitatie' ? '?version=2' : '';
                api.getByUrl(`${endpoint}${endpointVersion}`).then(function (data) {
                    data = dataFormatter.formatData(data, subject, vm.catalogFilters);

                    if (category === 'dcatd' && subject === 'datasets') {
                        data['dct:description'] = data['dct:description'] &&
                            markdownParser.parse(data['dct:description']);
                        data.canEditDataset = vm.user.scopes.includes('CAT/W');
                    }

                    vm.apiData = {
                        results: data
                    };

                    vm.filterSelection = {
                        [subject]: vm.apiData.results.naam
                    };

                    geometry.getGeoJSON(endpoint).then(function (geoJSON) {
                        if (geoJSON !== null) {
                            vm.location = crsConverter.rdToWgs84(geojson.getCenter(geoJSON));
                        }

                        if (vm.isMapHighlight) {
                            store.dispatch({
                                type: ACTIONS.DETAIL_FULLSCREEN,
                                payload: subject === 'api' || !geoJSON
                            });
                        }

                        store.dispatch({
                            type: ACTIONS.SHOW_DETAIL,
                            payload: {
                                display: data._display,
                                geometry: geoJSON
                            }
                        });
                    }, errorHandler);
                }, errorHandler);
            }
        }

        function errorHandler () {
            store.dispatch({
                type: ACTIONS.SHOW_DETAIL,
                payload: {}
            });
        }
    }
})();
<commit_msg>DP-5496 Switch to version 3 of grex api<commit_after>import { getMapClickLocation } from '../../../../src/map/ducks/click-location/map-click-location';

(function () {
    angular
        .module('dpDetail')
        .component('dpDetail', {
            bindings: {
                show: '=',
                endpoint: '@',
                reload: '=',
                isLoading: '=',
                isMapHighlight: '=',
                catalogFilters: '=',
                user: '<'
            },
            templateUrl: 'modules/detail/components/detail/detail.html',
            controller: DpDetailController,
            controllerAs: 'vm'
        });

    DpDetailController.$inject = [
        '$scope',
        'store',
        'ACTIONS',
        'api',
        'endpointParser',
        'geometry',
        'geojson',
        'crsConverter',
        'dataFormatter',
        'markdownParser'
    ];

    /* eslint-disable max-params */
    function DpDetailController (
        $scope,
        store,
        ACTIONS,
        api,
        endpointParser,
        geometry,
        geojson,
        crsConverter,
        dataFormatter,
        markdownParser
    ) {
        /* eslint-enable max-params */
        var vm = this;

        // Reload the data when the reload flag has been set (endpoint has not
        // changed)
        $scope.$watch('vm.reload', reload => {
            if (reload) {
                getData(vm.endpoint);
            }
        });

        // (Re)load the data when the endpoint is set or gets changed
        $scope.$watch('vm.endpoint', getData);

        // Ensure the catalog filters for dcatd endpoints
        $scope.$watch('vm.catalogFilters', () => {
            if (vm.catalogFilters) {
                getData(vm.endpoint);
            }
        });

        // (Re)load the data when the user logs in or out or on a change of authorization level
        $scope.$watch('vm.user.scopes', (newValue, oldValue) => {
            if (newValue !== oldValue) {
                getData(vm.endpoint);
            }
        });

        function getData (endpoint) {
            vm.location = null;

            vm.includeSrc = endpointParser.getTemplateUrl(endpoint);

            const location = getMapClickLocation(store.getState());

            vm.geosearchButton = vm.isMapHighlight ? false : [location.latitude, location.longitude];

            const [category, subject] = endpointParser.getParts(endpoint);

            if ((category === 'brk' && subject === 'subject' && !vm.user.scopes.includes('BRK/RS')) ||
                (category === 'handelsregister' && !vm.user.scopes.includes('HR/R')) ||
                (category === 'grondexploitatie' && !vm.user.scopes.includes('GREX/R'))
            ) {
                // User is not authorized to view
                //   BRK Kadastrale Subjecten, nor
                //   handelsregister, nor
                //   grondexploitatie
                // so do not fetch data
                delete vm.apiData;
                errorHandler();
            } else if (category === 'dcatd' && subject === 'datasets' && !vm.catalogFilters) {
                // The catalogFilters data is not present so do not fetch data
                delete vm.apiData;
                errorHandler();
            } else {
                const endpointVersion = category === 'grondexploitatie' ? '?version=3' : '';
                api.getByUrl(`${endpoint}${endpointVersion}`).then(function (data) {
                    data = dataFormatter.formatData(data, subject, vm.catalogFilters);

                    if (category === 'dcatd' && subject === 'datasets') {
                        data['dct:description'] = data['dct:description'] &&
                            markdownParser.parse(data['dct:description']);
                        data.canEditDataset = vm.user.scopes.includes('CAT/W');
                    }

                    vm.apiData = {
                        results: data
                    };

                    vm.filterSelection = {
                        [subject]: vm.apiData.results.naam
                    };

                    geometry.getGeoJSON(endpoint).then(function (geoJSON) {
                        if (geoJSON !== null) {
                            vm.location = crsConverter.rdToWgs84(geojson.getCenter(geoJSON));
                        }

                        if (vm.isMapHighlight) {
                            store.dispatch({
                                type: ACTIONS.DETAIL_FULLSCREEN,
                                payload: subject === 'api' || !geoJSON
                            });
                        }

                        store.dispatch({
                            type: ACTIONS.SHOW_DETAIL,
                            payload: {
                                display: data._display,
                                geometry: geoJSON
                            }
                        });
                    }, errorHandler);
                }, errorHandler);
            }
        }

        function errorHandler () {
            store.dispatch({
                type: ACTIONS.SHOW_DETAIL,
                payload: {}
            });
        }
    }
})();
<|endoftext|>


<commit_before>import { shallow } from 'enzyme';
import simple from 'simple-mock';
import React from 'react';

import ReservationPopover from '../../../../../reservation-popover/ReservationPopover';
import { UninjectedReservationSlot as ReservationSlot } from '../ReservationSlot';
import utils from '../../utils';

function getWrapper(props) {
  const defaults = {
    begin: '2017-01-01T10:00:00Z',
    end: '2017-01-01T10:30:00Z',
    resourceId: '1',
    isSelectable: true,
    t: s => s,
  };
  return shallow(<ReservationSlot {...defaults} {...props} />);
}

describe('shared/availability-view/ReservationSlot', () => {
  test('returns a button.reservation-slot', () => {
    const wrapper = getWrapper();
    expect(wrapper.is('button')).toBe(true);
    expect(wrapper.hasClass('reservation-slot')).toBe(true);
  });

  test('has correct width', () => {
    const expected = utils.getTimeSlotWidth();
    const actual = getWrapper().prop('style');
    expect(actual).toEqual({ width: expected });
  });

  test('binds onClick to handleClick', () => {
    const wrapper = getWrapper();
    const instance = wrapper.instance();
    expect(wrapper.prop('onClick')).toBe(instance.handleClick);
  });

  describe('Popover', () => {
    function getPopover(props) {
      const wrapper = getWrapper(props);
      return wrapper.find(ReservationPopover);
    }

    describe('is not rendered when the slot', () => {
      test('has no selection', () => {
        const popover = getPopover({ selection: null });
        expect(popover).toHaveLength(0);
      });

      test('is not in selection', () => {
        const popover = getPopover({
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T10:30:00Z',
          selection: {
            begin: '2016-01-01T10:30:00Z',
            end: '2016-01-01T12:00:00Z',
            resourceId: '1',
          },
        });
        expect(popover).toHaveLength(0);
      });

      test('is inside selection but not the first slot', () => {
        const popover = getPopover({
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T10:30:00Z',
          selection: {
            begin: '2016-01-01T09:30:00Z',
            end: '2016-01-01T12:00:00Z',
            resourceId: '1',
          },
        });
        expect(popover).toHaveLength(0);
      });

      test('is inside hover selection', () => {
        const popover = getPopover({
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T10:30:00Z',
          selection: {
            begin: '2016-01-01T10:00:00Z',
            end: '2016-01-01T12:00:00Z',
            resourceId: '1',
            hover: true,
          },
        });
        expect(popover).toHaveLength(0);
      });
    });

    test('is rendered if beginning of selection', () => {
      const popover = getPopover({
        begin: '2016-01-01T10:00:00Z',
        end: '2016-01-01T10:30:00Z',
        selection: {
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T12:00:00Z',
          resourceId: '1',
        },
      });
      expect(popover).toHaveLength(1);
    });
  });

  describe('selection', () => {
    function isSelected(props, selection) {
      const defaultProps = {
        begin: '2016-01-01T10:00:00',
        end: '2016-01-01T10:30:00',
        selection: {
          begin: '2016-01-01T10:00:00',
          end: '2016-01-01T11:00:00',
          resourceId: '1',
          ...selection,
        },
        resourceId: '1',
      };
      const wrapper = getWrapper({ ...defaultProps, ...props });
      return wrapper.find('button').hasClass('reservation-slot-selected');
    }

    test('is selected if begin and end are same as selected', () => {
      const actual = isSelected({}, { end: '2016-01-01T10:30:00' });
      expect(actual).toBe(true);
    });

    test('is selected if begin and end are inside selected', () => {
      const actual = isSelected({}, { begin: '2016-01-01T09:00:00' });
      expect(actual).toBe(true);
    });

    test('is not selected if begin before selection', () => {
      const actual = isSelected({}, { begin: '2016-01-01T10:15:00' });
      expect(actual).toBe(false);
    });

    test('is not selected if end after selection', () => {
      const actual = isSelected({}, { end: '2016-01-01T10:15:00' });
      expect(actual).toBe(false);
    });

    test('is not selected if no selection', () => {
      const wrapper = getWrapper();
      const actual = wrapper.hasClass('reservation-slot-selected');
      expect(actual).toBe(false);
    });

    test('is not selected if selection.resourceId is different', () => {
      const actual = isSelected({}, { resourceId: '2' });
      expect(actual).toBe(false);
    });

    test('is selected if selection.resourceId is the same', () => {
      const actual = isSelected({}, { resourceId: '1' });
      expect(actual).toBe(true);
    });
  });

  describe('handleClick', () => {
    describe('if isSelectable', () => {
      function callHandleClick({ preventDefault }, props) {
        const wrapper = getWrapper({ onClick: () => null, ...props });
        const event = { preventDefault: preventDefault || (() => null) };
        return wrapper.instance().handleClick(event);
      }

      test('calls event.preventDefault', () => {
        const preventDefault = simple.mock();
        callHandleClick({ preventDefault });
        expect(preventDefault.callCount).toBe(1);
      });

      test('calls onClick', () => {
        const onClick = simple.mock();
        const begin = '2017-01-02T14:00:00Z';
        const end = '2017-01-02T14:30:00Z';
        const resourceId = 'auuxn391';
        callHandleClick({}, {
          begin, end, onClick, resourceId
        });
        expect(onClick.callCount).toBe(1);
        expect(onClick.lastCall.args).toEqual([{ begin, end, resourceId }]);
      });

      test('does not call onSelectionCancel', () => {
        const onSelectionCancel = simple.mock();
        callHandleClick({}, { onSelectionCancel, isSelectable: true });
        expect(onSelectionCancel.called).toBe(false);
      });
    });

    describe('if not isSelectable', () => {
      function callHandleClick({ preventDefault }, props) {
        const wrapper = getWrapper({
          isSelectable: false,
          onSelectionCancel: () => null,
          ...props,
        });
        const event = { preventDefault: preventDefault || (() => null) };
        return wrapper.instance().handleClick(event);
      }

      test('calls event.preventDefault', () => {
        const preventDefault = simple.mock();
        callHandleClick({ preventDefault });
        expect(preventDefault.callCount).toBe(1);
      });

      test('does not call onClick', () => {
        const onClick = simple.mock();
        callHandleClick({}, { onClick });
        expect(onClick.called).toBe(false);
      });

      test('calls onSelectionCancel', () => {
        const onSelectionCancel = simple.mock();
        callHandleClick({}, { onSelectionCancel });
        expect(onSelectionCancel.callCount).toBe(1);
      });
    });

    describe('if no click handler', () => {
      function callHandleClick({ preventDefault }) {
        const wrapper = getWrapper({ onClick: undefined });
        const event = { preventDefault: preventDefault || (() => null) };
        return wrapper.instance().handleClick(event);
      }

      test('does not call event.preventDefault', () => {
        const preventDefault = simple.mock();
        callHandleClick({ preventDefault });
        expect(preventDefault.called).toBe(false);
      });
    });
  });
});
<commit_msg>Removed tests because components structure changed fundamentally.<commit_after>import { shallow } from 'enzyme';
import simple from 'simple-mock';
import React from 'react';

import ReservationPopover from '../../../../../reservation-popover/ReservationPopover';
import { UninjectedReservationSlot as ReservationSlot } from '../ReservationSlot';

function getWrapper(props) {
  const defaults = {
    begin: '2017-01-01T10:00:00Z',
    end: '2017-01-01T10:30:00Z',
    resourceId: '1',
    isSelectable: true,
    t: s => s,
  };
  return shallow(<ReservationSlot {...defaults} {...props} />);
}

describe('shared/availability-view/ReservationSlot', () => {
  describe('Popover', () => {
    function getPopover(props) {
      const wrapper = getWrapper(props);
      return wrapper.find(ReservationPopover);
    }

    describe('is not rendered when the slot', () => {
      test('has no selection', () => {
        const popover = getPopover({ selection: null });
        expect(popover).toHaveLength(0);
      });

      test('is not in selection', () => {
        const popover = getPopover({
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T10:30:00Z',
          selection: {
            begin: '2016-01-01T10:30:00Z',
            end: '2016-01-01T12:00:00Z',
            resourceId: '1',
          },
        });
        expect(popover).toHaveLength(0);
      });

      test('is inside selection but not the first slot', () => {
        const popover = getPopover({
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T10:30:00Z',
          selection: {
            begin: '2016-01-01T09:30:00Z',
            end: '2016-01-01T12:00:00Z',
            resourceId: '1',
          },
        });
        expect(popover).toHaveLength(0);
      });

      test('is inside hover selection', () => {
        const popover = getPopover({
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T10:30:00Z',
          selection: {
            begin: '2016-01-01T10:00:00Z',
            end: '2016-01-01T12:00:00Z',
            resourceId: '1',
            hover: true,
          },
        });
        expect(popover).toHaveLength(0);
      });
    });

    test('is rendered if beginning of selection', () => {
      const popover = getPopover({
        begin: '2016-01-01T10:00:00Z',
        end: '2016-01-01T10:30:00Z',
        selection: {
          begin: '2016-01-01T10:00:00Z',
          end: '2016-01-01T12:00:00Z',
          resourceId: '1',
        },
      });
      expect(popover).toHaveLength(1);
    });
  });

  describe('selection', () => {
    function isSelected(props, selection) {
      const defaultProps = {
        begin: '2016-01-01T10:00:00',
        end: '2016-01-01T10:30:00',
        selection: {
          begin: '2016-01-01T10:00:00',
          end: '2016-01-01T11:00:00',
          resourceId: '1',
          ...selection,
        },
        resourceId: '1',
      };
      const wrapper = getWrapper({ ...defaultProps, ...props });
      return wrapper.find('button').hasClass('reservation-slot-selected');
    }

    test('is selected if begin and end are same as selected', () => {
      const actual = isSelected({}, { end: '2016-01-01T10:30:00' });
      expect(actual).toBe(true);
    });

    test('is selected if begin and end are inside selected', () => {
      const actual = isSelected({}, { begin: '2016-01-01T09:00:00' });
      expect(actual).toBe(true);
    });

    test('is not selected if begin before selection', () => {
      const actual = isSelected({}, { begin: '2016-01-01T10:15:00' });
      expect(actual).toBe(false);
    });

    test('is not selected if end after selection', () => {
      const actual = isSelected({}, { end: '2016-01-01T10:15:00' });
      expect(actual).toBe(false);
    });

    test('is not selected if no selection', () => {
      const wrapper = getWrapper();
      const actual = wrapper.hasClass('reservation-slot-selected');
      expect(actual).toBe(false);
    });

    test('is not selected if selection.resourceId is different', () => {
      const actual = isSelected({}, { resourceId: '2' });
      expect(actual).toBe(false);
    });

    test('is selected if selection.resourceId is the same', () => {
      const actual = isSelected({}, { resourceId: '1' });
      expect(actual).toBe(true);
    });
  });

  describe('handleClick', () => {
    describe('if isSelectable', () => {
      function callHandleClick({ preventDefault }, props) {
        const wrapper = getWrapper({ onClick: () => null, ...props });
        const event = { preventDefault: preventDefault || (() => null) };
        return wrapper.instance().handleClick(event);
      }

      test('calls event.preventDefault', () => {
        const preventDefault = simple.mock();
        callHandleClick({ preventDefault });
        expect(preventDefault.callCount).toBe(1);
      });

      test('calls onClick', () => {
        const onClick = simple.mock();
        const begin = '2017-01-02T14:00:00Z';
        const end = '2017-01-02T14:30:00Z';
        const resourceId = 'auuxn391';
        callHandleClick({}, {
          begin, end, onClick, resourceId
        });
        expect(onClick.callCount).toBe(1);
        expect(onClick.lastCall.args).toEqual([{ begin, end, resourceId }]);
      });

      test('does not call onSelectionCancel', () => {
        const onSelectionCancel = simple.mock();
        callHandleClick({}, { onSelectionCancel, isSelectable: true });
        expect(onSelectionCancel.called).toBe(false);
      });
    });

    describe('if not isSelectable', () => {
      function callHandleClick({ preventDefault }, props) {
        const wrapper = getWrapper({
          isSelectable: false,
          onSelectionCancel: () => null,
          ...props,
        });
        const event = { preventDefault: preventDefault || (() => null) };
        return wrapper.instance().handleClick(event);
      }

      test('calls event.preventDefault', () => {
        const preventDefault = simple.mock();
        callHandleClick({ preventDefault });
        expect(preventDefault.callCount).toBe(1);
      });

      test('does not call onClick', () => {
        const onClick = simple.mock();
        callHandleClick({}, { onClick });
        expect(onClick.called).toBe(false);
      });

      test('calls onSelectionCancel', () => {
        const onSelectionCancel = simple.mock();
        callHandleClick({}, { onSelectionCancel });
        expect(onSelectionCancel.callCount).toBe(1);
      });
    });

    describe('if no click handler', () => {
      function callHandleClick({ preventDefault }) {
        const wrapper = getWrapper({ onClick: undefined });
        const event = { preventDefault: preventDefault || (() => null) };
        return wrapper.instance().handleClick(event);
      }

      test('does not call event.preventDefault', () => {
        const preventDefault = simple.mock();
        callHandleClick({ preventDefault });
        expect(preventDefault.called).toBe(false);
      });
    });
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, FormattedNumber, FormattedMessage } from 'react-intl';
import { imagePreview, capitalize } from '../../../lib/utils';
import withIntl from '../../../lib/withIntl';
import { get } from 'lodash';

import RefundTransactionBtn from './RefundTransactionBtn';

class TransactionDetails extends React.Component {

  static propTypes = {
    collective: PropTypes.object,
    transaction: PropTypes.object,
    LoggedInUser: PropTypes.object,
    intl: PropTypes.object.isRequired,
    mode: PropTypes.string, // open or closed
  };

  constructor(props) {
    super(props);
    this.messages = defineMessages({
      'hostFeeInHostCurrency': { id: 'transaction.hostFeeInHostCurrency', defaultMessage: '{hostFeePercent} host fee' },
      'platformFeeInHostCurrency': { id: 'transaction.platformFeeInHostCurrency', defaultMessage: '5% Open Collective fee' },
      'paymentProcessorFeeInHostCurrency': { id: 'transaction.paymentProcessorFeeInHostCurrency', defaultMessage: 'payment processor fee' }
    });
    this.currencyStyle = { style: 'currency', currencyDisplay: 'symbol', minimumFractionDigits: 0, maximumFractionDigits: 2};
  }

  render() {
    const { intl, collective, LoggedInUser, transaction } = this.props;
    const type = transaction.type.toLowerCase();
    const hostFeePercent = `${transaction.host.hostFeePercent}%`;
    const amountDetails = [intl.formatNumber(transaction.amount / 100, { currency: transaction.currency, ...this.currencyStyle })];
    if (transaction.hostCurrencyFxRate && transaction.hostCurrencyFxRate !== 1) {
      const amountInHostCurrency = transaction.amount * transaction.hostCurrencyFxRate;
      amountDetails.push(` (${intl.formatNumber(amountInHostCurrency / 100, { currency: transaction.hostCurrency, ...this.currencyStyle })})`);
    }
    const addFees = (feesArray) => {
      feesArray.forEach(feeName => {
        if (transaction[feeName]) {
          amountDetails.push(`${intl.formatNumber(transaction[feeName] / 100, { currency: transaction.hostCurrency, ...this.currencyStyle })} (${intl.formatMessage(this.messages[feeName], { hostFeePercent })})`);
        }
      })
    }

    addFees(['hostFeeInHostCurrency', 'platformFeeInHostCurrency', 'paymentProcessorFeeInHostCurrency']);

    const amountDetailsStr = amountDetails.length > 1 ? amountDetails.join(' ') : null;

    return (
      <div className={`TransactionDetails ${this.props.mode}`}>

        {type === 'debit' &&

            {transaction.attachment &&

            }
            {!transaction.attachment &&

            }

        }
        { get(transaction, 'host.name') &&

            <FormattedMessage id="transaction.host" defaultMessage="host" />
            {transaction.host.name} ({transaction.hostCurrency})

        }

          <FormattedMessage id="transaction.paymentMethod" defaultMessage="payment method" />
          {transaction.paymentMethod && capitalize(transaction.paymentMethod.service)}

        { transaction.hostCurrencyFxRate && transaction.hostCurrencyFxRate !== 1 &&

            <FormattedMessage id="transaction.fxrate" defaultMessage="fx rate" />
            {transaction.hostCurrencyFxRate}

        }

          <FormattedMessage id="transaction.amountDetails" defaultMessage="amount details" />

            { amountDetailsStr &&

                {amountDetailsStr}
                 =

            }

              <FormattedNumber
                value={transaction.netAmountInCollectiveCurrency / 100}
                currency={collective.currency}
                {...this.currencyStyle}
                />

              (<FormattedMessage id="transaction.netAmountInCollectiveCurrency.description" defaultMessage="net amount added to your collective's balance" />)

        { type === 'debit' && LoggedInUser && (LoggedInUser.canEditCollective(collective) || LoggedInUser.isRoot()) && !transaction.refundTransaction &&

            <FormattedMessage id="transaction.invoice" defaultMessage="invoice" />

              <a href={`/${collective.slug}/transactions/${transaction.uuid}/invoice.pdf`}>
                <FormattedMessage id="transaction.downloadPDF" defaultMessage="Download (pdf)" />

        }

          { (LoggedInUser && LoggedInUser.isRoot()) &&

              <RefundTransactionBtn
                transaction={transaction}
                collective={collective}
                />

 }

    );
  }
}

export default withIntl(TransactionDetails);
<commit_msg>show the net amount of a transaction in transaction.currency instead of collective.currency<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, FormattedNumber, FormattedMessage } from 'react-intl';
import { imagePreview, capitalize } from '../../../lib/utils';
import withIntl from '../../../lib/withIntl';
import { get } from 'lodash';

import RefundTransactionBtn from './RefundTransactionBtn';

class TransactionDetails extends React.Component {

  static propTypes = {
    collective: PropTypes.object,
    transaction: PropTypes.object,
    LoggedInUser: PropTypes.object,
    intl: PropTypes.object.isRequired,
    mode: PropTypes.string, // open or closed
  };

  constructor(props) {
    super(props);
    this.messages = defineMessages({
      'hostFeeInHostCurrency': { id: 'transaction.hostFeeInHostCurrency', defaultMessage: '{hostFeePercent} host fee' },
      'platformFeeInHostCurrency': { id: 'transaction.platformFeeInHostCurrency', defaultMessage: '5% Open Collective fee' },
      'paymentProcessorFeeInHostCurrency': { id: 'transaction.paymentProcessorFeeInHostCurrency', defaultMessage: 'payment processor fee' }
    });
    this.currencyStyle = { style: 'currency', currencyDisplay: 'symbol', minimumFractionDigits: 0, maximumFractionDigits: 2};
  }

  render() {
    const { intl, collective, LoggedInUser, transaction } = this.props;
    const type = transaction.type.toLowerCase();
    const hostFeePercent = `${transaction.host.hostFeePercent}%`;
    const amountDetails = [intl.formatNumber(transaction.amount / 100, { currency: transaction.currency, ...this.currencyStyle })];
    if (transaction.hostCurrencyFxRate && transaction.hostCurrencyFxRate !== 1) {
      const amountInHostCurrency = transaction.amount * transaction.hostCurrencyFxRate;
      amountDetails.push(` (${intl.formatNumber(amountInHostCurrency / 100, { currency: transaction.hostCurrency, ...this.currencyStyle })})`);
    }
    const addFees = (feesArray) => {
      feesArray.forEach(feeName => {
        if (transaction[feeName]) {
          amountDetails.push(`${intl.formatNumber(transaction[feeName] / 100, { currency: transaction.hostCurrency, ...this.currencyStyle })} (${intl.formatMessage(this.messages[feeName], { hostFeePercent })})`);
        }
      })
    }

    addFees(['hostFeeInHostCurrency', 'platformFeeInHostCurrency', 'paymentProcessorFeeInHostCurrency']);

    const amountDetailsStr = amountDetails.length > 1 ? amountDetails.join(' ') : null;

    return (
      <div className={`TransactionDetails ${this.props.mode}`}>

        {type === 'debit' &&

            {transaction.attachment &&

            }
            {!transaction.attachment &&

            }

        }
        { get(transaction, 'host.name') &&

            <FormattedMessage id="transaction.host" defaultMessage="host" />
            {transaction.host.name} ({transaction.hostCurrency})

        }

          <FormattedMessage id="transaction.paymentMethod" defaultMessage="payment method" />
          {transaction.paymentMethod && capitalize(transaction.paymentMethod.service)}

        { transaction.hostCurrencyFxRate && transaction.hostCurrencyFxRate !== 1 &&

            <FormattedMessage id="transaction.fxrate" defaultMessage="fx rate" />
            {transaction.hostCurrencyFxRate}

        }

          <FormattedMessage id="transaction.amountDetails" defaultMessage="amount details" />

            { amountDetailsStr &&

                {amountDetailsStr}
                 =

            }

              <FormattedNumber
                value={transaction.netAmountInCollectiveCurrency / 100}
                currency={transaction.currency}
                {...this.currencyStyle}
                />

              (<FormattedMessage id="transaction.netAmountInCollectiveCurrency.description" defaultMessage="net amount added to your collective's balance" />)

        { type === 'debit' && LoggedInUser && (LoggedInUser.canEditCollective(collective) || LoggedInUser.isRoot()) && !transaction.refundTransaction &&

            <FormattedMessage id="transaction.invoice" defaultMessage="invoice" />

              <a href={`/${collective.slug}/transactions/${transaction.uuid}/invoice.pdf`}>
                <FormattedMessage id="transaction.downloadPDF" defaultMessage="Download (pdf)" />

        }

          { (LoggedInUser && LoggedInUser.isRoot()) &&

              <RefundTransactionBtn
                transaction={transaction}
                collective={collective}
                />

 }

    );
  }
}

export default withIntl(TransactionDetails);
<|endoftext|>