<commit_before>/*
 *   Copyright 2012 OSBI 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.
 */

/**
 * Controls the appearance and behavior of the dimension list
 *
 * This is where drag and drop lives
 */
var DimensionList = Backbone.View.extend({
    events: {
        'click span': 'select',
        'click a': 'select',
        'click .parent_dimension ul li a' : 'select_dimension',
        'click .measure' : 'select_measure'
    },

    initialize: function(args) {
        // Don't lose this
        _.bindAll(this, "render", "load_dimension","select_dimension");

        // Bind parent element
        this.workspace = args.workspace;
        this.dimension = args.dimension;

        // Fetch from the server if we haven't already
        if (args.dimension && args.dimension.has('template')) {
            this.load_dimension();
        } else if (! args.dimension){
            $(this.el).html('Could not load dimension. Please log out and log in again.');
        } else {
            $(this.el).html('Loading...');
            args.dimension.fetch({ success: this.load_dimension });
        }
    },

    load_dimension: function() {
        this.template = this.dimension.get('template');
        this.render();
        this.workspace.trigger('dimensions:loaded', $(this.el));

    },

    render: function() {
        // Pull the HTML from cache and hide all dimensions
        var self = this;
        $(this.el).hide().html(this.template);
        if (isIE && isIE <= 8) {
            $(this.el).show();
        } else {
            $(this.el).fadeTo(500,1);
        }

        // Add draggable behavior
        $(this.el).find('.measure,.level').parent('li').mousedown(function() {
            if (self.workspace.query.get('type') == "QM") {
                if ( $(self.workspace.toolbar.el).find('.toggle_fields').hasClass('on')) {
                    $(self.workspace.el).find('.workspace_fields').delay(0).slideDown({ queue: false});
                }
            }
        });
        $(this.el).find('.measure,.level').parent('li').draggable({
            cancel: '.not-draggable, .hierarchy',
            connectToSortable: $(this.workspace.el)
                .find('.columns > ul, .rows > ul, .filter > ul'),
            helper: 'clone',
            opacity: 0.60,
            tolerance: 'touch',
            tolerance: 'pointer',
            stop: function() {
                if (self.workspace.query.get('type') == "QM") {
                    if ( $(self.workspace.toolbar.el).find('.toggle_fields').hasClass('on')) {
                        $(self.workspace.el).find('.workspace_fields').slideUp( {queue: false });
                    }
                }
            },
            cursorAt: {
                top: 10,
                left: 35
            }
        });
    },

    select: function(event) {
        var $target = $(event.target).hasClass('root')
            ? $(event.target) : $(event.target).parent().find('span');
        if ($target.hasClass('root')) {
            $target.find('a').toggleClass('folder_collapsed').toggleClass('folder_expand');
            $target.toggleClass('collapsed').toggleClass('expand');
            $target.parents('li').find('ul').children('li').toggle();
        }

        return false;
    },

     select_dimension: function(event, ui) {
        if ($(event.target).parent().hasClass('ui-state-disabled')) {
            return;
        }

        var isAlreadyOnAxis = false;
        var href = $(event.target).attr('href');
        var hierarchy = href.substring(0,_.lastIndexOf(href, "/"));
        if ($(this.workspace.el).find(".workspace_fields ul li a[href^='" + hierarchy + "']:first").length > 0) {
            $axis = $(this.workspace.el).find(".workspace_fields ul li a[href^='" + hierarchy + "']").parent().parent();
        } else {
            $axis = $(this.workspace.el).find(".columns ul li").length > 0 ?
                $(this.workspace.el).find(".rows ul") :
                $(this.workspace.el).find(".columns ul");
        }
        $target = $(event.target).parent().clone()
            .appendTo($axis);
        this.workspace.drop_zones.select_dimension({
            target: $axis
        }, {
            item: $target
        });
        return false;
    },

    select_measure: function(event, ui) {
        if ($(event.target).parent().hasClass('ui-state-disabled')) {
            return;
        }

        var $axis;
        if ($(this.workspace.el).find(".rows ul .d_measure").length > 0) $axis = $(this.workspace.el).find(".rows ul");
        else if ($(this.workspace.el).find(".columns ul .d_measure").length > 0) $axis = $(this.workspace.el).find(".columns ul");
        else if ($(this.workspace.el).find(".filter ul .d_measure").length > 0) $axis = $(this.workspace.el).find(".filter ul");
        else $axis = $(this.workspace.el).find(".columns ul");

        $target = $(event.target).parent().clone();
        if ($axis.find(".d_measure").length != 0)
            $target.insertAfter($axis.find(".d_measure:last"));
        else {
            $target.appendTo($axis);
        }
        this.workspace.drop_zones.select_dimension({
            target: $axis
        }, {
            item: $target
        });
        return false;
    }
});
<commit_msg>when in mdx mode dont accept clicks on dim tree<commit_after>/*
 *   Copyright 2012 OSBI 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.
 */

/**
 * Controls the appearance and behavior of the dimension list
 *
 * This is where drag and drop lives
 */
var DimensionList = Backbone.View.extend({
    events: {
        'click span': 'select',
        'click a': 'select',
        'click .parent_dimension ul li a' : 'select_dimension',
        'click .measure' : 'select_measure'
    },

    initialize: function(args) {
        // Don't lose this
        _.bindAll(this, "render", "load_dimension","select_dimension");

        // Bind parent element
        this.workspace = args.workspace;
        this.dimension = args.dimension;

        // Fetch from the server if we haven't already
        if (args.dimension && args.dimension.has('template')) {
            this.load_dimension();
        } else if (! args.dimension){
            $(this.el).html('Could not load dimension. Please log out and log in again.');
        } else {
            $(this.el).html('Loading...');
            args.dimension.fetch({ success: this.load_dimension });
        }
    },

    load_dimension: function() {
        this.template = this.dimension.get('template');
        this.render();
        this.workspace.trigger('dimensions:loaded', $(this.el));

    },

    render: function() {
        // Pull the HTML from cache and hide all dimensions
        var self = this;
        $(this.el).hide().html(this.template);
        if (isIE && isIE <= 8) {
            $(this.el).show();
        } else {
            $(this.el).fadeTo(500,1);
        }

        // Add draggable behavior
        $(this.el).find('.measure,.level').parent('li').mousedown(function() {
            if (self.workspace.query.get('type') == "QM") {
                if ( $(self.workspace.toolbar.el).find('.toggle_fields').hasClass('on')) {
                    $(self.workspace.el).find('.workspace_fields').delay(0).slideDown({ queue: false});
                }
            }
        });
        $(this.el).find('.measure,.level').parent('li').draggable({
            cancel: '.not-draggable, .hierarchy',
            connectToSortable: $(this.workspace.el)
                .find('.columns > ul, .rows > ul, .filter > ul'),
            helper: 'clone',
            opacity: 0.60,
            tolerance: 'touch',
            tolerance: 'pointer',
            stop: function() {
                if (self.workspace.query.get('type') == "QM") {
                    if ( $(self.workspace.toolbar.el).find('.toggle_fields').hasClass('on')) {
                        $(self.workspace.el).find('.workspace_fields').slideUp( {queue: false });
                    }
                }
            },
            cursorAt: {
                top: 10,
                left: 35
            }
        });
    },

    select: function(event) {
        var $target = $(event.target).hasClass('root')
            ? $(event.target) : $(event.target).parent().find('span');
        if ($target.hasClass('root')) {
            $target.find('a').toggleClass('folder_collapsed').toggleClass('folder_expand');
            $target.toggleClass('collapsed').toggleClass('expand');
            $target.parents('li').find('ul').children('li').toggle();
        }

        return false;
    },

     select_dimension: function(event, ui) {
        if (this.workspace.query.get('type') != "QM") {
            return;
        }
        if ($(event.target).parent().hasClass('ui-state-disabled')) {
            event.preventDefault();
            return;
        }

        var isAlreadyOnAxis = false;
        var href = $(event.target).attr('href');
        var hierarchy = href.substring(0,_.lastIndexOf(href, "/"));
        if ($(this.workspace.el).find(".workspace_fields ul li a[href^='" + hierarchy + "']:first").length > 0) {
            $axis = $(this.workspace.el).find(".workspace_fields ul li a[href^='" + hierarchy + "']").parent().parent();
        } else {
            $axis = $(this.workspace.el).find(".columns ul li").length > 0 ?
                $(this.workspace.el).find(".rows ul") :
                $(this.workspace.el).find(".columns ul");
        }
        $target = $(event.target).parent().clone()
            .appendTo($axis);
        this.workspace.drop_zones.select_dimension({
            target: $axis
        }, {
            item: $target
        });
        return false;
    },

    select_measure: function(event, ui) {
        if ($(event.target).parent().hasClass('ui-state-disabled')) {
            return;
        }

        var $axis;
        if ($(this.workspace.el).find(".rows ul .d_measure").length > 0) $axis = $(this.workspace.el).find(".rows ul");
        else if ($(this.workspace.el).find(".columns ul .d_measure").length > 0) $axis = $(this.workspace.el).find(".columns ul");
        else if ($(this.workspace.el).find(".filter ul .d_measure").length > 0) $axis = $(this.workspace.el).find(".filter ul");
        else $axis = $(this.workspace.el).find(".columns ul");

        $target = $(event.target).parent().clone();
        if ($axis.find(".d_measure").length != 0)
            $target.insertAfter($axis.find(".d_measure:last"));
        else {
            $target.appendTo($axis);
        }
        this.workspace.drop_zones.select_dimension({
            target: $axis
        }, {
            item: $target
        });
        return false;
    }
});
<|endoftext|>


