<commit_before>define(["knockout", "jquery"],
function(ko, $) {
	return function (instance) {
		instance.frameSingleData = {};
		instance.frameSingleData.selectedTopics = ko.observableArray(globalData.TOPIC_SORTING).subscribeTo("selectedTopics");
		instance.frameSingleData.frameTypes = instance.singleData[instance.active()].DOCUMENT.FRAME_LIST;

		generateFrameTexts = function() {
			for(frameType in instance.frameSingleData.frameTypes) {
				var frames = instance.singleData[instance.active()].DOCUMENT.FRAME_LIST[frameType];

				var text = instance.singleData[instance.active()].DOCUMENT.TEXT$FULLTEXT; // text with all frames
				var text2 = text; // text with all inactive frames
				var text3 = text; // text with all frames of topic x
				var text4 = text; // text with all frames of topic x and type y
				var lastStart = text.length;
				var lastStart2  = text.length;
				var lastStart3  = text.length;
				var lastStart4  = text.length;
				var frameSpan;
				var textActive = false;
				var textInactive = false;
				var textTopic = false;
				var textTopicFrame =  false;

				for(key in frames) {
					if(instance.frameSingleData.selectedTopics().indexOf(parseInt(frames[key].TOPIC_ID)) > -1) {
						frameSpan = text.substring(0, frames[key].START_POSITION)
							+ ''
							+ text.substring(frames[key].START_POSITION, frames[key].END_POSITION)
							+ '';
						if(frames[key].ACTIVE == 1) {
							if(parseInt(frames[key].END_POSITION) < lastStart) { // avoid covering each other
								text = frameSpan + text.substring(parseInt(frames[key].END_POSITION));
								lastStart = parseInt(frames[key].START_POSITION);
								textActive = true;
							}
							if(typeof instance.singleData[instance.active()].data.topicId != 'undefined') {
								if(frames[key].TOPIC_ID == instance.singleData[instance.active()].data.topicId) {
									if(parseInt(frames[key].END_POSITION) < lastStart3) { // avoid covering each other
										text3 = frameSpan + text3.substring(parseInt(frames[key].END_POSITION));
										lastStart3 = parseInt(frames[key].START_POSITION);
										textTopic = true;
									}
									if(typeof instance.singleData[instance.active()].data.frame != 'undefined') {
										if(frames[key].FRAME == instance.singleData[instance.active()].data.frame) {
											if(parseInt(frames[key].END_POSITION) < lastStart4) { // avoid covering each other
												text4 = frameSpan + text4.substring(parseInt(frames[key].END_POSITION));
												lastStart4 = parseInt(frames[key].START_POSITION);
												textTopicFrame = true;
											}
										}
									}
								}
							}
						} else {
							if(parseInt(frames[key].END_POSITION) < lastStart2) { // avoid covering each other
								text2 = frameSpan + text2.substring(parseInt(frames[key].END_POSITION));
								lastStart2 = parseInt(frames[key].START_POSITION);
								textInactive = true;
							}
						}
					}
				}
				if(textActive) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_ACTIVE_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_ACTIVE_FRAMES_' + frameType] = text;
					instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frames of type ' + frameType, 'TEXT_ACTIVE_FRAMES_' + frameType));
				}
				if(textInactive) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_ACTIVE_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_ACTIVE_FRAMES_' + frameType] = text2;
					instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with inactive Frames of type ' + frameType, 'TEXT_ACTIVE_FRAMES_' + frameType));
				}
				if(textTopic) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_TOPIC_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_TOPIC_FRAMES_' + frameType] = text3;
					if(instance.frameSingleData.selectedTopics().indexOf(parseInt(instance.singleData[instance.active()].data.topicId)) > -1)
						instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frames of type ' + frameType + ' and Topic ' + instance.singleData[instance.active()].data.topicId, 'TEXT_TOPIC_FRAMES_' + frameType));
					else
						instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frames of type ' + frameType + ' and Topic ' + instance.singleData[instance.active()].data.topicId, 'TEXT_TOPIC_FRAMES_' + frameType));
				}
				if(textTopicFrame) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_TOPIC_FRAME_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_TOPIC_FRAME_FRAMES_' + frameType] = text4;
					instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frame "'  + instance.singleData[instance.active()].data.frame + '" and Topic ' + instance.singleData[instance.active()].data.topicId, 'TEXT_TOPIC_FRAME_FRAMES_' + frameType));
				}
			};
		};
		instance.frameSingleData.selectedTopics.subscribe(function(newValue) {
			var selectArray = instance.singleData[instance.active()].textSelectArray().slice();
			oldSelection = instance.singleData[instance.active()].textSelection().label;
			for(var i = selectArray.length - 1; i > 0 ; i--) {
				if(selectArray[i].field.indexOf('FRAME') > -1) {
					selectArray.splice(i, 1);
				}
			}
			instance.singleData[instance.active()].textSelectArray(selectArray);
			generateFrameTexts();
			var pos = instance.singleData[instance.active()].textSelectArray().map(function(e) {
				return e.label; }).indexOf(oldSelection);
			if(pos > -1) {
				instance.singleData[instance.active()].textSelection(instance.singleData[instance.active()].textSelectArray()[pos]);
			} else {
				$('#desktop').animate({scrollTop: 0});
			}
		});

		generateFrameTexts();
	};
});
<commit_msg>#149 bugfix: document-show was showing inactive frames when all frames was selected<commit_after>define(["knockout", "jquery"],
function(ko, $) {
	return function (instance) {
		instance.frameSingleData = {};
		instance.frameSingleData.selectedTopics = ko.observableArray(globalData.TOPIC_SORTING).subscribeTo("selectedTopics");
		instance.frameSingleData.frameTypes = instance.singleData[instance.active()].DOCUMENT.FRAME_LIST;

		generateFrameTexts = function() {
			for(frameType in instance.frameSingleData.frameTypes) {
				var frames = instance.singleData[instance.active()].DOCUMENT.FRAME_LIST[frameType];

				var text = instance.singleData[instance.active()].DOCUMENT.TEXT$FULLTEXT; // text with all frames
				var text2 = text; // text with all inactive frames
				var text3 = text; // text with all frames of topic x
				var text4 = text; // text with all frames of topic x and type y
				var lastStart = text.length;
				var lastStart2  = text.length;
				var lastStart3  = text.length;
				var lastStart4  = text.length;
				var frameSpan;
				var textActive = false;
				var textInactive = false;
				var textTopic = false;
				var textTopicFrame =  false;

				for(key in frames) {
					if(instance.frameSingleData.selectedTopics().indexOf(parseInt(frames[key].TOPIC_ID)) > -1) {
						frameSpan = text.substring(0, frames[key].START_POSITION)
							+ ''
							+ text.substring(frames[key].START_POSITION, frames[key].END_POSITION)
							+ '';
						if(frames[key].ACTIVE == 1) {
							if(parseInt(frames[key].END_POSITION) < lastStart) { // avoid covering each other
								text = frameSpan + text.substring(parseInt(frames[key].END_POSITION));
								lastStart = parseInt(frames[key].START_POSITION);
								textActive = true;
							}
							if(typeof instance.singleData[instance.active()].data.topicId != 'undefined') {
								if(frames[key].TOPIC_ID == instance.singleData[instance.active()].data.topicId) {
									if(parseInt(frames[key].END_POSITION) < lastStart3) { // avoid covering each other
										text3 = frameSpan + text3.substring(parseInt(frames[key].END_POSITION));
										lastStart3 = parseInt(frames[key].START_POSITION);
										textTopic = true;
									}
									if(typeof instance.singleData[instance.active()].data.frame != 'undefined') {
										if(frames[key].FRAME == instance.singleData[instance.active()].data.frame) {
											if(parseInt(frames[key].END_POSITION) < lastStart4) { // avoid covering each other
												text4 = frameSpan + text4.substring(parseInt(frames[key].END_POSITION));
												lastStart4 = parseInt(frames[key].START_POSITION);
												textTopicFrame = true;
											}
										}
									}
								}
							}
						} else {
							if(parseInt(frames[key].END_POSITION) < lastStart2) { // avoid covering each other
								text2 = frameSpan + text2.substring(parseInt(frames[key].END_POSITION));
								lastStart2 = parseInt(frames[key].START_POSITION);
								textInactive = true;
							}
						}
					}
				}
				if(textActive) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_ACTIVE_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_ACTIVE_FRAMES_' + frameType] = text;
					instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frames of type ' + frameType, 'TEXT_ACTIVE_FRAMES_' + frameType));
				}
				if(textInactive) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_INACTIVE_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_INACTIVE_FRAMES_' + frameType] = text2;
					instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with inactive Frames of type ' + frameType, 'TEXT_INACTIVE_FRAMES_' + frameType));
				}
				if(textTopic) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_TOPIC_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_TOPIC_FRAMES_' + frameType] = text3;
					if(instance.frameSingleData.selectedTopics().indexOf(parseInt(instance.singleData[instance.active()].data.topicId)) > -1)
						instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frames of type ' + frameType + ' and Topic ' + instance.singleData[instance.active()].data.topicId, 'TEXT_TOPIC_FRAMES_' + frameType));
					else
						instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frames of type ' + frameType + ' and Topic ' + instance.singleData[instance.active()].data.topicId, 'TEXT_TOPIC_FRAMES_' + frameType));
				}
				if(textTopicFrame) {
					instance.singleData[instance.active()].TITLE_REPRESENTATION['TEXT_TOPIC_FRAME_FRAMES_' + frameType] = instance.singleData[instance.active()].DOCUMENT.TEXT$TITLE;
					instance.singleData[instance.active()].TEXT_REPRESENTATION['TEXT_TOPIC_FRAME_FRAMES_' + frameType] = text4;
					instance.singleData[instance.active()].textSelectArray.push(new instance.TextRepresentation('Text with Frame "'  + instance.singleData[instance.active()].data.frame + '" and Topic ' + instance.singleData[instance.active()].data.topicId, 'TEXT_TOPIC_FRAME_FRAMES_' + frameType));
				}
			};
		};
		instance.frameSingleData.selectedTopics.subscribe(function(newValue) {
			var selectArray = instance.singleData[instance.active()].textSelectArray().slice();
			oldSelection = instance.singleData[instance.active()].textSelection().label;
			for(var i = selectArray.length - 1; i > 0 ; i--) {
				if(selectArray[i].field.indexOf('FRAME') > -1) {
					selectArray.splice(i, 1);
				}
			}
			instance.singleData[instance.active()].textSelectArray(selectArray);
			generateFrameTexts();
			var pos = instance.singleData[instance.active()].textSelectArray().map(function(e) {
				return e.label; }).indexOf(oldSelection);
			if(pos > -1) {
				instance.singleData[instance.active()].textSelection(instance.singleData[instance.active()].textSelectArray()[pos]);
			} else {
				$('#desktop').animate({scrollTop: 0});
			}
		});

		generateFrameTexts();
	};
});
<|endoftext|>


<commit_before>//
// ShatterPlatePiece.js
//
// Author: Liv Erickson
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
/* globals Entities, SoundCache */

