<commit_before>define([
], function(
) {
  'use strict';

  function getRefreshProvider(tasklistData) {
    return {
      refreshTaskList : function () {
        tasklistData.changed('taskList');
      }
    };
  }

  var operatorTable = {
    "<" : "lt",
    ">" : "gt",
    "=" : "eq",
    "!=": "neq",
    ">=": "gteq",
    "<=": "lteq",
    "like":"like",
    "BEFORE":"lteq",
    "AFTER":"gteq"
  };

  var typeTable = {
    "Process Variable" : "processVariables",
    "Task Variable" : "taskVariables",
    "Case Variable" : "caseInstanceVariables"
  };

  var sanitizeValue = function(value, operator) {
    if(operator === 'like') {
      return '%'+value+'%';
    }
    return value;
  };

  return [
    '$scope',
    '$q',
    '$location',
    '$interval',
    'search',
    'dataDepend',
    'camAPI',
  function(
    $scope,
    $q,
    $location,
    $interval,
    search,
    dataDepend,
    camAPI
  ) {

    function getPropertyFromLocation(property) {
      var search = $location.search() || {};
      return search[property] || null;
    }

    function updateSilently(params) {
      search.updateSilently(params);
    }

    $scope.$on('$destroy', function () {
      $scope.tasklistApp.refreshProvider = null;
    });

    // init data depend for task list data
    var tasklistData = $scope.tasklistData = dataDepend.create($scope);

    // init taslist app with a refresh provider
    if ($scope.tasklistApp) {
      $scope.tasklistApp.refreshProvider = getRefreshProvider(tasklistData);
    }

    // get current task id from location
    var taskId = getPropertyFromLocation('task');
    var detailsTab = getPropertyFromLocation('detailsTab');

    // resources
    var Filter = camAPI.resource('filter');
    var Task = camAPI.resource('task');

    // current selected filter
    var currentFilter;

    // provide /////////////////////////////////////////////////////////////////////////////////

    /**
     * Provides the list of filters
     */
    tasklistData.provide('filters', [ function() {
      var deferred = $q.defer();

      Filter.list({
        itemCount: false,
        resoureType: 'Task'
      }, function(err, res) {
        if(!!err) {
          deferred.reject(err);

        }
        else {
          deferred.resolve(res);
        }
      });

      return deferred.promise;
    }]);

    tasklistData.provide('currentFilter', ['filters', function(filters) {

      var focused,
          filterId = getPropertyFromLocation('filter');

      for (var i = 0, filter; !!(filter = filters[i]); i++) {

          if (filterId === filter.id) {
            focused = filter;
            break;
          }
          // auto focus first filter
          if(!focused || filter.properties.priority < focused.properties.priority) {
            focused = filter;
          }
      }
      if(currentFilter) {
        var currentPage = getPropertyFromLocation('page');
        if (currentPage) {
          updateSilently({
            page: '1'
          });
        }

      }

      if(focused && focused.id !== filterId) {
        updateSilently({
          filter: focused.id
        });
      }

      return angular.copy(focused);

    }]);

    tasklistData.provide('taskListQuery', ['currentFilter', function(currentFilter) {
      if (!currentFilter) {
        return null;
      }

      var querySearchParam = getPropertyFromLocation('query');
      var searches = JSON.parse(querySearchParam);

      var query = {};

      query.processVariables = [];
      query.taskVariables = [];
      query.caseInstanceVariables = [];

      angular.forEach(searches, function(search) {

         query[typeTable[search.type]].push({
           name: search.name,
           operator: operatorTable[search.operator],
           value: sanitizeValue(search.value, search.operator)
         });

      });

      var firstResult = ((getPropertyFromLocation('page') || 1) - 1) * 15;
      var sortBy = getPropertyFromLocation('sortBy') || 'created';
      var sortOrder = getPropertyFromLocation('sortOrder') || 'desc';

      return {
        id : currentFilter.id,
        firstResult : firstResult,
        maxResults : 15,
        sortBy : sortBy,
        sortOrder: sortOrder,
        active: true,
        processVariables : query.processVariables,
        taskVariables : query.taskVariables,
        caseInstanceVariables : query.caseInstanceVariables
      };

    }]);

     /**
      * Provide the list of tasks
      */
     tasklistData.provide('taskList', [ 'taskListQuery', function(taskListQuery) {
       var deferred = $q.defer();

       if(!taskListQuery || taskListQuery.id === null) {
         // no filter selected
         deferred.resolve({
           count: 0,
           _embedded : {}
         });
       }
       else {
         // filter selected
         Filter.getTasks(angular.copy(taskListQuery), function(err, res) {
           if(err) {
             deferred.reject(err);
           }
           else {
             deferred.resolve(res);
           }
         });
       }
       return deferred.promise;
     }]);

   /**
     * Provide current task id
     */
    tasklistData.provide('taskId', { 'taskId' : taskId });

    /**
     * Provide the current task or the value 'null' in case no task is selected
     */
    tasklistData.provide('task', ['taskId', function(task) {

      var deferred = $q.defer();

      var taskId = task.taskId;

      if(typeof taskId !== 'string') {
        deferred.resolve(null);
      }
      else {
        Task.get(taskId, function(err, res) {
          if(err) {
            deferred.reject(err);
          }
          else {
            deferred.resolve(res);
          }

        });
      }

      return deferred.promise;
    }]);

    // observe //////////////////////////////////////////////////////////////////////////////

    tasklistData.observe('currentFilter', function(_currentFilter) {
      currentFilter = _currentFilter;
    });

    /*
     * automatically refresh the taskList every 10 seconds so that changes
     * (such as claims) are represented in realtime
     */
    var intervalPromise;
    tasklistData.observe('currentFilter', function(currentFilter) {
      // stop current refresh
      if(intervalPromise) {
        $interval.cancel(intervalPromise);
      }

      if(currentFilter && currentFilter.properties.refresh) {
        intervalPromise = $interval(function(){

          if($scope.tasklistApp && $scope.tasklistApp.refreshProvider) {
            $scope.tasklistApp.refreshProvider.refreshTaskList();

          }
          else {
            $interval.cancel(intervalPromise);
          }

        }, 10000);
      }
    });

    // routeChanged listener ////////////////////////////////////////////////////////////////

    /**
     * Update task if location changes
     */
    $scope.$on('$routeChanged', function(prev, current) {
      var oldTaskId = taskId;
      var oldDetailsTab = detailsTab;

      taskId = getPropertyFromLocation('task');
      detailsTab = getPropertyFromLocation('detailsTab');

      if (oldTaskId !== taskId || oldDetailsTab === detailsTab) {
        tasklistData.set('taskId', { 'taskId' : taskId });
      }

      currentFilter = null;
      tasklistData.changed('currentFilter');

    });
  }];
});
<commit_msg>fix(page): only change page when another filter is selected<commit_after>define([
], function(
) {
  'use strict';

  function getRefreshProvider(tasklistData) {
    return {
      refreshTaskList : function () {
        tasklistData.changed('taskList');
      }
    };
  }

  var operatorTable = {
    "<" : "lt",
    ">" : "gt",
    "=" : "eq",
    "!=": "neq",
    ">=": "gteq",
    "<=": "lteq",
    "like":"like",
    "BEFORE":"lteq",
    "AFTER":"gteq"
  };

  var typeTable = {
    "Process Variable" : "processVariables",
    "Task Variable" : "taskVariables",
    "Case Variable" : "caseInstanceVariables"
  };

  var sanitizeValue = function(value, operator) {
    if(operator === 'like') {
      return '%'+value+'%';
    }
    return value;
  };

  return [
    '$scope',
    '$q',
    '$location',
    '$interval',
    'search',
    'dataDepend',
    'camAPI',
  function(
    $scope,
    $q,
    $location,
    $interval,
    search,
    dataDepend,
    camAPI
  ) {

    function getPropertyFromLocation(property) {
      var search = $location.search() || {};
      return search[property] || null;
    }

    function updateSilently(params) {
      search.updateSilently(params);
    }

    $scope.$on('$destroy', function () {
      $scope.tasklistApp.refreshProvider = null;
    });

    // init data depend for task list data
    var tasklistData = $scope.tasklistData = dataDepend.create($scope);

    // init taslist app with a refresh provider
    if ($scope.tasklistApp) {
      $scope.tasklistApp.refreshProvider = getRefreshProvider(tasklistData);
    }

    // get current task id from location
    var taskId = getPropertyFromLocation('task');
    var detailsTab = getPropertyFromLocation('detailsTab');

    // resources
    var Filter = camAPI.resource('filter');
    var Task = camAPI.resource('task');

    // current selected filter
    var currentFilter;

    // provide /////////////////////////////////////////////////////////////////////////////////

    /**
     * Provides the list of filters
     */
    tasklistData.provide('filters', [ function() {
      var deferred = $q.defer();

      Filter.list({
        itemCount: false,
        resoureType: 'Task'
      }, function(err, res) {
        if(!!err) {
          deferred.reject(err);

        }
        else {
          deferred.resolve(res);
        }
      });

      return deferred.promise;
    }]);

    tasklistData.provide('currentFilter', ['filters', function(filters) {

      var focused,
          filterId = getPropertyFromLocation('filter');

      for (var i = 0, filter; !!(filter = filters[i]); i++) {

          if (filterId === filter.id) {
            focused = filter;
            break;
          }
          // auto focus first filter
          if(!focused || filter.properties.priority < focused.properties.priority) {
            focused = filter;
          }
      }

      if(currentFilter && currentFilter.id !== focused.id) {
        var currentPage = getPropertyFromLocation('page');
        if (currentPage) {
          updateSilently({
            page: '1'
          });
        }
      }

      if(focused && focused.id !== filterId) {
        updateSilently({
          filter: focused.id
        });
      }

      return angular.copy(focused);

    }]);

    tasklistData.provide('taskListQuery', ['currentFilter', function(currentFilter) {
      if (!currentFilter) {
        return null;
      }

      var querySearchParam = getPropertyFromLocation('query');
      var searches = JSON.parse(querySearchParam);

      var query = {};

      query.processVariables = [];
      query.taskVariables = [];
      query.caseInstanceVariables = [];

      angular.forEach(searches, function(search) {

         query[typeTable[search.type]].push({
           name: search.name,
           operator: operatorTable[search.operator],
           value: sanitizeValue(search.value, search.operator)
         });

      });

      var firstResult = ((getPropertyFromLocation('page') || 1) - 1) * 15;
      var sortBy = getPropertyFromLocation('sortBy') || 'created';
      var sortOrder = getPropertyFromLocation('sortOrder') || 'desc';

      return {
        id : currentFilter.id,
        firstResult : firstResult,
        maxResults : 15,
        sortBy : sortBy,
        sortOrder: sortOrder,
        active: true,
        processVariables : query.processVariables,
        taskVariables : query.taskVariables,
        caseInstanceVariables : query.caseInstanceVariables
      };

    }]);

     /**
      * Provide the list of tasks
      */
     tasklistData.provide('taskList', [ 'taskListQuery', function(taskListQuery) {
       var deferred = $q.defer();

       if(!taskListQuery || taskListQuery.id === null) {
         // no filter selected
         deferred.resolve({
           count: 0,
           _embedded : {}
         });
       }
       else {
         // filter selected
         Filter.getTasks(angular.copy(taskListQuery), function(err, res) {
           if(err) {
             deferred.reject(err);
           }
           else {
             deferred.resolve(res);
           }
         });
       }
       return deferred.promise;
     }]);

   /**
     * Provide current task id
     */
    tasklistData.provide('taskId', { 'taskId' : taskId });

    /**
     * Provide the current task or the value 'null' in case no task is selected
     */
    tasklistData.provide('task', ['taskId', function(task) {

      var deferred = $q.defer();

      var taskId = task.taskId;

      if(typeof taskId !== 'string') {
        deferred.resolve(null);
      }
      else {
        Task.get(taskId, function(err, res) {
          if(err) {
            deferred.reject(err);
          }
          else {
            deferred.resolve(res);
          }

        });
      }

      return deferred.promise;
    }]);

    // observe //////////////////////////////////////////////////////////////////////////////

    tasklistData.observe('currentFilter', function(_currentFilter) {
      currentFilter = _currentFilter;
    });

    /*
     * automatically refresh the taskList every 10 seconds so that changes
     * (such as claims) are represented in realtime
     */
    var intervalPromise;
    tasklistData.observe('currentFilter', function(currentFilter) {
      // stop current refresh
      if(intervalPromise) {
        $interval.cancel(intervalPromise);
      }

      if(currentFilter && currentFilter.properties.refresh) {
        intervalPromise = $interval(function(){

          if($scope.tasklistApp && $scope.tasklistApp.refreshProvider) {
            $scope.tasklistApp.refreshProvider.refreshTaskList();

          }
          else {
            $interval.cancel(intervalPromise);
          }

        }, 10000);
      }
    });

    // routeChanged listener ////////////////////////////////////////////////////////////////

    /**
     * Update task if location changes
     */
    $scope.$on('$routeChanged', function(prev, current) {
      var oldTaskId = taskId;
      var oldDetailsTab = detailsTab;

      taskId = getPropertyFromLocation('task');
      detailsTab = getPropertyFromLocation('detailsTab');

      if (oldTaskId !== taskId || oldDetailsTab === detailsTab) {
        tasklistData.set('taskId', { 'taskId' : taskId });
      }

      currentFilter = null;
      tasklistData.changed('currentFilter');
    });
  }];
});
<|endoftext|>