<commit_before>Wu.Fullscreen = Wu.Evented.extend({

	_inputs : [],

	_initialize : function () {

		// create content
		this._initContent();

		// events
		this.addEvents();
	},

	_initContent : function () {

		// create fullscreen
		this._container = Wu.DomUtil.create('div', 'smooth-fullscreen', app._appPane);

		var innerClassName = this.options.innerClassName || 'smooth-fullscreen-inner';

		var titleClassName = this.options.titleClassName ? 'smooth-fullscreen-title ' + this.options.titleClassName : 'smooth-fullscreen-title';

		// wrappers
		this._inner = Wu.DomUtil.create('div', innerClassName, this._container);
		this._header = Wu.DomUtil.create('div', titleClassName, this._inner, this.options.title);
		this._content = Wu.DomUtil.create('div', 'smooth-fullscreen-content', this._inner);
		this._closer = Wu.DomUtil.create('div', 'close-smooth-fullscreen', this._container, 'x');
	},

	addInput : function (options) {

		// create input
		var label = Wu.DomUtil.create('div', 'smooth-fullscreen-name-label', this._content, options.label);
		var input = Wu.DomUtil.create('input', 'smooth-input', this._content);
		input.setAttribute('placeholder', options.placeholder);
		input.value = options.value;
		var error = Wu.DomUtil.create('div', 'smooth-fullscreen-error-label', this._content);

		// remember
		this._inputs.push({
			label : label,
			input : input,
			error : error
		});
	},

	addEvents : function () {

		// close trigger
		Wu.DomEvent.on(this._closer, 'click', this.destroy, this);
		window.addEventListener('popstate', this.destroy.bind(this), false);

		// add esc key trigger for close fullscreen
		this._addEscapeKey();
	},

	removeEvents : function () {

		// close trigger
		Wu.DomEvent.off(this._closer, 'click', this.destroy, this);
        window.removeEventListener('popstate', this.destroy.bind(this), false);

		// add esc key trigger for close fullscreen
		this._removeEscapeKey();
	},

	close : function (options) {
		this.destroy(options);
	},

	destroy : function (options) {
		var options = options || {};
		// remove events
		this.removeEvents();

		// remove container
		this._container.innerHTML = '';
		Wu.DomUtil.remove(this._container);

		var closeCallback = this.options.closeCallback;
		closeCallback && closeCallback();
		Wu.Mixin.Events.fire('closeFullscreen', {detail : {
			projectId: options.projectId || null
		}});

		return false;
	},

	_addEscapeKey : function () {
		keymaster('esc', this.destroy.bind(this));
	},

	_removeEscapeKey : function () {
		if (keymaster.unbind) keymaster.unbind('esc');
	},

})<commit_msg>Use Wu.DomEvent instead of event listners<commit_after>Wu.Fullscreen = Wu.Evented.extend({

	_inputs : [],

	_initialize : function () {

		// create content
		this._initContent();

		// events
		this.addEvents();
	},

	_initContent : function () {

		// create fullscreen
		this._container = Wu.DomUtil.create('div', 'smooth-fullscreen', app._appPane);

		var innerClassName = this.options.innerClassName || 'smooth-fullscreen-inner';

		var titleClassName = this.options.titleClassName ? 'smooth-fullscreen-title ' + this.options.titleClassName : 'smooth-fullscreen-title';

		// wrappers
		this._inner = Wu.DomUtil.create('div', innerClassName, this._container);
		this._header = Wu.DomUtil.create('div', titleClassName, this._inner, this.options.title);
		this._content = Wu.DomUtil.create('div', 'smooth-fullscreen-content', this._inner);
		this._closer = Wu.DomUtil.create('div', 'close-smooth-fullscreen', this._container, 'x');
	},

	addInput : function (options) {

		// create input
		var label = Wu.DomUtil.create('div', 'smooth-fullscreen-name-label', this._content, options.label);
		var input = Wu.DomUtil.create('input', 'smooth-input', this._content);
		input.setAttribute('placeholder', options.placeholder);
		input.value = options.value;
		var error = Wu.DomUtil.create('div', 'smooth-fullscreen-error-label', this._content);

		// remember
		this._inputs.push({
			label : label,
			input : input,
			error : error
		});
	},

	addEvents : function () {

		// close trigger
		Wu.DomEvent.on(this._closer, 'click', this.destroy, this);
		Wu.DomEvent.on(window, 'popstate', this.destroy, this);

		// add esc key trigger for close fullscreen
		this._addEscapeKey();
	},

	removeEvents : function () {

		// close trigger
		Wu.DomEvent.off(this._closer, 'click', this.destroy, this);
		Wu.DomEvent.off(window, 'popstate', this.destroy, this);

		// add esc key trigger for close fullscreen
		this._removeEscapeKey();
	},

	close : function (options) {
		this.destroy(options);
	},

	destroy : function (options) {
		var options = options || {};
		// remove events
		this.removeEvents();

		// remove container
		this._container.innerHTML = '';
		Wu.DomUtil.remove(this._container);

		var closeCallback = this.options.closeCallback;
		closeCallback && closeCallback();
		Wu.Mixin.Events.fire('closeFullscreen', {detail : {
			projectId: options.projectId || null
		}});

		return false;
	},

	_addEscapeKey : function () {
		keymaster('esc', this.destroy.bind(this));
	},

	_removeEscapeKey : function () {
		if (keymaster.unbind) keymaster.unbind('esc');
	},

})<|endoftext|>


<commit_before>/******************************************
* Teams List View
*/
app.Views.TeamsListView = app.Views.GenericListView.extend({

	templateHTML : 'teamsList',

	itemsPerPage : 10,

	// The DOM events //
	events: function(){
		return _.defaults({
			'click a.modalCreateTeam'  : 'modalCreateTeam',
		},
			app.Views.GenericListView.prototype.events
		);
	},

	/** View Initialization
	*/
	initialize: function () {

		var self = this;

		this.initCollection().done(function(){

			// Unbind & bind the collection //
			self.collection.off();
			self.listenTo(self.collection, 'add', self.add);

			app.router.render(self);
		})
	},

	/** When the model ara created //
	*/
	add: function(model){

		var itemTeamView  = new app.Views.ItemTeamView({ model: model });
		$('#rows-items').prepend(itemTeamView.render().el);
		app.Helpers.Main.highlight($(itemTeamView.el)).done(function(){
			itemTeamView.setSelected();
		});

		app.notify('', 'success', app.lang.infoMessages.information, model.getName()+' : '+app.lang.infoMessages.teamCreateOk);

		this.partialRender();

		// Display the team members and services View //
		this.displayTeamMembersAndServices(model);
		this.options.id = model.getId();
		app.router.navigate(app.views.teamsListView.urlBuilder(), {trigger: false, replace: false});
	},

	/** Display the view
	*/
	render: function () {
		var self = this;

		// Change the page title //
		app.router.setPageTitle(app.lang.viewsTitles.teamsList);

		// Change the active menu item //
		app.views.headerView.selectMenuItem(app.router.mainMenus.configuration);

		// Retrieve the template //
		$.get("templates/" + this.templateHTML + ".html", function(templateData){
			var template = _.template(templateData, {
				nbTeams: self.collection.cpt,
				lang   : app.lang
			});

			$(self.el).html(template);

			// Call the render Generic View //
			app.Views.GenericListView.prototype.render(self.options);

			// Create item place view //
			_.each(self.collection.models, function(team, i){
				var itemTeamView  = new app.Views.ItemTeamView({model: team});
				$('#rows-items').append(itemTeamView.render().el);
			});

			// Pagination view //
			app.views.paginationView = new app.Views.PaginationView({
				page         : self.options.page.page,
				collection   : self.collection,
				itemsPerPage : self.itemsPerPage
			})
			app.views.paginationView.render();

			// If an ID is selected display the "Team members, services view" //
			if(!_.isUndefined(self.options.id)){

				// Check if the model was load in the collection //
				if(!_.isUndefined(self.collection.get(self.options.id))){
					self.displayTeamMembersAndServices(self.collection.get(self.options.id));
				}
				else{
					self.displayTeamMembersAndServices(self.options.id);
				}
			}
			// If there is only One result on the collection display the "Team members, services view" //
			else if(_.size(self.collection) == 1){
				self.displayTeamMembersAndServices(_.first(self.collection.models));
			}

		});

		$(this.el).hide().fadeIn();

		return this;
	},

	/** Partial Render of the view
	*/
	partialRender: function (type) {
		var self = this;

		this.collection.count(this.fetchParams).done(function(){
			$('#bagdeNbTeams').html(self.collection.cpt);
			app.views.paginationView.render();
		});
	},

	/** Modal form to create a new Team
	*/
	modalCreateTeam: function(e){
		e.preventDefault();

		app.views.modalTeamView = new app.Views.ModalTeamView({
			el  : '#modalSaveTeam'
		});
	},

	/** Display the form to add members and services to the team
	*/
	displayTeamMembersAndServices: function(model){
		$('#teamMembersAndServices').removeClass('hide');

		// Undelegate the events of the view //
		if(!_.isUndefined(app.views.teamMembersAndServices)){ app.views.teamMembersAndServices.undelegateEvents(); }
		app.views.teamMembersAndServices = new app.Views.TeamMembersAndServices({
			el    : '#teamMembersAndServices',
			model : model
		});
	},

	/** Collection Initialisation
	*/
	initCollection: function(){

		// Check if the collections is instantiate //
		if(_.isUndefined(this.collection)){ this.collection = new app.Collections.Teams(); }

		// Check the parameters //
		if(_.isUndefined(this.options.sort)){
			this.options.sort = this.collection.default_sort;
		}
		else{
			this.options.sort = app.Helpers.Main.calculPageSort(this.options.sort);
		}

		this.options.page = app.Helpers.Main.calculPageOffset(this.options.page, this.itemsPerPage);

		// Create Fetch params //
		this.fetchParams = {
			silent : true,
			data   : {
				limit  : (!_.isUndefined(this.itemsPerPage) ? this.itemsPerPage : app.config.itemsPerPage),
				offset : this.options.page.offset,
				sort   : this.options.sort.by+' '+this.options.sort.order
			}
		};
		if(!_.isUndefined(this.options.search)){
			this.fetchParams.data.filters = app.Helpers.Main.calculSearch({search: this.options.search }, app.Models.Team.prototype.searchable_fields);
		}

		return $.when(this.collection.fetch(this.fetchParams))
			.fail(function(e){
				console.log(e);
			})
	}
});<commit_msg>refs #1566 : supprimer une équipe, on doit prendre en compte les tâches de cette équipe dans le planning quand même<commit_after>/******************************************
* Teams List View
*/
app.Views.TeamsListView = app.Views.GenericListView.extend({

	templateHTML : 'teamsList',

	itemsPerPage : 10,

	// The DOM events //
	events: function(){
		return _.defaults({
			'click a.modalCreateTeam'  : 'modalCreateTeam',
		},
			app.Views.GenericListView.prototype.events
		);
	},

	/** View Initialization
	*/
	initialize: function () {

		var self = this;

		this.initCollection().done(function(){

			// Unbind & bind the collection //
			self.collection.off();
			self.listenTo(self.collection, 'add', self.add);

			app.router.render(self);
		})
	},

	/** When the model ara created //
	*/
	add: function(model){

		var itemTeamView  = new app.Views.ItemTeamView({ model: model });
		$('#rows-items').prepend(itemTeamView.render().el);
		app.Helpers.Main.highlight($(itemTeamView.el)).done(function(){
			itemTeamView.setSelected();
		});

		app.notify('', 'success', app.lang.infoMessages.information, model.getName()+' : '+app.lang.infoMessages.teamCreateOk);

		this.partialRender();

		// Display the team members and services View //
		this.displayTeamMembersAndServices(model);
		this.options.id = model.getId();
		app.router.navigate(app.views.teamsListView.urlBuilder(), {trigger: false, replace: false});
	},

	/** Display the view
	*/
	render: function () {
		var self = this;

		// Change the page title //
		app.router.setPageTitle(app.lang.viewsTitles.teamsList);

		// Change the active menu item //
		app.views.headerView.selectMenuItem(app.router.mainMenus.configuration);

		// Retrieve the template //
		$.get("templates/" + this.templateHTML + ".html", function(templateData){
			var template = _.template(templateData, {
				nbTeams: self.collection.cpt,
				lang   : app.lang
			});

			$(self.el).html(template);

			// Call the render Generic View //
			app.Views.GenericListView.prototype.render(self.options);

			// Create item place view //
			_.each(self.collection.models, function(team, i){
				var itemTeamView  = new app.Views.ItemTeamView({model: team});
				$('#rows-items').append(itemTeamView.render().el);
			});

			// Pagination view //
			app.views.paginationView = new app.Views.PaginationView({
				page         : self.options.page.page,
				collection   : self.collection,
				itemsPerPage : self.itemsPerPage
			})
			app.views.paginationView.render();

			// If an ID is selected display the "Team members, services view" //
			if(!_.isUndefined(self.options.id)){

				// Check if the model was load in the collection //
				if(!_.isUndefined(self.collection.get(self.options.id))){
					self.displayTeamMembersAndServices(self.collection.get(self.options.id));
				}
				else{
					self.displayTeamMembersAndServices(self.options.id);
				}
			}
			// If there is only One result on the collection display the "Team members, services view" //
			else if(_.size(self.collection) == 1){
				self.displayTeamMembersAndServices(_.first(self.collection.models));
			}

		});

		$(this.el).hide().fadeIn();

		return this;
	},

	/** Partial Render of the view
	*/
	partialRender: function (type) {
		var self = this;

		this.collection.count(this.fetchParams).done(function(){
			$('#bagdeNbTeams').html(self.collection.cpt);
			app.views.paginationView.render();
		});
	},

	/** Modal form to create a new Team
	*/
	modalCreateTeam: function(e){
		e.preventDefault();

		app.views.modalTeamView = new app.Views.ModalTeamView({
			el  : '#modalSaveTeam'
		});
	},

	/** Display the form to add members and services to the team
	*/
	displayTeamMembersAndServices: function(model){
		$('#teamMembersAndServices').removeClass('hide');

		// Undelegate the events of the view //
		if(!_.isUndefined(app.views.teamMembersAndServices)){ app.views.teamMembersAndServices.undelegateEvents(); }
		app.views.teamMembersAndServices = new app.Views.TeamMembersAndServices({
			el    : '#teamMembersAndServices',
			model : model
		});
	},

	/** Collection Initialisation
	*/
	initCollection: function(){

		// Check if the collections is instantiate //
		if(_.isUndefined(this.collection)){ this.collection = new app.Collections.Teams(); }

		// Check the parameters //
		if(_.isUndefined(this.options.sort)){
			this.options.sort = this.collection.default_sort;
		}
		else{
			this.options.sort = app.Helpers.Main.calculPageSort(this.options.sort);
		}

		this.options.page = app.Helpers.Main.calculPageOffset(this.options.page, this.itemsPerPage);

		// Create Fetch params //
		this.fetchParams = {
			silent : true,
			data   : {
				limit  : (!_.isUndefined(this.itemsPerPage) ? this.itemsPerPage : app.config.itemsPerPage),
				offset : this.options.page.offset,
				sort   : this.options.sort.by+' '+this.options.sort.order
			}
		};
		this.fetchParams.data.filters = [];
		if(!_.isUndefined(this.options.search)){
			this.fetchParams.data.filters = app.Helpers.Main.calculSearch({search: this.options.search }, app.Models.Team.prototype.searchable_fields, true);
		}
		//No displays teams deleted
		this.fetchParams.data.filters.push({field:'deleted_at',operator:'=',value:'False'})

		return $.when(this.collection.fetch(this.fetchParams))
			.fail(function(e){
				console.log(e);
			})
	}
});<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