(function() {
    var VELOCITY_TO_BREAK = 2;
    var EMIT_TIME = 2000;
    var breakURL = Script.resolvePath("sound/glass-break2.wav");
    var breakSound = SoundCache.getSound(breakURL);
    var volumeLevel = 0.25;
    var canBreak = false;
    var _entityID;

    var PlatePiece = function(){};
    var shouldBreak = function(velocity){
        return Math.abs(velocity.x) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.y) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.z) >= VELOCITY_TO_BREAK;
    };

    function makeFragile() {
        Entities.editEntity(_entityID, {
            collidesWith: "static,dynamic,kinematic,"
        });
        canBreak = true;
    }

    var createParticles = function(position) {
        var splat = Entities.addEntity({
            "type":"ParticleEffect",
            "position": position,
            "collisionless":1,
            "dynamic":0,
            "name":"Plate Particle Effect",
            "isEmitting":true,
            "lifespan":"0.2",
            "lifetime" : 0.5,
            "maxParticles":"500",
            "textures":"http://hifi-content.s3.amazonaws.com/alan/dev/Particles/Bokeh-Particle.png",
            "emitRate":"145",
            "emitSpeed": 0.05,
            "emitDimensions":{"x":"0.1","y":".1","z":".1"},
            "emitOrientation":{"x":"-90","y":"0","z":"0"},
            "emitterShouldTrail":false,
            "particleRadius":"0.02",
            "radiusSpread":"6",
            "radiusStart":"0.01",
            "radiusFinish":"0",
            "color":{"red":"171","blue":"171","green":"171"},
            "colorSpread":{"red":"0","blue":"0","green":"0"},
            "colorStart":{"red":"255","blue":"255","green":"255"},
            "colorFinish":{"red":"255","blue":"255","green":"255"},
            "emitAcceleration":{"x":"-0.0","y":"2.5","z":"-0.1"},
            "accelerationSpread":{"x":"0.5","y":"3","z":"0.5"},
            "alpha":"1",
            "alphaSpread":"0",
            "alphaStart":"1",
            "alphaFinish":"1",
            "polarStart":"0",
            "polarFinish":"17",
            "azimuthStart":"-180",
            "azimuthFinish":"180"
        }, true);
        Entities.editEntity(_entityID, {visible: false});
        Script.setTimeout(function() {
            Entities.editEntity(splat, { isEmitting: false });
            Entities.deleteEntity(_entityID);
        }, EMIT_TIME);
    };

    PlatePiece.prototype = {
        preload: function(entityID) {
            _entityID = entityID;
        },
        startNearGrab: function() {

        },
        collisionWithEntity : function(myID, theirID, collision) {
            if (canBreak) {
                var properties = Entities.getEntityProperties(myID, 'velocity', 'position');
                var velocity = properties.velocity;
                var position = properties.position;
                if (shouldBreak(velocity)) {
                    if (breakSound.downloaded) {
                        Audio.playSound(breakSound, {
                            volume: volumeLevel,
                            position: position
                        });
                    }
                    createParticles(position);
                }
            }

        }
    };

    return new PlatePiece();

});
<commit_msg>fix for small plate piece<commit_after>//
// ShatterPlatePiece.js
//
// Author: Liv Erickson
// Copyright High Fidelity 2018
//
// Licensed under the Apache 2.0 License
// See accompanying license file or http://apache.org/
//
/* globals Entities, SoundCache */

(function() {
    var VELOCITY_TO_BREAK = 2;
    var EMIT_TIME = 2000;
    var breakURL = Script.resolvePath("sound/glass-break2.wav");
    var breakSound = SoundCache.getSound(breakURL);
    var volumeLevel = 0.25;
    var canBreak = false;
    var _entityID;

    var PlatePiece = function(){};
    var shouldBreak = function(velocity){
        return Math.abs(velocity.x) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.y) >= VELOCITY_TO_BREAK ||
            Math.abs(velocity.z) >= VELOCITY_TO_BREAK;
    };

    var createParticles = function(position) {
        var splat = Entities.addEntity({
            "type":"ParticleEffect",
            "position": position,
            "collisionless":1,
            "dynamic":0,
            "name":"Plate Particle Effect",
            "isEmitting":true,
            "lifespan":"0.2",
            "lifetime" : 0.5,
            "maxParticles":"500",
            "textures":"http://hifi-content.s3.amazonaws.com/alan/dev/Particles/Bokeh-Particle.png",
            "emitRate":"145",
            "emitSpeed": 0.05,
            "emitDimensions":{"x":"0.1","y":".1","z":".1"},
            "emitOrientation":{"x":"-90","y":"0","z":"0"},
            "emitterShouldTrail":false,
            "particleRadius":"0.02",
            "radiusSpread":"6",
            "radiusStart":"0.01",
            "radiusFinish":"0",
            "color":{"red":"171","blue":"171","green":"171"},
            "colorSpread":{"red":"0","blue":"0","green":"0"},
            "colorStart":{"red":"255","blue":"255","green":"255"},
            "colorFinish":{"red":"255","blue":"255","green":"255"},
            "emitAcceleration":{"x":"-0.0","y":"2.5","z":"-0.1"},
            "accelerationSpread":{"x":"0.5","y":"3","z":"0.5"},
            "alpha":"1",
            "alphaSpread":"0",
            "alphaStart":"1",
            "alphaFinish":"1",
            "polarStart":"0",
            "polarFinish":"17",
            "azimuthStart":"-180",
            "azimuthFinish":"180"
        }, true);
        Entities.editEntity(_entityID, {visible: false});
        Script.setTimeout(function() {
            Entities.deleteEntity(splat);
            Entities.deleteEntity(_entityID);
        }, EMIT_TIME);
    };

    function makeFragile(){
        Entities.editEntity(_entityID, {
            collidesWith: "static,dynamic,kinematic,"
        });
        canBreak = true;
    }

    PlatePiece.prototype = {
        preload: function(entityID) {
            _entityID = entityID;
        },
        startNearGrab: function() {
            makeFragile();
        },
        mousePressOnEntity: function() {
            makeFragile();
        },
        collisionWithEntity : function(myID, theirID, collision) {
            if (canBreak) {
                var properties = Entities.getEntityProperties(myID, 'velocity', 'position');
                var velocity = properties.velocity;
                var position = properties.position;
                if (shouldBreak(velocity)) {
                    if (breakSound.downloaded) {
                        Audio.playSound(breakSound, {
                            volume: volumeLevel,
                            position: position
                        });
                    }
                    createParticles(position);
                }
            }

        }
    };

    return new PlatePiece();

});
<|endoftext|>


<commit_before>controlloQML = function(req, res) {
    var corpo = JSON.parse(req);
    var success;
    var tipologiaDomande = ["veroFalso", "rispostaMultipla", "ordinamentoStringhe", "ordinamentoImmagini", "collegamentoElementi", "areaCliccabile", "riempimentoSpaziVuoti", "custom"];
    if (corpo.hasOwnProperty('type')) {
        if (corpo.type == tipologiaDomande[0]) {
             success = veroFalso(corpo,res);
        }
        else if(corpo.type == tipologiaDomande[1]){
            success = rispostaMultipla(corpo,res);
        }
        else if(corpo.type == tipologiaDomande[2]){
            success = ordinamentoStringhe(corpo,res);
        }
        else if(corpo.type == tipologiaDomande[3]){
            success = ordinamentoImmagini(corpo,res);
        }
        else if(corpo.type == tipologiaDomande[4]){
            success = collegamentoElementi(corpo,res);
        }
        else if(corpo.type == tipologiaDomande[5]){
            success = areaCliccabile(corpo,res);
        }
        else if(corpo.type == tipologiaDomande[6]){
            success = riempimentoSpaziVuoti(corpo,res);
        }
        else if(corpo.type == tipologiaDomande[7]){
            success = custom(corpo,res);
        }
        else{
            success = false;
            console.log("tipologia di domanda sconosciuta");
        }
        return success;
    }
    else{
        res = "type non trovato";
        console.log(res);
        return false;
    }
}
<commit_msg>update editor QML<commit_after>controlloQML = function(req, res) {

    var corpo = JSON.parse(req);
    var success;
    var tipologiaDomande = ["veroFalso", "rispostaMultipla", "ordinamentoStringhe", "ordinamentoImmagini", "collegamentoElementi", "areaCliccabile", "riempimentoSpaziVuoti", "custom"];
    if (corpo.hasOwnProperty('type')) {
        if (corpo.type == tipologiaDomande[0]) {
            success = veroFalso(corpo,res);
            if(success){
                createJSON(corpo, res, "veroFalso");
            }
        }
        else if(corpo.type == tipologiaDomande[1]){
            success = rispostaMultipla(corpo,res);
            if(success){
                createJSON(corpo, res, "rispostaMultipla");
            }
        }
        else if(corpo.type == tipologiaDomande[2]){
            success = ordinamentoStringhe(corpo,res);
            if(success){
                createJSON(corpo, res, "ordinamentoStringhe");
            }
        }
        else if(corpo.type == tipologiaDomande[3]){
            success = ordinamentoImmagini(corpo,res);
            if(success){
                createJSON(corpo, res, "ordinamentoImmagini");
            }
        }
        else if(corpo.type == tipologiaDomande[4]){
            success = collegamentoElementi(corpo,res);
            if(success){
                createJSON(corpo, res, "collegamentoElementi");
            }
        }
        else if(corpo.type == tipologiaDomande[5]){
            success = areaCliccabile(corpo,res);
            if(success){
                createJSON(corpo, res, "areaCliccabile");
            }
        }
        else if(corpo.type == tipologiaDomande[6]){
            success = riempimentoSpaziVuoti(corpo,res);
            if(success){
                createJSON(corpo, res, "riempimentoSpaziVuoti");
            }
        }
        else if(corpo.type == tipologiaDomande[7]){
            success = custom(corpo,res);
            if(success){
                createJSON(corpo, res, "custom");
            }
        }
        else{
            success = false;
            console.log("tipologia di domanda sconosciuta");
        }
        return success;
    }
    else{
        res = "type non trovato";
        console.log(res);
        return false;
    }
}

<|endoftext|>


