<commit_before>describe('dataservice', function () {
    var $controller,
        dataservice,
        $httpBackend,
        $location,
        $q,
        $rootScope,
        $route,
        scope,
        toastr,
        mocks = {};

    beforeEach(function () {
        module('app', fakeLogger);
        inject(function (_$controller_, _$httpBackend_, _$location_, _$q_, _$rootScope_, _$route_, _dataservice_, _toastr_) {
            $controller = _$controller_;
            $httpBackend = _$httpBackend_;
            $location = _$location_;
            $q = _$q_;
            $rootScope = _$rootScope_;
            $route = _$route_;
            dataservice = _dataservice_;
            toastr = _toastr_;
        });
    });

    beforeEach(function () {
        $httpBackend.when('GET', 'app/dashboard/dashboard.html').respond(200);
        $httpBackend.flush();

        mocks.maaData = [{
            data: { results: testctx.getMockAvengers() }
        }];
        // sinon.stub(dataservice, 'getAvengers', function () {
        //     var deferred = $q.defer();
        //     deferred.resolve(testctx.getMockAvengers());
        //     return deferred.promise;
        // });
    });

    it("should be registered", function() {
      expect(dataservice).not.to.equal(null);
    });

    describe('getAvengers function', function () {
        it('should return 5 Avengers', function (done) {
            $httpBackend.when('GET', '/api/maa').respond(200, mocks.maaData);
            dataservice.getAvengers().then(function(data) {
                expect(data.length).to.equal(5);
                done();
            })
            $rootScope.$apply();
            $httpBackend.flush();
        });

        it('should contain Black Widow', function (done) {
            $httpBackend.when('GET', '/api/maa').respond(200, mocks.maaData);
            dataservice.getAvengers().then(function(data) {
                var hasBlackWidow = data.some(function isPrime(element, index, array) {
                    return element.name.indexOf('Black Widow') >= 0;
                });
                expect(hasBlackWidow).to.be.true;
                done();
            })
            $rootScope.$apply();
            $httpBackend.flush();
        });
    });

    describe('getAvengerCount function', function () {
        it('should return 11 Avengers', function (done) {
            dataservice.getAvengerCount().then(function(count) {
                expect(count).to.equal(11);
                done();
            })
            $rootScope.$apply();
        });
    });

    describe('getAvengersCast function', function () {
        it('should return 11 Avengers', function (done) {
            dataservice.getAvengersCast().then(function(data) {
                expect(data.length).to.equal(11);
                done();
            })
            $rootScope.$apply();
        });

        it('should contain Natasha', function (done) {
            dataservice.getAvengersCast().then(function(data) {
                var hasBlackWidow = data.some(function isPrime(element, index, array) {
                    return element.character.indexOf('Natasha') >= 0;
                });
                expect(hasBlackWidow).to.be.true;
                done();
            })
            $rootScope.$apply();
        });
    });

    describe('ready function', function () {
        it('should return a resolved promise', function (done) {
            dataservice.ready()
            .then(function(data) {
                expect(true).to.be.true;
                done();
            }, function(data){
                expect('promise rejected').to.be.true;
                done();
            });
            $rootScope.$apply();
        });
    });

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });
});<commit_msg>modular: unit tests to check that dataservice functions exist<commit_after>describe('dataservice', function () {
    var $controller,
        dataservice,
        $httpBackend,
        $location,
        $q,
        $rootScope,
        $route,
        scope,
        toastr,
        mocks = {};

    beforeEach(function () {
        module('app', fakeLogger);
        inject(function (_$controller_, _$httpBackend_, _$location_, _$q_, _$rootScope_, _$route_, _dataservice_, _toastr_) {
            $controller = _$controller_;
            $httpBackend = _$httpBackend_;
            $location = _$location_;
            $q = _$q_;
            $rootScope = _$rootScope_;
            $route = _$route_;
            dataservice = _dataservice_;
            toastr = _toastr_;
        });
    });

    beforeEach(function () {
        $httpBackend.when('GET', 'app/dashboard/dashboard.html').respond(200);
        $httpBackend.flush();

        mocks.maaData = [{
            data: { results: testctx.getMockAvengers() }
        }];
        // sinon.stub(dataservice, 'getAvengers', function () {
        //     var deferred = $q.defer();
        //     deferred.resolve(testctx.getMockAvengers());
        //     return deferred.promise;
        // });
    });

    it('should be registered', function() {
      expect(dataservice).not.to.equal(null);
    });

    describe('getAvengers function', function () {
        it('should exist', function () {
            expect(dataservice.getAvengers).not.to.equal(null);
        });

        it('should return 5 Avengers', function (done) {
            $httpBackend.when('GET', '/api/maa').respond(200, mocks.maaData);
            dataservice.getAvengers().then(function(data) {
                expect(data.length).to.equal(5);
                done();
            })
            $rootScope.$apply();
            $httpBackend.flush();
        });

        it('should contain Black Widow', function (done) {
            $httpBackend.when('GET', '/api/maa').respond(200, mocks.maaData);
            dataservice.getAvengers().then(function(data) {
                var hasBlackWidow = data.some(function isPrime(element, index, array) {
                    return element.name.indexOf('Black Widow') >= 0;
                });
                expect(hasBlackWidow).to.be.true;
                done();
            })
            $rootScope.$apply();
            $httpBackend.flush();
        });
    });

    describe('getAvengerCount function', function () {
        it('should exist', function () {
            expect(dataservice.getAvengerCount).not.to.equal(null);
        });

        it('should return 11 Avengers', function (done) {
            dataservice.getAvengerCount().then(function(count) {
                expect(count).to.equal(11);
                done();
            })
            $rootScope.$apply();
        });
    });

    describe('getAvengersCast function', function () {
        it('should exist', function () {
            expect(dataservice.getAvengersCast).not.to.equal(null);
        });

        it('should return 11 Avengers', function (done) {
            dataservice.getAvengersCast().then(function(data) {
                expect(data.length).to.equal(11);
                done();
            })
            $rootScope.$apply();
        });

        it('should contain Natasha', function (done) {
            dataservice.getAvengersCast()
                .then(function(data) {
                    var hasBlackWidow = data.some(function isPrime(element, index, array) {
                        return element.character.indexOf('Natasha') >= 0;
                    });
                    expect(hasBlackWidow).to.be.true;
                    done();
                })
            $rootScope.$apply();
        });
    });

    describe('ready function', function () {
        it('should exist', function () {
            expect(dataservice.ready).not.to.equal(null);
        });

        it('should return a resolved promise', function (done) {
            dataservice.ready()
                .then(function(data) {
                    expect(true).to.be.true;
                    done();
                }, function(data){
                    expect('promise rejected').to.be.true;
                    done();
                });
            $rootScope.$apply();
        });
    });

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });
});<|endoftext|>


<commit_before>Template.residentFeelings.onCreated(function () {
  // Get reference to template instance
  const templateInstance = this;

  // Get resident ID from template instance
  const residentId = templateInstance.data.residentId;

  // Subscribe to count of resident feelings
  // Used to trigger call to 'get resident feelings percentages' method
  // TODO: figure out a 'cleaner' way to signal that feelings data have changed
  // https://forums.meteor.com/t/send-reactive-signal-from-server-to-client/39141
  templateInstance.subscribe('residentFeelingsCount', residentId);

  // Set up reactive variable to hold resident feelings percentages
  templateInstance.residentFeelingsPercentages = new ReactiveVar();

  // Reactively fetch resident feelings percentages from server
  // by using 'resident ID feelings count' to trigger a call to 'get resident feelings percentages' method
  // TODO: figure out a 'cleaner' way to signal that feelings data have changed
  // https://forums.meteor.com/t/send-reactive-signal-from-server-to-client/39141
  templateInstance.autorun(() => {
    // Get resident feelings
    const feelingsCount = Counts.get(`resident_${ residentId }_feelings_count`);

    // Get resident feelings percentages when feelings count changes
    Meteor.call('getFeelingsPercentagesByResidentId', residentId, function (error, residentFeelingsPercentages) {
      // Update resident feelings counts with returned value from method call
      templateInstance.residentFeelingsPercentages.set(residentFeelingsPercentages);
    });
  });

  /*
  Template helper methods
  */

  // Method to clear and render chart
  templateInstance.clearAndRenderChart = function (chartData) {
    // Clear any previous chart
    this.$('#residentFeelingsChart').empty();

    // Render chart with current feeling percentages
    MG.data_graphic({
      title: TAPi18n.__('residentFeelings-chart-title'),
      data: chartData,
      chart_type: 'bar',
      x_accessor: 'value',
      format: 'percentage',
      xax_format: d3.format('.0%'),
      y_accessor: 'localizedFeeling',
      height:300,
      full_width: true,
      target: '#residentFeelingsChart',
    });
  };

  templateInstance.localizeChartData = function (chartData) {
    // Create localized data for chart
    const localizedChartData = _.map(chartData, function (datum) {
      // Get feeling
      const feeling = datum.key;

      // Get localization string for feeling
      const feelingL10n = TAPi18n.__(`residentFeelings-chart-feelingName-${ feeling }`);

      // Update feeling with localized name
      datum.localizedFeeling = feelingL10n;

      return datum;
    });

    return localizedChartData
  };
});