( function() {

    "use strict";

    var UnivariateTile = require('./UnivariateTile');

    function getResolutionScale(layer) {
        return parseInt(layer.div.style.width, 10) / 100;
    }

    function clampBounds( bounds, layer ) {
        bounds = bounds.clone();
        if ( layer.dimension === "x" ) {
            bounds.bottom = layer.map.getMaxExtent().bottom;
            bounds.top = layer.map.getMaxExtent().bottom + 1;
        } else {
            bounds.left = layer.map.getMaxExtent().left;
            bounds.right = layer.map.getMaxExtent().left + 1;
        }
        return bounds;
    }

    function repositionLayer( map, layer ) {
        var $viewport = $( map.viewPortDiv ),
            $div = $( layer.div ),
            height = $viewport.height();
        if ( layer.dimension === "x" )  {
            $div.css( 'top', height );
        } else {
            $div.css( 'left', 0 );
        }
    }

    function onMapMove( map, layer ) {
        return function() {
            var $container = $( layer.div ).parent(),
                $viewport = $( map.viewPortDiv ),
                $div = $( layer.div ),
                offset = $container.position(),
                height = $viewport.height();
            if ( layer.dimension === "x" ) {
                // reset tile position within the layer div
                $div.children().each( function() {
                    $( this ).css( 'top', -256 );
                });
                // then set div position
                $div.css( 'top', height - offset.top );
            } else {
                // reset tile position within the layer div
                $div.children().each( function() {
                    $( this ).css( 'left', 0 );
                });
                // then set div position
                $div.css( 'left', -offset.left );
            }
        };
    }

    OpenLayers.Layer.Univariate = function( name, url, options ) {
        OpenLayers.Layer.Grid.call( this, name, url, options );
        this.getURL = options.getURL;
        this.layername = options.layername;
        this.dimension = options.dimension || 'x';
        this.type = options.type;
        this.tileClass = options.tileClass || UnivariateTile;
        this.html = options.html;
        this.renderer = options.renderer;
        this.CLASS_NAME = 'OpenLayers.Layer.Univariate';
    };

    OpenLayers.Layer.Univariate.prototype = Object.create( OpenLayers.Layer.Grid.prototype );

    /**
     * Override to set all children the opacity.
     */
    OpenLayers.Layer.Univariate.prototype.setOpacity = function( opacity ) {
        if ( opacity !== this.opacity ) {
            this.opacity = Math.max( Math.min( opacity, 1 ), 0 );
            var childNodes = this.div.childNodes;
            for( var i = 0, len = childNodes.length; i < len; ++i ) {
                childNodes[i].style.opacity = this.opacity;
            }
            if ( this.map !== null ) {
                this.map.events.triggerEvent( "changelayer", {
                    layer: this,
                    property: "opacity"
                });
            }
        }
    };

    /**
     * Override this method to add a positioning function to clamp
     * the layers tiles to the appropriate axis.
     */
    OpenLayers.Layer.Univariate.prototype.setMap = function( map ) {
        OpenLayers.Layer.Grid.prototype.setMap.apply( this, arguments );
        this.onMapMove = onMapMove( map, this );
        map.events.register( 'move', map, this.onMapMove );
        repositionLayer( map, this ); // set position
    };

    /**
     * Override this method to remove the positioning function to clamp
     * the layers tiles to the appropriate axis.
     */
    OpenLayers.Layer.Univariate.prototype.removeMap = function( map ) {
        OpenLayers.Layer.Grid.prototype.removeMap.apply( this, arguments );
        map.events.unregister( 'move', map, this.onMapMove );
        this.onMapMove = null;
    };

    /**
     * Override this method to re-position the layer and prevent a redraw which
     * will reposition the tiles.
     */
    OpenLayers.Layer.Univariate.prototype.setVisibility = function( visibility ) {
        OpenLayers.Layer.Grid.prototype.setVisibility.apply( this, arguments );
        if ( this.onMapMove && visibility ) {
            repositionLayer( this.map, this );
        }
    };

    OpenLayers.Layer.Univariate.prototype.getExtent = function() {
        return clampBounds( this.map.calculateBounds(), this );
    };

    OpenLayers.Layer.Univariate.prototype.redraw = function() {
        var redrawn = false;
        if (this.map) {
            // min/max Range may have changed
            this.inRange = this.calculateInRange();
            // map's center might not yet be set
            var extent = this.getExtent();
            if ( extent && this.inRange && this.visibility ) {
                var zoomChanged = true;
                this.moveTo( extent, zoomChanged, false );
                this.events.triggerEvent("moveend",
                    {"zoomChanged": zoomChanged});
                redrawn = true;
                repositionLayer( this.map, this );
            }
        }
        return redrawn;
    };

    /**
     * Override this method to clamp the 'maxExtents' value returned from the
     * map object.
     */
    OpenLayers.Layer.Univariate.prototype.moveTo = function( bounds, zoomChanged, dragging ) {

        if ( !bounds ) {
            bounds = this.map.getExtent();
        }

        if ( bounds !== null ) {

            bounds = clampBounds( bounds, this );

            // if grid is empty or zoom has changed, we *must* re-tile
            var forceReTile = !this.grid.length || zoomChanged;

            // total bounds of the tiles
            var tilesBounds = this.getTilesBounds();

            // the new map resolution
            var resolution = this.map.getResolution();

            // the server-supported resolution for the new map resolution
            var serverResolution = this.getServerResolution(resolution);

            if ( this.singleTile ) {

                // We want to redraw whenever even the slightest part of the
                //  current bounds is not contained by our tile.
                //  (thus, we do not specify partial -- its default is false)

                if ( forceReTile ||
                     ( !dragging && !tilesBounds.containsBounds( bounds ) ) ) {

                    // In single tile mode with no transition effect, we insert
                    // a non-scaled backbuffer when the layer is moved. But if
                    // a zoom occurs right after a move, i.e. before the new
                    // image is received, we need to remove the backbuffer, or
                    // an ill-positioned image will be visible during the zoom
                    // transition.

                    if ( zoomChanged && this.transitionEffect !== 'resize' ) {
                        this.removeBackBuffer();
                    }

                    if ( !zoomChanged || this.transitionEffect === 'resize' ) {
                        this.applyBackBuffer( serverResolution );
                    }

                    this.initSingleTile( bounds );
                }
            } else {

                // if the bounds have changed such that they are not even
                // *partially* contained by our tiles (e.g. when user has
                // programmatically panned to the other side of the earth on
                // zoom level 18), then moveGriddedTiles could potentially have
                // to run through thousands of cycles, so we want to reTile
                // instead (thus, partial true).
                forceReTile = forceReTile ||
                    !tilesBounds.intersectsBounds( bounds, {
                        worldBounds: this.map.baseLayer.wrapDateLine &&
                            clampBounds( this.map.getMaxExtent(), this )
                    });

                if ( resolution !== serverResolution ) {
                    bounds = this.map.calculateBounds( null, serverResolution );
                    bounds = clampBounds( bounds, this );
                    if( forceReTile ) {
                        // stretch the layer div
                        var scale = serverResolution / resolution;
                        this.transformDiv( scale );
                    }
                } else {
                    // reset the layer width, height, left, top, to deal with
                    // the case where the layer was previously transformed
                    this.div.style.width = '100%';
                    this.div.style.height = '100%';
                    this.div.style.left = '0%';
                    this.div.style.top = '0%';
                }

                if ( forceReTile ) {
                    if ( zoomChanged && this.transitionEffect === 'resize' ) {
                        this.applyBackBuffer( serverResolution );
                    }
                    this.initGriddedTiles( bounds );
                } else {
                    this.moveGriddedTiles();
                }
            }
        }
    };

    /**
     * Override this method to only shift the appropriate row or column
     * of the grid depending the the dimension this layer represents.
     */
    OpenLayers.Layer.Univariate.prototype.moveGriddedTiles = function(deferred) {
        var buffer = this.buffer + 1;
        while(true) {
            var tlTile = this.grid[0][0];
            var tlViewPort = {
                x: tlTile.position.x +
                this.map.layerContainerOriginPx.x,
                y: tlTile.position.y +
                this.map.layerContainerOriginPx.y
            };
            var ratio = this.getServerResolution() / this.map.getResolution();
            var tileSize = {
                w: Math.round(this.tileSize.w * ratio),
                h: Math.round(this.tileSize.h * ratio)
            };
            if (tlViewPort.x > -tileSize.w * (buffer - 1)) {
                this.shiftColumn(true, tileSize);
            } else if (tlViewPort.x < -tileSize.w * buffer) {
                this.shiftColumn(false, tileSize);
            } else if (tlViewPort.y > -tileSize.h * (buffer - 1)) {
                this.shiftRow(true, tileSize);
            } else if (tlViewPort.y < -tileSize.h * buffer) {
                this.shiftRow(false, tileSize);
            } else {
                break;
            }
        }
    }
    //    if ( !deferred && !OpenLayers.Animation.isNative ) {
    //        if ( this.moveTimerId !== null ) {
    //            window.clearTimeout( this.moveTimerId );
    //        }
    //        this.moveTimerId = window.setTimeout(
    //            this.deferMoveGriddedTiles, this.tileLoadingDelay
    //        );
    //        return;
    //    }
    //    var buffer = this.buffer || 1;
    //    var scale = getResolutionScale(this);
    //    while ( true ) {
    //        var gridIdx = 0;
    //        for (var i = 0; i < this.grid.length; i++) {
    //            gridIdx = i;
    //            if (this.grid[i].length != 0) {
    //                break;
    //            }
    //        }
    //        console.log(this.grid);
    //        var tlViewPort = {
    //            x: ( this.grid[gridIdx][0].position.x * scale ) +
    //                parseInt( this.div.style.left, 10 ) +
    //                parseInt( this.map.layerContainerDiv.style.left ),
    //            y: ( this.grid[gridIdx][0].position.y * scale ) +
    //                parseInt( this.div.style.top, 10 ) +
    //                parseInt( this.map.layerContainerDiv.style.top )
    //        };
    //        var tileSize = {
    //            w: this.tileSize.w * scale,
    //            h: this.tileSize.h * scale
    //        };
    //
    //        if ( this.dimension === 'x' ) {
    //            if (tlViewPort.x > -tileSize.w * (buffer - 1)) {
    //                this.shiftColumn( true );
    //            } else if (tlViewPort.x < -tileSize.w * buffer) {
    //                this.shiftColumn( false );
    //            } else {
    //                break;
    //            }
    //        } else {
    //            if (tlViewPort.y > -tileSize.h * (buffer - 1)) {
    //                this.shiftRow( true );
    //            } else if (tlViewPort.y < -tileSize.h * buffer) {
    //                this.shiftRow( false );
    //            } else {
    //                break;
    //            }
    //        }
    //    }
    //};

    module.exports = OpenLayers.Layer.Univariate;
}());
<commit_msg>restricts row/columnt shift based on layer dimension<commit_after>/*
 * Copyright (c) 2014 Oculus Info Inc.
 * http://www.oculusinfo.com/
 *
 * Released under the MIT License.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

( function() {

    "use strict";

    var UnivariateTile = require('./UnivariateTile');

    function getResolutionScale(layer) {
        return parseInt(layer.div.style.width, 10) / 100;
    }

    function clampBounds( bounds, layer ) {
        bounds = bounds.clone();
        if ( layer.dimension === "x" ) {
            bounds.bottom = layer.map.getMaxExtent().bottom;
            bounds.top = layer.map.getMaxExtent().bottom + 1;
        } else {
            bounds.left = layer.map.getMaxExtent().left;
            bounds.right = layer.map.getMaxExtent().left + 1;
        }
        return bounds;
    }

    function repositionLayer( map, layer ) {
        var $viewport = $( map.viewPortDiv ),
            $div = $( layer.div ),
            height = $viewport.height();
        if ( layer.dimension === "x" )  {
            $div.css( 'top', height );
        } else {
            $div.css( 'left', 0 );
        }
    }

    function onMapMove( map, layer ) {
        return function() {
            var $container = $( layer.div ).parent(),
                $viewport = $( map.viewPortDiv ),
                $div = $( layer.div ),
                offset = $container.position(),
                height = $viewport.height();
            if ( layer.dimension === "x" ) {
                // reset tile position within the layer div
                $div.children().each( function() {
                    $( this ).css( 'top', -256 );
                });
                // then set div position
                $div.css( 'top', height - offset.top );
            } else {
                // reset tile position within the layer div
                $div.children().each( function() {
                    $( this ).css( 'left', 0 );
                });
                // then set div position
                $div.css( 'left', -offset.left );
            }
        };
    }

    OpenLayers.Layer.Univariate = function( name, url, options ) {
        OpenLayers.Layer.Grid.call( this, name, url, options );
        this.getURL = options.getURL;
        this.layername = options.layername;
        this.dimension = options.dimension || 'x';
        this.type = options.type;
        this.tileClass = options.tileClass || UnivariateTile;
        this.html = options.html;
        this.renderer = options.renderer;
        this.CLASS_NAME = 'OpenLayers.Layer.Univariate';
    };

    OpenLayers.Layer.Univariate.prototype = Object.create( OpenLayers.Layer.Grid.prototype );

    /**
     * Override to set all children the opacity.
     */
    OpenLayers.Layer.Univariate.prototype.setOpacity = function( opacity ) {
        if ( opacity !== this.opacity ) {
            this.opacity = Math.max( Math.min( opacity, 1 ), 0 );
            var childNodes = this.div.childNodes;
            for( var i = 0, len = childNodes.length; i < len; ++i ) {
                childNodes[i].style.opacity = this.opacity;
            }
            if ( this.map !== null ) {
                this.map.events.triggerEvent( "changelayer", {
                    layer: this,
                    property: "opacity"
                });
            }
        }
    };

    /**
     * Override this method to add a positioning function to clamp
     * the layers tiles to the appropriate axis.
     */
    OpenLayers.Layer.Univariate.prototype.setMap = function( map ) {
        OpenLayers.Layer.Grid.prototype.setMap.apply( this, arguments );
        this.onMapMove = onMapMove( map, this );
        map.events.register( 'move', map, this.onMapMove );
        repositionLayer( map, this ); // set position
    };

    /**
     * Override this method to remove the positioning function to clamp
     * the layers tiles to the appropriate axis.
     */
    OpenLayers.Layer.Univariate.prototype.removeMap = function( map ) {
        OpenLayers.Layer.Grid.prototype.removeMap.apply( this, arguments );
        map.events.unregister( 'move', map, this.onMapMove );
        this.onMapMove = null;
    };

    /**
     * Override this method to re-position the layer and prevent a redraw which
     * will reposition the tiles.
     */
    OpenLayers.Layer.Univariate.prototype.setVisibility = function( visibility ) {
        OpenLayers.Layer.Grid.prototype.setVisibility.apply( this, arguments );
        if ( this.onMapMove && visibility ) {
            repositionLayer( this.map, this );
        }
    };

    OpenLayers.Layer.Univariate.prototype.getExtent = function() {
        return clampBounds( this.map.calculateBounds(), this );
    };

    OpenLayers.Layer.Univariate.prototype.redraw = function() {
        var redrawn = false;
        if (this.map) {
            // min/max Range may have changed
            this.inRange = this.calculateInRange();
            // map's center might not yet be set
            var extent = this.getExtent();
            if ( extent && this.inRange && this.visibility ) {
                var zoomChanged = true;
                this.moveTo( extent, zoomChanged, false );
                this.events.triggerEvent("moveend",
                    {"zoomChanged": zoomChanged});
                redrawn = true;
                repositionLayer( this.map, this );
            }
        }
        return redrawn;
    };

    /**
     * Override this method to clamp the 'maxExtents' value returned from the
     * map object.
     */
    OpenLayers.Layer.Univariate.prototype.moveTo = function( bounds, zoomChanged, dragging ) {

        if ( !bounds ) {
            bounds = this.map.getExtent();
        }

        if ( bounds !== null ) {

            bounds = clampBounds( bounds, this );

            // if grid is empty or zoom has changed, we *must* re-tile
            var forceReTile = !this.grid.length || zoomChanged;

            // total bounds of the tiles
            var tilesBounds = this.getTilesBounds();

            // the new map resolution
            var resolution = this.map.getResolution();

            // the server-supported resolution for the new map resolution
            var serverResolution = this.getServerResolution(resolution);

            if ( this.singleTile ) {

                // We want to redraw whenever even the slightest part of the
                //  current bounds is not contained by our tile.
                //  (thus, we do not specify partial -- its default is false)

                if ( forceReTile ||
                     ( !dragging && !tilesBounds.containsBounds( bounds ) ) ) {

                    // In single tile mode with no transition effect, we insert
                    // a non-scaled backbuffer when the layer is moved. But if
                    // a zoom occurs right after a move, i.e. before the new
                    // image is received, we need to remove the backbuffer, or
                    // an ill-positioned image will be visible during the zoom
                    // transition.

                    if ( zoomChanged && this.transitionEffect !== 'resize' ) {
                        this.removeBackBuffer();
                    }

                    if ( !zoomChanged || this.transitionEffect === 'resize' ) {
                        this.applyBackBuffer( serverResolution );
                    }

                    this.initSingleTile( bounds );
                }
            } else {

                // if the bounds have changed such that they are not even
                // *partially* contained by our tiles (e.g. when user has
                // programmatically panned to the other side of the earth on
                // zoom level 18), then moveGriddedTiles could potentially have
                // to run through thousands of cycles, so we want to reTile
                // instead (thus, partial true).
                forceReTile = forceReTile ||
                    !tilesBounds.intersectsBounds( bounds, {
                        worldBounds: this.map.baseLayer.wrapDateLine &&
                            clampBounds( this.map.getMaxExtent(), this )
                    });

                if ( resolution !== serverResolution ) {
                    bounds = this.map.calculateBounds( null, serverResolution );
                    bounds = clampBounds( bounds, this );
                    if( forceReTile ) {
                        // stretch the layer div
                        var scale = serverResolution / resolution;
                        this.transformDiv( scale );
                    }
                } else {
                    // reset the layer width, height, left, top, to deal with
                    // the case where the layer was previously transformed
                    this.div.style.width = '100%';
                    this.div.style.height = '100%';
                    this.div.style.left = '0%';
                    this.div.style.top = '0%';
                }

                if ( forceReTile ) {
                    if ( zoomChanged && this.transitionEffect === 'resize' ) {
                        this.applyBackBuffer( serverResolution );
                    }
                    this.initGriddedTiles( bounds );
                } else {
                    this.moveGriddedTiles();
                }
            }
        }
    };

    /**
     * Override this method to only shift the appropriate row or column
     * of the grid depending the the dimension this layer represents.
     */
    OpenLayers.Layer.Univariate.prototype.moveGriddedTiles = function(deferred) {
        var buffer = this.buffer + 1;
        while(true) {
            var tlTile = this.grid[0][0];
            var tlViewPort = {
                x: tlTile.position.x +
                this.map.layerContainerOriginPx.x,
                y: tlTile.position.y +
                this.map.layerContainerOriginPx.y
            };
            var ratio = this.getServerResolution() / this.map.getResolution();
            var tileSize = {
                w: Math.round(this.tileSize.w * ratio),
                h: Math.round(this.tileSize.h * ratio)
            };
            if (this.dimension === 'x') {
                if (tlViewPort.x > -tileSize.w * (buffer - 1)) {
                    this.shiftColumn(true, tileSize);
                } else if (tlViewPort.x < -tileSize.w * buffer) {
                    this.shiftColumn(false, tileSize);
                } else {
                    break;
                }
            } else {
                if (tlViewPort.y > -tileSize.h * (buffer - 1)) {
                    this.shiftRow(true, tileSize);
                } else if (tlViewPort.y < -tileSize.h * buffer) {
                    this.shiftRow(false, tileSize);
                } else {
                    break;
                }
            }
        }
    }
    module.exports = OpenLayers.Layer.Univariate;
}());
<|endoftext|>