<commit_before>/**
* directive.diGameMenu Module
*
* Description
*/
angular.module('directive.diGameMenu', [
    'service.GameManager',
    'directive.diBootstrapSlider',
    'directive.diDesignPiece'
])
.controller('GameMenuCtrl', [
    '$scope',
    'GameManager',
function (
    $scope,
    GameManager
){
    $scope.continueGame = function continueGame() {
        if (GameManager.getOpenDesignBeforeStart()) {
            GameManager.setOpenDesignBeforeStart(false);
        } else {
            GameManager.setPause();
        }
        $scope.closeModal();
    };

    $scope.restartGame = function restartGame() {
        GameManager.newGame();
        $scope.closeModal();
        GameManager.setGameStart();
    };

    $scope.endGame = function endGame() {
        GameManager.gameOver();
        $scope.closeModal();
    };

    $scope.restoreGame = function restoreGame() {
        GameManager.restoreGame();
        GameManager.setPause();
        $scope.closeModal();
    };

    $scope.hasGameHistory = function hasGameHistory() {
        return GameManager.hasGameHistory();
    };

    $scope.getCurrentView = function getCurrentView() {
        var key = (GameManager.getIsOpenGameDesign() ||
                    GameManager.getOpenDesignBeforeStart()) ?  'design' : 'instructions';
        return key;
    };

    $scope.goBack = function goBack() {
        var notDesignPage = false;
        GameManager.setIsOpenGameDesign(notDesignPage);
    };

    $scope.designNewPiece = function designNewPiece() {
        var designPage = true;
        GameManager.setIsOpenGameDesign(designPage);
    };

    $scope.getSavedTime = function getSavedTime() {
        return GameManager.getGameSavedTime();
    };

    $scope.isShowSaveGameBtn = function isShowSaveGameBtn() {
        return !GameManager.getIsOpenGameDesign();
    };

    $scope.isShowBackBtn = function isShowBackBtn() {
        return !GameManager.getOpenDesignBeforeStart();
    };

    this.isPause = function isPause() {
        return GameManager.isPause();
    };

    this.isGameStart = function isGameStart() {
        return GameManager.isGameStart();
    };
}])
.directive('diGameMenu', [
    'GameManager',
function(
    GameManager
){
    var GameMenu = {};

    GameMenu.controller = 'GameMenuCtrl';

    GameMenu.templateUrl = 'directives/diGameMenu/diGameMenu.tpl.html';

    GameMenu.restrict = 'A';

    GameMenu.replace = true;

    GameMenu.scope = true;

    GameMenu.link = function link(scope, element, attrs, controller) {
        scope.$on('app.pause', function() {
            if ((!controller.isPause() && controller.isGameStart()) ||
                GameManager.getOpenDesignBeforeStart()) {
                $(element).modal({
                    backdrop: 'static'
                });
            } else {
                scope.closeModal();
            }
        });

        scope.closeModal = function closeModal() {
            $(element).modal('hide');
        };

    };

    return GameMenu;
}]);<commit_msg>hide the instruction in mobile<commit_after>/**
* directive.diGameMenu Module
*
* Description
*/
angular.module('directive.diGameMenu', [
    'service.GameManager',
    'directive.diBootstrapSlider',
    'directive.diDesignPiece'
])
.controller('GameMenuCtrl', [
    '$scope',
    'GameManager',
    'Device',
function (
    $scope,
    GameManager,
    Device
){
    $scope.continueGame = function continueGame() {
        if (GameManager.getOpenDesignBeforeStart()) {
            GameManager.setOpenDesignBeforeStart(false);
        } else {
            GameManager.setPause();
        }
        $scope.closeModal();
    };

    $scope.restartGame = function restartGame() {
        GameManager.newGame();
        $scope.closeModal();
        GameManager.setGameStart();
    };

    $scope.endGame = function endGame() {
        GameManager.gameOver();
        $scope.closeModal();
    };

    $scope.restoreGame = function restoreGame() {
        GameManager.restoreGame();
        GameManager.setPause();
        $scope.closeModal();
    };

    $scope.hasGameHistory = function hasGameHistory() {
        return GameManager.hasGameHistory();
    };

    $scope.getCurrentView = function getCurrentView() {
        var key = (GameManager.getIsOpenGameDesign() ||
                    GameManager.getOpenDesignBeforeStart()) ?  'design' : 'instructions';
        return key;
    };

    $scope.goBack = function goBack() {
        var notDesignPage = false;
        GameManager.setIsOpenGameDesign(notDesignPage);
    };

    $scope.designNewPiece = function designNewPiece() {
        var designPage = true;
        GameManager.setIsOpenGameDesign(designPage);
    };

    $scope.getSavedTime = function getSavedTime() {
        return GameManager.getGameSavedTime();
    };

    $scope.isShowSaveGameBtn = function isShowSaveGameBtn() {
        return !GameManager.getIsOpenGameDesign();
    };

    $scope.isShowBackBtn = function isShowBackBtn() {
        return !GameManager.getOpenDesignBeforeStart();
    };

    $scope.isMobileDevice = function() {
        return Device.device;
    };

    this.isPause = function isPause() {
        return GameManager.isPause();
    };

    this.isGameStart = function isGameStart() {
        return GameManager.isGameStart();
    };
}])
.directive('diGameMenu', [
    'GameManager',
function(
    GameManager
){
    var GameMenu = {};

    GameMenu.controller = 'GameMenuCtrl';

    GameMenu.templateUrl = 'directives/diGameMenu/diGameMenu.tpl.html';

    GameMenu.restrict = 'A';

    GameMenu.replace = true;

    GameMenu.scope = true;

    GameMenu.link = function link(scope, element, attrs, controller) {
        scope.$on('app.pause', function() {
            if ((!controller.isPause() && controller.isGameStart()) ||
                GameManager.getOpenDesignBeforeStart()) {
                $(element).modal({
                    backdrop: 'static'
                });
            } else {
                scope.closeModal();
            }
        });

        scope.closeModal = function closeModal() {
            $(element).modal('hide');
        };

    };

    return GameMenu;
}]);<|endoftext|>


<commit_before>
let i18nMixin = require('../../i18n').mixin;
import validate from 'focus-core/definition/validator/validate';
let {isNull, isUndefined, isFunction} = require('lodash/lang');
let validationMixin ={
    mixins: [i18nMixin],
    /** @inheritdoc */
    getDefaultProps: function getDefaultProps() {
        return {
            isRequired: false,
            validator: undefined
        };
    },
    /**
    * Compute the validation status and merge all errors into one.
    * @param  {object} validationStatus - The result from the validation.
    * @return {true | string} - true if the validation is ok and a message if it is not the case.
    */
    _computeValidationStatus(validationStatus) {
        if(validationStatus.isValid) {
            return true;
        }
        return validationStatus.errors.join(', ');
    },
    /**
    * Validate the input.
    * @return {object}
    */
    validateInput: function validateInputText() {
        let value = this.getValue();
        let {isRequired, validator, label} = this.props;
        if (isRequired && (undefined === value || null === value)) {
            return this.i18n('field.required', {name: this.i18n(label)});
        }
        //The validation is performed only when the field has a value, otherwise, only the required validation is performed.
        if (validator && !isUndefined(value) && !isNull(value)) {
            let validStat = this._computeValidationStatus(
                validate(
                    {value: value, name: this.i18n(label)},
                    validator
                )
            );
            if(true !== validStat) {
                validStat = this.i18n(validStat);
            }
            return validStat;
        }
        return true;
    },
    _customValidate({validate: componentValidation}) {
        const {isValid, message} = componentValidation();
        return isValid ? true : this.i18n(message);
    },
    /**
    * Validate the input.
    * @return {object}
    */
    validateInputDate: function validateInputDate() {
        let value = this.getValue();
        let {isRequired, validator, label} = this.props;
        if (isRequired && (undefined === value || null === value)) {
            return this.i18n('field.required', {name: this.i18n(label)});
        }
        //The validation is performed only when the field has a value, otherwise, only the required validation is performed.
        if (validator && !isUndefined(value) && !isNull(value)) {
            let validStat = this._computeValidationStatus(
                validate(
                    {value: value, name: this.i18n(label)},
                    validator
                )
            );
            if(true !== validStat) {
                validStat = this.i18n(validStat);
            }
            return validStat;
        }
        return this._customValidate(this.refs.input);
    },
    _customValidate({validate: componentValidation}) {
        const {isValid, message} = componentValidation();
        return isValid ? true : this.i18n(message);
    },
    /**
    * Validate the field.
    * @return {object} - undefined if valid, {name: "errors"} if not valid.
    */
    validate() {
        const shouldComponentHandleValidation = this.refs && this.refs.input && isFunction(this.refs.input.validate);
        let validationStatus = shouldComponentHandleValidation ? this.validateInputDate() : this.validateInput();
        if(true !== validationStatus) {
            this.setError(validationStatus);
            return validationStatus;
        }
    },
    /**
    * Set the error on the field.
    * @param error Error to set.
    */
    setError: function setErrorOnField(error) {
        this.setState({ error: error });
    }
};
module.exports = validationMixin;
<commit_msg>Minor change<commit_after>
let i18nMixin = require('../../i18n').mixin;
import validate from 'focus-core/definition/validator/validate';
let {isNull, isUndefined, isFunction} = require('lodash/lang');
let validationMixin ={
    mixins: [i18nMixin],
    /** @inheritdoc */
    getDefaultProps: function getDefaultProps() {
        return {
            isRequired: false,
            validator: undefined
        };
    },
    /**
    * Compute the validation status and merge all errors into one.
    * @param  {object} validationStatus - The result from the validation.
    * @return {true | string} - true if the validation is ok and a message if it is not the case.
    */
    _computeValidationStatus(validationStatus) {
        if(validationStatus.isValid) {
            return true;
        }
        return validationStatus.errors.join(', ');
    },
    /**
    * Validate the input.
    * @return {object}
    */
    validateInput: function validateInputText() {
        let value = this.getValue();
        let {isRequired, validator, label} = this.props;
        if (isRequired && (undefined === value || null === value)) {
            return this.i18n('field.required', {name: this.i18n(label)});
        }
        //The validation is performed only when the field has a value, otherwise, only the required validation is performed.
        if (validator && !isUndefined(value) && !isNull(value)) {
            let validStat = this._computeValidationStatus(
                validate(
                    {value: value, name: this.i18n(label)},
                    validator
                )
            );
            if(true !== validStat) {
                validStat = this.i18n(validStat);
            }
            return validStat;
        }
        return true;
    },
    _customValidate({validate: componentValidation}) {
        const {isValid, message} = componentValidation();
        return isValid ? true : this.i18n(message);
    },
    /**
    * Validate the input date.
    * @return {object}
    */
    validateInputDate: function validateInputDate() {
        let value = this.getValue();
        let {isRequired, validator, label} = this.props;
        if (isRequired && (undefined === value || null === value)) {
            return this.i18n('field.required', {name: this.i18n(label)});
        }
        //The validation is performed only when the field has a value, otherwise, only the required validation is performed.
        if (validator && !isUndefined(value) && !isNull(value)) {
            let validStat = this._computeValidationStatus(
                validate(
                    {value: value, name: this.i18n(label)},
                    validator
                )
            );
            if(true !== validStat) {
                validStat = this.i18n(validStat);
            }
            return validStat;
        }
        return this._customValidate(this.refs.input);
    },
    _customValidate({validate: componentValidation}) {
        const {isValid, message} = componentValidation();
        return isValid ? true : this.i18n(message);
    },
    /**
    * Validate the field.
    * @return {object} - undefined if valid, {name: "errors"} if not valid.
    */
    validate() {
        const shouldComponentHandleValidation = this.refs && this.refs.input && isFunction(this.refs.input.validate);
        let validationStatus = shouldComponentHandleValidation ? this.validateInputDate() : this.validateInput();
        if(true !== validationStatus) {
            this.setError(validationStatus);
            return validationStatus;
        }
    },
    /**
    * Set the error on the field.
    * @param error Error to set.
    */
    setError: function setErrorOnField(error) {
        this.setState({ error: error });
    }
};
module.exports = validationMixin;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import './index.css'
import _ from 'lodash'
import Toggle from 'react-toggle'
import { Tooltip } from 'react-tippy'
import axios from 'axios'
import 'rc-slider/assets/index.css'
import 'rc-tooltip/assets/bootstrap.css'
import 'react-tippy/dist/tippy.css';
import RcTooltip from 'rc-tooltip'
import Slider from 'rc-slider'

const petLoader = axios.get(`https://labs.maplestory.io/api/gms/latest/pet`)
  .then(petResp =>
    {
      let petPairs = _.toPairs(petResp.data)
      let uniqPets = _.uniqBy(petPairs, pet => pet[1])
      pets = uniqPets.map(pet => {
        return {
          petId: pet[0],
          name: pet[1]
        }
      })
    }) // For some reason the standard [].map doesn't work here. :(

let pets = []