Template.residentFeelings.onRendered(function () {
  // Get reference to template instance
  const templateInstance = this;

  templateInstance.autorun(() => {
    // Get resident feelings percentages
    const residentFeelingsPercentages = templateInstance.residentFeelingsPercentages.get();

    // Make sure resident feelings percentages data is available
    if (residentFeelingsPercentages) {
      // Sort feelings percentages
      const sortedResidentFeelingsPercentages = residentFeelingsPercentages.sort(function (a, b) {
        // Sort from high to low
        return b.value - a.value;
      });

      // Create localized data for chart
      const localizedChartData = templateInstance.localizeChartData(sortedResidentFeelingsPercentages);

      // Render chart with localized data
      templateInstance.clearAndRenderChart(localizedChartData);
    }
  });
});

Template.residentFeelings.helpers({
  residentFeelingsCount () {
    // Get reference to template instance
    const templateInstance = Template.instance();

    // Return value of resident feelings percentages reactive variable
    return templateInstance.residentFeelingsPercentages.get();
  }
});
<commit_msg>Clarify comment<commit_after>Template.residentFeelings.onCreated(function () {
  // Get reference to template instance
  const templateInstance = this;

  // Get resident ID from template instance
  const residentId = templateInstance.data.residentId;

  // Subscribe to count of resident feelings
  // Used to trigger call to 'get resident feelings percentages' method
  // TODO: figure out a 'cleaner' way to signal that feelings data have changed
  // https://forums.meteor.com/t/send-reactive-signal-from-server-to-client/39141
  templateInstance.subscribe('residentFeelingsCount', residentId);

  // Set up reactive variable to hold resident feelings percentages
  templateInstance.residentFeelingsPercentages = new ReactiveVar();

  // Reactively fetch resident feelings percentages from server
  // by using 'resident ID feelings count' to trigger a call to 'get resident feelings percentages' method
  // TODO: figure out a 'cleaner' way to signal that feelings data have changed
  // https://forums.meteor.com/t/send-reactive-signal-from-server-to-client/39141
  templateInstance.autorun(() => {
    // Get resident feelings count
    // This is just a reactive trigger to fetch resident feelings percentages
    const feelingsCount = Counts.get(`resident_${ residentId }_feelings_count`);

    // Get resident feelings percentages when feelings count changes
    Meteor.call('getFeelingsPercentagesByResidentId', residentId, function (error, residentFeelingsPercentages) {
      // Update resident feelings counts with returned value from method call
      templateInstance.residentFeelingsPercentages.set(residentFeelingsPercentages);
    });
  });

  /*
  Template helper methods
  */

  // Method to clear and render chart
  templateInstance.clearAndRenderChart = function (chartData) {
    // Clear any previous chart
    this.$('#residentFeelingsChart').empty();

    // Render chart with current feeling percentages
    MG.data_graphic({
      title: TAPi18n.__('residentFeelings-chart-title'),
      data: chartData,
      chart_type: 'bar',
      x_accessor: 'value',
      format: 'percentage',
      xax_format: d3.format('.0%'),
      y_accessor: 'localizedFeeling',
      height:300,
      full_width: true,
      target: '#residentFeelingsChart',
    });
  };

  templateInstance.localizeChartData = function (chartData) {
    // Create localized data for chart
    const localizedChartData = _.map(chartData, function (datum) {
      // Get feeling
      const feeling = datum.key;

      // Get localization string for feeling
      const feelingL10n = TAPi18n.__(`residentFeelings-chart-feelingName-${ feeling }`);

      // Update feeling with localized name
      datum.localizedFeeling = feelingL10n;

      return datum;
    });

    return localizedChartData
  };
});

Template.residentFeelings.onRendered(function () {
  // Get reference to template instance
  const templateInstance = this;

  templateInstance.autorun(() => {
    // Get resident feelings percentages
    const residentFeelingsPercentages = templateInstance.residentFeelingsPercentages.get();

    // Make sure resident feelings percentages data is available
    if (residentFeelingsPercentages) {
      // Sort feelings percentages
      const sortedResidentFeelingsPercentages = residentFeelingsPercentages.sort(function (a, b) {
        // Sort from high to low
        return b.value - a.value;
      });

      // Create localized data for chart
      const localizedChartData = templateInstance.localizeChartData(sortedResidentFeelingsPercentages);

      // Render chart with localized data
      templateInstance.clearAndRenderChart(localizedChartData);
    }
  });
});

Template.residentFeelings.helpers({
  residentFeelingsCount () {
    // Get reference to template instance
    const templateInstance = Template.instance();

    // Return value of resident feelings percentages reactive variable
    return templateInstance.residentFeelingsPercentages.get();
  }
});
<|endoftext|>


<commit_before>import { updateApp } from "./update-app";

import {
    GREY_EDGES_DASHED_MENU,
    GREY_EDGES_DASHED_SIDEBAR,
    SET_NORMALIZATION_SIDEBAR,
    SET_NORMALIZATION_MENU,
    RESET_NORMALIZATION_MENU,
    RESET_NORMALIZATION_SIDEBAR,
    GREY_EDGE_THRESHOLD_MENU,
    GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR,
    WEIGHTS_SHOW_MOUSE_OVER_CLASS,
    WEIGHTS_SHOW_ALWAYS_CLASS,
    WEIGHTS_HIDE_CLASS,
    SHOW_WEIGHTS_MOUSEOVER,
    SHOW_ALL_WEIGHTS,
    HIDE_ALL_WEIGHTS,
    LOCK_SLIDERS_BUTTON,
    LOCK_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_CLASS,
    RESET_SLIDERS_CLASS,
    RESET_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_MENU,
    GRID_LAYOUT_BUTTON,
    GRID_LAYOUT_CLASS,
    FORCE_GRAPH_CLASS,
    NODE_COLORING_TOGGLE_CLASS,
    AVG_REPLICATE_VALS_TOP_MENU,
    AVG_REPLICATE_VALS_TOP_SIDEBAR,
    AVG_REPLICATE_VALS_BOTTOM_MENU,
    AVG_REPLICATE_VALS_BOTTOM_SIDEBAR,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON,
    LOG_FOLD_CHANGE_MAX_VALUE_MENU,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT,
    TOP_DATASET_SELECTION_SIDEBAR,
    BOTTOM_DATASET_SELECTION_SIDEBAR,
    TOP_DATASET_SELECTION_MENU,
    BOTTOM_DATASET_SELECTION_MENU,
} from "./constants";

import { setupLoadAndImportHandlers } from "./setup-load-and-import-handlers";