<commit_before>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.StartQueryBuilderView = Backbone.View.extend({
    el: "#developer-playground",

    template: _.template($('#playground-template').html()),

    events: {
        'change .form-control#entity': 'changeParam',
        'change .form-control#parameter': 'changeFilter',
        'click .btn#san-francisco': 'changeMapSF',
        'click .btn#new-york': 'changeMapNY',
        'click .btn#run-query-btn' : 'submit'
    },

    initialize: function () {
        this.operators = new DeveloperPlayground.Operators();
        this.stops = new DeveloperPlayground.Stops();
        this.routes = new DeveloperPlayground.Routes();
        this.render();
    },

    render: function() {
        this.$el.html(this.template());
        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");
        this.mapview = new DeveloperPlayground.MapView();
        this.mapview.render();
        this.downloadview = new DeveloperPlayground.DownloadView();
        this.downloadview.render();
        return this;
    },

    changeMapSF: function(){
        if($(".btn#new-york").hasClass("selected")) $(".btn#new-york").removeClass("selected");
        $(".btn#san-francisco").addClass("selected");
        this.mapview.setMapviewSF();
    },

    changeMapNY: function(){
        if($(".btn#san-francisco").hasClass("selected")) $(".btn#san-francisco").removeClass("selected");
        $(".btn#new-york").addClass("selected");
        this.mapview.setMapviewNY();
    },

    changeParam: function() {

        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var selectValues = {
            "base": {
                " ": "",
            },
            "stops": {
                " ": "",
                "map view": "",
                "operator": "",
            },
            "operators": {
                " ": "",
                "map view": "",
                "name": "",
                // "mode": "",
            },
            "routes": {
                " ": "",
                "map view": "",
                "operator": "",
                // "route number": "",
            }
        };

        $parameterSelect.empty().append(function() {
            var output = '';
            $.each(selectValues[$entitySelect.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });

        return this;
    },

    changeFilter: function() {
        var $parameterSelect = $('select.form-control#parameter');

        if($parameterSelect.val() == "name" || $parameterSelect.val() == "operator") {
            collection = this.operators;
            $(".form-control#name").show();
            $(".btn#new-york").hide();
            $(".btn#san-francisco").hide();

            if(!$("#nameMenu").hasClass("dropdown")) $("#nameMenu").addClass("dropdown");
            if ('undefined' !== typeof this.nameListView) {
                this.nameListView.close();
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            } else {
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            }
            this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/operators.json?per_page=5000'
                });
            collection.fetch();
            return this;

        } else {
            $(".form-control#name").hide();
            this.changeMapSF();
            $(".btn#new-york").show();
            $(".btn#san-francisco").show();

            if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        }
    },

    submit: function() {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var $nameSelect = $('select.form-control#name');
        var bounds = this.mapview.getBounds();
        var identifier = $nameSelect.val();

        var shouldFetchAndResetCollection = true;

        // FOR STOP QUERIES

        if ($entitySelect.val() == "stops") {
            // for search by map view
            if($parameterSelect.val() == "map view") {
            collection = this.stops;
            this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            // for search by operator name
            } else if($parameterSelect.val() == "operator") {
                collection = this.stops;
                this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?servedBy='+identifier+'&per_page=5000',
                });
            }

        // FOR OPERATOR QUERIES

        } else if ($entitySelect.val() == "operators") {

            if($parameterSelect.val() == "map view") {
                collection = this.operators;
                this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "name") {
                this.operators.hideAll();
                this.operators.get(identifier).set({ display: true });
                shouldFetchAndResetCollection = false;
            } else {
                alert("Please select either map view or name.");
            }

        //  FOR ROUTE QUERIES

        } else if ($entitySelect.val() == "routes") {
            if($parameterSelect.val() == "map view") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "operator") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?operatedBy='+identifier+'&per_page=5000',
                });
            } else if($parameterSelect.val() == "route number") {
                collection = this.routes;
                alert("routes by route number not yet functional");
            }
        } else {
            alert("Please select a parameter.");
        }

        if (shouldFetchAndResetCollection) {
            collection.reset();
        }

        $("#download-bar").show();
        this.mapview.markerclustergroup.clearLayers();
        this.mapview.clearCollection();
        this.mapview.setCollection({collection: collection});
        this.mapview.initialize({collection: collection});
        this.downloadview.setCollection({collection: collection});

        if ('undefined' !== typeof this.gridview) this.gridview.close();
        this.gridview = new DeveloperPlayground.GridView({collection: collection});

        if (shouldFetchAndResetCollection) {
            collection.fetch();
        }

        if ($parameterSelect.val() == "name"){
            ga('send', 'event', 'button', 'click', $entitySelect.val()+' by '+$parameterSelect.val()+' , '+$nameSelect.val());
        } else {
            ga('send', 'event', 'button', 'click', $entitySelect.val()+' by '+$parameterSelect.val());
        }

        // $('#run-query-btn').on('click', function() {
        //     ga('send', 'event', 'button', 'click', 'run-query-btn');
        // });

    },
});<commit_msg>add analytics on operator query<commit_after>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.StartQueryBuilderView = Backbone.View.extend({
    el: "#developer-playground",

    template: _.template($('#playground-template').html()),

    events: {
        'change .form-control#entity': 'changeParam',
        'change .form-control#parameter': 'changeFilter',
        'click .btn#san-francisco': 'changeMapSF',
        'click .btn#new-york': 'changeMapNY',
        'click .btn#run-query-btn' : 'submit'
    },

    initialize: function () {
        this.operators = new DeveloperPlayground.Operators();
        this.stops = new DeveloperPlayground.Stops();
        this.routes = new DeveloperPlayground.Routes();
        this.render();
    },

    render: function() {
        this.$el.html(this.template());
        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");
        this.mapview = new DeveloperPlayground.MapView();
        this.mapview.render();
        this.downloadview = new DeveloperPlayground.DownloadView();
        this.downloadview.render();
        return this;
    },

    changeMapSF: function(){
        if($(".btn#new-york").hasClass("selected")) $(".btn#new-york").removeClass("selected");
        $(".btn#san-francisco").addClass("selected");
        this.mapview.setMapviewSF();
    },

    changeMapNY: function(){
        if($(".btn#san-francisco").hasClass("selected")) $(".btn#san-francisco").removeClass("selected");
        $(".btn#new-york").addClass("selected");
        this.mapview.setMapviewNY();
    },

    changeParam: function() {

        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var selectValues = {
            "base": {
                " ": "",
            },
            "stops": {
                " ": "",
                "map view": "",
                "operator": "",
            },
            "operators": {
                " ": "",
                "map view": "",
                "name": "",
                // "mode": "",
            },
            "routes": {
                " ": "",
                "map view": "",
                "operator": "",
                // "route number": "",
            }
        };

        $parameterSelect.empty().append(function() {
            var output = '';
            $.each(selectValues[$entitySelect.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });

        return this;
    },

    changeFilter: function() {
        var $parameterSelect = $('select.form-control#parameter');

        if($parameterSelect.val() == "name" || $parameterSelect.val() == "operator") {
            collection = this.operators;
            $(".form-control#name").show();
            $(".btn#new-york").hide();
            $(".btn#san-francisco").hide();

            if(!$("#nameMenu").hasClass("dropdown")) $("#nameMenu").addClass("dropdown");
            if ('undefined' !== typeof this.nameListView) {
                this.nameListView.close();
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            } else {
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            }
            this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/operators.json?per_page=5000'
                });
            collection.fetch();
            return this;

        } else {
            $(".form-control#name").hide();
            this.changeMapSF();
            $(".btn#new-york").show();
            $(".btn#san-francisco").show();

            if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        }
    },

    submit: function() {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var $nameSelect = $('select.form-control#name');
        var bounds = this.mapview.getBounds();
        var identifier = $nameSelect.val();

        var shouldFetchAndResetCollection = true;

        // FOR STOP QUERIES

        if ($entitySelect.val() == "stops") {
            // for search by map view
            if($parameterSelect.val() == "map view") {
            collection = this.stops;
            this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            // for search by operator name
            } else if($parameterSelect.val() == "operator") {
                collection = this.stops;
                this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?servedBy='+identifier+'&per_page=5000',
                });
            }

        // FOR OPERATOR QUERIES

        } else if ($entitySelect.val() == "operators") {

            if($parameterSelect.val() == "map view") {
                collection = this.operators;
                this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "name") {
                this.operators.hideAll();
                this.operators.get(identifier).set({ display: true });
                shouldFetchAndResetCollection = false;
            } else {
                alert("Please select either map view or name.");
            }

        //  FOR ROUTE QUERIES

        } else if ($entitySelect.val() == "routes") {
            if($parameterSelect.val() == "map view") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "operator") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?operatedBy='+identifier+'&per_page=5000',
                });
            } else if($parameterSelect.val() == "route number") {
                collection = this.routes;
                alert("routes by route number not yet functional");
            }
        } else {
            alert("Please select a parameter.");
        }

        if (shouldFetchAndResetCollection) {
            collection.reset();
        }

        $("#download-bar").show();
        this.mapview.markerclustergroup.clearLayers();
        this.mapview.clearCollection();
        this.mapview.setCollection({collection: collection});
        this.mapview.initialize({collection: collection});
        this.downloadview.setCollection({collection: collection});

        if ('undefined' !== typeof this.gridview) this.gridview.close();
        this.gridview = new DeveloperPlayground.GridView({collection: collection});

        if (shouldFetchAndResetCollection) {
            collection.fetch();
        }

        if ($parameterSelect.val() == "name" || $parameterSelect.val() == "operator"){
            ga('send', 'event', 'button', 'click', $entitySelect.val()+' by '+$parameterSelect.val()+' , '+$nameSelect.val());
        } else {
            ga('send', 'event', 'button', 'click', $entitySelect.val()+' by '+$parameterSelect.val());
        }

        // $('#run-query-btn').on('click', function() {
        //     ga('send', 'event', 'button', 'click', 'run-query-btn');
        // });

    },
});<|endoftext|>