class PetEntry extends Component {
  constructor(props) {
    super(props)
    this.state = {
      actions: ['stand1', 'stand0']
    }

    // Populate true action list
    axios.get(`https://labs.maplestory.io/api/gms/latest/pet/actions/${(props.pet || {}).petId || 5000000}`)
      .then(response => this.setState({actions: _.sortBy(_.keys(response.data), a => a)}))
    if (pets.length > 0) this.state.petsLoaded = true;
    else petLoader.then(() => this.setState({ petsLoaded: true }))
  }

  componentDidUpdate(prevProps) {
    if (prevProps.pet && this.props.pet && prevProps.pet.petId == this.props.pet.petId) return
    const { pet: { petId } } = this.props

    axios.get(`https://labs.maplestory.io/api/gms/latest/pet/actions/${petId || 5000000}`)
      .then(response => this.setState({actions: _.sortBy(_.keys(response.data), a => a)}))
  }

  render() {
    const { pet, isSelected, canvasMode, onUpdatePet, onDeletePet, ...otherProps } = this.props
    return (
      <Tooltip html={this.customizePet(pet)} delay={[100, 300]} position={canvasMode ? undefined : 'bottom'} interactive={true} theme='light' distance={295} arrow={true}>

      </Tooltip>
    )
  }

  customizePet(pet) {
    return (

        Delete Pet

        Pet Type
        <select onChange={this.changePetId.bind(this)} value={pet.petId}>
          {
            pets.map(a => (
              <option value={a.petId} key={'petSelect' + a.petId}>{a.name}</option>
            ))
          }
        </select>

        Pose / Action
        <select onChange={this.changeAction.bind(this)} value={pet.animation}>
          {
            this.state.actions.map(a => (
              <option value={a} key={a}>{a}</option>
            ))
          }
        </select>

        Frame
        <Slider
          value={pet.frame || 0}
          min={0}
          max={10}
          handle={handle}
          onChange={this.changeFrame.bind(this)} />

        Zoom
        <Slider
          value={pet.zoom || 1}
          min={1}
          max={10}
          handle={handle}
          onChange={this.changeZoom.bind(this)} />

        Visible
        <Toggle onChange={this.toggleVisibility.bind(this)} checked={pet.visible} />

        Flip Horizontal
        <Toggle onChange={this.toggleFlipX.bind(this)} checked={pet.flipX} />

        Foothold Snapping
        <Toggle onChange={this.toggleFHSnap.bind(this)} checked={pet.fhSnap || false} />

        Lock
        <Toggle onChange={this.toggleLock.bind(this)} checked={pet.locked} />

)
  }

  toggleFHSnap(e) {
    this.props.onUpdateCharacter(this.props.pet, { fhSnap: !this.props.pet.fhSnap })
  }

  toggleFlipX(e) {
    this.props.onUpdatePet(this.props.pet, { flipX: !this.props.pet.flipX })
  }

  deletePet() {
    this.props.onDeletePet(this.props.pet)
  }

  changePetId (e) {
    this.props.onUpdatePet(this.props.pet, { petId: e.target.value })
  }

  changeAction (e) {
    this.props.onUpdatePet(this.props.pet, { animation: e.target.value })
  }

  changeFrame(e) {
    this.props.onUpdatePet(this.props.pet, { frame: e });
  }

  changeZoom(e) {
    this.props.onUpdatePet(this.props.pet, { zoom: e });
  }

  toggleVisibility(e) {
    this.props.onUpdatePet(this.props.pet, { visible: !this.props.pet.visible })
  }

  toggleLock(e) {
    this.props.onUpdatePet(this.props.pet, { locked: !this.props.pet.locked })
  }
}

const createSliderWithTooltip = Slider.createSliderWithTooltip;
const Range = createSliderWithTooltip(Slider.Range);
const Handle = Slider.Handle;

const handle = (props) => {
  const { value, dragging, index, ...restProps } = props;
  return (
    <RcTooltip
      prefixCls="rc-slider-tooltip"
      overlay={value}
      visible={dragging}
      placement="top"
      style={{border: "solid 2px hsl("+value+", 53%, 53%)"}}
      key={index}
    >
      <Handle value={value} {...restProps} />
    </RcTooltip>
  );
};

export default PetEntry
<commit_msg>Correcting not being able to toggle FH snapping for pets<commit_after>import React, { Component } from 'react'
import './index.css'
import _ from 'lodash'
import Toggle from 'react-toggle'
import { Tooltip } from 'react-tippy'
import axios from 'axios'
import 'rc-slider/assets/index.css'
import 'rc-tooltip/assets/bootstrap.css'
import 'react-tippy/dist/tippy.css';
import RcTooltip from 'rc-tooltip'
import Slider from 'rc-slider'

const petLoader = axios.get(`https://labs.maplestory.io/api/gms/latest/pet`)
  .then(petResp =>
    {
      let petPairs = _.toPairs(petResp.data)
      let uniqPets = _.uniqBy(petPairs, pet => pet[1])
      pets = uniqPets.map(pet => {
        return {
          petId: pet[0],
          name: pet[1]
        }
      })
    }) // For some reason the standard [].map doesn't work here. :(

let pets = []

class PetEntry extends Component {
  constructor(props) {
    super(props)
    this.state = {
      actions: ['stand1', 'stand0']
    }

    // Populate true action list
    axios.get(`https://labs.maplestory.io/api/gms/latest/pet/actions/${(props.pet || {}).petId || 5000000}`)
      .then(response => this.setState({actions: _.sortBy(_.keys(response.data), a => a)}))
    if (pets.length > 0) this.state.petsLoaded = true;
    else petLoader.then(() => this.setState({ petsLoaded: true }))
  }

  componentDidUpdate(prevProps) {
    if (prevProps.pet && this.props.pet && prevProps.pet.petId == this.props.pet.petId) return
    const { pet: { petId } } = this.props

    axios.get(`https://labs.maplestory.io/api/gms/latest/pet/actions/${petId || 5000000}`)
      .then(response => this.setState({actions: _.sortBy(_.keys(response.data), a => a)}))
  }

  render() {
    const { pet, isSelected, canvasMode, onUpdatePet, onDeletePet, ...otherProps } = this.props
    return (
      <Tooltip html={this.customizePet(pet)} delay={[100, 300]} position={canvasMode ? undefined : 'bottom'} interactive={true} theme='light' distance={295} arrow={true}>

      </Tooltip>
    )
  }

  customizePet(pet) {
    return (

        Delete Pet

        Pet Type
        <select onChange={this.changePetId.bind(this)} value={pet.petId}>
          {
            pets.map(a => (
              <option value={a.petId} key={'petSelect' + a.petId}>{a.name}</option>
            ))
          }
        </select>

        Pose / Action
        <select onChange={this.changeAction.bind(this)} value={pet.animation}>
          {
            this.state.actions.map(a => (
              <option value={a} key={a}>{a}</option>
            ))
          }
        </select>

        Frame
        <Slider
          value={pet.frame || 0}
          min={0}
          max={10}
          handle={handle}
          onChange={this.changeFrame.bind(this)} />

        Zoom
        <Slider
          value={pet.zoom || 1}
          min={1}
          max={10}
          handle={handle}
          onChange={this.changeZoom.bind(this)} />

        Visible
        <Toggle onChange={this.toggleVisibility.bind(this)} checked={pet.visible} />

        Flip Horizontal
        <Toggle onChange={this.toggleFlipX.bind(this)} checked={pet.flipX} />

        Foothold Snapping
        <Toggle onChange={this.toggleFHSnap.bind(this)} checked={pet.fhSnap || false} />

        Lock
        <Toggle onChange={this.toggleLock.bind(this)} checked={pet.locked} />

)
  }

  toggleFHSnap(e) {
    this.props.onUpdatePet(this.props.pet, { fhSnap: !this.props.pet.fhSnap })
  }

  toggleFlipX(e) {
    this.props.onUpdatePet(this.props.pet, { flipX: !this.props.pet.flipX })
  }

  deletePet() {
    this.props.onDeletePet(this.props.pet)
  }

  changePetId (e) {
    this.props.onUpdatePet(this.props.pet, { petId: e.target.value })
  }

  changeAction (e) {
    this.props.onUpdatePet(this.props.pet, { animation: e.target.value })
  }

  changeFrame(e) {
    this.props.onUpdatePet(this.props.pet, { frame: e });
  }

  changeZoom(e) {
    this.props.onUpdatePet(this.props.pet, { zoom: e });
  }

  toggleVisibility(e) {
    this.props.onUpdatePet(this.props.pet, { visible: !this.props.pet.visible })
  }

  toggleLock(e) {
    this.props.onUpdatePet(this.props.pet, { locked: !this.props.pet.locked })
  }
}

const createSliderWithTooltip = Slider.createSliderWithTooltip;
const Range = createSliderWithTooltip(Slider.Range);
const Handle = Slider.Handle;

const handle = (props) => {
  const { value, dragging, index, ...restProps } = props;
  return (
    <RcTooltip
      prefixCls="rc-slider-tooltip"
      overlay={value}
      visible={dragging}
      placement="top"
      style={{border: "solid 2px hsl("+value+", 53%, 53%)"}}
      key={index}
    >
      <Handle value={value} {...restProps} />
    </RcTooltip>
  );
};

export default PetEntry
<|endoftext|>


<commit_before>/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Relevance UI Team,
 * Aug 2015
 */