export const setupHandlers = grnState => {
    setupLoadAndImportHandlers(grnState);

    $(GREY_EDGES_DASHED_SIDEBAR).change(() => {
        grnState.dashedLine = $(GREY_EDGES_DASHED_SIDEBAR).prop("checked");
        updateApp(grnState);
    });

    $(GREY_EDGES_DASHED_MENU).click(() => {
        grnState.dashedLine = !$(GREY_EDGES_DASHED_MENU).prop("checked");
        updateApp(grnState);
    });

    $(SET_NORMALIZATION_MENU).change(() => {
        grnState.normalizationMax = $(SET_NORMALIZATION_MENU).val();
        updateApp(grnState);
    });

    $(SET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = $(SET_NORMALIZATION_SIDEBAR).val();
        updateApp(grnState);
    });

    $(RESET_NORMALIZATION_MENU, RESET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = grnState.resetNormalizationMax;
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_MENU).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_MENU).val());
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).val() * 100);
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_MOUSE_OVER_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_WEIGHTS_MOUSEOVER;
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_ALWAYS_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $(WEIGHTS_HIDE_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = HIDE_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $("#colorEdges").click(() => {
        grnState.colorOptimal = true;
        updateApp(grnState);
    });

    $("#blackEdges").click(() => {
        grnState.colorOptimal = false;
        updateApp(grnState);
    });

// Sliders code
    $(LOCK_SLIDERS_MENU_OPTION).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });
    $(LOCK_SLIDERS_BUTTON).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_CLASS).click(() => {
        grnState.resetTriggered = true;
        grnState.undoResetTriggered = false;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_CLASS).click(() => {
        grnState.resetTriggered = false;
        grnState.undoResetTriggered = true;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_MENU_OPTION).click(() => {
        grnState.resetTriggered = false;
        grnState.undoResetTriggered = true;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_MENU).click(() => {
        grnState.resetTriggered = true;
        grnState.undoResetTriggered = false;
        updateApp(grnState);
    });

// Grid buttons
    $(GRID_LAYOUT_BUTTON).click(() => {
        if (grnState.graphLayout === "FORCE_GRAPH") {
            grnState.graphLayout = "GRID_LAYOUT";
            grnState.slidersLocked === true;
        } else if (grnState.graphLayout === "GRID_LAYOUT") {
            grnState.graphLayout = "FORCE_GRAPH";
            grnState.slidersLocked === false;
        }
        updateApp(grnState);
    });

    $(FORCE_GRAPH_CLASS).click(() => {
        grnState.graphLayout = "FORCE_GRAPH";
        updateApp(grnState);

    });

    $(GRID_LAYOUT_CLASS).click(() => {
        grnState.graphLayout = "GRID_LAYOUT";
        updateApp(grnState);
    });

// Node Coloring
    $(NODE_COLORING_TOGGLE_CLASS).click(() => {
        grnState.nodeColoring.nodeColoringEnabled = !grnState.nodeColoring.nodeColoringEnabled;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_SIDEBAR).change(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_MENU).click(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_SIDEBAR).change(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_MENU).click(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON).click(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).change(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(TOP_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(BOTTOM_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (grnState.nodeColoring.bottomDataset === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (selection === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });
};
<commit_msg>handlers<commit_after>import { updateApp } from "./update-app";

import {
    SET_NORMALIZATION_SIDEBAR,
    SET_NORMALIZATION_MENU,
    RESET_NORMALIZATION_SIDEBAR,
    RESET_NORMALIZATION_MENU,
    GREY_EDGES_DASHED_MENU,
    GREY_EDGES_DASHED_SIDEBAR,
    GREY_EDGE_THRESHOLD_MENU,
    GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR,
    WEIGHTS_SHOW_MOUSE_OVER_CLASS,
    WEIGHTS_SHOW_ALWAYS_CLASS,
    WEIGHTS_HIDE_CLASS,
    SHOW_WEIGHTS_MOUSEOVER,
    SHOW_ALL_WEIGHTS,
    HIDE_ALL_WEIGHTS,
    COLOR_EDGES,
    BLACK_EDGES,
    LINK_DIST_SLIDER_ID,
    LINK_DIST_MENU,
    CHARGE_SLIDER_ID,
    CHARGE_MENU,
    CHARGE_DEFAULT_VALUE,
    LINK_DIST_DEFAULT_VALUE,
    LOCK_SLIDERS_BUTTON,
    LOCK_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_CLASS,
    RESET_SLIDERS_CLASS,
    RESET_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_MENU,
    GRID_LAYOUT_BUTTON,
    GRID_LAYOUT_CLASS,
    FORCE_GRAPH_CLASS,
    NODE_COLORING_TOGGLE_CLASS,
    AVG_REPLICATE_VALS_TOP_MENU,
    AVG_REPLICATE_VALS_TOP_SIDEBAR,
    AVG_REPLICATE_VALS_BOTTOM_MENU,
    AVG_REPLICATE_VALS_BOTTOM_SIDEBAR,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON,
    LOG_FOLD_CHANGE_MAX_VALUE_MENU,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT,
    TOP_DATASET_SELECTION_SIDEBAR,
    BOTTOM_DATASET_SELECTION_SIDEBAR,
    TOP_DATASET_SELECTION_MENU,
    BOTTOM_DATASET_SELECTION_MENU,
} from "./constants";

import { setupLoadAndImportHandlers } from "./setup-load-and-import-handlers";

export const setupHandlers = grnState => {
    setupLoadAndImportHandlers(grnState);

    $(SET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = $("#normalization-max").val();
        updateApp(grnState);
    });

    $(SET_NORMALIZATION_MENU).change(() => {
        grnState.normalizationMax = $(SET_NORMALIZATION_MENU).val();
        updateApp(grnState);
    });

    $(RESET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = grnState.resetNormalizationMax;
        updateApp(grnState);
    });

    $(RESET_NORMALIZATION_MENU).click(() => {
        grnState.normalizationMax = grnState.resetNormalizationMax;
        updateApp(grnState);
    });

    $(GREY_EDGES_DASHED_SIDEBAR).change(() => {
        grnState.dashedLine = $(GREY_EDGES_DASHED_SIDEBAR).prop("checked");
        updateApp(grnState);
    });

    $(GREY_EDGES_DASHED_MENU).click(() => {
        grnState.dashedLine = !$(GREY_EDGES_DASHED_MENU).prop("checked");
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_MENU).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_MENU).val());
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).val() * 100);
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_MOUSE_OVER_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_WEIGHTS_MOUSEOVER;
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_ALWAYS_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $(WEIGHTS_HIDE_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = HIDE_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $(COLOR_EDGES).click(() => {
        grnState.colorOptimal = true;
        updateApp(grnState);
    });

    $(BLACK_EDGES).click(() => {
        grnState.colorOptimal = false;
        updateApp(grnState);
    });

// Sliders Code
    var valueValidator = (min, max, value) => {
        return Math.min(max, Math.max(min, value));
    };

    var linkDistValidator = value => {
        return valueValidator(1, 1000, value);
    };

    var chargeValidator = value => {
        return valueValidator(-2000, 0, value);
    };

    $(LINK_DIST_MENU).change(() => {
        var value = linkDistValidator($(LINK_DIST_MENU).val());
        grnState.linkDistanceSlider.currentVal = value;
        updateApp(grnState);
    });

    $(LINK_DIST_SLIDER_ID).change(() => {
        var value = linkDistValidator($(LINK_DIST_SLIDER_ID).val());
        grnState.linkDistanceSlider.currentVal = value;
        updateApp(grnState);
    });

    $(CHARGE_MENU).change(() => {
        var value = chargeValidator($(CHARGE_MENU).val());
        grnState.chargeSlider.currentVal = value;
        updateApp(grnState);
    });

    $(CHARGE_SLIDER_ID).change(() => {
        var value = chargeValidator($(CHARGE_SLIDER_ID).val());
        grnState.chargeSlider.currentVal = value;
        updateApp(grnState);
    });

    $(LOCK_SLIDERS_MENU_OPTION).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });

    $(LOCK_SLIDERS_BUTTON).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_CLASS).click(() => {
        grnState.chargeSlider.backup = grnState.chargeSlider.currentVal;
        grnState.linkDistanceSlider.backup = grnState.linkDistanceSlider.currentVal;
        grnState.chargeSlider.currentVal = CHARGE_DEFAULT_VALUE;
        grnState.linkDistanceSlider.currentVal = LINK_DIST_DEFAULT_VALUE;
        grnState.showUndoReset = true;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_MENU_OPTION).click(() => {
        grnState.chargeSlider.backup = grnState.chargeSlider.currentVal;
        grnState.linkDistanceSlider.backup = grnState.linkDistanceSlider.currentVal;
        grnState.chargeSlider.currentVal = CHARGE_DEFAULT_VALUE;
        grnState.linkDistanceSlider.currentVal = LINK_DIST_DEFAULT_VALUE;
        grnState.showUndoReset = true;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_CLASS).click(() => {
        grnState.chargeSlider.currentVal = grnState.chargeSlider.backup;
        grnState.linkDistanceSlider.currentVal = grnState.linkDistanceSlider.backup ;
        grnState.showUndoReset = false;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_MENU).click(() => {
        grnState.chargeSlider.currentVal = grnState.chargeSlider.backup;
        grnState.linkDistanceSlider.currentVal = grnState.linkDistanceSlider.backup ;
        grnState.showUndoReset = false;
        updateApp(grnState);
    });

// Grid buttons
    $(GRID_LAYOUT_BUTTON).click(() => {
        if (grnState.graphLayout === "FORCE_GRAPH") {
            grnState.graphLayout = "GRID_LAYOUT";
            grnState.slidersLocked = true;
        } else if (grnState.graphLayout === "GRID_LAYOUT") {
            grnState.graphLayout = "FORCE_GRAPH";
            grnState.slidersLocked = false;
        }
        updateApp(grnState);
    });

    $(FORCE_GRAPH_CLASS).click(() => {
        grnState.graphLayout = "FORCE_GRAPH";
        grnState.slidersLocked = false;
        updateApp(grnState);

    });

    $(GRID_LAYOUT_CLASS).click(() => {
        grnState.graphLayout = "GRID_LAYOUT";
        grnState.slidersLocked = true;
        updateApp(grnState);
    });

// Node Coloring
    $(NODE_COLORING_TOGGLE_CLASS).click(() => {
        grnState.nodeColoring.nodeColoringEnabled = !grnState.nodeColoring.nodeColoringEnabled;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_SIDEBAR).change(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_MENU).click(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_SIDEBAR).change(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_MENU).click(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON).click(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).change(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(TOP_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(BOTTOM_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (grnState.nodeColoring.bottomDataset === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (selection === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });
};
<|endoftext|>


<commit_before>/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */if(!Koowa)var Koowa={};Function.prototype.bind||(Function.prototype.bind=function(e){if(typeof this!="function")throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var t=Array.prototype.slice.call(arguments,1),n=this,r=function(){},i=function(){return n.apply(this instanceof r&&e?this:e,t.concat(Array.prototype.slice.call(arguments)))};return r.prototype=this.prototype,i.prototype=new r,i}),function(e){!function(e,t,n){typeof define=="function"?define(n):t[e]=n()}("klass",this,function(){function s(e){return f.call(o(e)?e:function(){},e,1)}function o(e){return typeof e===n}function u(e,t,n){return function(){var r=this.supr;this.supr=n[i][e];var s={}.fabricatedUndefined,o=s;try{o=t.apply(this,arguments)}finally{this.supr=r}return o}}function a(e,t,n){for(var s in t)t.hasOwnProperty(s)&&(e[s]=o(t[s])&&o(n[i][s])&&r.test(t[s])?u(s,t[s],n):t[s])}function f(e,t){function n(){}function c(){this.initialize?this.initialize.apply(this,arguments):(t||u&&r.apply(this,arguments),f.apply(this,arguments))}n[i]=this[i];var r=this,s=new n,u=o(e),f=u?e:this,l=u?{}:e;return c.methods=function(e){return a(s,e,r),c[i]=s,this},c.methods.call(c,l).prototype.constructor=c,c.extend=arguments.callee,c[i].implement=c.statics=function(e,t){return e=typeof e=="string"?function(){var n={};return n[e]=t,n}():e,a(this,e,r),this},c}var e=this,t=e.klass,n="function",r=/xyz/.test(function(){xyz})?/\bsupr\b/:/.*/,i="prototype";return s.noConflict=function(){return e.klass=t,this},s}),e(function(){e(".submittable").on("click.koowa",function(t){t.preventDefault(),(new Koowa.Form(e(t.target).data("config"))).submit()}),e(".-koowa-grid").each(function(){new Koowa.Controller.Grid({form:this})}),e(".-koowa-form").each(function(){new Koowa.Controller.Form({form:this})})}),Koowa.Class=klass({options:{},getOptions:function(){return{}},initialize:function(){this.setOptions(this.getOptions())},setOptions:function(t){return typeof t=="object"&&(this.options=e.extend(!0,{},this.options,t)),this}}),Koowa.Form=Koowa.Class.extend({initialize:function(t){this.config=t,this.config.element?this.form=e(document[this.config.element]):(this.form=e("<form/>",{name:"dynamicform",method:this.config.method||"POST",action:this.config.url}),e(document.body).append(this.form))},addField:function(t,n){var r=e("<input/>",{name:t,value:n,type:"hidden"});return r.appendTo(this.form),this},submit:function(){var t=this;this.config.params&&e.each(this.config.params,function(e,n){t.addField(e,n)}),this.form.submit()}}),Koowa.Grid=Koowa.Class.extend({initialize:function(t){var n=this;this.element=e(t),this.form=this.element.is("form")?this.element:this.element.closest("form"),this.toggles=this.element.find(".-koowa-grid-checkall"),this.checkboxes=this.element.find(".-koowa-grid-checkbox").filter(function(t,n){return!e(n).prop("disabled")}),this.checkboxes.length||this.toggles.prop("disabled",!0),this.toggles.on("change.koowa",function(t,r){r||n.checkAll(e(this).prop("checked"))}),this.checkboxes.on("change.koowa",function(e,t){t||n.setCheckAll()})},checkAll:function(t){var n=this.checkboxes.filter(function(n,r){return e(r).prop("checked")!==t});this.checkboxes.prop("checked",t),n.trigger("change",!0)},uncheckAll:function(){this.checkAll(!1)},setCheckAll:function(){var t=this.checkboxes.filter(function(t,n){return e(n).prop("checked")!==!1}).length;this.toggles.prop("checked",this.checkboxes.length===t),this.toggles.trigger("change",!0)}}),Koowa.Grid.getAllSelected=function(t){return e(".-koowa-grid-checkbox:checked",t)},Koowa.Grid.getIdQuery=function(e){return decodeURIComponent(this.getAllSelected(e).serialize())},Koowa.Controller=Koowa.Class.extend({form:null,toolbar:null,buttons:null,token_name:null,token_value:null,getOptions:function(){return e.extend(this.supr(),{toolbar:".koowa-toolbar",url:window.location.href})},initialize:function(t){var n=this;this.supr(),this.setOptions(t),this.form=e(this.options.form),this.setOptions(this.form.data()),this.form.prop("action")&&(this.options.url=this.form.attr("action")),this.toolbar=e(this.options.toolbar),this.form.data("controller",this),this.on("execute",function(){return n.execute.apply(n,arguments)}),this.token_name=this.form.data("token-name"),this.token_value=this.form.data("token-value"),this.toolbar&&this.setToolbar()},setToolbar:function(){var t=this;this.buttons=this.toolbar.find(".toolbar[data-action]"),this.buttons.each(function(){var n=e(this),r={},i=n.data(),s=i.data;if(i.eventAdded)return;typeof s!="object"&&(s=s&&e.type(s)==="string"?e.parseJSON(s):{}),t.token_name&&(s[t.token_name]=t.token_value),r.validate=i.novalidate!=="novalidate",r.data=s,r.action=i.action,n.on("click.koowa",function(e){e.preventDefault(),r.trigger=n;if(!n.hasClass("disabled")){var s=n.data("prompt");if(s&&!confirm(s))return;t.setOptions(i),t.trigger("execute",[r])}}),n.data("event-added",!0)})},execute:function(e,t){var n=t.action[0].toUpperCase()+t.action.substr(1),r="_action"+n;return typeof t.validate=="undefined"&&(t.validate=!0),this.trigger("before"+n,t)&&(r=this[r]?r:"_actionDefault",this[r].call(this,t),this.trigger("after"+n,t)),this},on:function(e,t){return this.form.on("koowa:"+e,t)},off:function(e,t){return this.form.off("koowa:"+e,t)},trigger:function(t,n){var r=e.Event("koowa:"+t);return this.form.trigger(r,n),!r.isDefaultPrevented()},checkValidity:function(){var e;this.buttons&&(this.trigger("beforeValidate"),e=this.buttons.filter('[data-novalidate!="novalidate"]'),this.trigger("validate")?e.removeClass("disabled"):e.addClass("disabled"),this.trigger("afterValidate"))}}),Koowa.Controller.Grid=Koowa.Controller.extend({getOptions:function(){return e.extend(this.supr(),{inputs:".-koowa-grid-checkbox, .-koowa-grid-checkall",ajaxify:!1})},initialize:function(e){var t,n=this;this.supr(e),this.grid=new Koowa.Grid(this.form),this.on("validate",this.validate),this.options.inputs&&this.buttons&&(this.checkValidity(),this.form.find(this.options.inputs).on("change.koowa",function(e,t){t||n.checkValidity()})),this.token_name=this.form.data("token-name"),this.token_value=this.form.data("token-value"),this.setTableHeaders(),this.setTableRows(),this.form.find("thead select, tfoot select").on("change.koowa",function(){n.grid.uncheckAll(),n.options.ajaxify&&(event.preventDefault(),n.options.transport(n.options.url,n.form.serialize(),"get")),n.form.submit()})},setTableHeaders:function(){this.form.find("thead tr > *").each(function(){var t=e(this),n=t.find("a"),r=t.find(".-koowa-grid-checkall");if(n.length)return t.on("click.koowa",function(e){if(e.target!=t[0])return;n.prop("href")?window.location.href=n.prop("href"):n.trigger("click",e)}),n.hasClass("-koowa-asc")?t.addClass("-koowa-asc"):n.hasClass("-koowa-desc")&&t.addClass("-koowa-desc"),this;r.length&&t.on("click.koowa",function(e){if(e.target!=t[0])return!0;r.prop("checked",r.is(":checked")?!1:!0).trigger("change")}),t.addClass("void")})},setTableRows:function(){var t=this,n=this.form.find("tbody tr .-koowa-grid-checkbox");this.form.find("tbody tr").each(function(){var r=e(this),i=r.find(".-koowa-grid-checkbox");if(r.data("readonly")==1||!i.length)return;r.on("click.koowa",function(t){var n=e(t.target);if(n.is("[type=radio], [type=checkbox], a[href]"))return;i.prop("checked",!i.prop("checked")).trigger("change")}),i.on("change.koowa",function(){var t,n=r.parent();e(this).is("[type=radio]")&&n.find(".selected").removeClass("selected"),e(this).prop("checked")?r.addClass("selected"):r.removeClass("selected"),t=r.hasClass("selected")+r.siblings(".selected").length,t>1?n.addClass("selected-multiple").removeClass("selected-single"):n.removeClass("selected-multiple").addClass("selected-single")}).trigger("change",!0),r.find("[data-action]").each(function(){var r=e(this),s={},o=r.data("data"),u=r.data(),a=r.data("event-type");typeof o!="object"&&(o=o&&e.type(o)==="string"?e.parseJSON(o):{}),t.token_name&&(o[t.token_name]=t.token_value),a||(a=r.is('[type="radio"],[type="checkbox"],select')?"change":"click"),s.validate=u.novalidate!=="novalidate",s.data=o,s.action=u.action,r.on(a+".koowa",function(){n.prop("checked",""),i.prop("checked","checked"),n.trigger("change",!0),s.trigger=r,t.setOptions(u),t.trigger("execute",[s])})})})},validate:function(){return Koowa.Grid.getIdQuery()||!1},_actionDelete:function(e){return e.method="delete",this._actionDefault(e)},_actionDefault:function(t){var n=Koowa.Grid.getIdQuery(),r=this.options.url.match(/\?/)?"&":"?",i;if(t.validate&&!this.trigger("validate",[t]))return!1;i={method:"post",url:this.options.url+(n?r+n:""),params:e.extend({},{_action:t.action},t.data)},t.method&&(i.params._method=t.method),(new Koowa.Form(i)).submit()}}),Koowa.Controller.Form=Koowa.Controller.extend({_actionDefault:function(t){if(t.validate&&!this.trigger("validate",[t]))return!1;this.form.append(e("<input/>",{name:"_action",type:"hidden",value:t.action})),this.form.submit()}})}(window.kQuery);<commit_msg>Update minimized file<commit_after>/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */if(!Koowa)var Koowa={};Function.prototype.bind||(Function.prototype.bind=function(e){if(typeof this!="function")throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var t=Array.prototype.slice.call(arguments,1),n=this,r=function(){},i=function(){return n.apply(this instanceof r&&e?this:e,t.concat(Array.prototype.slice.call(arguments)))};return r.prototype=this.prototype,i.prototype=new r,i}),function(e){!function(e,t,n){typeof define=="function"?define(n):t[e]=n()}("klass",this,function(){function s(e){return f.call(o(e)?e:function(){},e,1)}function o(e){return typeof e===n}function u(e,t,n){return function(){var r=this.supr;this.supr=n[i][e];var s={}.fabricatedUndefined,o=s;try{o=t.apply(this,arguments)}finally{this.supr=r}return o}}function a(e,t,n){for(var s in t)t.hasOwnProperty(s)&&(e[s]=o(t[s])&&o(n[i][s])&&r.test(t[s])?u(s,t[s],n):t[s])}function f(e,t){function n(){}function c(){this.initialize?this.initialize.apply(this,arguments):(t||u&&r.apply(this,arguments),f.apply(this,arguments))}n[i]=this[i];var r=this,s=new n,u=o(e),f=u?e:this,l=u?{}:e;return c.methods=function(e){return a(s,e,r),c[i]=s,this},c.methods.call(c,l).prototype.constructor=c,c.extend=arguments.callee,c[i].implement=c.statics=function(e,t){return e=typeof e=="string"?function(){var n={};return n[e]=t,n}():e,a(this,e,r),this},c}var e=this,t=e.klass,n="function",r=/xyz/.test(function(){xyz})?/\bsupr\b/:/.*/,i="prototype";return s.noConflict=function(){return e.klass=t,this},s}),e(function(){e(".submittable").on("click.koowa",function(t){t.preventDefault(),(new Koowa.Form(e(t.target).data("config"))).submit()}),e(".-koowa-grid").each(function(){new Koowa.Controller.Grid({form:this})}),e(".-koowa-form").each(function(){new Koowa.Controller.Form({form:this})})}),Koowa.Class=klass({options:{},getOptions:function(){return{}},initialize:function(){this.setOptions(this.getOptions())},setOptions:function(t){return typeof t=="object"&&(this.options=e.extend(!0,{},this.options,t)),this}}),Koowa.Translator||(Koowa.Translator=Koowa.Class.extend({translations:{},translate:function(e,t){typeof this.translations[e.toLowerCase()]!="undefined"&&(e=this.translations[e.toLowerCase()]);if(typeof t=="object"&&t!==null)for(var n in t)if(t.hasOwnProperty(n)){var r="{"+n+"}".replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");e=e.replace(new RegExp(r,"g"),t[n])}return e},loadTranslations:function(e){for(var t in e)e.hasOwnProperty(t)&&(this.translations[t.toLowerCase()]=e[t]);return this}}),Koowa.translator=new Koowa.Translator,Koowa.translate=Koowa.translator.translate.bind(Koowa.translator)),Koowa.Form=Koowa.Class.extend({initialize:function(t){this.config=t,this.config.element?this.form=e(document[this.config.element]):(this.form=e("<form/>",{name:"dynamicform",method:this.config.method||"POST",action:this.config.url}),e(document.body).append(this.form))},addField:function(t,n){var r=e("<input/>",{name:t,value:n,type:"hidden"});return r.appendTo(this.form),this},submit:function(){var t=this;this.config.params&&e.each(this.config.params,function(e,n){t.addField(e,n)}),this.form.submit()}}),Koowa.Grid=Koowa.Class.extend({initialize:function(t){var n=this;this.element=e(t),this.form=this.element.is("form")?this.element:this.element.closest("form"),this.toggles=this.element.find(".-koowa-grid-checkall"),this.checkboxes=this.element.find(".-koowa-grid-checkbox").filter(function(t,n){return!e(n).prop("disabled")}),this.checkboxes.length||this.toggles.prop("disabled",!0),this.toggles.on("change.koowa",function(t,r){r||n.checkAll(e(this).prop("checked"))}),this.checkboxes.on("change.koowa",function(e,t){t||n.setCheckAll()})},checkAll:function(t){var n=this.checkboxes.filter(function(n,r){return e(r).prop("checked")!==t});this.checkboxes.prop("checked",t),n.trigger("change",!0)},uncheckAll:function(){this.checkAll(!1)},setCheckAll:function(){var t=this.checkboxes.filter(function(t,n){return e(n).prop("checked")!==!1}).length;this.toggles.prop("checked",this.checkboxes.length===t),this.toggles.trigger("change",!0)}}),Koowa.Grid.getAllSelected=function(t){return e(".-koowa-grid-checkbox:checked",t)},Koowa.Grid.getIdQuery=function(e){return decodeURIComponent(this.getAllSelected(e).serialize())},Koowa.Controller=Koowa.Class.extend({form:null,toolbar:null,buttons:null,token_name:null,token_value:null,getOptions:function(){return e.extend(this.supr(),{toolbar:".koowa-toolbar",url:window.location.href})},initialize:function(t){var n=this;this.supr(),this.setOptions(t),this.form=e(this.options.form),this.setOptions(this.form.data()),this.form.prop("action")&&(this.options.url=this.form.attr("action")),this.toolbar=e(this.options.toolbar),this.form.data("controller",this),this.on("execute",function(){return n.execute.apply(n,arguments)}),this.token_name=this.form.data("token-name"),this.token_value=this.form.data("token-value"),this.toolbar&&this.setToolbar()},setToolbar:function(){var t=this;this.buttons=this.toolbar.find(".toolbar[data-action]"),this.buttons.each(function(){var n=e(this),r={},i=n.data(),s=i.data;if(i.eventAdded)return;typeof s!="object"&&(s=s&&e.type(s)==="string"?e.parseJSON(s):{}),t.token_name&&(s[t.token_name]=t.token_value),r.validate=i.novalidate!=="novalidate",r.data=s,r.action=i.action,n.on("click.koowa",function(e){e.preventDefault(),r.trigger=n;if(!n.hasClass("disabled")){var s=n.data("prompt");if(s&&!confirm(s))return;t.setOptions(i),t.trigger("execute",[r])}}),n.data("event-added",!0)})},execute:function(e,t){var n=t.action[0].toUpperCase()+t.action.substr(1),r="_action"+n;return typeof t.validate=="undefined"&&(t.validate=!0),this.trigger("before"+n,t)&&(r=this[r]?r:"_actionDefault",this[r].call(this,t),this.trigger("after"+n,t)),this},on:function(e,t){return this.form.on("koowa:"+e,t)},off:function(e,t){return this.form.off("koowa:"+e,t)},trigger:function(t,n){var r=e.Event("koowa:"+t);return this.form.trigger(r,n),!r.isDefaultPrevented()},checkValidity:function(){var e;this.buttons&&(this.trigger("beforeValidate"),e=this.buttons.filter('[data-novalidate!="novalidate"]'),this.trigger("validate")?e.removeClass("disabled"):e.addClass("disabled"),this.trigger("afterValidate"))}}),Koowa.Controller.Grid=Koowa.Controller.extend({getOptions:function(){return e.extend(this.supr(),{inputs:".-koowa-grid-checkbox, .-koowa-grid-checkall",ajaxify:!1})},initialize:function(e){var t,n=this;this.supr(e),this.grid=new Koowa.Grid(this.form),this.on("validate",this.validate),this.options.inputs&&this.buttons&&(this.checkValidity(),this.form.find(this.options.inputs).on("change.koowa",function(e,t){t||n.checkValidity()})),this.token_name=this.form.data("token-name"),this.token_value=this.form.data("token-value"),this.setTableHeaders(),this.setTableRows(),this.form.find("thead select, tfoot select").on("change.koowa",function(){n.grid.uncheckAll(),n.options.ajaxify&&(event.preventDefault(),n.options.transport(n.options.url,n.form.serialize(),"get")),n.form.submit()})},setTableHeaders:function(){this.form.find("thead tr > *").each(function(){var t=e(this),n=t.find("a"),r=t.find(".-koowa-grid-checkall");if(n.length)return t.on("click.koowa",function(e){if(e.target!=t[0])return;n.prop("href")?window.location.href=n.prop("href"):n.trigger("click",e)}),n.hasClass("-koowa-asc")?t.addClass("-koowa-asc"):n.hasClass("-koowa-desc")&&t.addClass("-koowa-desc"),this;r.length&&t.on("click.koowa",function(e){if(e.target!=t[0])return!0;r.prop("checked",r.is(":checked")?!1:!0).trigger("change")}),t.addClass("void")})},setTableRows:function(){var t=this,n=this.form.find("tbody tr .-koowa-grid-checkbox");this.form.find("tbody tr").each(function(){var r=e(this),i=r.find(".-koowa-grid-checkbox");if(r.data("readonly")==1||!i.length)return;r.on("click.koowa",function(t){var n=e(t.target);if(n.is("[type=radio], [type=checkbox], a[href]"))return;i.prop("checked",!i.prop("checked")).trigger("change")}),i.on("change.koowa",function(){var t,n=r.parent();e(this).is("[type=radio]")&&n.find(".selected").removeClass("selected"),e(this).prop("checked")?r.addClass("selected"):r.removeClass("selected"),t=r.hasClass("selected")+r.siblings(".selected").length,t>1?n.addClass("selected-multiple").removeClass("selected-single"):n.removeClass("selected-multiple").addClass("selected-single")}).trigger("change",!0),r.find("[data-action]").each(function(){var r=e(this),s={},o=r.data("data"),u=r.data(),a=r.data("event-type");typeof o!="object"&&(o=o&&e.type(o)==="string"?e.parseJSON(o):{}),t.token_name&&(o[t.token_name]=t.token_value),a||(a=r.is('[type="radio"],[type="checkbox"],select')?"change":"click"),s.validate=u.novalidate!=="novalidate",s.data=o,s.action=u.action,r.on(a+".koowa",function(){n.prop("checked",""),i.prop("checked","checked"),n.trigger("change",!0),s.trigger=r,t.setOptions(u),t.trigger("execute",[s])})})})},validate:function(){return Koowa.Grid.getIdQuery()||!1},_actionDelete:function(e){return e.method="delete",this._actionDefault(e)},_actionDefault:function(t){var n=Koowa.Grid.getIdQuery(),r=this.options.url.match(/\?/)?"&":"?",i;if(t.validate&&!this.trigger("validate",[t]))return!1;i={method:"post",url:this.options.url+(n?r+n:""),params:e.extend({},{_action:t.action},t.data)},t.method&&(i.params._method=t.method),(new Koowa.Form(i)).submit()}}),Koowa.Controller.Form=Koowa.Controller.extend({_actionDefault:function(t){if(t.validate&&!this.trigger("validate",[t]))return!1;this.form.append(e("<input/>",{name:"_action",type:"hidden",value:t.action})),this.form.submit()}})}(window.kQuery);<|endoftext|>


<commit_before>import { updateApp } from "./update-app";

import {
    SET_NORMALIZATION_SIDEBAR,
    SET_NORMALIZATION_MENU,
    RESET_NORMALIZATION_SIDEBAR,
    RESET_NORMALIZATION_MENU,
    GREY_EDGES_DASHED_MENU,
    GREY_EDGES_DASHED_SIDEBAR,
    GREY_EDGE_THRESHOLD_MENU,
    GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR,
    WEIGHTS_SHOW_MOUSE_OVER_CLASS,
    WEIGHTS_SHOW_ALWAYS_CLASS,
    WEIGHTS_HIDE_CLASS,
    SHOW_WEIGHTS_MOUSEOVER,
    SHOW_ALL_WEIGHTS,
    HIDE_ALL_WEIGHTS,
    COLOR_EDGES,
    BLACK_EDGES,
    LINK_DIST_SLIDER_ID,
    LINK_DIST_MENU,
    CHARGE_SLIDER_ID,
    CHARGE_MENU,
    CHARGE_DEFAULT_VALUE,
    LINK_DIST_DEFAULT_VALUE,
    LOCK_SLIDERS_BUTTON,
    LOCK_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_CLASS,
    RESET_SLIDERS_CLASS,
    RESET_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_MENU,
    GRID_LAYOUT_BUTTON,
    GRID_LAYOUT_CLASS,
    FORCE_GRAPH_CLASS,
    NODE_COLORING_TOGGLE_CLASS,
    AVG_REPLICATE_VALS_TOP_MENU,
    AVG_REPLICATE_VALS_TOP_SIDEBAR,
    AVG_REPLICATE_VALS_BOTTOM_MENU,
    AVG_REPLICATE_VALS_BOTTOM_SIDEBAR,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON,
    LOG_FOLD_CHANGE_MAX_VALUE_MENU,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT,
    TOP_DATASET_SELECTION_SIDEBAR,
    BOTTOM_DATASET_SELECTION_SIDEBAR,
    TOP_DATASET_SELECTION_MENU,
    BOTTOM_DATASET_SELECTION_MENU,
} from "./constants";

import { setupLoadAndImportHandlers } from "./setup-load-and-import-handlers";

export const setupHandlers = grnState => {
    setupLoadAndImportHandlers(grnState);

    $(SET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = $("#normalization-max").val();
        updateApp(grnState);
    });

    $(SET_NORMALIZATION_MENU).change(() => {
        grnState.normalizationMax = $(SET_NORMALIZATION_MENU).val();
        updateApp(grnState);
    });

    $(RESET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = grnState.resetNormalizationMax;
        updateApp(grnState);
    });

    $(RESET_NORMALIZATION_MENU).click(() => {
        grnState.normalizationMax = grnState.resetNormalizationMax;
        updateApp(grnState);
    });

    $(GREY_EDGES_DASHED_SIDEBAR).change(() => {
        grnState.dashedLine = $(GREY_EDGES_DASHED_SIDEBAR).prop("checked");
        updateApp(grnState);
    });

    $(GREY_EDGES_DASHED_MENU).click(() => {
        grnState.dashedLine = !$(GREY_EDGES_DASHED_MENU).prop("checked");
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_MENU).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_MENU).val());
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).val() * 100);
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_MOUSE_OVER_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_WEIGHTS_MOUSEOVER;
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_ALWAYS_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $(WEIGHTS_HIDE_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = HIDE_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $(COLOR_EDGES).click(() => {
        grnState.colorOptimal = true;
        updateApp(grnState);
    });

    $(BLACK_EDGES).click(() => {
        grnState.colorOptimal = false;
        updateApp(grnState);
    });

// Sliders Code
    var valueValidator = (min, max, value) => {
        return Math.min(max, Math.max(min, value));
    };

    var linkDistValidator = value => {
        return valueValidator(1, 1000, value);
    };

    var chargeValidator = value => {
        return valueValidator(-2000, 0, value);
    };

    $(LINK_DIST_MENU).change(() => {
        var value = linkDistValidator($(LINK_DIST_MENU).val());
        grnState.linkDistanceSlider.currentVal = value;
        updateApp(grnState);
    });

    $(LINK_DIST_SLIDER_ID).change(() => {
        var value = linkDistValidator($(LINK_DIST_SLIDER_ID).val());
        grnState.linkDistanceSlider.currentVal = value;
        updateApp(grnState);
    });

    $(CHARGE_MENU).change(() => {
        var value = chargeValidator($(CHARGE_MENU).val());
        grnState.chargeSlider.currentVal = value;
        updateApp(grnState);
    });

    $(CHARGE_SLIDER_ID).change(() => {
        var value = chargeValidator($(CHARGE_SLIDER_ID).val());
        grnState.chargeSlider.currentVal = value;
        updateApp(grnState);
    });

    $(LOCK_SLIDERS_MENU_OPTION).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });

    $(LOCK_SLIDERS_BUTTON).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_CLASS).click(() => {
        grnState.chargeSlider.backup = grnState.chargeSlider.currentVal;
        grnState.linkDistanceSlider.backup = grnState.linkDistanceSlider.currentVal;
        grnState.chargeSlider.currentVal = CHARGE_DEFAULT_VALUE;
        grnState.linkDistanceSlider.currentVal = LINK_DIST_DEFAULT_VALUE;
        grnState.showUndoReset = true;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_MENU_OPTION).click(() => {
        grnState.chargeSlider.backup = grnState.chargeSlider.currentVal;
        grnState.linkDistanceSlider.backup = grnState.linkDistanceSlider.currentVal;
        grnState.chargeSlider.currentVal = CHARGE_DEFAULT_VALUE;
        grnState.linkDistanceSlider.currentVal = LINK_DIST_DEFAULT_VALUE;
        grnState.showUndoReset = true;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_CLASS).click(() => {
        grnState.chargeSlider.currentVal = grnState.chargeSlider.backup;
        grnState.linkDistanceSlider.currentVal = grnState.linkDistanceSlider.backup ;
        grnState.showUndoReset = false;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_MENU).click(() => {
        grnState.chargeSlider.currentVal = grnState.chargeSlider.backup;
        grnState.linkDistanceSlider.currentVal = grnState.linkDistanceSlider.backup ;
        grnState.showUndoReset = false;
        updateApp(grnState);
    });

// Grid buttons
    $(GRID_LAYOUT_BUTTON).click(() => {
        if (grnState.graphLayout === "FORCE_GRAPH") {
            grnState.graphLayout = "GRID_LAYOUT";
            grnState.slidersLocked = true;
        } else if (grnState.graphLayout === "GRID_LAYOUT") {
            grnState.graphLayout = "FORCE_GRAPH";
            grnState.slidersLocked = false;
        }
        updateApp(grnState);
    });

    $(FORCE_GRAPH_CLASS).click(() => {
        grnState.graphLayout = "FORCE_GRAPH";
        grnState.slidersLocked = false;
        updateApp(grnState);

    });

    $(GRID_LAYOUT_CLASS).click(() => {
        grnState.graphLayout = "GRID_LAYOUT";
        grnState.slidersLocked = true;
        updateApp(grnState);
    });

// Node Coloring
    $(NODE_COLORING_TOGGLE_CLASS).click(() => {
        grnState.nodeColoring.nodeColoringEnabled = !grnState.nodeColoring.nodeColoringEnabled;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_SIDEBAR).change(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_MENU).click(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_SIDEBAR).change(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_MENU).click(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON).click(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).change(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(TOP_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(BOTTOM_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (grnState.nodeColoring.bottomDataset === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (selection === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });
};
<commit_msg>constants addd<commit_after>import { updateApp } from "./update-app";

import {
    GREY_EDGES_DASHED_MENU,
    GREY_EDGES_DASHED_SIDEBAR,
    SET_NORMALIZATION_SIDEBAR,
    SET_NORMALIZATION_MENU,
    RESET_NORMALIZATION_MENU,
    RESET_NORMALIZATION_SIDEBAR,
    GREY_EDGE_THRESHOLD_MENU,
    GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR,
    WEIGHTS_SHOW_MOUSE_OVER_CLASS,
    WEIGHTS_SHOW_ALWAYS_CLASS,
    WEIGHTS_HIDE_CLASS,
    SHOW_WEIGHTS_MOUSEOVER,
    SHOW_ALL_WEIGHTS,
    HIDE_ALL_WEIGHTS,
    LOCK_SLIDERS_BUTTON,
    LOCK_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_CLASS,
    RESET_SLIDERS_CLASS,
    RESET_SLIDERS_MENU_OPTION,
    UNDO_SLIDERS_RESET_MENU,
    GRID_LAYOUT_BUTTON,
    GRID_LAYOUT_CLASS,
    FORCE_GRAPH_CLASS,
    NODE_COLORING_TOGGLE_CLASS,
    AVG_REPLICATE_VALS_TOP_MENU,
    AVG_REPLICATE_VALS_TOP_SIDEBAR,
    AVG_REPLICATE_VALS_BOTTOM_MENU,
    AVG_REPLICATE_VALS_BOTTOM_SIDEBAR,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON,
    LOG_FOLD_CHANGE_MAX_VALUE_MENU,
    LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT,
    TOP_DATASET_SELECTION_SIDEBAR,
    BOTTOM_DATASET_SELECTION_SIDEBAR,
    TOP_DATASET_SELECTION_MENU,
    BOTTOM_DATASET_SELECTION_MENU,
} from "./constants";

import { setupLoadAndImportHandlers } from "./setup-load-and-import-handlers";

export const setupHandlers = grnState => {
    setupLoadAndImportHandlers(grnState);

    $(GREY_EDGES_DASHED_SIDEBAR).change(() => {
        grnState.dashedLine = $(GREY_EDGES_DASHED_SIDEBAR).prop("checked");
        updateApp(grnState);
    });

    $(GREY_EDGES_DASHED_MENU).click(() => {
        grnState.dashedLine = !$(GREY_EDGES_DASHED_MENU).prop("checked");
        updateApp(grnState);
    });

    $(SET_NORMALIZATION_MENU).change(() => {
        grnState.normalizationMax = $(SET_NORMALIZATION_MENU).val();
        updateApp(grnState);
    });

    $(SET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = $(SET_NORMALIZATION_SIDEBAR).val();
        updateApp(grnState);
    });

    $(RESET_NORMALIZATION_MENU, RESET_NORMALIZATION_SIDEBAR).click(() => {
        grnState.normalizationMax = grnState.resetNormalizationMax;
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_MENU).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_MENU).val());
        updateApp(grnState);
    });

    $(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).change(() => {
        grnState.grayEdgeThreshold = Math.round($(GREY_EDGE_THRESHOLD_SLIDER_SIDEBAR).val() * 100);
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_MOUSE_OVER_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_WEIGHTS_MOUSEOVER;
        updateApp(grnState);
    });

    $(WEIGHTS_SHOW_ALWAYS_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = SHOW_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $(WEIGHTS_HIDE_CLASS).click(() => {
        grnState.edgeWeightDisplayOption = HIDE_ALL_WEIGHTS;
        updateApp(grnState);
    });

    $("#colorEdges").click(() => {
        grnState.colorOptimal = true;
        updateApp(grnState);
    });

    $("#blackEdges").click(() => {
        grnState.colorOptimal = false;
        updateApp(grnState);
    });

// Sliders code
    $(LOCK_SLIDERS_MENU_OPTION).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });
    $(LOCK_SLIDERS_BUTTON).click(() => {
        grnState.slidersLocked = !grnState.slidersLocked;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_CLASS).click(() => {
        grnState.resetTriggered = true;
        grnState.undoResetTriggered = false;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_CLASS).click(() => {
        grnState.resetTriggered = false;
        grnState.undoResetTriggered = true;
        updateApp(grnState);
    });

    $(RESET_SLIDERS_MENU_OPTION).click(() => {
        grnState.resetTriggered = false;
        grnState.undoResetTriggered = true;
        updateApp(grnState);
    });

    $(UNDO_SLIDERS_RESET_MENU).click(() => {
        grnState.resetTriggered = true;
        grnState.undoResetTriggered = false;
        updateApp(grnState);
    });

// Grid buttons
    $(GRID_LAYOUT_BUTTON).click(() => {
        if (grnState.graphLayout === "FORCE_GRAPH") {
            grnState.graphLayout = "GRID_LAYOUT";
            grnState.slidersLocked === true;
        } else if (grnState.graphLayout === "GRID_LAYOUT") {
            grnState.graphLayout = "FORCE_GRAPH";
            grnState.slidersLocked === false;
        }
        updateApp(grnState);
    });

    $(FORCE_GRAPH_CLASS).click(() => {
        grnState.graphLayout = "FORCE_GRAPH";
        updateApp(grnState);

    });

    $(GRID_LAYOUT_CLASS).click(() => {
        grnState.graphLayout = "GRID_LAYOUT";
        updateApp(grnState);
    });

// Node Coloring
    $(NODE_COLORING_TOGGLE_CLASS).click(() => {
        grnState.nodeColoring.nodeColoringEnabled = !grnState.nodeColoring.nodeColoringEnabled;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_SIDEBAR).change(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_TOP_MENU).click(() => {
        grnState.nodeColoring.averageTopDataset = !grnState.nodeColoring.averageTopDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_SIDEBAR).change(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(AVG_REPLICATE_VALS_BOTTOM_MENU).click(() => {
        grnState.nodeColoring.averageBottomDataset = !grnState.nodeColoring.averageBottomDataset;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_BUTTON).click(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_SIDEBAR_INPUT).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).change(() => {
        var value = $(LOG_FOLD_CHANGE_MAX_VALUE_MENU).val();
        grnState.nodeColoring.logFoldChangeMaxValue = value;
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(TOP_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(TOP_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.topDataset = selection;
        if (grnState.nodeColoring.bottomDataSameAsTop) {
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_SIDEBAR).change(() => {
        var selection = $(BOTTOM_DATASET_SELECTION_SIDEBAR).find(":selected").attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (grnState.nodeColoring.bottomDataset === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
        }
        updateApp(grnState);
    });

    $(BOTTOM_DATASET_SELECTION_MENU).click(() => {
        var selection = $(this).attr("value");
        grnState.nodeColoring.bottomDataset = selection;
        if (selection === "Same as Top Dataset") {
            grnState.nodeColoring.bottomDataset = grnState.nodeColoring.topDataset;
            grnState.nodeColoring.bottomDataSameAsTop = true;
        } else {
            grnState.nodeColoring.bottomDataSameAsTop = false;
            grnState.nodeColoring.bottomDataset = selection;
        }
        updateApp(grnState);
    });
};
<|endoftext|>


<commit_before><commit_msg>CPR-1826<commit_after><|endoftext|>


<commit_before><commit_msg>removed commented code<commit_after><|endoftext|>


<commit_before>window.wait(() => {
  window.GPM.on('change:playback', (mode) => {
    switch (mode) {
      case window.GMusic.Playback.STOPPED:
        Emitter.fire('playback:isStopped');
        break;
      case window.GMusic.Playback.PAUSED:
        Emitter.fire('playback:isPaused');
        break;
      case window.GMusic.Playback.PLAYING:
        Emitter.fire('playback:isPlaying');
        break;
      default:
        break;
    }
  });

  let lastScrobble = {};
  let lastScrobbleTime = 0;
  let currentSong;

  window.GPM.on('change:song', (song) => {
    currentSong = song;
    Emitter.fire('change:song', song);
    const rating = window.GPM.rating.getRating();
    if (rating === '0') {
      // we have to emit this manually if the user hasn't rated the song
      Emitter.fire('change:rating', rating);
    }
  });

  window.GPM.on('change:rating', (rating) => {
    Emitter.fire('change:rating', rating);
  });

  window.GPM.on('change:shuffle', (mode) => {
    console.log(mode);
    Emitter.fire('change:shuffle', mode);
  });
  // DEV: Set inital shuffle value
  setTimeout(() => {
    Emitter.fire('change:shuffle', window.GPM.playback.getShuffle());
  }, 100);

  window.GPM.on('change:repeat', (mode) => {
    Emitter.fire('change:repeat', mode);
  });
  // DEV: Set inital repeat value
  setTimeout(() => {
    Emitter.fire('change:repeat', window.GPM.playback.getRepeat());
  }, 100);

  window.GPM.on('change:playback-time', (playbackInfo) => {
    Emitter.fire('change:playback-time', playbackInfo);
    if (playbackInfo.current >= playbackInfo.total / 2
          && Date.now() - 10000 >= lastScrobbleTime && currentSong !== null
          && JSON.stringify(lastScrobble) !== JSON.stringify(currentSong)) {
      Emitter.fire('change:song:scrobble', {
        title: currentSong.title,
        artist: currentSong.artist,
        album: currentSong.album,
        timestamp: Math.round((Date.now() - playbackInfo.current) / 1000),
      });
      lastScrobbleTime = Date.now();
      lastScrobble = currentSong;
    }
  });

  Emitter.on('execute:gmusic', (event, cmd) => {
    if (window.GPM && GPM[cmd.namespace] && GPM[cmd.namespace][cmd.method]
      && typeof GPM[cmd.namespace][cmd.method] === 'function') {
      GPM[cmd.namespace][cmd.method].apply(GPM, cmd.args || []);
    }
  });
});
<commit_msg>Removed console.log from playback handler<commit_after>window.wait(() => {
  window.GPM.on('change:playback', (mode) => {
    switch (mode) {
      case window.GMusic.Playback.STOPPED:
        Emitter.fire('playback:isStopped');
        break;
      case window.GMusic.Playback.PAUSED:
        Emitter.fire('playback:isPaused');
        break;
      case window.GMusic.Playback.PLAYING:
        Emitter.fire('playback:isPlaying');
        break;
      default:
        break;
    }
  });

  let lastScrobble = {};
  let lastScrobbleTime = 0;
  let currentSong;

  window.GPM.on('change:song', (song) => {
    currentSong = song;
    Emitter.fire('change:song', song);
    const rating = window.GPM.rating.getRating();
    if (rating === '0') {
      // we have to emit this manually if the user hasn't rated the song
      Emitter.fire('change:rating', rating);
    }
  });

  window.GPM.on('change:rating', (rating) => {
    Emitter.fire('change:rating', rating);
  });

  window.GPM.on('change:shuffle', (mode) => {
    Emitter.fire('change:shuffle', mode);
  });
  // DEV: Set inital shuffle value
  setTimeout(() => {
    Emitter.fire('change:shuffle', window.GPM.playback.getShuffle());
  }, 100);

  window.GPM.on('change:repeat', (mode) => {
    Emitter.fire('change:repeat', mode);
  });
  // DEV: Set inital repeat value
  setTimeout(() => {
    Emitter.fire('change:repeat', window.GPM.playback.getRepeat());
  }, 100);

  window.GPM.on('change:playback-time', (playbackInfo) => {
    Emitter.fire('change:playback-time', playbackInfo);
    if (playbackInfo.current >= playbackInfo.total / 2
          && Date.now() - 10000 >= lastScrobbleTime && currentSong !== null
          && JSON.stringify(lastScrobble) !== JSON.stringify(currentSong)) {
      Emitter.fire('change:song:scrobble', {
        title: currentSong.title,
        artist: currentSong.artist,
        album: currentSong.album,
        timestamp: Math.round((Date.now() - playbackInfo.current) / 1000),
      });
      lastScrobbleTime = Date.now();
      lastScrobble = currentSong;
    }
  });

  Emitter.on('execute:gmusic', (event, cmd) => {
    if (window.GPM && GPM[cmd.namespace] && GPM[cmd.namespace][cmd.method]
      && typeof GPM[cmd.namespace][cmd.method] === 'function') {
      GPM[cmd.namespace][cmd.method].apply(GPM, cmd.args || []);
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

const createItem = require('./../helperDelegates/createItem');

module.exports = function(handler, table) {

    const slots = handler.event.request.intent.slots
    var baseQuantity = 1;
    var addedQuantity = 1;

    if (slots.Item && slots.Item.value) {
        table
        .find({ hash: handler.event.session.user.userId,
                range: slots.Item.value
                })
        .then(function(resp) {
            if (resp == undefined) {
              createItem(handler, table);
            } else {
              if (resp.quantity != undefined) {
                baseQuantity = resp.quantity;
              }
            }
        })

      if (slots.Quantity && slots.Quantity.value) {
        addedQuantity = slots.Quantity.value;
      }
      var total = baseQuantity + addedQuantity;
      table
      .update({hash: handler.event.session.user.userId, range: slots.Item.value.toLowerCase()}, { quantity: total })
      .then(function(resp) {
          handler.emit('Affirmative');
      })
      .catch(function(err) {
          console.log(err);
          handler.emit('Error');
      });

    } else {
        console.log("error with itemName slot");
        handler.emit('Error')
    }
}
<commit_msg>Dynasty update method sanity check<commit_after>'use strict';

const createItem = require('./../helperDelegates/createItem');

module.exports = function(handler, table) {

    const slots = handler.event.request.intent.slots
    var baseQuantity = 1;
    var addedQuantity = 1;

    if (slots.Item && slots.Item.value) {
        table
        .find({ hash: handler.event.session.user.userId,
                range: slots.Item.value
                })
        .then(function(resp) {
            if (resp == undefined) {
              createItem(handler, table);
            } else {
              if (resp.quantity != undefined) {
                baseQuantity = resp.quantity;
              }
            }
        })

      if (slots.Quantity && slots.Quantity.value) {
        addedQuantity = slots.Quantity.value;
      }
      var total = baseQuantity + addedQuantity;
      table
      //.update({hash: handler.event.session.user.userId, range: slots.Item.value.toLowerCase()}, { quantity: total })
      .insert({userId: handler.event.session.user.userId, itemName: slots.Item.value.toLowerCase(), quantity: total})
      .then(function(resp) {
          handler.emit('Affirmative');
      })
      .catch(function(err) {
          console.log(err);
          handler.emit('Error');
      });

    } else {
        console.log("error with itemName slot");
        handler.emit('Error')
    }
}
<|endoftext|>


<commit_before>ngapp.service('themeService', function(settingsService) {
    let service = this,
        unknownMetaData = {
            author: 'Unknown',
            released: '?',
            updated: '?',
            description: 'This theme does not have embedded metadata.'
        };

    this.getThemes = function() {
        let themes = fh.appDir.find('app\\themes', { matching: '*.css' });
        return themes.map(function(theme) {
            let fileContents = fh.jetpack.read(theme),
                filename = theme.split('\\').last(),
                defaultMetaData = Object.assign(unknownMetaData, {
                    name: filename.match(/(.*)\.css/)[1]
                }),
                match = fileContents.match(new RegExp(/^\/\*\{([\w\W]+)\}\*\//)),
                metaData = defaultMetaData;
            try {
                if (match) metaData = JSON.parse(`{${match[1]}}`);
            } catch (x) {
                console.log(`Error parsing metadata for theme ${filename}: ${x.message}`);
            }
            metaData.filename = filename;
            return metaData;
        });
    };

    this.getCurrentTheme = function() {
        let settingsTheme = settingsService.globalSettings.theme;
        if (!settingsTheme || !fh.appDir.exists(`themes/${settingsTheme}`)) {
            let availableThemes = service.getThemes();
            return availableThemes[0].filename;
        }
        return settingsTheme;
    };
});<commit_msg>fixed bug with loading themes when built<commit_after>ngapp.service('themeService', function(settingsService) {
    let service = this,
        unknownMetaData = {
            author: 'Unknown',
            released: '?',
            updated: '?',
            description: 'This theme does not have embedded metadata.'
        };

    this.getThemes = function() {
        let themes = fh.appDir.find('app\\themes', { matching: '*.css' });
        return themes.map(function(theme) {
            let fileContents = fh.appDir.read(theme),
                filename = theme.split('\\').last(),
                defaultMetaData = Object.assign(unknownMetaData, {
                    name: filename.match(/(.*)\.css/)[1]
                }),
                match = fileContents.match(new RegExp(/^\/\*\{([\w\W]+)\}\*\//)),
                metaData = defaultMetaData;
            try {
                if (match) metaData = JSON.parse(`{${match[1]}}`);
            } catch (x) {
                console.log(`Error parsing metadata for theme ${filename}: ${x.message}`);
            }
            metaData.filename = filename;
            return metaData;
        });
    };

    this.getCurrentTheme = function() {
        let settingsTheme = settingsService.globalSettings.theme;
        if (!settingsTheme || !fh.appDir.exists(`themes/${settingsTheme}`)) {
            let availableThemes = service.getThemes();
            return availableThemes[0].filename;
        }
        return settingsTheme;
    };
});<|endoftext|>