<commit_before>// This file is a workaround to keep a record of strings that don't get extracted by gettext.
// It is not loaded or invoked by the app.

import {
  t,
} from './utils';

test = t("Add another condition");

test = t("Question should match all of these criteria");
test = t("Question should match any of these criteria");
test = t("Click to add another response...");
test = t("AUTOMATIC");
test = t("Skip Logic");
test = t("Question Options");
test = t("Validation Criteria");
test = t("Response Type");
test = t("A constraint message to be read in case of error:");
test = t("Row could not be displayed:");
test = t("This question could not be imported. Please re-create it manually. Please contact us at support@kobotoolbox.org so we can fix this bug!");
test = t("Add Question");
test = t("or");
test = t("Import XLS");
test = t("This question will only be displayed if the following conditions apply");
test = t("Save and Exit");
test = t("Show All Responses");
test = t("Question Library");
test = t("Form ID");
test = t("Unique form name");
test = t("Web form style (Optional)");
test = t("This allows using different Enketo styles, e.g. 'theme-grid'");
test = t("Multiple pages + Grid theme");
test = t("Version (Optional)");
test = t("A version ID of the form");
test = t("Hidden meta questions to include in your form to help with analysis");
test = t("Meta questions for collecting with cell phones");
test = t("This form is currently empty.");
test = t("You can add questions, notes, prompts, or other fields by clicking on the '+' sign below.");
test = t("Vertical");
test = t("Donut");
test = t("Area");
test = t("Horizontal");
test = t("Pie");
test = t("Line");
test = t("Draft");