(function (angular) {
	"use strict";
	angular.module('workzone.application', ['ui.bootstrap', 'apis.workzone', 'workzonePermission', 'filter.currentTime'])
	.service('appDeployResponseFormatter', [function(){}])
		.controller('applicationCtrl', ['$scope', '$rootScope', 'workzoneServices', 'applicationPermission', '$modal', 'workzoneUIUtils', 'uiGridOptionsService', function ($scope, $rootScope, workzoneServices, applicationPerms, $modal, workzoneUIUtils, uiGridOptiSer) {
			var gridOpt=uiGridOptiSer.options();
			$rootScope.selectedCardClass='';
			var gridBottomSpace = 5;
			var gridBottomSpaceSummary = 5;
			angular.extend($scope, {
				cardGridData:[],
				selectedGridRow:[],
				pipelineConfig:'',
				pipeLineActBarShow:false,
				isApplicationPageLoading :true,
				isAppallCardTab : {icon:true,template:false},
				isHistoryTab:{icon:true,template:false},
				isAppActiveCardTab:{icon:false,template:true},
				requestParams:{},
				currentTargetId:'',
				pagiOptionsHistory :gridOpt.pagination,
				pagiOptionsCard : gridOpt.pagination,
				pagiOptionsSummary : gridOpt.pagination,
				applicationPipelineTab : function(param) {
					switch (param){
						case 'allCards' :
							$scope.isAppallCardTab = {icon:false,template:true};
							$scope.isAppActiveCardTab = {icon:true,template:false};
							$scope.isHistoryTab = {icon:true,template:false};
							removeSelect();
						break;
						case 'activeCards' :
							$scope.isAppallCardTab = {icon:true,template:false};
							$scope.isAppActiveCardTab =  {icon:false,template:true};
							$scope.isHistoryTab = {icon:true,template:false};
							removeSelect();
						break;
						case 'history' :
							$scope.isAppallCardTab = {icon:true,template:false};
							$scope.isAppActiveCardTab = {icon:true,template:false};
							$scope.isHistoryTab = {icon:false,template:true};
							removeSelect();
						break;
					}
				},
				appCardDetail :function(items) {
					$modal.open({
							animate: true,
							templateUrl: "src/partials/sections/dashboard/workzone/application/popups/applicationCardDetails.html",
							controller: "applicationCardDetailsCtrl as cardDetails",
							backdrop : 'static',
							keyboard: false,
							resolve: {
								items: function() {
									return angular.extend(items,$scope.requestParams);
								}
							}
						})
						.result.then(function() {

					}, function() {

					});
				},
				deployNewApp: function() {
					$modal.open({
							animate: true,
							templateUrl: "src/partials/sections/dashboard/workzone/application/popups/deployNewApp.html",
							controller: "deployNewAppCtrl as depNewApp",
							backdrop : 'static',
							keyboard: false,
							resolve: {
								items: $scope.requestParams
							}
						})
						.result.then(function() {

					}, function() {

					});
				},
				appInfo: function(app) {
					$modal.open({
						animation: true,
						templateUrl: 'src/partials/sections/dashboard/workzone/application/popups/applicationHistoryLogs.html',
						controller: 'applicationHistoryLogsCtrl',
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return app;
							}
						}
					}).
					result.then(function() {

					}, function() {

					});
				},
				configureAppPipelineView: function() {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/configurePipelineView.html",
						controller: "configurePipelineViewCtrl as envConfig",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return $scope.envDetails.proj;
							}
						}
					}).
					result.then(function(newEnvList) {
						$scope.pipeGridOptions.columnDefs=createColUIGrid(newEnvList,'pipeline');
						$scope.summaryGridOptions.columnDefs=createColUIGrid(newEnvList,'summary');
						if($scope.pipeLineActBarShow){
							$scope.isLastEnv=($scope.pipelineConfig.envId.length-1 === $scope.pipelineConfig.envId.indexOf($scope.pipeLineActBarData.envName)) ? true :false;
						}
					}, function() {

					});
				},
				upgradeApp: function(cardDetails) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/upgradeApp.html",
						controller: "upgradeAppCtrl as upGrdApp",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return cardDetails;
							}
						}
					}).
					result.then(function() {

					}, function() {

					});
				},
				appApprove: function(cardDetails) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/applicationApprove.html",
						controller: "applicationApproveCtrl as approveApp",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return cardDetails;
							}
						}
					}).
					result.then(function(selectedItem) {
						$scope.pipeGridOptions.data[$scope.rowIndex][selectedItem.envName]=selectedItem;
					}, function() {

					});
				},
				promoteApp: function(cardDetails) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/applicationPromote.html",
						controller: "applicationPromoteCtrl as promApp",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return angular.extend(cardDetails,{config:$scope.pipelineConfig});
							}
						}
					}).
					result.then(function() {

					}, function() {

					});
				},
				appCardRefresh :function () {
					getApplicationCardService($scope.requestParams.params,$scope.pagiOptionsCard);
				},
				appSummaryRefresh :function () {
					getSummaryCardService($scope.requestParams.params);
				},
				appHistoryRefresh :function () {
					$rootScope.$emit('REFRESH-HISTORY');
				}
			});
			var count = 0;
			/*User permission set example*/
			//defining an object for permission.
			var _permSet = {
				createApp : applicationPerms.createApp()
			};
			$scope.perms = _permSet;
			function createColUIGrid(envList,cardType){
				$scope.pipelineConfig=envList;
				var pipecolumnDefs=[];
					pipecolumnDefs = [{
						name: 'appName',
						displayName: 'App Name',
						cellTemplate: '

',
						cellTooltip: true,
						width:180
					}];
					if(envList) {
						angular.forEach(envList.envSequence, function (val) {
							if (envList.envId.indexOf(val) !== -1) {
								var optionObject = {
									name: val,
									field: val,
									displayName: val,
									cellTooltip: true,
									cellTemplate: '

'
								};
								pipecolumnDefs.push(optionObject);
							}
						});
					}
				return pipecolumnDefs;
			}
			function getApplicationPipeLineData(envParams) {
				workzoneServices.getPipelineConfig(envParams).then(function(configResult){
					//Api response is in array but it is only one object.
					$scope.pipelineConfig = configResult.data[0];
					$scope.pipeGridOptions = angular.extend(gridOpt.gridOption, {enableSorting: false}, {
						onRegisterApi: function (gridApi) {
							$scope.gridApi=gridApi;
							gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
								$scope.pagiOptionsCard.page = newPage;
								$scope.pagiOptionsCard.pageSize = pageSize;
								getApplicationCardService(envParams, $scope.pagiOptionsCard);
							});
						}
					});
					$scope.pipeGridOptions.rowTemplate = "

";
					//Api response is in array but it is only one object.
					$scope.pipeGridOptions.columnDefs=createColUIGrid(configResult.data[0],'pipeline');
					$scope.pagiOptionsCard.page=1;
					getApplicationCardService(envParams, $scope.pagiOptionsCard);
					getApplicationSummary(envParams,configResult.data[0]);
				});
			}
			function getApplicationCardService(envParams,pagiOptionsCard){
				workzoneServices.getPipelineView(envParams,pagiOptionsCard).then(function(cardResult){
					$scope.pipeGridOptions.data= cardResult.data.appDeploy;
					if(pagiOptionsCard.page === 1){
						$scope.pipeGridOptions.paginationCurrentPage = 1;
					}
					$scope.isApplicationPageLoading=false;
					removeSelect();
					$scope.pipeGridOptions.totalItems = cardResult.data.metaData.totalRecords;

				});
			}
			function getApplicationSummary(envParams,config){
				//workzoneServices.getPipelineConfig(envParams).then(function(configResult){
					$scope.summaryGridOptions = angular.extend({enableColumnMenus: false}, {enableSorting: false},
					//Api response is in array but it is only one object.
						{columnDefs:createColUIGrid(config,'summary')});
					$scope.summaryGridOptions.rowTemplate = "

";
				//});
				getSummaryCardService(envParams, $scope.pagiOptionsSummary);
			}
			function getSummaryCardService(envParams){
				workzoneServices.getSummaryCard(envParams).then(function(cardResult){
					$scope.summaryGridOptions.data= cardResult.data.pipeLineView;
					removeSelect();
					$scope.summaryGridOptions.totalItems = cardResult.data.metaData.totalRecords;
				});
			}
			$scope.selectRow = function (row,flg) {
				$scope.selectedGridRow=[];
				$scope.selectedGridRow=row;
				$scope.rowIndex = -1;
				var hash = row.entity.$$hashKey;
				var data =(flg===1)?$scope.pipeGridOptions.data:$scope.summaryGridOptions.data;     // original rows of data
				for (var ndx = 0; ndx < data.length; ndx++) {
					if (data[ndx].$$hashKey === hash) {
						$scope.rowIndex = ndx;
						break;
					}
				}
			};
			$scope.$on('SELECTED-CARD' ,function ($event,cardDetails,appName,envName){
				$scope.pipeLineActBarData ='';
				if(!cardDetails || !cardDetails.applicationInstanceName){
					$scope.pipeLineActBarShow =false;
					$rootScope.selectedCardClass='';
					$scope.currentTargetId='';
					angular.element('.card').removeClass('selected-card');
					return true;
				}
				$scope.pipeLineActBarData = angular.extend(cardDetails,{appName:appName},{envName:envName},$scope.requestParams);
				$scope.isLastEnv=($scope.pipelineConfig.envId.length-1 === $scope.pipelineConfig.envId.indexOf(envName)) ? true :false;
				if(!$scope.currentTargetId) {
					$scope.pipeLineActBarShow =true;
					$rootScope.selectedCardClass='selected-card';
					$scope.currentTargetId = cardDetails.applicationLastDeploy;
				} else if($scope.currentTargetId && cardDetails.applicationLastDeploy !== $scope.currentTargetId){
					$scope.pipeLineActBarShow =true;
					$rootScope.selectedCardClass='selected-card';
					$scope.currentTargetId = cardDetails.applicationLastDeploy;
				} else {
					$scope.pipeLineActBarShow =false;
					$rootScope.selectedCardClass='';
					$scope.currentTargetId='';
				}
			});
			function removeSelect(){
				$scope.pipeLineActBarShow =false;
				$rootScope.selectedCardClass='';
				$scope.currentTargetId='';
				angular.element('.card').removeClass('selected-card');
			}
			$rootScope.$on('VIEW-APP-LOGS',function($event,los){
				$scope.appInfo(los);
				$event.stopPropagation();
			});
			$rootScope.$on('WZ_ENV_CHANGE_START', function(event, requestParams, requestParamNames) {
				$scope.isApplicationPageLoading = true; //Application data fetch from 2 apis is about to start
				count = 0;
				getApplicationPipeLineData(requestParams);
				$scope.requestParams={params:requestParams,paramNames:requestParamNames};
				$scope.envDetails = requestParams;
				$scope.orgName = requestParamNames.org;
				$scope.selectedEnv = requestParamNames.env;
				$scope.gridHeight = workzoneUIUtils.makeTabScrollable('applicationPage')-gridBottomSpace;
				$scope.gridHeightSummary = workzoneUIUtils.makeTabScrollable('applicationPage')-gridBottomSpaceSummary;
				workzoneUIUtils.makeTabScrollable('applicationPage');
			});
		}]).controller('PipeLineViewCtrl', ['$scope', '$rootScope', 'applicationPermission',  function ($scope, $rootScope) {
			var pipeLineData={
				selectedCardClass:''
			};
			pipeLineData.getAppCardStatus = function(appCardStatus,type) {
				var colorSuffix = '';
				var appCardStateImagePrefix='instance-state-';
				var instanceStateTextPrefix='instance-state-text-';
				switch(appCardStatus) {
					case 'SUCCESSFUL':
					case 'SUCCESSFULL':
					case 'SUCCESS':
					case 'Successful':
						colorSuffix = 'running';
						break;
					case 'stopped':
						colorSuffix = 'stopped';
						break;
					case 'Failure':
						colorSuffix = 'failure';
						break;
					default:
						colorSuffix = 'unknown';
						break;
				}
				return type==="image" ? appCardStateImagePrefix + colorSuffix : instanceStateTextPrefix + colorSuffix;
			};
			pipeLineData.selectedCard = function(cardDetails,appName,envName,id,cardType){
				$scope.$emit('SELECTED-CARD',cardDetails,appName,envName);
				angular.element('.card').removeClass('selected-card');
				if($rootScope.selectedCardClass){
					angular.element('#'+id+cardType).addClass('selected-card');
				}
			};
			return pipeLineData;
		}
	]);
})(angular);<commit_msg>Notice message added in the depeloy new app<commit_after>/* Copyright (C) Relevance Lab Private Limited- All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Relevance UI Team,
 * Aug 2015
 */