<commit_before>var $ = require('jquery');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var UserActions = require('../../../../../../javascripts/cartodb3/data/user-actions');
var StackLayoutModel = require('../../../../../../javascripts/cartodb3/components/stack-layout/stack-layout-model');
var LayerDefinitionModel = require('../../../../../../javascripts/cartodb3/data/layer-definition-model');
var DataLayerView = require('../../../../../../javascripts/cartodb3/editor/layers/layer-views/data-layer-view');
var AnalysisDefinitionNodeModel = require('../../../../../../javascripts/cartodb3/data/analysis-definition-node-model');
var StyleDefinitionModel = require('../../../../../../javascripts/cartodb3/editor/style/style-definition-model');
var QueryRowsCollection = require('../../../../../../javascripts/cartodb3/data/query-rows-collection');
var QuerySchemaModel = require('../../../../../../javascripts/cartodb3/data/query-schema-model');
var QueryGeometryModel = require('../../../../../../javascripts/cartodb3/data/query-geometry-model');

describe('editor/layers/data-layer-view', function () {
  beforeEach(function () {
    spyOn(QueryGeometryModel.prototype, 'fetch');
    spyOn(QuerySchemaModel.prototype, 'fetch');
    spyOn(QueryRowsCollection.prototype, 'fetch');

    this.layerDefinitionsCollection = new Backbone.Collection([]);
    this.layerDefinitionsCollection.save = jasmine.createSpy('save');

    this.modals = {
      create: function () {}
    };

    spyOn(this.modals, 'create');

    var a0 = new AnalysisDefinitionNodeModel({
      id: 'a0',
      type: 'buffer',
      params: {}
    }, {
      configModel: {}
    });

    this.model = new LayerDefinitionModel({
      id: 'layer-A',
      name: 'table_name',
      letter: 'a',
      source: 'a0',
      visible: true
    }, {
      configModel: {},
      collection: this.layerDefinitionsCollection
    });
    this.model.styleModel = new StyleDefinitionModel({}, {
      configModel: {}
    });
    spyOn(this.model, 'canBeDeletedByUser');
    spyOn(this.model, 'getNumberOfAnalyses').and.returnValue(3);
    spyOn(this.model, 'getAnalysisDefinitionNodeModel').and.returnValue(a0);

    a0.queryGeometryModel.set('simple_geom', 'polygon');
    this.queryGeometryModel = a0.queryGeometryModel;

    var c2 = new AnalysisDefinitionNodeModel({
      id: 'c2',
      type: 'buffer',
      params: {}
    }, {
      configModel: {}
    });
    spyOn(this.model, 'findAnalysisDefinitionNodeModel').and.returnValue(c2);

    this.stackLayoutModel = new StackLayoutModel(null, {stackLayoutItems: {}});
    spyOn(this.stackLayoutModel, 'nextStep');

    this.newAnalysesViewSpy = jasmine.createSpy('newAnalysesView').and.callFake(function (el) {
      var view = new CoreView({
        el: el
      });
      view.render = function () {
        this.$el.html('ANALYSES');
        return this;
      };
      return view;
    });

    this.userActions = UserActions({
      userModel: {},
      analysisDefinitionsCollection: {},
      analysisDefinitionNodesCollection: {},
      layerDefinitionsCollection: {},
      widgetDefinitionsCollection: {}
    });
    this.promise = $.Deferred();
    spyOn(this.userActions, 'saveLayer').and.returnValue(this.promise);

    var widgetDefinitionsCollection = new Backbone.Collection();
    widgetDefinitionsCollection.widgetsOwnedByLayer = function () { return 0; };

    var visDefinitionModel = new Backbone.Model();

    this.view = new DataLayerView({
      modals: this.modals,
      model: this.model,
      userActions: this.userActions,
      stackLayoutModel: this.stackLayoutModel,
      newAnalysesView: this.newAnalysesViewSpy,
      layerDefinitionsCollection: this.layerDefinitionsCollection,
      configModel: {},
      stateDefinitionModel: {},
      visDefinitionModel: visDefinitionModel,
      widgetDefinitionsCollection: widgetDefinitionsCollection,
      analysisDefinitionNodesCollection: {}
    });

    spyOn(this.view, '_renameLayer').and.callThrough();

    this.view.$el.appendTo(document.body);
    this.view.render();
  });

  afterEach(function () {
    this.view.clean();
  });

  it('should have no leaks', function () {
    expect(this.view).toHaveNoLeaks();
  });

  it('should render title of layer', function () {
    expect(this.view.$el.text()).toContain('table_name');
  });

  it('should add sortable class', function () {
    expect(this.view.$el.hasClass('js-sortable-item')).toBeTruthy();
  });

  it('should be displayed as hidden when layer is hidden', function () {
    expect(this.view.$('.js-thumbnail').hasClass('is-hidden')).toBe(false);
    expect(this.view.$('.js-title').hasClass('is-hidden')).toBe(false);
    expect(this.view.$('.js-analyses').hasClass('is-hidden')).toBe(false);
    expect(this.view.$('.js-analyses-widgets-info').hasClass('is-hidden')).toBe(false);

    this.model.set('visible', false);

    expect(this.view.$('.js-thumbnail').hasClass('is-hidden')).toBe(true);
    expect(this.view.$('.js-title').hasClass('is-hidden')).toBe(true);
    expect(this.view.$('.js-analyses').hasClass('is-hidden')).toBe(true);
    expect(this.view.$('.js-analyses-widgets-info').hasClass('is-hidden')).toBe(true);
  });

  it('should be with errors when layer has errors', function () {
    expect(this.view.$('.js-error').length).toBe(0);
    this.model.set('error', 'an error');
    expect(this.view.$('.js-error').length).toBe(1);
  });

  it('should not add js-sortable-item class if layer is torque', function () {
    this.model.set('type', 'torque');
    this.view.render();
    expect(this.view.$el.hasClass('js-sortable-item')).toBeFalsy();
    expect(this.view.$el.hasClass('is-animated')).toBeTruthy();
  });

  describe('when layer has an analysis', function () {
    it('should render analysis views', function () {
      expect(this.view.$el.text()).toContain('ANALYSES');

      // Assert args being what's expected too
      expect(this.newAnalysesViewSpy).toHaveBeenCalled();
      expect(this.newAnalysesViewSpy.calls.argsFor(0)[0]).toEqual(this.view.$('.js-analyses'));
      expect(this.newAnalysesViewSpy.calls.argsFor(0)[1]).toEqual(this.model);
    });
  });

  describe('context menu', function () {
    it('should toggle the context-menu box when option is clicked', function () {
      expect(this.view.$el.find('.CDB-Box-modal').length).toBe(0);

      this.view.$('.js-toggle-menu').click();

      expect($('body').find('.CDB-Box-modal').css('display')).toEqual('block');

      this.view.$('.js-toggle-menu').click();

      expect($('body').find('.CDB-Box-modal').length).toBe(0);
    });

    describe('Delete layer…', function () {
      it('should not be posible to delete a layer if canBeDeletedByUser return false', function () {
        this.model.canBeDeletedByUser.and.returnValue(false);

        this.view.$('.js-toggle-menu').click();
        expect($('body').find(".CDB-Box-modal button[title='editor.layers.options.delete']").length).toEqual(0);
      });

      it('should be posible to delete a layer if canBeDeletedByUser', function () {
        this.model.canBeDeletedByUser.and.returnValue(true);

        this.view.$('.js-toggle-menu').click();
        expect($('body').find(".CDB-Box-modal button[title='editor.layers.options.delete']").length).toEqual(1);
      });
    });
  });

  describe('when title is clicked', function () {
    beforeEach(function () {
      jasmine.clock().install();
      this.view.$('.js-title').click();
      jasmine.clock().tick(300);
    });

    it('should edit layer', function () {
      expect(this.stackLayoutModel.nextStep).toHaveBeenCalled();
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[1]).toEqual('layer-content');
    });

    afterEach(function () {
      jasmine.clock().uninstall();
    });
  });

  describe('when title is doubleclicked', function () {
    beforeEach(function () {
      jasmine.clock().install();
      this.view.$('.js-title').click();
      this.view.$('.js-title').click();
      jasmine.clock().tick(300);
    });

    it('should show inline editor', function () {
      expect(this.view.$('.js-input').is(':visible')).toBe(true);
    });

    afterEach(function () {
      jasmine.clock().uninstall();
    });
  });

  describe('when thumbnail is clicked', function () {
    beforeEach(function () {
      this.view.$('.js-thumbnail').click();
    });

    it('should edit layer', function () {
      expect(this.stackLayoutModel.nextStep).toHaveBeenCalled();
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[1]).toEqual('layer-content');
    });
  });

  describe('when the toggle icon is clicked', function () {
    beforeEach(function () {
      this.model.set({autoStyle: 'foo'});
    });

    it('should toggle the layer', function () {
      this.view.$('.js-toggle').click();

      expect(this.model.get('visible')).toEqual(false);
      expect(this.userActions.saveLayer).toHaveBeenCalled();
      expect(this.userActions.saveLayer.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.userActions.saveLayer.calls.argsFor(0)[1]).toEqual({
        shouldPreserveAutoStyle: true
      });
      expect(this.model.get('autoStyle')).toEqual('foo');

      this.userActions.saveLayer.calls.reset();
      this.view.$('.js-toggle').click();
      expect(this.model.get('visible')).toEqual(true);
      expect(this.userActions.saveLayer).toHaveBeenCalled();
      expect(this.userActions.saveLayer.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.userActions.saveLayer.calls.argsFor(0)[1]).toEqual({
        shouldPreserveAutoStyle: true
      });
      expect(this.model.get('autoStyle')).toEqual('foo');
    });
  });

  describe('expanded/collapsed states', function () {
    it('should expand and collapse the layer', function () {
      expect(this.view.$('.js-analyses').hasClass('is-collapsed')).toBe(false);

      // Show the context menu and collapse the layer
      this.view.$('.js-toggle-menu').click();
      $('body').find('.CDB-Box-modal button[title="editor.layers.options.collapse"]').click();

      expect(this.view.$('.js-analyses').hasClass('is-collapsed')).toBe(true);

      // Show the context menu and expand the layer
      this.view.$('.js-toggle-menu').click();
      $('body').find('.CDB-Box-modal button[title="editor.layers.options.expand"]').click();

      // Show the context menu and expand the layer again
      expect(this.view.$('.js-analyses').hasClass('is-collapsed')).toBe(false);
    });
  });

  describe('rename layer', function () {
    it('should rename the layer', function () {
      // Show the context menu and collapse the layer
      this.view.$('.js-toggle-menu').click();
      $('body').find('.CDB-Box-modal button[title="editor.layers.options.rename"]').click();

      expect(this.view.$('.js-input').is(':visible')).toBe(true);
      this.view.$('.js-input').val('Foo');

      var e = $.Event('keyup');
      e.which = 13;
      this.view.$('.js-input').trigger(e);

      expect(this.model.get('table_name_alias')).toBe('Foo');
      expect(this.userActions.saveLayer).toHaveBeenCalledWith(this.model);
    });
  });

  describe('geometry type', function () {
    it('should show polygon svg', function () {
      expect(this.view.$('svg').length).toBe(1);
      expect(this.view.$('svg circle').length).toBe(4);
    });
  });

  describe('._showContextMenu', function () {
    it('should show center map option if geom and clicking on it should call _centerMap', function () {
      spyOn(this.view, '_centerMap');
      this.view._showContextMenu();

      expect(this.view._menuView.$('button[title^="editor.layers.options.center-map"]').length).toBe(1);

      this.view._menuView.$('button[title^="editor.layers.options.center-map"]').click();
      expect(this.view._centerMap).toHaveBeenCalled();
    });

    it('should not show center map option if no geom', function () {
      this.queryGeometryModel.set('simple_geom', '');
      this.view._showContextMenu();

      expect(this.view._menuView.$('button[title^="editor.layers.options.center-map"]').length).toBe(0);

      this.queryGeometryModel.set('simple_geom', 'polygon');
    });
  });

  describe('._centerMap', function () {
    it('should call to zoomToData with query from queryGeometryModel', function () {
      var theView = this.view;
      this.queryGeometryModel.set('simple_geom', '');

      // The only way we have to know if zoomToData has been called is to provoke an
      // error. This way we know that the query has been extracted from our querySchemaModel
      // and that zoomToData has been called.
      expect(function () {
        theView._centerMap();
      }).toThrowError('query is required');

      this.queryGeometryModel.set('simple_geom', 'polygon');
    });
  });
});
<commit_msg>Added test for warning icon<commit_after>var $ = require('jquery');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var UserActions = require('../../../../../../javascripts/cartodb3/data/user-actions');
var StackLayoutModel = require('../../../../../../javascripts/cartodb3/components/stack-layout/stack-layout-model');
var LayerDefinitionModel = require('../../../../../../javascripts/cartodb3/data/layer-definition-model');
var DataLayerView = require('../../../../../../javascripts/cartodb3/editor/layers/layer-views/data-layer-view');
var AnalysisDefinitionNodeModel = require('../../../../../../javascripts/cartodb3/data/analysis-definition-node-model');
var StyleDefinitionModel = require('../../../../../../javascripts/cartodb3/editor/style/style-definition-model');
var QueryRowsCollection = require('../../../../../../javascripts/cartodb3/data/query-rows-collection');
var QuerySchemaModel = require('../../../../../../javascripts/cartodb3/data/query-schema-model');
var QueryGeometryModel = require('../../../../../../javascripts/cartodb3/data/query-geometry-model');