test = t("This question could not be imported. Please re-create it manually. Please contact us at support@kobotoolbox.org so we can fix this bug!");

test = t("This question will only be displayed if the following conditions apply");
test = t("You can add questions, notes, prompts, or other fields by clicking on the '+' sign below.");
test = t("Value:");

test = t("Items cannot be selected more than once");
test = t("Manually enter your validation logic in XLSForm code");

test = t("[button triggers] Settings");
test = t("[button triggers] Delete Question");
test = t("[button triggers] Duplicate Question");
test = t("[button triggers] Add Question to Library");
test= t("Text");
test= t("Number");
test= t("Decimal");
test= t("Date");
test= t("Time");
test= t("Date & time");
test= t("GPS");
test= t("Photo");
test= t("Audio");
test= t("Video");
test= t("Note");
test= t("Barcode");
test= t("Acknowledge");
test= t("Calculate");
test= t("Matrix / Rating");
test= t("Ranking");
test= t("Are you sure you want to split apart this group?");
test= t("You can't display nested groups on the same screen - the setting has been removed from the parent group");
test= t("Note: Rank and Matrix question types are currently in beta.");
test= t("Enter your question");
test= t("Note: Rank and Matrix question types are currently in beta");
test= t("Select question from list");
test= t("Question hint");
test= t("Error Message");
test= t("Data column name");
test= t("Default response");
test= t("Repeat");
test= t("Repeat this group if necessary");
test= t("Mandatory response");
test= t("Appearance (advanced)");
test= t("Show all questions in this group on the same screen");
test= t("Please check your connection and try again.");
test= t("The server encountered an error while trying to deploy the project. If this problem persists, please contact support@kobotoolbox.org.");
test= t("The form id was not valid.");
test= t("failed to change password");
test= t("Tags are loading...");
test= t("collection");
test= t("library");
test= t("Collection");
test= t("collection loading...");
test= t("new collection inside \"___\"");
test= t("new question inside \"___\"");
test= t("new block inside \"___\"");
test= t("upload into \"___\"");
test= t("Are you sure you want to delete this collection?");
test= t("This action cannot be undone.");
test= t("Add a condition");
test= t("Manually enter your skip logic in XLSForm code");
test= t("response value");
test= t("Are you sure you want to delete this question?");
test= t("Select One");
test= t("Select Many");
test= t("Unable to deploy");

// Temporary strings from upcoming UI
test = t("Current version");
test = t("Form history");
test = t("Version");<commit_msg>keep some legacy strings for transifex translations (strins deprecated as of updates in develop branch)<commit_after>// This file is a workaround to keep a record of strings that don't get extracted by gettext.
// It is not loaded or invoked by the app.

import {
  t,
} from './utils';

test = t("Add another condition");

test = t("Question should match all of these criteria");
test = t("Question should match any of these criteria");
test = t("Click to add another response...");
test = t("AUTOMATIC");
test = t("Skip Logic");
test = t("Question Options");
test = t("Validation Criteria");
test = t("Response Type");
test = t("A constraint message to be read in case of error:");
test = t("Row could not be displayed:");
test = t("This question could not be imported. Please re-create it manually. Please contact us at support@kobotoolbox.org so we can fix this bug!");
test = t("Add Question");
test = t("or");
test = t("Import XLS");
test = t("This question will only be displayed if the following conditions apply");
test = t("Save and Exit");
test = t("Show All Responses");
test = t("Question Library");
test = t("Form ID");
test = t("Unique form name");
test = t("Web form style (Optional)");
test = t("This allows using different Enketo styles, e.g. 'theme-grid'");
test = t("Multiple pages + Grid theme");
test = t("Version (Optional)");
test = t("A version ID of the form");
test = t("Hidden meta questions to include in your form to help with analysis");
test = t("Meta questions for collecting with cell phones");
test = t("This form is currently empty.");
test = t("You can add questions, notes, prompts, or other fields by clicking on the '+' sign below.");
test = t("Vertical");
test = t("Donut");
test = t("Area");
test = t("Horizontal");
test = t("Pie");
test = t("Line");
test = t("Draft");
test = t("Value:");
test = t("Items cannot be selected more than once");
test = t("Manually enter your validation logic in XLSForm code");
test = t("[button triggers] Settings");
test = t("[button triggers] Delete Question");
test = t("[button triggers] Duplicate Question");
test = t("[button triggers] Add Question to Library");
test= t("Text");
test= t("Number");
test= t("Decimal");
test= t("Date");
test= t("Time");
test= t("Date & time");
test= t("GPS");
test= t("Photo");
test= t("Audio");
test= t("Video");
test= t("Note");
test= t("Barcode");
test= t("Acknowledge");
test= t("Calculate");
test= t("Matrix / Rating");
test= t("Ranking");
test= t("Are you sure you want to split apart this group?");
test= t("You can't display nested groups on the same screen - the setting has been removed from the parent group");
test= t("Note: Rank and Matrix question types are currently in beta.");
test= t("Enter your question");
test= t("Note: Rank and Matrix question types are currently in beta");
test= t("Select question from list");
test= t("Question hint");
test= t("Error Message");
test= t("Data column name");
test= t("Default response");
test= t("Repeat");
test= t("Repeat this group if necessary");
test= t("Mandatory response");
test= t("Appearance (advanced)");
test= t("Show all questions in this group on the same screen");
test= t("Please check your connection and try again.");
test= t("The server encountered an error while trying to deploy the project. If this problem persists, please contact support@kobotoolbox.org.");
test= t("The form id was not valid.");
test= t("failed to change password");
test= t("Tags are loading...");
test= t("library");
test= t("Collection");
test= t("collection loading...");
test= t("new collection inside \"___\"");
test= t("new question inside \"___\"");
test= t("new block inside \"___\"");
test= t("upload into \"___\"");
test= t("Are you sure you want to delete this collection?");
test= t("This action cannot be undone.");
test= t("Add a condition");
test= t("Manually enter your skip logic in XLSForm code");
test= t("response value");
test= t("Are you sure you want to delete this question?");
test= t("Select One");
test= t("Select Many");
test= t("Unable to deploy");