(function (angular) {
	"use strict";
	angular.module('workzone.application', ['ui.bootstrap', 'apis.workzone', 'workzonePermission', 'filter.currentTime'])
	.service('appDeployResponseFormatter', [function(){}])
		.controller('applicationCtrl', ['$scope', '$rootScope', 'workzoneServices', 'applicationPermission', '$modal', 'workzoneUIUtils', 'uiGridOptionsService', function ($scope, $rootScope, workzoneServices, applicationPerms, $modal, workzoneUIUtils, uiGridOptiSer) {
			var gridOpt=uiGridOptiSer.options();
			$rootScope.selectedCardClass='';
			var gridBottomSpace = 5;
			var gridBottomSpaceSummary = 5;
			angular.extend($scope, {
				cardGridData:[],
				selectedGridRow:[],
				pipelineConfig:'',
				pipeLineActBarShow:false,
				isApplicationPageLoading :true,
				isAppallCardTab : {icon:true,template:false},
				isHistoryTab:{icon:true,template:false},
				isAppActiveCardTab:{icon:false,template:true},
				requestParams:{},
				currentTargetId:'',
				pagiOptionsHistory :gridOpt.pagination,
				pagiOptionsCard : gridOpt.pagination,
				pagiOptionsSummary : gridOpt.pagination,
				applicationPipelineTab : function(param) {
					switch (param){
						case 'allCards' :
							$scope.isAppallCardTab = {icon:false,template:true};
							$scope.isAppActiveCardTab = {icon:true,template:false};
							$scope.isHistoryTab = {icon:true,template:false};
							removeSelect();
						break;
						case 'activeCards' :
							$scope.isAppallCardTab = {icon:true,template:false};
							$scope.isAppActiveCardTab =  {icon:false,template:true};
							$scope.isHistoryTab = {icon:true,template:false};
							removeSelect();
						break;
						case 'history' :
							$scope.isAppallCardTab = {icon:true,template:false};
							$scope.isAppActiveCardTab = {icon:true,template:false};
							$scope.isHistoryTab = {icon:false,template:true};
							removeSelect();
						break;
					}
				},
				appCardDetail :function(items) {
					$modal.open({
							animate: true,
							templateUrl: "src/partials/sections/dashboard/workzone/application/popups/applicationCardDetails.html",
							controller: "applicationCardDetailsCtrl as cardDetails",
							backdrop : 'static',
							keyboard: false,
							resolve: {
								items: function() {
									return angular.extend(items,$scope.requestParams);
								}
							}
						})
						.result.then(function() {

					}, function() {

					});
				},
				deployNewApp: function() {
					$modal.open({
							animate: true,
							templateUrl: "src/partials/sections/dashboard/workzone/application/popups/deployNewApp.html",
							controller: "deployNewAppCtrl as depNewApp",
							backdrop : 'static',
							keyboard: false,
							resolve: {
								items: $scope.requestParams
							}
						})
						.result.then(function() {

					}, function() {

					});
				},
				appInfo: function(app) {
					$modal.open({
						animation: true,
						templateUrl: 'src/partials/sections/dashboard/workzone/application/popups/applicationHistoryLogs.html',
						controller: 'applicationHistoryLogsCtrl',
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return app;
							}
						}
					}).
					result.then(function() {

					}, function() {

					});
				},
				configureAppPipelineView: function() {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/configurePipelineView.html",
						controller: "configurePipelineViewCtrl as envConfig",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return $scope.envDetails.proj;
							}
						}
					}).
					result.then(function(newEnvList) {
						$scope.pipeGridOptions.columnDefs=createColUIGrid(newEnvList,'pipeline');
						$scope.summaryGridOptions.columnDefs=createColUIGrid(newEnvList,'summary');
						if($scope.pipeLineActBarShow){
							$scope.isLastEnv=($scope.pipelineConfig.envId.length-1 === $scope.pipelineConfig.envId.indexOf($scope.pipeLineActBarData.envName)) ? true :false;
						}
					}, function() {

					});
				},
				upgradeApp: function(cardDetails) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/upgradeApp.html",
						controller: "upgradeAppCtrl as upGrdApp",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return cardDetails;
							}
						}
					}).
					result.then(function() {

					}, function() {

					});
				},
				appApprove: function(cardDetails) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/applicationApprove.html",
						controller: "applicationApproveCtrl as approveApp",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return cardDetails;
							}
						}
					}).
					result.then(function(selectedItem) {
						$scope.pipeGridOptions.data[$scope.rowIndex][selectedItem.envName]=selectedItem;
					}, function() {

					});
				},
				promoteApp: function(cardDetails) {
					$modal.open({
						animate: true,
						templateUrl: "src/partials/sections/dashboard/workzone/application/popups/applicationPromote.html",
						controller: "applicationPromoteCtrl as promApp",
						backdrop : 'static',
						keyboard: false,
						resolve: {
							items: function() {
								return angular.extend(cardDetails,{config:$scope.pipelineConfig});
							}
						}
					}).
					result.then(function() {

					}, function() {

					});
				},
				appCardRefresh :function () {
					getApplicationCardService($scope.requestParams.params,$scope.pagiOptionsCard);
				},
				appSummaryRefresh :function () {
					getSummaryCardService($scope.requestParams.params);
				},
				appHistoryRefresh :function () {
					$rootScope.$emit('REFRESH-HISTORY');
				}
			});
			var count = 0;
			/*User permission set example*/
			//defining an object for permission.
			var _permSet = {
				createApp : applicationPerms.createApp()
			};
			$scope.perms = _permSet;
			function createColUIGrid(envList,cardType){
				$scope.pipelineConfig=envList;
				var pipecolumnDefs=[];
					pipecolumnDefs = [{
						name: 'appName',
						displayName: 'App Name',
						cellTemplate: '

',
						cellTooltip: true,
						width:180
					}];
					if(envList) {
						angular.forEach(envList.envSequence, function (val) {
							if (envList.envId.indexOf(val) !== -1) {
								var optionObject = {
									name: val,
									field: val,
									displayName: val,
									cellTooltip: true,
									cellTemplate: '

'
								};
								pipecolumnDefs.push(optionObject);
							}
						});
					}
				return pipecolumnDefs;
			}
			function getApplicationPipeLineData(envParams) {
				workzoneServices.getPipelineConfig(envParams).then(function(configResult){
					//Api response is in array but it is only one object.
					$scope.pipelineConfig = configResult.data[0];
					$scope.pipeGridOptions = angular.extend(gridOpt.gridOption, {enableSorting: false}, {
						onRegisterApi: function (gridApi) {
							$scope.gridApi=gridApi;
							gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
								$scope.pagiOptionsCard.page = newPage;
								$scope.pagiOptionsCard.pageSize = pageSize;
								getApplicationCardService(envParams, $scope.pagiOptionsCard);
							});
						}
					});
					$scope.pipeGridOptions.rowTemplate = "

";
					//Api response is in array but it is only one object.
					$scope.pipeGridOptions.columnDefs=createColUIGrid(configResult.data[0],'pipeline');
					$scope.pagiOptionsCard.page=1;
					getApplicationCardService(envParams, $scope.pagiOptionsCard);
					getApplicationSummary(envParams,configResult.data[0]);
				});
			}
			function getApplicationCardService(envParams,pagiOptionsCard){
				workzoneServices.getPipelineView(envParams,pagiOptionsCard).then(function(cardResult){
					$scope.pipeGridOptions.data= cardResult.data.appDeploy;
					if(pagiOptionsCard.page === 1){
						$scope.pipeGridOptions.paginationCurrentPage = 1;
					}
					$scope.isApplicationPageLoading=false;
					removeSelect();
					$scope.pipeGridOptions.totalItems = cardResult.data.metaData.totalRecords;

				});
			}
			function getApplicationSummary(envParams,config){
				//workzoneServices.getPipelineConfig(envParams).then(function(configResult){
					$scope.summaryGridOptions = angular.extend({enableColumnMenus: false}, {enableSorting: false},
					//Api response is in array but it is only one object.
						{columnDefs:createColUIGrid(config,'summary')});
					$scope.summaryGridOptions.rowTemplate = "

";
				//});
				getSummaryCardService(envParams, $scope.pagiOptionsSummary);
			}
			function getSummaryCardService(envParams){
				workzoneServices.getSummaryCard(envParams).then(function(cardResult){
					$scope.summaryGridOptions.data= cardResult.data.pipeLineView;
					removeSelect();
					$scope.summaryGridOptions.totalItems = cardResult.data.metaData.totalRecords;
				});
			}
			$scope.selectRow = function (row,flg) {
				$scope.selectedGridRow=[];
				$scope.selectedGridRow=row;
				$scope.rowIndex = -1;
				var hash = row.entity.$$hashKey;
				var data =(flg===1)?$scope.pipeGridOptions.data:$scope.summaryGridOptions.data;     // original rows of data
				for (var ndx = 0; ndx < data.length; ndx++) {
					if (data[ndx].$$hashKey === hash) {
						$scope.rowIndex = ndx;
						break;
					}
				}
			};
			$scope.$on('SELECTED-CARD' ,function ($event,cardDetails,appName,envName){
				$scope.pipeLineActBarData ='';
				if(!cardDetails || !cardDetails.applicationInstanceName){
					$scope.pipeLineActBarShow =false;
					$rootScope.selectedCardClass='';
					$scope.currentTargetId='';
					angular.element('.card').removeClass('selected-card');
					return true;
				}
				$scope.pipeLineActBarData = angular.extend(cardDetails,{appName:appName},{envName:envName},$scope.requestParams);
				$scope.isLastEnv=($scope.pipelineConfig.envId.length-1 === $scope.pipelineConfig.envId.indexOf(envName)) ? true :false;
				if(!$scope.currentTargetId) {
					$scope.pipeLineActBarShow =true;
					$rootScope.selectedCardClass='selected-card';
					$scope.currentTargetId = cardDetails.applicationLastDeploy;
				} else if($scope.currentTargetId && cardDetails.applicationLastDeploy !== $scope.currentTargetId){
					$scope.pipeLineActBarShow =true;
					$rootScope.selectedCardClass='selected-card';
					$scope.currentTargetId = cardDetails.applicationLastDeploy;
				} else {
					$scope.pipeLineActBarShow =false;
					$rootScope.selectedCardClass='';
					$scope.currentTargetId='';
				}
			});
			function removeSelect(){
				$scope.pipeLineActBarShow =false;
				$rootScope.selectedCardClass='';
				$scope.currentTargetId='';
				angular.element('.card').removeClass('selected-card');
			}
			$rootScope.$on('VIEW-APP-LOGS',function($event,los){
				$scope.appInfo(los);
				$event.stopPropagation();
			});
			$rootScope.$on('WZ_ENV_CHANGE_START', function(event, requestParams, requestParamNames) {
				$scope.isApplicationPageLoading = true; //Application data fetch from 2 apis is about to start
				count = 0;
				getApplicationPipeLineData(requestParams);
				$scope.requestParams={params:requestParams,paramNames:requestParamNames};
				$scope.envDetails = requestParams;
				$scope.orgName = requestParamNames.org;
				$scope.selectedEnv = requestParamNames.env;
				$scope.gridHeight = workzoneUIUtils.makeTabScrollable('applicationPage')-gridBottomSpace;
				$scope.gridHeightSummary = workzoneUIUtils.makeTabScrollable('applicationPage')-gridBottomSpaceSummary;
				workzoneUIUtils.makeTabScrollable('applicationPage');
			});
		}]).controller('PipeLineViewCtrl', ['$scope', '$rootScope', 'applicationPermission',  function ($scope, $rootScope) {
			var pipeLineData={
				selectedCardClass:''
			};
			pipeLineData.getAppCardStatus = function(appCardStatus,type) {
				var colorSuffix = '';
				var appCardStateImagePrefix='instance-state-';
				var instanceStateTextPrefix='instance-state-text-';
				switch(appCardStatus) {
					case 'SUCCESSFUL':
					case 'SUCCESSFULL':
					case 'SUCCESS':
					case 'Successful':
						colorSuffix = 'running';
						break;
					case 'stopped':
						colorSuffix = 'stopped';
						break;
					case 'Failure':
						colorSuffix = 'failure';
						break;
					default:
						colorSuffix = 'unknown';
						break;
				}
				return type==="image" ? appCardStateImagePrefix + colorSuffix : instanceStateTextPrefix + colorSuffix;
			};
			pipeLineData.selectedCard = function(cardDetails,appName,envName,id,cardType){
				$scope.$emit('SELECTED-CARD',cardDetails,appName,envName);
				angular.element('.card').removeClass('selected-card');
				if($rootScope.selectedCardClass){
					angular.element('#'+id+cardType).addClass('selected-card');
				}
			};
			return pipeLineData;
		}
	]);
})(angular);
<|endoftext|>