describe('editor/layers/data-layer-view', function () {
  beforeEach(function () {
    spyOn(QueryGeometryModel.prototype, 'fetch');
    spyOn(QuerySchemaModel.prototype, 'fetch');
    spyOn(QueryRowsCollection.prototype, 'fetch');

    this.layerDefinitionsCollection = new Backbone.Collection([]);
    this.layerDefinitionsCollection.save = jasmine.createSpy('save');

    this.modals = {
      create: function () {}
    };

    spyOn(this.modals, 'create');

    var a0 = new AnalysisDefinitionNodeModel({
      id: 'a0',
      type: 'buffer',
      params: {}
    }, {
      configModel: {}
    });

    this.model = new LayerDefinitionModel({
      id: 'layer-A',
      name: 'table_name',
      letter: 'a',
      source: 'a0',
      visible: true
    }, {
      configModel: {},
      collection: this.layerDefinitionsCollection
    });
    this.model.styleModel = new StyleDefinitionModel({}, {
      configModel: {}
    });
    spyOn(this.model, 'canBeDeletedByUser');
    spyOn(this.model, 'getNumberOfAnalyses').and.returnValue(3);
    spyOn(this.model, 'getAnalysisDefinitionNodeModel').and.returnValue(a0);

    a0.queryGeometryModel.set('simple_geom', 'polygon');
    this.queryGeometryModel = a0.queryGeometryModel;

    var c2 = new AnalysisDefinitionNodeModel({
      id: 'c2',
      type: 'buffer',
      params: {}
    }, {
      configModel: {}
    });
    spyOn(this.model, 'findAnalysisDefinitionNodeModel').and.returnValue(c2);

    this.stackLayoutModel = new StackLayoutModel(null, {stackLayoutItems: {}});
    spyOn(this.stackLayoutModel, 'nextStep');

    this.newAnalysesViewSpy = jasmine.createSpy('newAnalysesView').and.callFake(function (el) {
      var view = new CoreView({
        el: el
      });
      view.render = function () {
        this.$el.html('ANALYSES');
        return this;
      };
      return view;
    });

    this.userActions = UserActions({
      userModel: {},
      analysisDefinitionsCollection: {},
      analysisDefinitionNodesCollection: {},
      layerDefinitionsCollection: {},
      widgetDefinitionsCollection: {}
    });
    this.promise = $.Deferred();
    spyOn(this.userActions, 'saveLayer').and.returnValue(this.promise);

    var widgetDefinitionsCollection = new Backbone.Collection();
    widgetDefinitionsCollection.widgetsOwnedByLayer = function () { return 0; };

    var visDefinitionModel = new Backbone.Model();

    this.view = new DataLayerView({
      modals: this.modals,
      model: this.model,
      userActions: this.userActions,
      stackLayoutModel: this.stackLayoutModel,
      newAnalysesView: this.newAnalysesViewSpy,
      layerDefinitionsCollection: this.layerDefinitionsCollection,
      configModel: {},
      stateDefinitionModel: {},
      visDefinitionModel: visDefinitionModel,
      widgetDefinitionsCollection: widgetDefinitionsCollection,
      analysisDefinitionNodesCollection: {}
    });

    spyOn(this.view, '_renameLayer').and.callThrough();

    this.view.$el.appendTo(document.body);
    this.view.render();
  });

  afterEach(function () {
    this.view.clean();
  });

  it('should have no leaks', function () {
    expect(this.view).toHaveNoLeaks();
  });

  it('should render title of layer', function () {
    expect(this.view.$el.text()).toContain('table_name');
  });

  it('should add sortable class', function () {
    expect(this.view.$el.hasClass('js-sortable-item')).toBeTruthy();
  });

  it('should be displayed as hidden when layer is hidden', function () {
    expect(this.view.$('.js-thumbnail').hasClass('is-hidden')).toBe(false);
    expect(this.view.$('.js-title').hasClass('is-hidden')).toBe(false);
    expect(this.view.$('.js-analyses').hasClass('is-hidden')).toBe(false);
    expect(this.view.$('.js-analyses-widgets-info').hasClass('is-hidden')).toBe(false);

    this.model.set('visible', false);

    expect(this.view.$('.js-thumbnail').hasClass('is-hidden')).toBe(true);
    expect(this.view.$('.js-title').hasClass('is-hidden')).toBe(true);
    expect(this.view.$('.js-analyses').hasClass('is-hidden')).toBe(true);
    expect(this.view.$('.js-analyses-widgets-info').hasClass('is-hidden')).toBe(true);
  });

  it('should render warning icon when layer can be georeferenced', function () {
    expect(this.view.$('.js-georeferenceIcon').length).toBe(0);
    spyOn(this.model, 'canBeGeoreferenced').and.returnValue(true);
    this.view.render();
    expect(this.view.$('.js-georeferenceIcon').length).toBe(1);
  });

  it('should be with errors when layer has errors', function () {
    expect(this.view.$('.js-error').length).toBe(0);
    this.model.set('error', 'an error');
    expect(this.view.$('.js-error').length).toBe(1);
  });

  it('should not add js-sortable-item class if layer is torque', function () {
    this.model.set('type', 'torque');
    this.view.render();
    expect(this.view.$el.hasClass('js-sortable-item')).toBeFalsy();
    expect(this.view.$el.hasClass('is-animated')).toBeTruthy();
  });

  describe('when layer has an analysis', function () {
    it('should render analysis views', function () {
      expect(this.view.$el.text()).toContain('ANALYSES');

      // Assert args being what's expected too
      expect(this.newAnalysesViewSpy).toHaveBeenCalled();
      expect(this.newAnalysesViewSpy.calls.argsFor(0)[0]).toEqual(this.view.$('.js-analyses'));
      expect(this.newAnalysesViewSpy.calls.argsFor(0)[1]).toEqual(this.model);
    });
  });

  describe('context menu', function () {
    it('should toggle the context-menu box when option is clicked', function () {
      expect(this.view.$el.find('.CDB-Box-modal').length).toBe(0);

      this.view.$('.js-toggle-menu').click();

      expect($('body').find('.CDB-Box-modal').css('display')).toEqual('block');

      this.view.$('.js-toggle-menu').click();

      expect($('body').find('.CDB-Box-modal').length).toBe(0);
    });

    describe('Delete layer…', function () {
      it('should not be posible to delete a layer if canBeDeletedByUser return false', function () {
        this.model.canBeDeletedByUser.and.returnValue(false);

        this.view.$('.js-toggle-menu').click();
        expect($('body').find(".CDB-Box-modal button[title='editor.layers.options.delete']").length).toEqual(0);
      });

      it('should be posible to delete a layer if canBeDeletedByUser', function () {
        this.model.canBeDeletedByUser.and.returnValue(true);

        this.view.$('.js-toggle-menu').click();
        expect($('body').find(".CDB-Box-modal button[title='editor.layers.options.delete']").length).toEqual(1);
      });
    });
  });

  describe('when title is clicked', function () {
    beforeEach(function () {
      jasmine.clock().install();
      this.view.$('.js-title').click();
      jasmine.clock().tick(300);
    });

    it('should edit layer', function () {
      expect(this.stackLayoutModel.nextStep).toHaveBeenCalled();
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[1]).toEqual('layer-content');
    });

    afterEach(function () {
      jasmine.clock().uninstall();
    });
  });

  describe('when title is doubleclicked', function () {
    beforeEach(function () {
      jasmine.clock().install();
      this.view.$('.js-title').click();
      this.view.$('.js-title').click();
      jasmine.clock().tick(300);
    });

    it('should show inline editor', function () {
      expect(this.view.$('.js-input').is(':visible')).toBe(true);
    });

    afterEach(function () {
      jasmine.clock().uninstall();
    });
  });

  describe('when thumbnail is clicked', function () {
    beforeEach(function () {
      this.view.$('.js-thumbnail').click();
    });

    it('should edit layer', function () {
      expect(this.stackLayoutModel.nextStep).toHaveBeenCalled();
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.stackLayoutModel.nextStep.calls.argsFor(0)[1]).toEqual('layer-content');
    });
  });

  describe('when the toggle icon is clicked', function () {
    beforeEach(function () {
      this.model.set({autoStyle: 'foo'});
    });

    it('should toggle the layer', function () {
      this.view.$('.js-toggle').click();

      expect(this.model.get('visible')).toEqual(false);
      expect(this.userActions.saveLayer).toHaveBeenCalled();
      expect(this.userActions.saveLayer.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.userActions.saveLayer.calls.argsFor(0)[1]).toEqual({
        shouldPreserveAutoStyle: true
      });
      expect(this.model.get('autoStyle')).toEqual('foo');

      this.userActions.saveLayer.calls.reset();
      this.view.$('.js-toggle').click();
      expect(this.model.get('visible')).toEqual(true);
      expect(this.userActions.saveLayer).toHaveBeenCalled();
      expect(this.userActions.saveLayer.calls.argsFor(0)[0]).toEqual(this.view.model);
      expect(this.userActions.saveLayer.calls.argsFor(0)[1]).toEqual({
        shouldPreserveAutoStyle: true
      });
      expect(this.model.get('autoStyle')).toEqual('foo');
    });
  });

  describe('expanded/collapsed states', function () {
    it('should expand and collapse the layer', function () {
      expect(this.view.$('.js-analyses').hasClass('is-collapsed')).toBe(false);

      // Show the context menu and collapse the layer
      this.view.$('.js-toggle-menu').click();
      $('body').find('.CDB-Box-modal button[title="editor.layers.options.collapse"]').click();

      expect(this.view.$('.js-analyses').hasClass('is-collapsed')).toBe(true);

      // Show the context menu and expand the layer
      this.view.$('.js-toggle-menu').click();
      $('body').find('.CDB-Box-modal button[title="editor.layers.options.expand"]').click();

      // Show the context menu and expand the layer again
      expect(this.view.$('.js-analyses').hasClass('is-collapsed')).toBe(false);
    });
  });

  describe('rename layer', function () {
    it('should rename the layer', function () {
      // Show the context menu and collapse the layer
      this.view.$('.js-toggle-menu').click();
      $('body').find('.CDB-Box-modal button[title="editor.layers.options.rename"]').click();

      expect(this.view.$('.js-input').is(':visible')).toBe(true);
      this.view.$('.js-input').val('Foo');

      var e = $.Event('keyup');
      e.which = 13;
      this.view.$('.js-input').trigger(e);

      expect(this.model.get('table_name_alias')).toBe('Foo');
      expect(this.userActions.saveLayer).toHaveBeenCalledWith(this.model);
    });
  });

  describe('geometry type', function () {
    it('should show polygon svg', function () {
      expect(this.view.$('svg').length).toBe(1);
      expect(this.view.$('svg circle').length).toBe(4);
    });
  });

  describe('._showContextMenu', function () {
    it('should show center map option if geom and clicking on it should call _centerMap', function () {
      spyOn(this.view, '_centerMap');
      this.view._showContextMenu();

      expect(this.view._menuView.$('button[title^="editor.layers.options.center-map"]').length).toBe(1);

      this.view._menuView.$('button[title^="editor.layers.options.center-map"]').click();
      expect(this.view._centerMap).toHaveBeenCalled();
    });

    it('should not show center map option if no geom', function () {
      this.queryGeometryModel.set('simple_geom', '');
      this.view._showContextMenu();

      expect(this.view._menuView.$('button[title^="editor.layers.options.center-map"]').length).toBe(0);

      this.queryGeometryModel.set('simple_geom', 'polygon');
    });
  });

  describe('._centerMap', function () {
    it('should call to zoomToData with query from queryGeometryModel', function () {
      var theView = this.view;
      this.queryGeometryModel.set('simple_geom', '');

      // The only way we have to know if zoomToData has been called is to provoke an
      // error. This way we know that the query has been extracted from our querySchemaModel
      // and that zoomToData has been called.
      expect(function () {
        theView._centerMap();
      }).toThrowError('query is required');

      this.queryGeometryModel.set('simple_geom', 'polygon');
    });
  });
});
<|endoftext|>


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

  var app = angular.module('ui.grid.body', []);

  app.directive('uiGridBody', ['$log', 'gridUtil', function($log, GridUtil) {
    return {
      replace: true,
      // priority: 1000,
      templateUrl: 'ui-grid/ui-grid-body',
      require: '?^uiGrid',
      scope: false,
      link: function($scope, $elm, $attrs, uiGridCtrl) {
        if (uiGridCtrl === undefined) {
          throw new Error('[ui-grid-body] uiGridCtrl is undefined!');
        }

        $log.debug('ui-grid-body link');

        // Stick the canvas in the controller
        uiGridCtrl.canvas = angular.element( $elm[0].getElementsByClassName('ui-grid-canvas')[0] );
        // uiGridCtrl.viewport = elm; //angular.element( elm[0].getElementsByClassName('ui-grid-viewport')[0] );
        uiGridCtrl.viewport = angular.element( $elm[0].getElementsByClassName('ui-grid-viewport')[0] );
        uiGridCtrl.viewportOuterHeight = GridUtil.outerElementHeight(uiGridCtrl.viewport[0]);

        uiGridCtrl.prevScrollTop = 0;
        uiGridCtrl.currentTopRow = 0;

        uiGridCtrl.adjustScrollVertical = function (scrollTop, scrollPercentage, force) {
          if (uiGridCtrl.prevScrollTop === scrollTop && !force) {
            return;
          }

          if (scrollTop > 0 && uiGridCtrl.canvas[0].scrollHeight - scrollTop <= uiGridCtrl.viewportOuterHeight) {
            // $scope.$emit('ngGridEventScroll');
          }

          // $log.debug('scrollPercentage', scrollPercentage);

          // var rowIndex = Math.floor(scrollTop / uiGridCtrl.grid.options.rowHeight);
          // $log.debug(uiGridCtrl.grid.options.data.length + ' * (' + scrollTop + ' / ' + uiGridCtrl.grid.options.canvasHeight + ')');
          // var rowIndex = Math.floor(uiGridCtrl.grid.options.data.length * scrollTop / uiGridCtrl.grid.options.canvasHeight);
          // scrollTop = Math.floor(uiGridCtrl.canvas[0].scrollHeight * scrollPercentage);
          scrollTop = uiGridCtrl.canvas[0].scrollHeight * scrollPercentage;

          var minRows = uiGridCtrl.grid.minRowsToRender();
          var maxRowIndex = uiGridCtrl.grid.options.data.length - minRows;
          uiGridCtrl.maxRowIndex = maxRowIndex;

          // var rowIndex = Math.ceil(Math.min(uiGridCtrl.grid.options.data.length, uiGridCtrl.grid.options.data.length * scrollPercentage));
          var rowIndex = Math.ceil(Math.min(maxRowIndex, maxRowIndex * scrollPercentage));
          // $log.debug('rowIndex', rowIndex);

          // Define a max row index that we can't scroll past
          if (rowIndex > maxRowIndex) {
            rowIndex = maxRowIndex;
          }

          // $log.debug('newScrollTop', scrollTop);
          // $log.debug('rowIndex', rowIndex);
          // $log.debug('data.length', uiGridCtrl.grid.options.data.length);
          var newRange = [];
          if (uiGridCtrl.grid.options.data.length > uiGridCtrl.grid.options.virtualizationThreshold) {
            // Have we hit the threshold going down?
            if (uiGridCtrl.prevScrollTop < scrollTop && rowIndex < uiGridCtrl.prevScrollIndex + uiGridCtrl.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
              return;
            }
            //Have we hit the threshold going up?
            if (uiGridCtrl.prevScrollTop > scrollTop && rowIndex > uiGridCtrl.prevScrollIndex - uiGridCtrl.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
              return;
            }

            // $log.debug('rowIndex | maxRowIndex | minRows', rowIndex, maxRowIndex, minRows);

            var rangeStart = Math.max(0, rowIndex - uiGridCtrl.grid.options.excessRows);
            var rangeEnd = Math.min(uiGridCtrl.grid.options.data.length, rowIndex + minRows + uiGridCtrl.grid.options.excessRows);

            // if (rangeEnd - rangeStart < minRows) {
            //   $log.debug('range too small', rangeStart);
            //   rangeStart = rangeEnd - minRows - uiGridCtrl.grid.options.excessRows; //rangeStart - (minRows - (rangeEnd - rangeStart));
            //   $log.debug('new start of range', rangeStart);
            // }

            // Check to make sure the range isn't too long
            // var rangeLength = rangeEnd - rangeStart;
            // if (rowIndex === maxRowIndex && (uiGridCtrl.grid.options.offsetTop + (uiGridCtrl.grid.options.rowHeight * rangeLength) > uiGridCtrl.grid.options.canvasHeight)) {
            //   $log.debug('range too big!', uiGridCtrl.grid.options.offsetTop, uiGridCtrl.grid.options.rowHeight * rangeLength, uiGridCtrl.grid.options.canvasHeight);

            //   var removeRange = Math.floor( (uiGridCtrl.grid.options.offsetTop + (uiGridCtrl.grid.options.rowHeight * rangeLength) - uiGridCtrl.grid.options.canvasHeight) / uiGridCtrl.grid.options.rowHeight);
            //   $log.debug('remove range', removeRange);

            //   rangeStart = rangeStart + removeRange;
            // }

            newRange = [rangeStart, rangeEnd];
          }
          else {
            var maxLen = uiGridCtrl.grid.options.data.length;
            newRange = [0, Math.max(maxLen, minRows + uiGridCtrl.grid.options.excessRows)];
          }

          uiGridCtrl.prevScrollTop = scrollTop;
          updateViewableRange(newRange);
          uiGridCtrl.prevScrollIndex = rowIndex;
        };

        // Listen for scroll events
        var scrollUnbinder = $scope.$on('uiGridScrollVertical', function(evt, args) {
          // $log.debug('scroll', args.scrollPercentage, uiGridCtrl.grid.options.canvasHeight, args.scrollPercentage * uiGridCtrl.grid.options.canvasHeight);

          var scrollLength = (uiGridCtrl.grid.getCanvasHeight() - uiGridCtrl.grid.viewportHeight);

          // $log.debug('scrollLength', scrollLength, scrollLength % uiGridCtrl.grid.options.rowHeight);
          var newScrollTop = Math.max(0, args.scrollPercentage * scrollLength);
          // $log.debug('mod', (scrollLength % uiGridCtrl.grid.options.rowHeight));
          // newScrollTop = newScrollTop + (scrollLength % uiGridCtrl.grid.options.rowHeight);

          // $log.debug('uiGridCtrl.canvas[0].scrollHeight', uiGridCtrl.canvas[0].scrollHeight);

          // var scrollMultiplier = (uiGridCtrl.grid.options.canvasHeight / (uiGridCtrl.grid.options.rowHeight * uiGridCtrl.grid.options.data.length)) * 100;
          var scrollMultiplier = 1; // (uiGridCtrl.grid.options.rowHeight * uiGridCtrl.grid.options.data.length) / uiGridCtrl.grid.options.canvasHeight;
          // $log.debug('scrollMultiplier', scrollMultiplier);
          // newScrollTop = newScrollTop * scrollMultiplier;

          var scrollPercentage = args.scrollPercentage * scrollMultiplier;

          // $log.debug('newScrollTop', newScrollTop);
          // $log.debug('scrollPercentage - newScrollTop', scrollPercentage, newScrollTop);

          // Prevent scroll top from going over the maximum (canvas height - viewport height)
          // if (newScrollTop > uiGridCtrl.grid.options.canvasHeight - uiGridCtrl.grid.options.viewportHeight) {
          //   $log.debug('too high!');
          //   newScrollTop = uiGridCtrl.grid.options.canvasHeight - uiGridCtrl.grid.options.viewportHeight;
          // }

          uiGridCtrl.adjustScrollVertical(newScrollTop, scrollPercentage);
          uiGridCtrl.viewport[0].scrollTop = newScrollTop;
          uiGridCtrl.grid.options.offsetTop = newScrollTop;

          // scope.$evalAsync(function() {

          // });
        });

        // Scroll the viewport when the mousewheel is used
        $elm.bind('wheel mousewheel DomMouseScroll MozMousePixelScroll', function(evt) {
          // use wheelDeltaY
          evt.preventDefault();

          // $log.debug('evt', evt);
          // $log.debug('evt.wheelDeltaY', evt.wheelDeltaY);

          var newEvent = GridUtil.normalizeWheelEvent(evt);

          var scrollAmount = newEvent.deltaY * -120;

          // Get the scroll percentage
          // var scrollPercentage = (uiGridCtrl.viewport[0].scrollTop + scrollAmount) / (uiGridCtrl.viewport[0].scrollHeight - uiGridCtrl.grid.options.viewportHeight);
          var scrollPercentage = (uiGridCtrl.viewport[0].scrollTop + scrollAmount) / (uiGridCtrl.grid.getCanvasHeight() - uiGridCtrl.grid.getViewportHeight());

          // TODO(c0bra): Keep scrollPercentage within the range 0-1.
          if (scrollPercentage < 0) { scrollPercentage = 0; }
          if (scrollPercentage > 1) { scrollPercentage = 1; }

          // $log.debug('scrollPercentage', scrollPercentage);

          // $log.debug('new scrolltop', uiGridCtrl.canvas[0].scrollTop + scrollAmount);
          // uiGridCtrl.canvas[0].scrollTop = uiGridCtrl.canvas[0].scrollTop + scrollAmount;
          // $log.debug('new scrolltop', uiGridCtrl.canvas[0].scrollTop);

          $scope.$broadcast('uiGridScrollVertical', { scrollPercentage: scrollPercentage, target: $elm });
        });

        // TODO(c0bra): Scroll the viewport when the up and down arrow keys are used
        $elm.bind('keyDown', function(evt, args) {

        });

        // Unbind all $watches and events on $destroy
        $elm.bind('$destroy', function() {
          scrollUnbinder();
          $elm.unbind('keyDown');

          ['wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function (eventName) {
            $elm.unbind(eventName);
          });
        });

        var setRenderedRows = function (newRows) {
          // NOTE: without the $evalAsync the new rows don't show up
          $scope.$evalAsync(function() {
            uiGridCtrl.grid.setRenderedRows(newRows);
          });
        };

        // Method for updating the visible rows
        var updateViewableRange = function(renderedRange) {
          // Slice out the range of rows from the data
          var rowArr = uiGridCtrl.grid.options.data.slice(renderedRange[0], renderedRange[1]);

          // Define the top-most rendered row
          uiGridCtrl.currentTopRow = renderedRange[0];

          setRenderedRows(rowArr);
        };

        $scope.rowStyle = function (index) {
          if (index === 0 && uiGridCtrl.currentTopRow !== 0) {
            // Here we need to add an extra bit on to our offset. We are calculating the offset below based on the number of rows
            //   that will fit into the viewport. If it's not an even amount there will be a remainder and the viewport will not scroll far enough.
            //   We add the remainder on by using the offset-able height's (canvas - viewport) modulus of the row height, and then we multiply
            //   by the percentage of the index of the row we're scrolled to so the modulus is added increasingly the further on we scroll
            var rowPercent = (uiGridCtrl.prevScrollIndex / uiGridCtrl.maxRowIndex);
            var mod = Math.ceil( ((uiGridCtrl.grid.getCanvasHeight() - uiGridCtrl.grid.getViewportHeight()) % uiGridCtrl.grid.options.rowHeight) * rowPercent);

            // We need to add subtract a row from the offset at the beginning to prevent a "jump/snap" effect where the grid moves down an extra rowHeight of pixels, then
            //   add it back until the offset is fully there are the bottom. Basically we add a percentage of a rowHeight back as we scroll down, from 0% at the top to 100%
            //   at the bottom
            var extraRowOffset = (1 - rowPercent);

            var offset = (uiGridCtrl.grid.options.offsetTop) - (uiGridCtrl.grid.options.rowHeight * (uiGridCtrl.grid.options.excessRows - extraRowOffset)) - mod;

            return { 'margin-top': offset + 'px' };
          }

          return null;
        };
      }
    };
  }]);

})();<commit_msg>another dumb name change<commit_after>(function(){
  'use strict';

  var app = angular.module('ui.grid.body', []);

  app.directive('uiGridBody', ['$log', 'gridUtil', function($log, GridUtil) {
    return {
      replace: true,
      // priority: 1000,
      templateUrl: 'ui-grid/ui-grid-body',
      require: '?^uiGrid',
      scope: false,
      link: function($scope, $elm, $attrs, uiGridCtrl) {
        if (uiGridCtrl === undefined) {
          throw new Error('[ui-grid-body] uiGridCtrl is undefined!');
        }

        $log.debug('ui-grid-body link');

        // Stick the canvas in the controller
        uiGridCtrl.canvas = angular.element( $elm[0].getElementsByClassName('ui-grid-canvas')[0] );
        // uiGridCtrl.viewport = elm; //angular.element( elm[0].getElementsByClassName('ui-grid-viewport')[0] );
        uiGridCtrl.viewport = angular.element( $elm[0].getElementsByClassName('ui-grid-viewport')[0] );
        uiGridCtrl.viewportOuterHeight = GridUtil.outerElementHeight(uiGridCtrl.viewport[0]);

        uiGridCtrl.prevScrollTop = 0;
        uiGridCtrl.currentTopRow = 0;

        uiGridCtrl.adjustScrollVertical = function (scrollTop, scrollPercentage, force) {
          if (uiGridCtrl.prevScrollTop === scrollTop && !force) {
            return;
          }

          if (scrollTop > 0 && uiGridCtrl.canvas[0].scrollHeight - scrollTop <= uiGridCtrl.viewportOuterHeight) {
            // $scope.$emit('ngGridEventScroll');
          }

          // $log.debug('scrollPercentage', scrollPercentage);

          // var rowIndex = Math.floor(scrollTop / uiGridCtrl.grid.options.rowHeight);
          // $log.debug(uiGridCtrl.grid.options.data.length + ' * (' + scrollTop + ' / ' + uiGridCtrl.grid.options.canvasHeight + ')');
          // var rowIndex = Math.floor(uiGridCtrl.grid.options.data.length * scrollTop / uiGridCtrl.grid.options.canvasHeight);
          // scrollTop = Math.floor(uiGridCtrl.canvas[0].scrollHeight * scrollPercentage);
          scrollTop = uiGridCtrl.canvas[0].scrollHeight * scrollPercentage;

          var minRows = uiGridCtrl.grid.minRowsToRender();
          var maxRowIndex = uiGridCtrl.grid.options.data.length - minRows;
          uiGridCtrl.maxRowIndex = maxRowIndex;

          // var rowIndex = Math.ceil(Math.min(uiGridCtrl.grid.options.data.length, uiGridCtrl.grid.options.data.length * scrollPercentage));
          var rowIndex = Math.ceil(Math.min(maxRowIndex, maxRowIndex * scrollPercentage));
          // $log.debug('rowIndex', rowIndex);

          // Define a max row index that we can't scroll past
          if (rowIndex > maxRowIndex) {
            rowIndex = maxRowIndex;
          }

          // $log.debug('newScrollTop', scrollTop);
          // $log.debug('rowIndex', rowIndex);
          // $log.debug('data.length', uiGridCtrl.grid.options.data.length);
          var newRange = [];
          if (uiGridCtrl.grid.options.data.length > uiGridCtrl.grid.options.virtualizationThreshold) {
            // Have we hit the threshold going down?
            if (uiGridCtrl.prevScrollTop < scrollTop && rowIndex < uiGridCtrl.prevScrollIndex + uiGridCtrl.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
              return;
            }
            //Have we hit the threshold going up?
            if (uiGridCtrl.prevScrollTop > scrollTop && rowIndex > uiGridCtrl.prevScrollIndex - uiGridCtrl.grid.options.scrollThreshold && rowIndex < maxRowIndex) {
              return;
            }

            // $log.debug('rowIndex | maxRowIndex | minRows', rowIndex, maxRowIndex, minRows);

            var rangeStart = Math.max(0, rowIndex - uiGridCtrl.grid.options.excessRows);
            var rangeEnd = Math.min(uiGridCtrl.grid.options.data.length, rowIndex + minRows + uiGridCtrl.grid.options.excessRows);

            // if (rangeEnd - rangeStart < minRows) {
            //   $log.debug('range too small', rangeStart);
            //   rangeStart = rangeEnd - minRows - uiGridCtrl.grid.options.excessRows; //rangeStart - (minRows - (rangeEnd - rangeStart));
            //   $log.debug('new start of range', rangeStart);
            // }

            // Check to make sure the range isn't too long
            // var rangeLength = rangeEnd - rangeStart;
            // if (rowIndex === maxRowIndex && (uiGridCtrl.grid.options.offsetTop + (uiGridCtrl.grid.options.rowHeight * rangeLength) > uiGridCtrl.grid.options.canvasHeight)) {
            //   $log.debug('range too big!', uiGridCtrl.grid.options.offsetTop, uiGridCtrl.grid.options.rowHeight * rangeLength, uiGridCtrl.grid.options.canvasHeight);

            //   var removeRange = Math.floor( (uiGridCtrl.grid.options.offsetTop + (uiGridCtrl.grid.options.rowHeight * rangeLength) - uiGridCtrl.grid.options.canvasHeight) / uiGridCtrl.grid.options.rowHeight);
            //   $log.debug('remove range', removeRange);

            //   rangeStart = rangeStart + removeRange;
            // }

            newRange = [rangeStart, rangeEnd];
          }
          else {
            var maxLen = uiGridCtrl.grid.options.data.length;
            newRange = [0, Math.max(maxLen, minRows + uiGridCtrl.grid.options.excessRows)];
          }

          uiGridCtrl.prevScrollTop = scrollTop;
          updateViewableRange(newRange);
          uiGridCtrl.prevScrollIndex = rowIndex;
        };

        // Listen for scroll events
        var scrollUnbinder = $scope.$on('uiGridScrollVertical', function(evt, args) {
          // $log.debug('scroll', args.scrollPercentage, uiGridCtrl.grid.options.canvasHeight, args.scrollPercentage * uiGridCtrl.grid.options.canvasHeight);

          var scrollLength = (uiGridCtrl.grid.getCanvasHeight() - uiGridCtrl.grid.getViewportHeight());

          // $log.debug('scrollLength', scrollLength, scrollLength % uiGridCtrl.grid.options.rowHeight);
          var newScrollTop = Math.max(0, args.scrollPercentage * scrollLength);
          // $log.debug('mod', (scrollLength % uiGridCtrl.grid.options.rowHeight));
          // newScrollTop = newScrollTop + (scrollLength % uiGridCtrl.grid.options.rowHeight);

          // $log.debug('uiGridCtrl.canvas[0].scrollHeight', uiGridCtrl.canvas[0].scrollHeight);

          // var scrollMultiplier = (uiGridCtrl.grid.options.canvasHeight / (uiGridCtrl.grid.options.rowHeight * uiGridCtrl.grid.options.data.length)) * 100;
          var scrollMultiplier = 1; // (uiGridCtrl.grid.options.rowHeight * uiGridCtrl.grid.options.data.length) / uiGridCtrl.grid.options.canvasHeight;
          // $log.debug('scrollMultiplier', scrollMultiplier);
          // newScrollTop = newScrollTop * scrollMultiplier;

          var scrollPercentage = args.scrollPercentage * scrollMultiplier;

          // $log.debug('newScrollTop', newScrollTop);
          // $log.debug('scrollPercentage - newScrollTop', scrollPercentage, newScrollTop);

          // Prevent scroll top from going over the maximum (canvas height - viewport height)
          // if (newScrollTop > uiGridCtrl.grid.options.canvasHeight - uiGridCtrl.grid.options.viewportHeight) {
          //   $log.debug('too high!');
          //   newScrollTop = uiGridCtrl.grid.options.canvasHeight - uiGridCtrl.grid.options.viewportHeight;
          // }

          uiGridCtrl.adjustScrollVertical(newScrollTop, scrollPercentage);
          uiGridCtrl.viewport[0].scrollTop = newScrollTop;
          uiGridCtrl.grid.options.offsetTop = newScrollTop;

          // scope.$evalAsync(function() {

          // });
        });

        // Scroll the viewport when the mousewheel is used
        $elm.bind('wheel mousewheel DomMouseScroll MozMousePixelScroll', function(evt) {
          // use wheelDeltaY
          evt.preventDefault();

          // $log.debug('evt', evt);
          // $log.debug('evt.wheelDeltaY', evt.wheelDeltaY);

          var newEvent = GridUtil.normalizeWheelEvent(evt);

          var scrollAmount = newEvent.deltaY * -120;

          // Get the scroll percentage
          // var scrollPercentage = (uiGridCtrl.viewport[0].scrollTop + scrollAmount) / (uiGridCtrl.viewport[0].scrollHeight - uiGridCtrl.grid.options.viewportHeight);
          var scrollPercentage = (uiGridCtrl.viewport[0].scrollTop + scrollAmount) / (uiGridCtrl.grid.getCanvasHeight() - uiGridCtrl.grid.getViewportHeight());

          // TODO(c0bra): Keep scrollPercentage within the range 0-1.
          if (scrollPercentage < 0) { scrollPercentage = 0; }
          if (scrollPercentage > 1) { scrollPercentage = 1; }

          // $log.debug('scrollPercentage', scrollPercentage);

          // $log.debug('new scrolltop', uiGridCtrl.canvas[0].scrollTop + scrollAmount);
          // uiGridCtrl.canvas[0].scrollTop = uiGridCtrl.canvas[0].scrollTop + scrollAmount;
          // $log.debug('new scrolltop', uiGridCtrl.canvas[0].scrollTop);

          $scope.$broadcast('uiGridScrollVertical', { scrollPercentage: scrollPercentage, target: $elm });
        });

        // TODO(c0bra): Scroll the viewport when the up and down arrow keys are used
        $elm.bind('keyDown', function(evt, args) {

        });

        // Unbind all $watches and events on $destroy
        $elm.bind('$destroy', function() {
          scrollUnbinder();
          $elm.unbind('keyDown');

          ['wheel', 'mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'].forEach(function (eventName) {
            $elm.unbind(eventName);
          });
        });

        var setRenderedRows = function (newRows) {
          // NOTE: without the $evalAsync the new rows don't show up
          $scope.$evalAsync(function() {
            uiGridCtrl.grid.setRenderedRows(newRows);
          });
        };

        // Method for updating the visible rows
        var updateViewableRange = function(renderedRange) {
          // Slice out the range of rows from the data
          var rowArr = uiGridCtrl.grid.options.data.slice(renderedRange[0], renderedRange[1]);

          // Define the top-most rendered row
          uiGridCtrl.currentTopRow = renderedRange[0];

          setRenderedRows(rowArr);
        };

        $scope.rowStyle = function (index) {
          if (index === 0 && uiGridCtrl.currentTopRow !== 0) {
            // Here we need to add an extra bit on to our offset. We are calculating the offset below based on the number of rows
            //   that will fit into the viewport. If it's not an even amount there will be a remainder and the viewport will not scroll far enough.
            //   We add the remainder on by using the offset-able height's (canvas - viewport) modulus of the row height, and then we multiply
            //   by the percentage of the index of the row we're scrolled to so the modulus is added increasingly the further on we scroll
            var rowPercent = (uiGridCtrl.prevScrollIndex / uiGridCtrl.maxRowIndex);
            var mod = Math.ceil( ((uiGridCtrl.grid.getCanvasHeight() - uiGridCtrl.grid.getViewportHeight()) % uiGridCtrl.grid.options.rowHeight) * rowPercent);

            // We need to add subtract a row from the offset at the beginning to prevent a "jump/snap" effect where the grid moves down an extra rowHeight of pixels, then
            //   add it back until the offset is fully there are the bottom. Basically we add a percentage of a rowHeight back as we scroll down, from 0% at the top to 100%
            //   at the bottom
            var extraRowOffset = (1 - rowPercent);

            var offset = (uiGridCtrl.grid.options.offsetTop) - (uiGridCtrl.grid.options.rowHeight * (uiGridCtrl.grid.options.excessRows - extraRowOffset)) - mod;

            return { 'margin-top': offset + 'px' };
          }

          return null;
        };
      }
    };
  }]);

})();<|endoftext|>