// legacy strings
test = t("profile");
test = t("logout");
test = t("log in");
test = t("Link to share");
test = t("Invite people and specify access rights");
test = t("Your username, bio, and links appear on your public profile");
test = t("Download form as");
test = t("add to library");
test = t("Allow others to access your project.");
test = t("Shared with ");
test = t("Share the sector and country with developers");
test = t("Leave Beta");
test = t("Form");
test = t("Data");
test = t("Reports");
test = t("Settings");
test = t("Undeployed draft");
test = t("Scheduled server maintenance");
test = t("Project description");
test = t("none");
test = t("report type");
test = t("create");
test = t("save");
test = t("form name");
test = t("Ask support about this error");
test = t("Collections");
test = t("collection not loaded");
test = t("collection name");
test = t("No assets to display");
test = t("Form Overview");
test = t("Edit in Form Builder");
test = t("make new collection: \"{label}\"");
test = t("owner");
test = t("viewer");
test = t("viewers");
test = t("editor");
test = t("editors");
test = t("status");
test = t("public");
test = t("private");
test = t("revisions");
test = t("created");
test = t("modified");
test = t("no language information");
test = t("no translations");
test = t("languages");
test = t("Collecting Data with Web Forms");
test = t("Learn more");
test = t("Choose an option");
test = t("Collecting Data with Android App");
test = t("preview");
test = t("clone");
test = t("new form name");
test = t("You are about to permanently delete this ___. Are you sure you want to continue?");
test = t("Current Version");
test = t("Modified Date");
test = t("(deployed)");
test = t("(archived)");
test = t("(undeployed draft)");
test = t("Previous Versions");
test = t("collections");
test = t("my forms");
test = t("shared with me");
test = t("error loading data");
test = t("results loaded");
test = t("Warning! You are about to delete this collection with all its questions and blocks. Are you sure you want to continue?");
test = t("new name?");
test = t("Delete Project");
test = t("More Actions");
<|endoftext|>


<commit_before>/** @babel */

import path from 'path';

import {CompositeDisposable, Disposable, File} from 'atom';

import React from 'react';

import EtchWrapper from '../views/etch-wrapper';
import StatusBar from '../views/status-bar';
import Panel from '../views/panel';
import PaneItem from '../views/pane-item';
import FilePatchController from './file-patch-controller';
import GitPanelController from './git-panel-controller';
import StatusBarTileController from './status-bar-tile-controller';
import ModelObserver from '../models/model-observer';

const nullFilePatchState = {
  filePath: null,
  filePatch: null,
  stagingStatus: null,
  amending: null,
};

export default class GitController extends React.Component {
  static propTypes = {
    workspace: React.PropTypes.object.isRequired,
    commandRegistry: React.PropTypes.object.isRequired,
    notificationManager: React.PropTypes.object.isRequired,
    repository: React.PropTypes.object,
    statusBar: React.PropTypes.object,
    savedState: React.PropTypes.object,
  }

  static defaultProps = {
    savedState: {},
  }

  serialize() {
    return {
      gitPanelActive: this.state.gitPanelActive,
    };
  }

  constructor(props, context) {
    super(props, context);
    this.state = {
      ...nullFilePatchState,
      gitPanelActive: !!props.savedState.gitPanelActive,
    };

    this.showFilePatchForPath = this.showFilePatchForPath.bind(this);
    this.showMergeConflictFileForPath = this.showMergeConflictFileForPath.bind(this);
    this.didChangeAmending = this.didChangeAmending.bind(this);
    this.onRepoRefresh = this.onRepoRefresh.bind(this);
    this.toggleGitPanel = this.toggleGitPanel.bind(this);
    this.focusFilePatchView = this.focusFilePatchView.bind(this);
    this.focusGitPanel = this.focusGitPanel.bind(this);
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      props.commandRegistry.add('atom-workspace', {
        'github:toggle-git-panel': this.toggleGitPanel.bind(this),
        'github:toggle-git-panel-focus': this.toggleGitPanelFocus.bind(this),
      }),
    );

    this.repositoryObserver = new ModelObserver({
      didUpdate: () => this.onRepoRefresh(),
    });
    this.repositoryObserver.setActiveModel(props.repository);
    this.subscriptions.add(
      new Disposable(() => this.repositoryObserver.destroy()),
    );
  }

  componentWillReceiveProps(newProps) {
    this.repositoryObserver.setActiveModel(newProps.repository);
  }

  render() {
    return (

        {this.renderStatusBarTile()}
        {this.renderGitPanel()}
        {(this.state.filePath && this.state.filePatch) ? this.renderFilePatchController() : null}

    );
  }

  renderStatusBarTile() {
    return (
      <StatusBar statusBar={this.props.statusBar} onConsumeStatusBar={sb => this.onConsumeStatusBar(sb)}>
        <EtchWrapper type="span">
          <StatusBarTileController
            workspace={this.props.workspace}
            repository={this.props.repository}
            toggleGitPanel={this.toggleGitPanel}
          />
        </EtchWrapper>
      </StatusBar>
    );
  }

  renderGitPanel() {
    return (
      <Panel
        workspace={this.props.workspace}
        location="right"
        getItem={({subtree}) => subtree.getWrappedComponent()}
        onDidClosePanel={() => this.setState({gitPanelActive: false})}
        visible={!!this.state.gitPanelActive}>
        <EtchWrapper ref={c => { this.gitPanelController = c; }} reattachDomNode={false}>
          <GitPanelController
            workspace={this.props.workspace}
            commandRegistry={this.props.commandRegistry}
            notificationManager={this.props.notificationManager}
            repository={this.props.repository}
            didSelectFilePath={this.showFilePatchForPath}
            didSelectMergeConflictFile={this.showMergeConflictFileForPath}
            didChangeAmending={this.didChangeAmending}
            focusFilePatchView={this.focusFilePatchView}
          />
        </EtchWrapper>
      </Panel>
    );
  }

  renderFilePatchController() {
    return (
      <PaneItem
        workspace={this.props.workspace}
        getItem={({subtree}) => subtree.getWrappedComponent()}
        ref={c => { this.filePatchControllerPane = c; }}
        onDidCloseItem={() => { this.setState({...nullFilePatchState}); }}>
        <EtchWrapper ref={c => { this.filePatchController = c; }} reattachDomNode={false}>
          <FilePatchController
            repository={this.props.repository}
            filePatch={this.state.filePatch}
            stagingStatus={this.state.stagingStatus}
            onRepoRefresh={this.onRepoRefresh}
          />
        </EtchWrapper>
      </PaneItem>
    );
  }

  componentWillUnmount() {
    this.subscriptions.dispose();
  }

  onConsumeStatusBar(statusBar) {
    if (statusBar.disableGitInfoTile) {
      statusBar.disableGitInfoTile();
    }
  }

  async showFilePatchForPath(filePath, stagingStatus, {activate, amending} = {}) {
    if (!filePath) { return; }
    const repository = this.props.repository;
    if (!repository) { return; }

    const filePatch = await repository.getFilePatchForPath(filePath, {staged: stagingStatus === 'staged', amending});
    if (filePatch) {
      this.setState({filePath, filePatch, stagingStatus, amending}, () => {
        // TODO: can be better done w/ a prop?
        if (activate && this.filePatchControllerPane) {
          this.filePatchControllerPane.activate();
        }
      });
    } else {
      this.setState({...nullFilePatchState});
    }
  }

  onRepoRefresh() {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: this.state.amending});
  }

  async showMergeConflictFileForPath(relativeFilePath, {focus} = {}) {
    const absolutePath = path.join(this.props.repository.getWorkingDirectoryPath(), relativeFilePath);
    if (await new File(absolutePath).exists()) {
      return this.props.workspace.open(absolutePath, {activatePane: Boolean(focus), pending: true});
    } else {
      this.props.notificationManager.addInfo('File has been deleted.');
      return null;
    }
  }

  didChangeAmending(isAmending) {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: isAmending});
  }

  toggleGitPanel() {
    this.setState(state => ({gitPanelActive: !state.gitPanelActive}));
  }

  toggleGitPanelFocus() {
    if (!this.state.gitPanelActive) {
      return new Promise((resolve, reject) => {
        this.setState({gitPanelActive: true}, () => this.toggleGitPanelFocus().then(resolve));
      });
    }

    if (this.gitPanelHasFocus()) {
      this.props.workspace.getActivePane().activate();
    } else {
      this.focusGitPanel();
    }
    return Promise.resolve();
  }

  focusGitPanel() {
    if (this.gitPanelController) {
      this.gitPanelController.getWrappedComponent().focus();
    }
  }

  gitPanelHasFocus() {
    if (!this.gitPanelController) {
      return false;
    }

    return this.gitPanelController.getWrappedComponent().isFocused();
  }

  focusFilePatchView() {
    if (this.filePatchController) {
      this.filePatchController.getWrappedComponent().focus();
    }
  }
}
<commit_msg>Bind event handling methods once<commit_after>/** @babel */

import path from 'path';

import {CompositeDisposable, Disposable, File} from 'atom';

import React from 'react';

import EtchWrapper from '../views/etch-wrapper';
import StatusBar from '../views/status-bar';
import Panel from '../views/panel';
import PaneItem from '../views/pane-item';
import FilePatchController from './file-patch-controller';
import GitPanelController from './git-panel-controller';
import StatusBarTileController from './status-bar-tile-controller';
import ModelObserver from '../models/model-observer';

const nullFilePatchState = {
  filePath: null,
  filePatch: null,
  stagingStatus: null,
  amending: null,
};