<commit_before>import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { replace } from 'react-router-redux';
import * as d3 from 'd3';
import QueryForm from './QueryForm';
import ItemSlider from '../../common/ItemSlider';
import QueryPickerItem from './QueryPickerItem';
import { selectQuery, updateQuery, addCustomQuery } from '../../../actions/explorerActions';
import { AddButton } from '../../common/IconButton';
import { getPastTwoWeeksDateRange } from '../../../lib/dateUtil';

const localMessages = {
  mainTitle: { id: 'explorer.querypicker.mainTitle', defaultMessage: 'Query List' },
  intro: { id: 'explorer.querypicker.intro', defaultMessage: 'Here are all available queries' },
  add: { id: 'explorer.querypicker.add', defaultMessage: 'Add query' },
  querySearch: { id: 'explorer.queryBuilder.advanced', defaultMessage: 'Search' },
  searchHint: { id: 'explorer.queryBuilder.hint', defaultMessage: 'Search' },
};

//
class QueryPicker extends React.Component {

  addAQuery(newQueryObj) {
    const { addAQuery } = this.props;
    addAQuery(newQueryObj);
  }

  updateQuery(obj) {
    const { updateCurrentQuery, selected, queries } = this.props;
    const updateObject = selected;
    const fieldName = obj.target ? obj.target.name : obj.name;
    const fieldValue = obj.target ? obj.target.value : obj.value;
    updateObject[fieldName] = fieldValue;
    updateCurrentQuery(updateObject, queries);
  }

  render() {
    const { selected, queries, sourcesResults, collectionsResults, setSelectedQuery, isEditable, handleSearch } = this.props;
    const { formatMessage } = this.props.intl;
    let content = null;
    let fixedQuerySlides = null;

    // if DEMO_MODE isEditable = true
    if (queries && queries.length > 0 && selected) {
      let mergedQueryWithSandCInfo = queries;
      if (sourcesResults && sourcesResults.length > 0) {
        mergedQueryWithSandCInfo = queries.map((r, idx) => Object.assign({}, r, { sources: sourcesResults[idx] }));
      }
      // TODO, make sure the indexes are ok here b/c query may not have had an id on either sources or coll
      // for new queries, we don't have this information for the default yet...
      if (collectionsResults && collectionsResults.length > 0) {
        mergedQueryWithSandCInfo = queries.map((r, idx) => Object.assign({}, r, { collections: collectionsResults[idx] ? collectionsResults[idx] : r.collections }));
      }

      fixedQuerySlides = mergedQueryWithSandCInfo.map((query, index) => (

          <QueryPickerItem
            key={index}
            query={query}
            selected={selected}
            isEditable={query.id === undefined ? true : isEditable} // if custom, true for either mode, else if logged in no
            selectThisQuery={() => setSelectedQuery(query, index)}
            updateQuery={q => this.updateQuery(q)}
          />

      ));

      // provide the add Query button, load with default values when Added is clicked
      if (isEditable) {
        const colorPallette = () => d3.scaleOrdinal(d3.schemeCategory20);
        const dateObj = getPastTwoWeeksDateRange();
        const newIndex = mergedQueryWithSandCInfo.length; // effectively a +1
        const genDefColor = colorPallette(newIndex)();
        const defaultQuery = { index: newIndex, label: 'enter query', q: 'enter here', description: 'new', startDate: dateObj.start, endDate: dateObj.end, collections: [{ tags_id: 8875027, label: 'U.S. Mainstream Media' }], sources: [], color: genDefColor, custom: true };

        const emptyQuerySlide = (

            <AddButton
              key={fixedQuerySlides.length} // this isn't working
              tooltip={formatMessage(localMessages.add)}
              onClick={() => this.addAQuery(defaultQuery)}
            />

        );

        fixedQuerySlides.push(emptyQuerySlide);
      }
      content = (
        <ItemSlider
          title={formatMessage(localMessages.intro)}
          slides={fixedQuerySlides}
          settings={{ height: 60, dots: false, slidesToShow: 4, slidesToScroll: 1, infinite: false, arrows: fixedQuerySlides.length > 4 }}
        />
      );

      // indicate which queryPickerItem is selected -
      const selectedWithSandCLabels = mergedQueryWithSandCInfo.find(q => q.index === selected.index);
      const initialValues = selectedWithSandCLabels ? { ...selectedWithSandCLabels } : {};
      return (

          {content}
          <QueryForm
            initialValues={initialValues}
            selected={selectedWithSandCLabels}
            form="queryForm"
            enableReinitialize
            destroyOnUnmount={false}
            buttonLabel={formatMessage(localMessages.querySearch)}
            onSave={handleSearch}
            onChange={event => this.updateQuery(event)}
            isEditable
          />

      );
    }
    return ('error - no queries ');
  }
}

QueryPicker.propTypes = {
  queries: React.PropTypes.array,
  sourcesResults: React.PropTypes.array,
  collectionsResults: React.PropTypes.array,
  fetchStatus: React.PropTypes.string.isRequired,
  selected: React.PropTypes.object,
  intl: React.PropTypes.object.isRequired,
  setSelectedQuery: React.PropTypes.func.isRequired,
  isEditable: React.PropTypes.bool.isRequired,
  handleSearch: React.PropTypes.func.isRequired,
  // formData: React.PropTypes.object,
  updateCurrentQuery: React.PropTypes.func.isRequired,
  addAQuery: React.PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  selected: state.explorer.selected,
  queries: state.explorer.queries,
  sourcesResults: state.explorer.sources.results ? state.explorer.sources.results : null,
  collectionsResults: state.explorer.collections.results ? state.explorer.collections.results : null,
  fetchStatus: state.explorer.collections.fetchStatus,
  // formData: formSelector(state, 'q', 'start_date', 'end_date', 'color'),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  setSelectedQuery: (query, index) => {
    const queryWithIndex = Object.assign({}, query, { index });
    dispatch(selectQuery(queryWithIndex));
  },
  updateCurrentQuery: (query, queries) => {
    // const infoToQuery = queries;
    if (query) {
      dispatch(updateQuery(query));
    } else {
      dispatch(updateQuery(ownProps.selected)); // this won't e right
    }
    // push all queries into url
    const urlParamString = queries.map(q => `{"index":${q.index},"q":${q.q},"startDate":${q.startDate},"endDate":${q.endDate},"sources":[${q.sources}],"collections":[${q.collections.map(c => c.tags_id || c.id)}]}`);
    // const urlParamString = queries.map(q => JSON.stringify(q));
    const display = urlParamString.join(',');
    const newLocation = `queries/demo/search/[${display}]`;
    dispatch(replace(newLocation)); // do a replace, not a push here so the non-snapshot url isn't in the history
  },
  addAQuery: (query) => {
    if (query) {
      dispatch(addCustomQuery(query));
      dispatch(selectQuery(query));
    }
  },
});

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps)(
      QueryPicker
    )
  );

<commit_msg>#514 need quotation marks around strings<commit_after>import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { replace } from 'react-router-redux';
import * as d3 from 'd3';
import QueryForm from './QueryForm';
import ItemSlider from '../../common/ItemSlider';
import QueryPickerItem from './QueryPickerItem';
import { selectQuery, updateQuery, addCustomQuery } from '../../../actions/explorerActions';
import { AddButton } from '../../common/IconButton';
import { getPastTwoWeeksDateRange } from '../../../lib/dateUtil';

const localMessages = {
  mainTitle: { id: 'explorer.querypicker.mainTitle', defaultMessage: 'Query List' },
  intro: { id: 'explorer.querypicker.intro', defaultMessage: 'Here are all available queries' },
  add: { id: 'explorer.querypicker.add', defaultMessage: 'Add query' },
  querySearch: { id: 'explorer.queryBuilder.advanced', defaultMessage: 'Search' },
  searchHint: { id: 'explorer.queryBuilder.hint', defaultMessage: 'Search' },
};

//
class QueryPicker extends React.Component {

  addAQuery(newQueryObj) {
    const { addAQuery } = this.props;
    addAQuery(newQueryObj);
  }

  updateQuery(obj) {
    const { updateCurrentQuery, selected, queries } = this.props;
    const updateObject = selected;
    const fieldName = obj.target ? obj.target.name : obj.name;
    const fieldValue = obj.target ? obj.target.value : obj.value;
    updateObject[fieldName] = fieldValue;
    updateCurrentQuery(updateObject, queries);
  }

  render() {
    const { selected, queries, sourcesResults, collectionsResults, setSelectedQuery, isEditable, handleSearch } = this.props;
    const { formatMessage } = this.props.intl;
    let content = null;
    let fixedQuerySlides = null;

    // if DEMO_MODE isEditable = true
    if (queries && queries.length > 0 && selected) {
      let mergedQueryWithSandCInfo = queries;
      if (sourcesResults && sourcesResults.length > 0) {
        mergedQueryWithSandCInfo = queries.map((r, idx) => Object.assign({}, r, { sources: sourcesResults[idx] }));
      }
      // TODO, make sure the indexes are ok here b/c query may not have had an id on either sources or coll
      // for new queries, we don't have this information for the default yet...
      if (collectionsResults && collectionsResults.length > 0) {
        mergedQueryWithSandCInfo = queries.map((r, idx) => Object.assign({}, r, { collections: collectionsResults[idx] ? collectionsResults[idx] : r.collections }));
      }

      fixedQuerySlides = mergedQueryWithSandCInfo.map((query, index) => (

          <QueryPickerItem
            key={index}
            query={query}
            selected={selected}
            isEditable={query.id === undefined ? true : isEditable} // if custom, true for either mode, else if logged in no
            selectThisQuery={() => setSelectedQuery(query, index)}
            updateQuery={q => this.updateQuery(q)}
          />

      ));

      // provide the add Query button, load with default values when Added is clicked
      if (isEditable) {
        const colorPallette = () => d3.scaleOrdinal(d3.schemeCategory20);
        const dateObj = getPastTwoWeeksDateRange();
        const newIndex = mergedQueryWithSandCInfo.length; // effectively a +1
        const genDefColor = colorPallette(newIndex)();
        const defaultQuery = { index: newIndex, label: 'enter query', q: 'enter here', description: 'new', startDate: dateObj.start, endDate: dateObj.end, collections: [{ tags_id: 8875027, label: 'U.S. Mainstream Media' }], sources: [], color: genDefColor, custom: true };

        const emptyQuerySlide = (

            <AddButton
              key={fixedQuerySlides.length} // this isn't working
              tooltip={formatMessage(localMessages.add)}
              onClick={() => this.addAQuery(defaultQuery)}
            />

        );

        fixedQuerySlides.push(emptyQuerySlide);
      }
      content = (
        <ItemSlider
          title={formatMessage(localMessages.intro)}
          slides={fixedQuerySlides}
          settings={{ height: 60, dots: false, slidesToShow: 4, slidesToScroll: 1, infinite: false, arrows: fixedQuerySlides.length > 4 }}
        />
      );

      // indicate which queryPickerItem is selected -
      const selectedWithSandCLabels = mergedQueryWithSandCInfo.find(q => q.index === selected.index);
      const initialValues = selectedWithSandCLabels ? { ...selectedWithSandCLabels } : {};
      return (

          {content}
          <QueryForm
            initialValues={initialValues}
            selected={selectedWithSandCLabels}
            form="queryForm"
            enableReinitialize
            destroyOnUnmount={false}
            buttonLabel={formatMessage(localMessages.querySearch)}
            onSave={handleSearch}
            onChange={event => this.updateQuery(event)}
            isEditable
          />

      );
    }
    return ('error - no queries ');
  }
}