<commit_before>var table = '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D';
var table = table.split(' ').map(function (s) { return parseInt(s, 16) });

String.prototype.crc32 = function () {
	var crc = crc ^ (-1);
	for (var i = 0, iTop = this.length; i < iTop; i += 1) {
		crc = (crc >>> 8) ^ table[(crc ^ this.charCodeAt(i)) & 0xFF];
	}
	return (crc ^ (-1)) >>> 0;
}
angular.module('ngPasscheck', []).directive('passCheck', function ($compile, passCheckService) {
	return {
		restrict: 'A',
		require: 'ngModel',
		scope: {
			password: '=ngModel'
		},
		link: function (scope, elem, attrs) {
			scope.$on('passCheckService:init', function () {

				elem.after(angular.element($compile('{{ result.numeric }}')(scope)));

				scope.$watch('password', function (n) {

					scope.result = n ? passCheckService.analyze(n) : null;
				});
			});
		}
	}
}).provider('passCheck', function () {
	return {
		init: function (options) {
			this.regex = {
				'strong': options.regex ? options.regex.strong : null,
				'medium': options.regex ? options.regex.medium : null
			}

			this.testCommon = options.testCommon ? { 'path': options.testCommon.path, 'limit': options.testCommon.limit } : null;
		},
		$get: function () {
			return {
				regex: {
					strong: this.regex && this.regex.strong ? this.regex.strong : new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{9,})'),
					medium: this.regex && this.regex.medium ? this.regex.medium : new RegExp('^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})'),
				},
				testCommon: this.testCommon || false
			}
		}
	}
})
.factory('passCheckService', function (passCheck, $http, $rootScope, $timeout) {

	var dictionary, passFormat;

	function appendTransform(defaults, transform) {
		defaults = angular.isArray(defaults) ? defaults : [defaults];
		return defaults.concat(transform);
	}

	function getNumericStrength(value, strength, isCommon) {

		var n = 0;

		var considerations = {
			'length': {
				'short': { 'min': 8, 'factor': 2 },
				'medium': { 'min': 16, 'factor': 4 },
				'long': { 'min': 24, 'factor': 6 }
			},
			'specialCharacters': {
				'count': value.replace(/[^\w\s]/gi, '').length !== value.length ? value.match(/[^\w\s]/gi, '').length : 0,
				'bonus': 2
			},
			'capitalCharacters': {
				'count': /[A-Z]/.test(value) ? value.replace(/[^A-Z]/g, '').length : 0,
				'bonus': 2
			}
		}

		if (value.length <= considerations.length.short.min) {
			n = considerations.length.short.factor * value.length;
			n += ((considerations.capitalCharacters.count * considerations.capitalCharacters.bonus) * considerations.length.short.factor);
			n += ((considerations.specialCharacters.count * considerations.specialCharacters.bonus) * considerations.length.short.factor);
		}

		if (value.length > considerations.length.short.min && value.length < considerations.length.long.min) {
			n = (considerations.length.medium.factor * value.length) - (considerations.length.short.factor * considerations.length.short.min);
			n += ((considerations.capitalCharacters.count * considerations.capitalCharacters.bonus) * considerations.length.medium.factor);
			n += ((considerations.specialCharacters.count * considerations.specialCharacters.bonus) * considerations.length.medium.factor);
		}

		if (value.length >= considerations.length.long.min) {
			n = (considerations.length.long.factor * value.length) - (considerations.length.medium.factor * considerations.length.medium.min);
			n += ((considerations.capitalCharacters.count * considerations.capitalCharacters.bonus) * considerations.length.long.factor);
			n += ((considerations.specialCharacters.count * considerations.specialCharacters.bonus) * considerations.length.long.factor);
		}

		return n > 100 ? 100 : n;

//if (value.length) {

		//	var score = 0;

		//	for (var i = 0; i < value.length; i += 1) {
		//
		//
		//
		//
		//
		//
		//	}
		//}

//var threshold = 18;

		//var maximum = {
		//	'strong': isCommon ? 50 : 100,
		//	'medium': isCommon ? 30 : 60,
		//	'weak': isCommon ? 15 : 30
		//}

		//var bonus = {
		//	'specialCharacters': 5 * (value.replace(/[^\w\s]/gi, '').length !== value.length ? value.match(/[^\w\s]/gi, '').length : 0),
		//	'capitalCharacters': 3 * (/[A-Z]/.test(value) ? value.replace(/[^A-Z]/g, '').length : 0),
		//	'increment': value.length > threshold ? 2* (value.length - threshold) : 0
		//}

		//var n = 4 * (value.length) + bonus.specialCharacters + bonus.capitalCharacters;

		//switch(strength) {
		//	case 2: n = n > maximum.strong ? maximum.strong : n; break;
		//	case 1: n = n > maximum.medium ? maximum.medium : n; break;
		//	case 0: n = n > maximum.weak ? maximum.weak : n; break;
		//}

		//n = n + bonus.increment;

		//return n > 100 ? 100 : n;

		//return value.length;
	}

	function analyze(value) {

		var result = {};

		var isCommon = passCheck.testCommon ? dictionary.indexOf(passFormat === 'crc32' ? value.crc32() : value) > -1 ? true : false : false;

		if (passCheck.regex.strong.test(value)) {
			result.strength = 2;
			result.description = 'strong';
		} else if (passCheck.regex.medium.test(value)) {
			result.strength = 1;
			result.description = 'ehh';
		} else {
			result.strength = 0;
			result.description = 'weak sauce';
		}

		result.numeric = getNumericStrength(value, result.strength, isCommon);

		return result;
	}

	function init(data) {
		dictionary = data;
		$timeout(function() {
			$rootScope.$broadcast('passCheckService:init');
		});
	}

	if (passCheck.testCommon) {
		$http.get(passCheck.testCommon.path, {
			transformResponse: appendTransform($http.defaults.transformResponse, function (data) {
				passFormat = data.format;
				return data.dictionary.slice(0, passCheck.testCommon.limit || data.dictionary.length);
			})
		}).then(function (response) {
			init(response.data);
		});
	} else {
		init();
	}

	return {
		'analyze': analyze
	}
})<commit_msg>stripping formula<commit_after>var table = '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D';
var table = table.split(' ').map(function (s) { return parseInt(s, 16) });