export default class GitController extends React.Component {
  static propTypes = {
    workspace: React.PropTypes.object.isRequired,
    commandRegistry: React.PropTypes.object.isRequired,
    notificationManager: React.PropTypes.object.isRequired,
    repository: React.PropTypes.object,
    statusBar: React.PropTypes.object,
    savedState: React.PropTypes.object,
  }

  static defaultProps = {
    savedState: {},
  }

  serialize() {
    return {
      gitPanelActive: this.state.gitPanelActive,
    };
  }

  constructor(props, context) {
    super(props, context);
    this.state = {
      ...nullFilePatchState,
      gitPanelActive: !!props.savedState.gitPanelActive,
    };

    this.showFilePatchForPath = this.showFilePatchForPath.bind(this);
    this.showMergeConflictFileForPath = this.showMergeConflictFileForPath.bind(this);
    this.didChangeAmending = this.didChangeAmending.bind(this);
    this.onRepoRefresh = this.onRepoRefresh.bind(this);
    this.toggleGitPanel = this.toggleGitPanel.bind(this);
    this.toggleGitPanelFocus = this.toggleGitPanelFocus.bind(this);
    this.focusFilePatchView = this.focusFilePatchView.bind(this);
    this.focusGitPanel = this.focusGitPanel.bind(this);

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      props.commandRegistry.add('atom-workspace', {
        'github:toggle-git-panel': this.toggleGitPanel,
        'github:toggle-git-panel-focus': this.toggleGitPanelFocus,
      }),
    );

    this.repositoryObserver = new ModelObserver({
      didUpdate: () => this.onRepoRefresh(),
    });
    this.repositoryObserver.setActiveModel(props.repository);
    this.subscriptions.add(
      new Disposable(() => this.repositoryObserver.destroy()),
    );
  }

  componentWillReceiveProps(newProps) {
    this.repositoryObserver.setActiveModel(newProps.repository);
  }

  render() {
    return (

        {this.renderStatusBarTile()}
        {this.renderGitPanel()}
        {(this.state.filePath && this.state.filePatch) ? this.renderFilePatchController() : null}

    );
  }

  renderStatusBarTile() {
    return (
      <StatusBar statusBar={this.props.statusBar} onConsumeStatusBar={sb => this.onConsumeStatusBar(sb)}>
        <EtchWrapper type="span">
          <StatusBarTileController
            workspace={this.props.workspace}
            repository={this.props.repository}
            toggleGitPanel={this.toggleGitPanel}
          />
        </EtchWrapper>
      </StatusBar>
    );
  }

  renderGitPanel() {
    return (
      <Panel
        workspace={this.props.workspace}
        location="right"
        getItem={({subtree}) => subtree.getWrappedComponent()}
        onDidClosePanel={() => this.setState({gitPanelActive: false})}
        visible={!!this.state.gitPanelActive}>
        <EtchWrapper ref={c => { this.gitPanelController = c; }} reattachDomNode={false}>
          <GitPanelController
            workspace={this.props.workspace}
            commandRegistry={this.props.commandRegistry}
            notificationManager={this.props.notificationManager}
            repository={this.props.repository}
            didSelectFilePath={this.showFilePatchForPath}
            didSelectMergeConflictFile={this.showMergeConflictFileForPath}
            didChangeAmending={this.didChangeAmending}
            focusFilePatchView={this.focusFilePatchView}
          />
        </EtchWrapper>
      </Panel>
    );
  }

  renderFilePatchController() {
    return (
      <PaneItem
        workspace={this.props.workspace}
        getItem={({subtree}) => subtree.getWrappedComponent()}
        ref={c => { this.filePatchControllerPane = c; }}
        onDidCloseItem={() => { this.setState({...nullFilePatchState}); }}>
        <EtchWrapper ref={c => { this.filePatchController = c; }} reattachDomNode={false}>
          <FilePatchController
            repository={this.props.repository}
            filePatch={this.state.filePatch}
            stagingStatus={this.state.stagingStatus}
            onRepoRefresh={this.onRepoRefresh}
          />
        </EtchWrapper>
      </PaneItem>
    );
  }

  componentWillUnmount() {
    this.subscriptions.dispose();
  }

  onConsumeStatusBar(statusBar) {
    if (statusBar.disableGitInfoTile) {
      statusBar.disableGitInfoTile();
    }
  }

  async showFilePatchForPath(filePath, stagingStatus, {activate, amending} = {}) {
    if (!filePath) { return; }
    const repository = this.props.repository;
    if (!repository) { return; }

    const filePatch = await repository.getFilePatchForPath(filePath, {staged: stagingStatus === 'staged', amending});
    if (filePatch) {
      this.setState({filePath, filePatch, stagingStatus, amending}, () => {
        // TODO: can be better done w/ a prop?
        if (activate && this.filePatchControllerPane) {
          this.filePatchControllerPane.activate();
        }
      });
    } else {
      this.setState({...nullFilePatchState});
    }
  }

  onRepoRefresh() {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: this.state.amending});
  }

  async showMergeConflictFileForPath(relativeFilePath, {focus} = {}) {
    const absolutePath = path.join(this.props.repository.getWorkingDirectoryPath(), relativeFilePath);
    if (await new File(absolutePath).exists()) {
      return this.props.workspace.open(absolutePath, {activatePane: Boolean(focus), pending: true});
    } else {
      this.props.notificationManager.addInfo('File has been deleted.');
      return null;
    }
  }

  didChangeAmending(isAmending) {
    return this.showFilePatchForPath(this.state.filePath, this.state.stagingStatus, {amending: isAmending});
  }

  toggleGitPanel() {
    this.setState(state => ({gitPanelActive: !state.gitPanelActive}));
  }

  toggleGitPanelFocus() {
    if (!this.state.gitPanelActive) {
      return new Promise((resolve, reject) => {
        this.setState({gitPanelActive: true}, () => this.toggleGitPanelFocus().then(resolve));
      });
    }

    if (this.gitPanelHasFocus()) {
      this.props.workspace.getActivePane().activate();
    } else {
      this.focusGitPanel();
    }
    return Promise.resolve();
  }

  focusGitPanel() {
    if (this.gitPanelController) {
      this.gitPanelController.getWrappedComponent().focus();
    }
  }

  gitPanelHasFocus() {
    if (!this.gitPanelController) {
      return false;
    }

    return this.gitPanelController.getWrappedComponent().isFocused();
  }

  focusFilePatchView() {
    if (this.filePatchController) {
      this.filePatchController.getWrappedComponent().focus();
    }
  }
}
<|endoftext|>


<commit_before>/*
front-end to the compiler
*/

var IR = (require('./IR'))(
	{
		filename: process.argv[2],
		ffi: ["@putch"]
	}
);

var meow = require("./meow").instance();
var backend = require("./backend");

backend.ffi["@putch"] = [
	//["doAsk", ["concatenate:with:", "@putch ", ["getParam", "param0", "r"]]]

	["doIfElse",
					["=", ["getParam", "param0", "r"], "13"],
					[["append:toList:", "", "TTY"]],
					[["setLine:ofList:to:",
							["lineCountOfList:", "TTY"],
							"TTY",
							["concatenate:with:", ["getLine:ofList:", ["lineCountOfList:", "TTY"], "TTY"], ["letter:of:", ["+", ["getParam", "param0", "r"], 1], ["readVariable", "alphabet"]]]]]]
];

console.log(JSON.stringify(IR));

var tty = new (require("./meow")).ListTuple("TTY");
tty.classicTTY();
meow.lists.push(tty);

meow.addList("Stack");
meow.addList("# of locals");
meow.addList("Label Stack");

var alphabet = "";
for(var i = 0; i < 256; ++i) {
	if(i >= 32 && i < 127) {
		c = String.fromCharCode(i);
		alphabet += c;
	} else {
		alphabet += ".";
	}
}

meow.addVariable("alphabet", alphabet);

for(var i = 0; i < IR.functions.length; ++i) {
	meow.addScript(backend.compileFunction(IR.functions[i]));
}

meow.addVariable("return value", 0);

meow.addScript([
		["whenGreenFlag"],
		["call", "init tty"],
		["call", "@main"] // TODO: argc + argv
	])
meow.addScript([
		["procDef", "init tty", [], [], false],
		["append:toList:", "", "TTY"]
	])

if(process.argv[3]) {
	meow.upload(process.argv[3], 'v426', process.argv[4], process.argv[5]);
} else {
	console.log(JSON.stringify(meow.serialize()));
}<commit_msg>Cleanup on meowcc to prevent bloat<commit_after>/*
front-end to the compiler
*/

var IR = (require('./IR'))(
	{
		filename: process.argv[2],
		ffi: ["@putch"]
	}
);

var meow = require("./meow").instance();
var backend = require("./backend");

backend.ffi["@putch"] = [
	//["doAsk", ["concatenate:with:", "@putch ", ["getParam", "param0", "r"]]]

	["doIfElse",
					["=", ["getParam", "param0", "r"], "13"],
					[["append:toList:", "", "TTY"]],
					[["setLine:ofList:to:",
							["lineCountOfList:", "TTY"],
							"TTY",
							["concatenate:with:", ["getLine:ofList:", ["lineCountOfList:", "TTY"], "TTY"], ["letter:of:", ["+", ["getParam", "param0", "r"], 1], ["readVariable", "alphabet"]]]]]]
];

console.log(JSON.stringify(IR));

var tty = new (require("./meow")).ListTuple("TTY");
tty.classicTTY();
meow.lists.push(tty);

meow.addList("Stack");
meow.addList("# of locals");
meow.addList("Label Stack");

var alphabet = "";
for(var i = 0; i < 256; ++i) {
	if(i >= 32 && i < 127) {
		c = String.fromCharCode(i);
		alphabet += c;
	} else {
		alphabet += ".";
	}
}

meow.addVariable("alphabet", alphabet);

for(var i = 0; i < IR.functions.length; ++i) {
	meow.addScript(backend.compileFunction(IR.functions[i]));
}

meow.addVariable("return value", 0);

meow.addScript([
		["whenGreenFlag"],
		["deleteLine:ofList:", "last", "# of locals"],
		["deleteLine:ofList:", "last", "Stack"],
		["deleteLine:ofList:", "last", "TTY"],
		["append:toList:", "", "TTY"],
		["call", "@main"] // TODO: argc + argv
	])

if(process.argv[3]) {
	meow.upload(process.argv[3], 'v426', process.argv[4], process.argv[5]);
} else {
	console.log(JSON.stringify(meow.serialize()));
}<|endoftext|>