QueryPicker.propTypes = {
  queries: React.PropTypes.array,
  sourcesResults: React.PropTypes.array,
  collectionsResults: React.PropTypes.array,
  fetchStatus: React.PropTypes.string.isRequired,
  selected: React.PropTypes.object,
  intl: React.PropTypes.object.isRequired,
  setSelectedQuery: React.PropTypes.func.isRequired,
  isEditable: React.PropTypes.bool.isRequired,
  handleSearch: React.PropTypes.func.isRequired,
  // formData: React.PropTypes.object,
  updateCurrentQuery: React.PropTypes.func.isRequired,
  addAQuery: React.PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  selected: state.explorer.selected,
  queries: state.explorer.queries,
  sourcesResults: state.explorer.sources.results ? state.explorer.sources.results : null,
  collectionsResults: state.explorer.collections.results ? state.explorer.collections.results : null,
  fetchStatus: state.explorer.collections.fetchStatus,
  // formData: formSelector(state, 'q', 'start_date', 'end_date', 'color'),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  setSelectedQuery: (query, index) => {
    const queryWithIndex = Object.assign({}, query, { index });
    dispatch(selectQuery(queryWithIndex));
  },
  updateCurrentQuery: (query, queries) => {
    // const infoToQuery = queries;
    if (query) {
      dispatch(updateQuery(query));
    } else {
      dispatch(updateQuery(ownProps.selected)); // this won't e right
    }
    // push all queries into url
    const urlParamString = queries.map(q => `{"index":${q.index},"q":"${q.q}","startDate":"${q.startDate}","endDate":"${q.endDate}","sources":[${q.sources}],"collections":[${q.collections.map(c => c.tags_id || c.id)}]}`);
    // const urlParamString = queries.map(q => JSON.stringify(q));
    const display = urlParamString.join(',');
    const newLocation = `queries/demo/search/[${display}]`;
    dispatch(replace(newLocation)); // do a replace, not a push here so the non-snapshot url isn't in the history
  },
  addAQuery: (query) => {
    if (query) {
      dispatch(addCustomQuery(query));
      dispatch(selectQuery(query));
    }
  },
});

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps)(
      QueryPicker
    )
  );

<|endoftext|>


<commit_before>/*
Copyright 2017 Vector Creations Ltd
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import PropTypes from 'prop-types';
import React from 'react';
import dis from '../../../dispatcher';
import Modal from '../../../Modal';
import sdk from '../../../index';
import { _t } from '../../../languageHandler';
import { GroupMemberType } from '../../../groups';
import { groupMemberFromApiObject } from '../../../groups';
import withMatrixClient from '../../../wrappers/withMatrixClient';
import AccessibleButton from '../elements/AccessibleButton';
import GeminiScrollbar from 'react-gemini-scrollbar';

module.exports = withMatrixClient(React.createClass({
    displayName: 'GroupMemberInfo',

    propTypes: {
        matrixClient: PropTypes.object.isRequired,
        groupId: PropTypes.string,
        groupMember: GroupMemberType,
    },

    getInitialState: function() {
        return {
            fetching: false,
            removingUser: false,
            groupMembers: null,
        };
    },

    componentWillMount: function() {
        this._fetchMembers();
    },

    _fetchMembers: function() {
        this.setState({fetching: true});
        this.props.matrixClient.getGroupUsers(this.props.groupId).then((result) => {
            this.setState({
                groupMembers: result.chunk.map((apiMember) => {
                    return groupMemberFromApiObject(apiMember);
                }),
                fetching: false,
            });
        }).catch((e) => {
            this.setState({fetching: false});
            console.error("Failed to get group groupMember list: ", e);
        });
    },

    _onKick: function() {
        const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
        Modal.createDialog(ConfirmUserActionDialog, {
            groupMember: this.props.groupMember,
            action: _t('Remove from group'),
            danger: true,
            onFinished: (proceed) => {
                if (!proceed) return;

                this.setState({removingUser: true});
                this.props.matrixClient.removeUserFromGroup(
                    this.props.groupId, this.props.groupMember.userId,
                ).then(() => {
                    // return to the user list
                    dis.dispatch({
                        action: "view_user",
                        member: null,
                    });
                }).catch((e) => {
                    const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
                    Modal.createTrackedDialog('Failed to remove user from group', '', ErrorDialog, {
                        title: _t('Error'),
                        description: _t('Failed to remove user from group'),
                    });
                }).finally(() => {
                    this.setState({removingUser: false});
                });
            },
        });
    },

    _onCancel: function(e) {
        // Go back to the user list
        dis.dispatch({
            action: "view_user",
            member: null,
        });
    },

    onRoomTileClick(roomId) {
        dis.dispatch({
            action: 'view_room',
            room_id: roomId,
        });
    },

    render: function() {
        if (this.state.fetching || this.state.removingUser) {
            const Spinner = sdk.getComponent("elements.Spinner");
            return <Spinner />;
        }
        if (!this.state.groupMembers) return null;

        const targetIsInGroup = this.state.groupMembers.some((m) => {
            return m.userId === this.props.groupMember.userId;
        });

        let kickButton;
        let adminButton;

        if (targetIsInGroup) {
            kickButton = (
                <AccessibleButton className="mx_MemberInfo_field"
                        onClick={this._onKick}>
                    {_t('Remove from group')}
                </AccessibleButton>
            );

            // No make/revoke admin API yet
            /*const opLabel = this.state.isTargetMod ? _t("Revoke Moderator") : _t("Make Moderator");
            giveModButton = <AccessibleButton className="mx_MemberInfo_field" onClick={this.onModToggle}>
                {giveOpLabel}
            </AccessibleButton>;*/
        }

        let adminTools;
        if (kickButton || adminButton) {
            adminTools =

{_t("Admin Tools")}

                        {kickButton}
                        {adminButton}

;
        }

        const BaseAvatar = sdk.getComponent('avatars.BaseAvatar');
        const avatar = (
            <BaseAvatar name={this.props.groupMember.userId} width={36} height={36} />
        );

        const groupMemberName = this.props.groupMember.userId;

        const EmojiText = sdk.getComponent('elements.EmojiText');
        return (

                <GeminiScrollbar autoshow={true}>
                    <AccessibleButton className="mx_MemberInfo_cancel"onClick={this._onCancel}>

                    </AccessibleButton>

                        {avatar}

                    <EmojiText element="h2">{groupMemberName}</EmojiText>

                            { this.props.groupMember.userId }

                    { adminTools }
                </GeminiScrollbar>

        );
    },
}));
<commit_msg>Show displayname / avatar in group member info<commit_after>/*
Copyright 2017 Vector Creations Ltd
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import PropTypes from 'prop-types';
import React from 'react';
import dis from '../../../dispatcher';
import Modal from '../../../Modal';
import sdk from '../../../index';
import { _t } from '../../../languageHandler';
import { GroupMemberType } from '../../../groups';
import { groupMemberFromApiObject } from '../../../groups';
import withMatrixClient from '../../../wrappers/withMatrixClient';
import AccessibleButton from '../elements/AccessibleButton';
import GeminiScrollbar from 'react-gemini-scrollbar';

module.exports = withMatrixClient(React.createClass({
    displayName: 'GroupMemberInfo',

    propTypes: {
        matrixClient: PropTypes.object.isRequired,
        groupId: PropTypes.string,
        groupMember: GroupMemberType,
    },

    getInitialState: function() {
        return {
            fetching: false,
            removingUser: false,
            groupMembers: null,
        };
    },

    componentWillMount: function() {
        this._fetchMembers();
    },

    _fetchMembers: function() {
        this.setState({fetching: true});
        this.props.matrixClient.getGroupUsers(this.props.groupId).then((result) => {
            this.setState({
                groupMembers: result.chunk.map((apiMember) => {
                    return groupMemberFromApiObject(apiMember);
                }),
                fetching: false,
            });
        }).catch((e) => {
            this.setState({fetching: false});
            console.error("Failed to get group groupMember list: ", e);
        });
    },

    _onKick: function() {
        const ConfirmUserActionDialog = sdk.getComponent("dialogs.ConfirmUserActionDialog");
        Modal.createDialog(ConfirmUserActionDialog, {
            groupMember: this.props.groupMember,
            action: _t('Remove from group'),
            danger: true,
            onFinished: (proceed) => {
                if (!proceed) return;

                this.setState({removingUser: true});
                this.props.matrixClient.removeUserFromGroup(
                    this.props.groupId, this.props.groupMember.userId,
                ).then(() => {
                    // return to the user list
                    dis.dispatch({
                        action: "view_user",
                        member: null,
                    });
                }).catch((e) => {
                    const ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
                    Modal.createTrackedDialog('Failed to remove user from group', '', ErrorDialog, {
                        title: _t('Error'),
                        description: _t('Failed to remove user from group'),
                    });
                }).finally(() => {
                    this.setState({removingUser: false});
                });
            },
        });
    },

    _onCancel: function(e) {
        // Go back to the user list
        dis.dispatch({
            action: "view_user",
            member: null,
        });
    },

    onRoomTileClick(roomId) {
        dis.dispatch({
            action: 'view_room',
            room_id: roomId,
        });
    },

    render: function() {
        if (this.state.fetching || this.state.removingUser) {
            const Spinner = sdk.getComponent("elements.Spinner");
            return <Spinner />;
        }
        if (!this.state.groupMembers) return null;

        const targetIsInGroup = this.state.groupMembers.some((m) => {
            return m.userId === this.props.groupMember.userId;
        });

        let kickButton;
        let adminButton;

        if (targetIsInGroup) {
            kickButton = (
                <AccessibleButton className="mx_MemberInfo_field"
                        onClick={this._onKick}>
                    {_t('Remove from group')}
                </AccessibleButton>
            );

            // No make/revoke admin API yet
            /*const opLabel = this.state.isTargetMod ? _t("Revoke Moderator") : _t("Make Moderator");
            giveModButton = <AccessibleButton className="mx_MemberInfo_field" onClick={this.onModToggle}>
                {giveOpLabel}
            </AccessibleButton>;*/
        }

        let adminTools;
        if (kickButton || adminButton) {
            adminTools =

{_t("Admin Tools")}

                        {kickButton}
                        {adminButton}

;
        }

        const BaseAvatar = sdk.getComponent('avatars.BaseAvatar');
        const avatar = (
            <BaseAvatar name={this.props.groupMember.userId} width={36} height={36}
                url={this.props.matrixClient.mxcUrlToHttp(this.props.groupMember.avatarUrl)}
            />
        );

        const groupMemberName = (
            this.props.groupMember.displayname || this.props.groupMember.userId
        );

        const EmojiText = sdk.getComponent('elements.EmojiText');
        return (

                <GeminiScrollbar autoshow={true}>
                    <AccessibleButton className="mx_MemberInfo_cancel"onClick={this._onCancel}>

                    </AccessibleButton>

                        {avatar}

                    <EmojiText element="h2">{groupMemberName}</EmojiText>

                            { this.props.groupMember.userId }

                    { adminTools }
                </GeminiScrollbar>

        );
    },
}));
<|endoftext|>