String.prototype.crc32 = function () {
	var crc = crc ^ (-1);
	for (var i = 0, iTop = this.length; i < iTop; i += 1) {
		crc = (crc >>> 8) ^ table[(crc ^ this.charCodeAt(i)) & 0xFF];
	}
	return (crc ^ (-1)) >>> 0;
}
angular.module('ngPasscheck', []).directive('passCheck', function ($compile, passCheckService) {
	return {
		restrict: 'A',
		require: 'ngModel',
		scope: {
			password: '=ngModel'
		},
		link: function (scope, elem, attrs) {
			scope.$on('passCheckService:init', function () {

				elem.after(angular.element($compile('{{ result.numeric }}')(scope)));

				scope.$watch('password', function (n) {

					scope.result = n ? passCheckService.analyze(n) : null;
				});
			});
		}
	}
}).provider('passCheck', function () {
	return {
		init: function (options) {
			this.regex = {
				'strong': options.regex ? options.regex.strong : null,
				'medium': options.regex ? options.regex.medium : null
			}

			this.testCommon = options.testCommon ? { 'path': options.testCommon.path, 'limit': options.testCommon.limit } : null;
		},
		$get: function () {
			return {
				regex: {
					strong: this.regex && this.regex.strong ? this.regex.strong : new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{9,})'),
					medium: this.regex && this.regex.medium ? this.regex.medium : new RegExp('^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})'),
				},
				testCommon: this.testCommon || false
			}
		}
	}
})
.factory('passCheckService', function (passCheck, $http, $rootScope, $timeout) {

	var dictionary, passFormat;

	function appendTransform(defaults, transform) {
		defaults = angular.isArray(defaults) ? defaults : [defaults];
		return defaults.concat(transform);
	}

	function getNumericStrength(value, strength, isCommon) {

		var n = 0;

		var considerations = {
			'length': {
				'short':
					{ 'charcount': 08, 'factor': 2 },
				'medium':
					{ 'charcount': 14, 'factor': 3 },
				'long':
					{ 'charcount': 20, 'factor': 5 }
			},
			'specialCharacters': {
				'count': /[^\w\s]/.test(value) ? value.match(/[^\w\s]/gi, '').length : 0,
				'bonus': 2
			},
			'capitalCharacters': {
				'count': /[A-Z]/.test(value) ? value.match(/[A-Z]+/g).length : 0,
				'bonus': 1.5
			},
			'numericCharacters': {
				'count': /\d+/.test(value) ? value.match(/\d+/gi, '').length : 0,
				'bonus': 1.5
			}
		}

		if (value.length <= considerations.length.short.charcount) {
			//n = considerations.length.short.factor * value.length;
			//n += ((considerations.capitalCharacters.count * considerations.capitalCharacters.bonus) * considerations.length.short.factor);
			//n += ((considerations.specialCharacters.count * considerations.specialCharacters.bonus) * considerations.length.short.factor);
			//n += ((considerations.numericCharacters.count * considerations.numericCharacters.bonus) * considerations.length.short.factor);
		}

		if (value.length > considerations.length.short.charcount && value.length < considerations.length.long.charcount) {
			//n = (considerations.length.medium.factor * value.length) - (considerations.length.short.factor * considerations.length.short.charcount);
			//n += ((considerations.capitalCharacters.count * considerations.capitalCharacters.bonus) * considerations.length.medium.factor);
			//n += ((considerations.specialCharacters.count * considerations.specialCharacters.bonus) * considerations.length.medium.factor);
			//n += ((considerations.numericCharacters.count * considerations.numericCharacters.bonus) * considerations.length.medium.factor);
		}

		if (value.length >= considerations.length.long.charcount) {
			//n = (considerations.length.long.factor * value.length) - (considerations.length.medium.factor * considerations.length.medium.charcount);
			//n += ((considerations.capitalCharacters.count * considerations.capitalCharacters.bonus) * considerations.length.long.factor);
			//n += ((considerations.specialCharacters.count * considerations.specialCharacters.bonus) * considerations.length.long.factor);
			//n += ((considerations.numericCharacters.count * considerations.numericCharacters.bonus) * considerations.length.long.factor);
		}

		return n > 100 ? 100 : n;
	}

	function analyze(value) {

		var result = {};

		var isCommon = passCheck.testCommon ? dictionary.indexOf(passFormat === 'crc32' ? value.crc32() : value) > -1 ? true : false : false;

		if (passCheck.regex.strong.test(value)) {
			result.strength = 2;
			result.description = 'strong';
		} else if (passCheck.regex.medium.test(value)) {
			result.strength = 1;
			result.description = 'ehh';
		} else {
			result.strength = 0;
			result.description = 'weak sauce';
		}

		result.numeric = getNumericStrength(value, result.strength, isCommon);

		return result;
	}

	function init(data) {
		dictionary = data;
		$timeout(function() {
			$rootScope.$broadcast('passCheckService:init');
		});
	}

	if (passCheck.testCommon) {
		$http.get(passCheck.testCommon.path, {
			transformResponse: appendTransform($http.defaults.transformResponse, function (data) {
				passFormat = data.format;
				return data.dictionary.slice(0, passCheck.testCommon.limit || data.dictionary.length);
			})
		}).then(function (response) {
			init(response.data);
		});
	} else {
		init();
	}

	return {
		'analyze': analyze
	}
})<|endoftext|>


<commit_before>import _ from 'lodash';
import { combineReducers } from 'redux';
import { fromJS } from 'immutable';

import { DEFAULT_CLUSTER_CONFIG } from './cluster-config';

import {
  awsActionTypes,
  clusterReadyActionTypes,
  configActionTypes,
  dirtyActionTypes,
  eventErrorsActionTypes,
  loadFactsActionTypes,
  restoreActionTypes,
  serverActionTypes,
  commitPhases,
} from './actions';

const UNLOADED_AWS_VALUE = {
  inFly: false,
  value: [],
  error: null,
};

const DEFAULT_AWS = {
  availableVpcs: UNLOADED_AWS_VALUE,
  availableVpcSubnets: UNLOADED_AWS_VALUE,
  availableSsh: UNLOADED_AWS_VALUE,
  availableIamRoles: UNLOADED_AWS_VALUE,
  availableRegions: UNLOADED_AWS_VALUE,
  availableKms: UNLOADED_AWS_VALUE,
  availableR53Zones: UNLOADED_AWS_VALUE,
  createdKms: UNLOADED_AWS_VALUE,
  domainInfo: UNLOADED_AWS_VALUE,
  subnets: UNLOADED_AWS_VALUE,
  validateSubnets: UNLOADED_AWS_VALUE,
  destroy: UNLOADED_AWS_VALUE,
};

// setIn({...}, 'a.b.c', 'd')
function setIn (object, path, value) {
  const array = _.isString(path) ? path.split('.') : path;
  return fromJS(object).setIn(array, value).toJS();
}

const reducersTogether = combineReducers({

  // State machine associated with server submissions
  commitState: (state, action) => {
    if (!state) {
      return {
        phase: commitPhases.IDLE,
        response: null,
      };
    }

    switch (action.type) {
    case serverActionTypes.COMMIT_REQUESTED:
      return {
        phase: commitPhases.REQUESTED,
      };
    case serverActionTypes.COMMIT_SENT:
      return {
        phase: commitPhases.WAITING,
      };
    case serverActionTypes.COMMIT_SUCCESSFUL:
      console.log('COMMIT SUCCESSFUL: provisioner has been configured');
      console.dir(action.payload);
      return {
        phase: commitPhases.SUCCEEDED,
        response: action.payload,
      };
    case serverActionTypes.COMMIT_FAILED:
      console.log('COMMIT FAILED');
      console.dir(action.payload);
      return {
        phase: commitPhases.FAILED,
        response: action.payload,
      };
    default:
      return state;
    }
  },

  aws: (state, action) => {
    if (!state) {
      return DEFAULT_AWS;
    }

    switch (action.type) {
    case awsActionTypes.SET:
      Object.keys(action.payload).forEach(k => {
        if (!DEFAULT_AWS.hasOwnProperty(k)) {
          throw Error(`attempt to set aws property ${k} missing from defaults`);
        }
      });
      return Object.assign({}, state, action.payload);
    default:
      return state;
    }
  },

  // The user's intentions for their cluster
  clusterConfig: (state, action) => {
    if (!state) {
      return DEFAULT_CLUSTER_CONFIG;
    }

    switch (action.type) {
    case configActionTypes.RESET:
      return {};
    case configActionTypes.SET:
      Object.keys(action.payload).forEach(k => {
        if (!DEFAULT_CLUSTER_CONFIG.hasOwnProperty(k)) {
          throw Error(`attempt to set cluster property ${k} missing from defaults`);
        }
      });
      return Object.assign({}, state, action.payload);

    case configActionTypes.BATCH_SET_IN: {
      let object = fromJS(state);
      action.payload.forEach(batch => {
        const [path, value] = batch;
        const array = _.isString(path) ? path.split('.') : path;
        object = object.setIn(array, value);
      });
      return object.toJS();
    }

    // Adds a value at a given path or no-op if a value already exists for the path
    case configActionTypes.ADD_IN:
      return _.isEmpty(_.get(state, action.payload.path))
        ? setIn(state, action.payload.path, action.payload.value)
        : state;

    case configActionTypes.SET_IN:
      return setIn(state, action.payload.path, action.payload.value);

    case configActionTypes.MERGE:
      return fromJS(state).mergeDeep(action.payload).toJS();

    case configActionTypes.APPEND: {
      const length = _.get(state, action.payload.path).length;
      const path = `${action.payload.path}.${length}`;
      return setIn(state, path, action.payload.value);
    }

    case configActionTypes.REMOVE_FIELD_LIST_ROW: {
      const {fieldListId, index} = action.payload;
      return fromJS(state).deleteIn([fieldListId, index]).toJS();
    }
    default:
      return state;
    }
  },

  // Errors resulting from server states, user uploads, network issues, or other transient phenomena
  eventErrors: (state, action) => {
    if (!state) {
      return {};
    }

    switch (action.type) {
    case eventErrorsActionTypes.ERROR:
      return Object.assign({}, state, {
        [action.payload.name]: action.payload.error,
      });
    default:
      return state;
    }
  },

  // Facts the server knows at load time, that we have to get asynchronously
  serverFacts: (state, action) => {
    if (state === undefined) {
      return {
        loaded: false,
        error: null,
      };
    }

    switch (action.type) {
    case loadFactsActionTypes.LOADED:
      return Object.assign({}, action.payload, {
        loaded: true,
        error: null,
      });
    case loadFactsActionTypes.ERROR:
      return {
        loaded: true,
        error: action.payload,
      };
    default:
      return state;
    }
  },

  // The status of the cluster
  cluster: (state, action) => {
    if (!state) {
      return {
        loaded: false,
        ready: false,
        error: null,
        status: null,
      };
    }

    switch (action.type) {
    case clusterReadyActionTypes.NOT_READY:
      return Object.assign({}, state, {
        loaded: true,
        ready: false,
        status: null,
      });
    case clusterReadyActionTypes.STATUS:
      return Object.assign({}, state, {
        loaded: true,
        ready: true,
        status: action.payload,
        error: null,
      });
    case clusterReadyActionTypes.ERROR:
      return Object.assign({}, state, {
        loaded: true,
        error: action.payload,
      });
    default:
      return state;
    }
  },

  // Stores the "dirtiness" of UI fields
  dirty: (state, action) => {
    // this isArray check is just to prevent errors with old progress files & dev mode
    if (!state || _.isArray(state)) {
      return {};
    }

    switch (action.type) {
    case configActionTypes.REMOVE_FIELD_LIST_ROW: {
      const {fieldListId, index} = action.payload;
      return fromJS(state).deleteIn([fieldListId, index]).toJS();
    }
    case dirtyActionTypes.ADD: {
      // {awsTags: [{key: true}]
      const split = action.payload.split('.')
        .map(s => {
          const int = parseInt(s, 10);
          return isNaN(int) ? s : int;
        });
      // mirror structure of clusterconfig for storing field dirtiness
      const obj = _.cloneDeep(state);
      let s = split[0];
      let current = obj;
      for (let i = 1; i < split.length; ++i) {
        if (!_.has(current, s) || current[s] === null) {
          current[s] = _.isInteger(split[i]) ? [] : {};
        }
        current = current[s];
        s = split[i];
      }
      current[s] = true;
      return obj;
    }
    case dirtyActionTypes.CLEAN: {
      const array = _.isString(action.payload) ? action.payload.split('.') : action.payload;
      return fromJS(state).deleteIn(array).toJS();
    }
    default:
      return state;
    }
  },
});

// Shim for tests
export const reducer = (state, action) => {
  let restored;
  switch (action.type) {
  case restoreActionTypes.RESTORE_STATE:
    restored = Object.assign({}, action.payload, {
      serverFacts: state.serverFacts,
      cluster: state.cluster,
    });
    restored.aws = _.defaults(restored.aws, DEFAULT_AWS);
    if (restored.clusterConfig) {
      restored.clusterConfig = _.defaults(restored.clusterConfig, DEFAULT_CLUSTER_CONFIG);
    }
    break;
  default:
    restored = state;
  }

  return reducersTogether(restored, action);
};

// Returns only the bits of state that should be saved and restored
export const savable = (state) => {
  const {dirty, clusterConfig} = state;
  return {dirty, clusterConfig: _.omit(clusterConfig, ['error', 'extra', 'extraError', 'extraInFly', 'inFly'])};
};
<commit_msg>frontend: Remove old check for progress files<commit_after>import _ from 'lodash';
import { combineReducers } from 'redux';
import { fromJS } from 'immutable';

import { DEFAULT_CLUSTER_CONFIG } from './cluster-config';

import {
  awsActionTypes,
  clusterReadyActionTypes,
  configActionTypes,
  dirtyActionTypes,
  eventErrorsActionTypes,
  loadFactsActionTypes,
  restoreActionTypes,
  serverActionTypes,
  commitPhases,
} from './actions';

const UNLOADED_AWS_VALUE = {
  inFly: false,
  value: [],
  error: null,
};

const DEFAULT_AWS = {
  availableVpcs: UNLOADED_AWS_VALUE,
  availableVpcSubnets: UNLOADED_AWS_VALUE,
  availableSsh: UNLOADED_AWS_VALUE,
  availableIamRoles: UNLOADED_AWS_VALUE,
  availableRegions: UNLOADED_AWS_VALUE,
  availableKms: UNLOADED_AWS_VALUE,
  availableR53Zones: UNLOADED_AWS_VALUE,
  createdKms: UNLOADED_AWS_VALUE,
  domainInfo: UNLOADED_AWS_VALUE,
  subnets: UNLOADED_AWS_VALUE,
  validateSubnets: UNLOADED_AWS_VALUE,
  destroy: UNLOADED_AWS_VALUE,
};

// setIn({...}, 'a.b.c', 'd')
function setIn (object, path, value) {
  const array = _.isString(path) ? path.split('.') : path;
  return fromJS(object).setIn(array, value).toJS();
}

const reducersTogether = combineReducers({

  // State machine associated with server submissions
  commitState: (state, action) => {
    if (!state) {
      return {
        phase: commitPhases.IDLE,
        response: null,
      };
    }

    switch (action.type) {
    case serverActionTypes.COMMIT_REQUESTED:
      return {
        phase: commitPhases.REQUESTED,
      };
    case serverActionTypes.COMMIT_SENT:
      return {
        phase: commitPhases.WAITING,
      };
    case serverActionTypes.COMMIT_SUCCESSFUL:
      console.log('COMMIT SUCCESSFUL: provisioner has been configured');
      console.dir(action.payload);
      return {
        phase: commitPhases.SUCCEEDED,
        response: action.payload,
      };
    case serverActionTypes.COMMIT_FAILED:
      console.log('COMMIT FAILED');
      console.dir(action.payload);
      return {
        phase: commitPhases.FAILED,
        response: action.payload,
      };
    default:
      return state;
    }
  },

  aws: (state, action) => {
    if (!state) {
      return DEFAULT_AWS;
    }

    switch (action.type) {
    case awsActionTypes.SET:
      Object.keys(action.payload).forEach(k => {
        if (!DEFAULT_AWS.hasOwnProperty(k)) {
          throw Error(`attempt to set aws property ${k} missing from defaults`);
        }
      });
      return Object.assign({}, state, action.payload);
    default:
      return state;
    }
  },

  // The user's intentions for their cluster
  clusterConfig: (state, action) => {
    if (!state) {
      return DEFAULT_CLUSTER_CONFIG;
    }

    switch (action.type) {
    case configActionTypes.RESET:
      return {};
    case configActionTypes.SET:
      Object.keys(action.payload).forEach(k => {
        if (!DEFAULT_CLUSTER_CONFIG.hasOwnProperty(k)) {
          throw Error(`attempt to set cluster property ${k} missing from defaults`);
        }
      });
      return Object.assign({}, state, action.payload);

    case configActionTypes.BATCH_SET_IN: {
      let object = fromJS(state);
      action.payload.forEach(batch => {
        const [path, value] = batch;
        const array = _.isString(path) ? path.split('.') : path;
        object = object.setIn(array, value);
      });
      return object.toJS();
    }

    // Adds a value at a given path or no-op if a value already exists for the path
    case configActionTypes.ADD_IN:
      return _.isEmpty(_.get(state, action.payload.path))
        ? setIn(state, action.payload.path, action.payload.value)
        : state;

    case configActionTypes.SET_IN:
      return setIn(state, action.payload.path, action.payload.value);

    case configActionTypes.MERGE:
      return fromJS(state).mergeDeep(action.payload).toJS();

    case configActionTypes.APPEND: {
      const length = _.get(state, action.payload.path).length;
      const path = `${action.payload.path}.${length}`;
      return setIn(state, path, action.payload.value);
    }

    case configActionTypes.REMOVE_FIELD_LIST_ROW: {
      const {fieldListId, index} = action.payload;
      return fromJS(state).deleteIn([fieldListId, index]).toJS();
    }
    default:
      return state;
    }
  },

  // Errors resulting from server states, user uploads, network issues, or other transient phenomena
  eventErrors: (state, action) => {
    if (!state) {
      return {};
    }

    switch (action.type) {
    case eventErrorsActionTypes.ERROR:
      return Object.assign({}, state, {
        [action.payload.name]: action.payload.error,
      });
    default:
      return state;
    }
  },

  // Facts the server knows at load time, that we have to get asynchronously
  serverFacts: (state, action) => {
    if (state === undefined) {
      return {
        loaded: false,
        error: null,
      };
    }

    switch (action.type) {
    case loadFactsActionTypes.LOADED:
      return Object.assign({}, action.payload, {
        loaded: true,
        error: null,
      });
    case loadFactsActionTypes.ERROR:
      return {
        loaded: true,
        error: action.payload,
      };
    default:
      return state;
    }
  },

  // The status of the cluster
  cluster: (state, action) => {
    if (!state) {
      return {
        loaded: false,
        ready: false,
        error: null,
        status: null,
      };
    }

    switch (action.type) {
    case clusterReadyActionTypes.NOT_READY:
      return Object.assign({}, state, {
        loaded: true,
        ready: false,
        status: null,
      });
    case clusterReadyActionTypes.STATUS:
      return Object.assign({}, state, {
        loaded: true,
        ready: true,
        status: action.payload,
        error: null,
      });
    case clusterReadyActionTypes.ERROR:
      return Object.assign({}, state, {
        loaded: true,
        error: action.payload,
      });
    default:
      return state;
    }
  },

  // Stores the "dirtiness" of UI fields
  dirty: (state, action) => {
    if (!state) {
      return {};
    }

    switch (action.type) {
    case configActionTypes.REMOVE_FIELD_LIST_ROW: {
      const {fieldListId, index} = action.payload;
      return fromJS(state).deleteIn([fieldListId, index]).toJS();
    }
    case dirtyActionTypes.ADD: {
      // {awsTags: [{key: true}]
      const split = action.payload.split('.')
        .map(s => {
          const int = parseInt(s, 10);
          return isNaN(int) ? s : int;
        });
      // mirror structure of clusterconfig for storing field dirtiness
      const obj = _.cloneDeep(state);
      let s = split[0];
      let current = obj;
      for (let i = 1; i < split.length; ++i) {
        if (!_.has(current, s) || current[s] === null) {
          current[s] = _.isInteger(split[i]) ? [] : {};
        }
        current = current[s];
        s = split[i];
      }
      current[s] = true;
      return obj;
    }
    case dirtyActionTypes.CLEAN: {
      const array = _.isString(action.payload) ? action.payload.split('.') : action.payload;
      return fromJS(state).deleteIn(array).toJS();
    }
    default:
      return state;
    }
  },
});

// Shim for tests
export const reducer = (state, action) => {
  let restored;
  switch (action.type) {
  case restoreActionTypes.RESTORE_STATE:
    restored = Object.assign({}, action.payload, {
      serverFacts: state.serverFacts,
      cluster: state.cluster,
    });
    restored.aws = _.defaults(restored.aws, DEFAULT_AWS);
    if (restored.clusterConfig) {
      restored.clusterConfig = _.defaults(restored.clusterConfig, DEFAULT_CLUSTER_CONFIG);
    }
    break;
  default:
    restored = state;
  }

  return reducersTogether(restored, action);
};

// Returns only the bits of state that should be saved and restored
export const savable = (state) => {
  const {dirty, clusterConfig} = state;
  return {dirty, clusterConfig: _.omit(clusterConfig, ['error', 'extra', 'extraError', 'extraInFly', 'inFly'])};
};
<|endoftext|>