<commit_before>/*!
 * ${copyright}
 */
/*global opaTest:true, QUnit */
/**
 * QUnit test adapter for opa.js has the same signature as a test of QUnit.
 * Suggested usage:
 *
 * sap.ui.require(["sap/ui/test/Opa5", "sap/ui/test/opaQunit"], function (Opa5, opaTest) {
 *
 *    Opa5.extendConfig({
 *        assertions: new Opa5({
 *            checkIfSomethingIsOk : function () {
 *                this.waitFor({
 *                    success: function () {
 *                        Opa5.assert.ok(true, "Everything is fine");
 *                    }
 *                });
 *            }
 *        })
 *    });
 *
 *    opaTest("Should test something", function (Given, When, Then) {
 *       // Implementation of the test
 *       Then.checkIfSomethingIsOk();
 *    });
 *
 * });
 *
 *
 * When you require this file, it will also introduce a global variable: opaTest
 * @public
 * @function
 * @param {string} testName the name of the created QUnit test.
 * @param {integer|function} expected Integer - How many qunit assertions are expected by the test. If a function is passed it is interpreted as callback and the expected is skipped.
 * @param {function} callback - The test function. It will get 3 arguments passed to it.
 * The first argument will be {@link sap.ui.test.Opa#.config}.arrangements.
 * The second argument will be {@link sap.ui.test.Opa#.config}.actions.
 * The third argument will be {@link sap.ui.test.Opa#.config}.assertions.
 * @alias sap.ui.test.opaQunit
 * @returns {QUnit.test} a function to register opaTests
 */
/////////////////////
//// OPA - One Page Acceptance testing the qUnit adapter
//// Currently this is distributed with UI5 but it does not have dependencies to it.
//// The only dependency is jQuery. As i plan to get this into a separate repository, i did not use the UI5 naming conventions
/////////////////////

// Eslint thinks window.opaTest is unused
/*eslint-disable no-unused-vars */
sap.ui.define(['./Opa', './Opa5'], function (Opa, Opa5) {
/*eslint-enable no-unused-vars */
	"use strict";
	var opaTest = function (testName, expected, callback, async) {
		var config = Opa.config;
		//Increase qunit's timeout to 90 seconds to match default OPA timeouts
		if (!QUnit.config.testTimeout) {
			QUnit.config.testTimeout  = 90000;
		}

		if (arguments.length === 2) {
			callback = expected;
			expected = null;
		}

		var testBody = function(assert) {
			var fnStart = assert.async();
			config.testName = testName;

			// provide current "assert" object to the tests
			Opa.assert = assert;
			Opa5.assert = assert;

			callback.call(this, config.arrangements, config.actions, config.assertions);

			var promise = Opa.emptyQueue();
			promise.done(function() {
				Opa.assert = undefined;
				Opa5.assert = undefined;
				fnStart();
			});

			promise.fail(function (oOptions) {
				QUnit.ok(false, oOptions.errorMessage);
				Opa.assert = undefined;
				Opa5.assert = undefined;
				fnStart();
			});
		};

		return QUnit.test(testName, expected, testBody, async);
	};
	// Export to global namespace to be backwards compatible
	window.opaTest = opaTest;

	return opaTest;
});

<commit_msg>[INTERNAL][FIX] sap.ui.test.opaQunit - docu is missing<commit_after>/*!
 * ${copyright}
 */
/*global opaTest:true, QUnit */

// Eslint thinks window.opaTest is unused
/*eslint-disable no-unused-vars */
sap.ui.define(['./Opa', './Opa5'], function (Opa, Opa5) {
/*eslint-enable no-unused-vars */
	"use strict";

	/**
	 * QUnit test adapter for opa.js has the same signature as a test of QUnit.
	 * Suggested usage:
	 *
	 * sap.ui.require(["sap/ui/test/Opa5", "sap/ui/test/opaQunit"], function (Opa5, opaTest) {
	 *
	 *    Opa5.extendConfig({
	 *        assertions: new Opa5({
	 *            checkIfSomethingIsOk : function () {
	 *                this.waitFor({
	 *                    success: function () {
	 *                        Opa5.assert.ok(true, "Everything is fine");
	 *                    }
	 *                });
	 *            }
	 *        })
	 *    });
	 *
	 *    opaTest("Should test something", function (Given, When, Then) {
	 *       // Implementation of the test
	 *       Then.checkIfSomethingIsOk();
	 *    });
	 *
	 * });
	 *
	 *
	 * When you require this file, it will also introduce a global variable: opaTest.
	 * @public
	 * @alias sap.ui.test.opaQunit
	 * @function
	 * @static
	 * @param {string} testName the name of the created QUnit test.
	 * @param {integer|function} expected Integer - How many qunit assertions are expected by the test. If a function is passed it is interpreted as callback and the expected is skipped.
	 * @param {function} callback - The test function. It will get 3 arguments passed to it.
	 * The first argument will be {@link sap.ui.test.Opa#.config}.arrangements.
	 * The second argument will be {@link sap.ui.test.Opa#.config}.actions.
	 * The third argument will be {@link sap.ui.test.Opa#.config}.assertions.
	 * @returns {QUnit.test} a function to register opaTests
	 */
	var opaTest = function (testName, expected, callback, async) {
		var config = Opa.config;
		//Increase QUnit's timeout to 90 seconds to match default OPA timeouts
		if (!QUnit.config.testTimeout) {
			QUnit.config.testTimeout  = 90000;
		}

		if (arguments.length === 2) {
			callback = expected;
			expected = null;
		}

		var testBody = function(assert) {
			var fnStart = assert.async();
			config.testName = testName;

			// provide current "assert" object to the tests
			Opa.assert = assert;
			Opa5.assert = assert;

			callback.call(this, config.arrangements, config.actions, config.assertions);

			var promise = Opa.emptyQueue();
			promise.done(function() {
				Opa.assert = undefined;
				Opa5.assert = undefined;
				fnStart();
			});

			promise.fail(function (oOptions) {
				QUnit.ok(false, oOptions.errorMessage);
				Opa.assert = undefined;
				Opa5.assert = undefined;
				fnStart();
			});
		};

		return QUnit.test(testName, expected, testBody, async);
	};
	// Export to global namespace to be backwards compatible
	window.opaTest = opaTest;

	return opaTest;
});

<|endoftext|>


<commit_before>/**
 * Manage a display
 *
 * @param {Display} display
 * @param {Application} display
 */
function DisplayManager(display, application){
  this.display = display;
  this.application = application;
  this.services = new Services();
};

/**
 * Draw the display manager
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.init = function(canvas){
  var self = this;
  var name = $('
').css('text-align', 'left');
  name.append($('').attr('for', 'display-name').html('Display Name: '));
  name.append($('<input>').attr('id', 'display-name').val(this.display.getName()).bind('change', function(){
    self.display.setName($(this).val());
  }));
  canvas.append(name);
  var button = $('<button>').html('Select All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item', div).not('.selected').each(function(i){
      var element = $(this).data('element');
      element.weight = startWeight +i;
      self.display.addElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var button = $('<button>').html('Deselect All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item.selected', div).each(function(i){
      var element = $(this).data('element');
      self.display.removeElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var div = $('
').addClass('yui-g');
  var left = $('
').addClass('yui-u first').attr('id', 'chooser');
  var right = $('
').addClass('yui-u').attr('id', 'chosen');
  div.append(left);
  div.append(right);
  canvas.append(div);
  this.drawChooser();
  this.drawChosen();

  canvas.on('click', '.shrink_button', function() {
    $(this).next().toggle('slow');
    return false;
  });
};

/**
 * Draw the chooser
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.drawChooser = function(){
  var self = this;
  var div = $('
');
  div.append($('
').html('Available Elements'));
  var maximumDisplay = this.services.getMaximumDisplay();

  div.append(this.shrinkButton('Applicant', this.applicantBox(maximumDisplay)));
  div.append(self.shrinkButton("Tags", self.tagBox(maximumDisplay)));

  $.each(this.application.listApplicationPages(), function(){
     div.append(self.shrinkButton(this.title, self.pageBox(this, maximumDisplay)));
  });

  $('#chooser').empty().append(div);
};

/**
 * Draw the displayed
 *
 */
DisplayManager.prototype.drawChosen = function(){
  var self = this;
  var div = $('
');
  $.each(this.display.listElements(),function(){
    var displayElement = this;
    var ol = $('
');
    var sourceName = displayElement.type == 'applicant'?'Applicant':self.display.getElementPageTitle(displayElement) + ' Page';
    ol.append($('
').html('Source: ' + sourceName).addClass('item'));
    ol.append($('
').html('Original Name: ' + $('#'+ this.type + this.name).data('element').title).addClass('item'));
    var elementDiv = self.shrinkButton(displayElement.title, ol);
    elementDiv.addClass('element');
    elementDiv.data('element', displayElement);
    $('.shrink_button', elementDiv).prepend($('').addClass('left').addClass('handle ui-icon ui-icon-arrowthick-2-n-s'));

    $('.shrink_button p', elementDiv).append($('').addClass('right ui-icon ui-icon-pencil'));
     $('.shrink_button p', elementDiv).editable(function(value, settings) {
        displayElement.title = value;
     },
     {
       displayElement: displayElement,
       data: displayElement.title,
       callback: function(value, setting){
         self.drawChosen();
       }
<<<<<<< HEAD
    });
    var removeSpan = $('').addClass('right').addClass('ui-icon ui-icon-circle-minus');
    removeSpan.on('click', function(){
      self.display.removeElement($(this).closest('.shrinkable').data('element'));
      self.drawChosen();
      self.refreshDisplayedChooserElements();
    });
=======
    });
    var removeSpan = $('').addClass('right').addClass('ui-icon ui-icon-circle-minus');
    removeSpan.on('click', function(){
      self.display.removeElement($(this).closest('.shrinkable').data('element'));
      self.drawChosen();
      self.refreshDisplayedChooserElements();
    });
>>>>>>> 9d814696081f9326594ca5b2c1223a028934e541
    $('.shrink_button', elementDiv).append(removeSpan);
    div.append(elementDiv);
  });
  $('div.element',div).sort(function(a,b){
    return $(a).data('element').weight > $(b).data('element').weight ? 1 : -1;
  }).appendTo(div);
  div.sortable({
    handle: '.handle'
  });
  div.bind("sortupdate", function(e, ui) {
    $('div.element',$(ui.item).parent()).each(function(i){
      var element = $(this).data('element');
      element.weight = i;
    });
  });
  var chosen = $('
');
  chosen.append($('
').html('Selected Items for ' + this.display.getName() + ' Display'));
  chosen.append(div);
  $('#chosen').empty().append(chosen);
};

/**
 * Draw the applicant box
 *
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.applicantBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var arr = [
    {type:'applicant', title: 'First Name', name: 'firstName'},
    {type:'applicant', title: 'Last Name', name: 'lastName'},
    {type:'applicant', title: 'Email', name: 'email'},
    {type:'applicant', title: 'Last Update', name: 'updatedAt'},
    {type:'applicant', title: 'Progress', name: 'percentComplete'},
    {type:'applicant', title: 'Last Login', name: 'lastLogin'},
    {type:'applicant', title: 'Account Created', name: 'createdAt'},
    {type:'applicant', title: 'Locked', name: 'isLocked'},
    {type:'applicant', title: 'Paid', name: 'hasPaid'},
    {type:'applicant', title: 'Attachments', name: 'attachments'},

    // these should really be a separate type (eg. tag or decision).
    // the name part here corresponds to keys in the FullApplication.php display.
    {type:'applicant', title: 'Declined', name: 'status_declined'},
    {type:'applicant', title: 'Admitted', name: 'status_admitted'},
    {type:'applicant', title: 'Denied', name: 'status_denied'},
    {type:'applicant', title: 'Accepted', name: 'status_accepted'},
    {type:'applicant', title: 'Nominate Admit', name: 'status_nominate_admit'},
    {type:'applicant', title: 'Nominate Deny', name: 'status_nominate_deny'}
  ];
  var hasItems = false;
  $.each(arr,function(){
	  if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element',this);
      li.attr('id', this.type + this.name);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
            }
  });
  if(hasItems){
    return $('
').append(list);
  } else {
    return false;
  }
};

/**
 * Draw the shrink button
 *
 * @param String title
 * @param {jquery} content
 */
DisplayManager.prototype.shrinkButton = function(title, content){
  var div = $('
').addClass('shrinkable');
  if(content === false ){
    return div;
  }
  div.append($('
').addClass('shrink_button').addClass('item').append($('
').html(title)));
  div.append($('
').addClass('shrink_list').append(content));

  return div;
};

/**
 * Draw the page box
 *
 * @param {} applicationPage
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.pageBox = function(applicationPage, maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var pageClass = this.application.getPageClassById(applicationPage.page.id);
  var pageDisplayElements = pageClass.listDisplayElements();
  if(pageDisplayElements.length == 0){
    return false;
  }
  var hasItems = false;
  $.each(pageDisplayElements, function(){
    if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
      li.attr('id', this.type + this.name);
<<<<<<< HEAD
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
    }
  });
  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

DisplayManager.prototype.tagBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var hasItems = false;
  try{
      $.each(maximumDisplay.listTags(), function(){
	  this.type = 'applicant';
	  this.name = this.id;
	  this.weight = 1;
	  hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
=======
>>>>>>> 9d814696081f9326594ca5b2c1223a028934e541
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);

      });
  }catch(ex){
      console.log("unable to create tag list: "+ex);
  }

  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

/**
 * Save the display
 *
 * @param url string
 * @param display Display
 */
DisplayManager.save = function(url, display){
  $.ajax({
    url: url + '/saveDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * REmvoe the display
 *
 * @param {} applicationPage
 */
DisplayManager.remove = function(url, display){
  $.ajax({
    url: url + '/deleteDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * Get the weight for the next piece
 *
 * @return integer
 */
DisplayManager.prototype.nextWeight = function(){
  return $('#chosen li').length+1;
};

/**
 * Refresh the list of chooser elements to see which ones should be displayed
 *
 * @param {}
 * @return {jQuery}
 */
DisplayManager.prototype.refreshDisplayedChooserElements = function(){
  var self = this;
  $('ul.block_list li.item', '#chooser').each(function(i){
      var element = $(this).data('element');
      if(self.display.displayElement(element)){
        $(this).addClass('selected');
      } else {
        $(this).removeClass('selected');
      }
    });
<<<<<<>>>>>> 9d814696081f9326594ca5b2c1223a028934e541
<commit_msg>Fix bad merge on DisplayManager.class.js<commit_after>/**
 * Manage a display
 *
 * @param {Display} display
 * @param {Application} display
 */
function DisplayManager(display, application){
  this.display = display;
  this.application = application;
  this.services = new Services();
};

/**
 * Draw the display manager
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.init = function(canvas){
  var self = this;
  var name = $('
').css('text-align', 'left');
  name.append($('').attr('for', 'display-name').html('Display Name: '));
  name.append($('<input>').attr('id', 'display-name').val(this.display.getName()).bind('change', function(){
    self.display.setName($(this).val());
  }));
  canvas.append(name);
  var button = $('<button>').html('Select All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item', div).not('.selected').each(function(i){
      var element = $(this).data('element');
      element.weight = startWeight +i;
      self.display.addElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var button = $('<button>').html('Deselect All').button();
  button.click(function(e){
    var startWeight = self.nextWeight();
    $('ul.block_list li.item.selected', div).each(function(i){
      var element = $(this).data('element');
      self.display.removeElement(element);
    });
    self.drawChosen();
    self.drawChooser();
    return false;
  });
  canvas.append(button);
  var div = $('
').addClass('yui-g');
  var left = $('
').addClass('yui-u first').attr('id', 'chooser');
  var right = $('
').addClass('yui-u').attr('id', 'chosen');
  div.append(left);
  div.append(right);
  canvas.append(div);
  this.drawChooser();
  this.drawChosen();

  canvas.on('click', '.shrink_button', function() {
    $(this).next().toggle('slow');
    return false;
  });
};

/**
 * Draw the chooser
 *
 * @param {jQuery} canvas
 */
DisplayManager.prototype.drawChooser = function(){
  var self = this;
  var div = $('
');
  div.append($('
').html('Available Elements'));
  var maximumDisplay = this.services.getMaximumDisplay();

  div.append(this.shrinkButton('Applicant', this.applicantBox(maximumDisplay)));
  div.append(self.shrinkButton("Tags", self.tagBox(maximumDisplay)));

  $.each(this.application.listApplicationPages(), function(){
     div.append(self.shrinkButton(this.title, self.pageBox(this, maximumDisplay)));
  });

  $('#chooser').empty().append(div);
};

/**
 * Draw the displayed
 *
 */
DisplayManager.prototype.drawChosen = function(){
  var self = this;
  var div = $('
');
  $.each(this.display.listElements(),function(){
    var displayElement = this;
    var ol = $('
');
    var sourceName = displayElement.type == 'applicant'?'Applicant':self.display.getElementPageTitle(displayElement) + ' Page';
    ol.append($('
').html('Source: ' + sourceName).addClass('item'));
    ol.append($('
').html('Original Name: ' + $('#'+ this.type + this.name).data('element').title).addClass('item'));
    var elementDiv = self.shrinkButton(displayElement.title, ol);
    elementDiv.addClass('element');
    elementDiv.data('element', displayElement);
    $('.shrink_button', elementDiv).prepend($('').addClass('left').addClass('handle ui-icon ui-icon-arrowthick-2-n-s'));

    $('.shrink_button p', elementDiv).append($('').addClass('right ui-icon ui-icon-pencil'));
     $('.shrink_button p', elementDiv).editable(function(value, settings) {
        displayElement.title = value;
     },
     {
       displayElement: displayElement,
       data: displayElement.title,
       callback: function(value, setting){
         self.drawChosen();
       }
    });
    var removeSpan = $('').addClass('right').addClass('ui-icon ui-icon-circle-minus');
    removeSpan.on('click', function(){
      self.display.removeElement($(this).closest('.shrinkable').data('element'));
      self.drawChosen();
      self.refreshDisplayedChooserElements();
    });
    $('.shrink_button', elementDiv).append(removeSpan);
    div.append(elementDiv);
  });
  $('div.element',div).sort(function(a,b){
    return $(a).data('element').weight > $(b).data('element').weight ? 1 : -1;
  }).appendTo(div);
  div.sortable({
    handle: '.handle'
  });
  div.bind("sortupdate", function(e, ui) {
    $('div.element',$(ui.item).parent()).each(function(i){
      var element = $(this).data('element');
      element.weight = i;
    });
  });
  var chosen = $('
');
  chosen.append($('
').html('Selected Items for ' + this.display.getName() + ' Display'));
  chosen.append(div);
  $('#chosen').empty().append(chosen);
};

/**
 * Draw the applicant box
 *
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.applicantBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var arr = [
    {type:'applicant', title: 'First Name', name: 'firstName'},
    {type:'applicant', title: 'Last Name', name: 'lastName'},
    {type:'applicant', title: 'Email', name: 'email'},
    {type:'applicant', title: 'Last Update', name: 'updatedAt'},
    {type:'applicant', title: 'Progress', name: 'percentComplete'},
    {type:'applicant', title: 'Last Login', name: 'lastLogin'},
    {type:'applicant', title: 'Account Created', name: 'createdAt'},
    {type:'applicant', title: 'Locked', name: 'isLocked'},
    {type:'applicant', title: 'Paid', name: 'hasPaid'},
    {type:'applicant', title: 'Attachments', name: 'attachments'},

    // these should really be a separate type (eg. tag or decision).
    // the name part here corresponds to keys in the FullApplication.php display.
    {type:'applicant', title: 'Declined', name: 'status_declined'},
    {type:'applicant', title: 'Admitted', name: 'status_admitted'},
    {type:'applicant', title: 'Denied', name: 'status_denied'},
    {type:'applicant', title: 'Accepted', name: 'status_accepted'},
    {type:'applicant', title: 'Nominate Admit', name: 'status_nominate_admit'},
    {type:'applicant', title: 'Nominate Deny', name: 'status_nominate_deny'}
  ];
  var hasItems = false;
  $.each(arr,function(){
	  if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element',this);
      li.attr('id', this.type + this.name);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.applicantBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
            }
  });
  if(hasItems){
    return $('
').append(list);
  } else {
    return false;
  }
};

/**
 * Draw the shrink button
 *
 * @param String title
 * @param {jquery} content
 */
DisplayManager.prototype.shrinkButton = function(title, content){
  var div = $('
').addClass('shrinkable');
  if(content === false ){
    return div;
  }
  div.append($('
').addClass('shrink_button').addClass('item').append($('
').html(title)));
  div.append($('
').addClass('shrink_list').append(content));

  return div;
};

/**
 * Draw the page box
 *
 * @param {} applicationPage
 * @param {Display} maximumDisplay
 */
DisplayManager.prototype.pageBox = function(applicationPage, maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var pageClass = this.application.getPageClassById(applicationPage.page.id);
  var pageDisplayElements = pageClass.listDisplayElements();
  if(pageDisplayElements.length == 0){
    return false;
  }
  var hasItems = false;
  $.each(pageDisplayElements, function(){
    if(maximumDisplay.displayElement(this)){
      hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
      li.attr('id', this.type + this.name);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.pageBox(applicationPage, maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);
    }
  });
  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

DisplayManager.prototype.tagBox = function(maximumDisplay){
  var self = this;
  var list = $('
').addClass('block_list');
  var hasItems = false;
  try{
      $.each(maximumDisplay.listTags(), function(){
	  this.type = 'applicant';
	  this.name = this.id;
	  this.weight = 1;
	  hasItems = true;
      var li = $('
').addClass('item').html(this.title).data('element', this);
      if(self.display.displayElement(this)){
          li.addClass('selected');
      }
      li.on('click', function(){
        var element = $(this).data('element');
        if(self.display.displayElement(element)){
          li.addClass('selected');
          self.display.removeElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        } else {
          li.removeClass('selected');
          element.weight = self.nextWeight();
          self.display.addElement(element);
          list.replaceWith(self.tagBox(maximumDisplay));
          self.drawChosen();
        }
      });
      list.append(li);

      });
  }catch(ex){
      console.log("unable to create tag list: "+ex);
  }

  if(hasItems){
    return $('
').append(list);
  }

  return false;
};

/**
 * Save the display
 *
 * @param url string
 * @param display Display
 */
DisplayManager.save = function(url, display){
  $.ajax({
    url: url + '/saveDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * REmvoe the display
 *
 * @param {} applicationPage
 */
DisplayManager.remove = function(url, display){
  $.ajax({
    url: url + '/deleteDisplay',
    type: 'POST',
    data: {display: $.toJSON(display.getObj())},
    async: false
  });
};

/**
 * Get the weight for the next piece
 *
 * @return integer
 */
DisplayManager.prototype.nextWeight = function(){
  return $('#chosen li').length+1;
};

/**
 * Refresh the list of chooser elements to see which ones should be displayed
 *
 * @param {}
 * @return {jQuery}
 */
DisplayManager.prototype.refreshDisplayedChooserElements = function(){
  var self = this;
  $('ul.block_list li.item', '#chooser').each(function(i){
      var element = $(this).data('element');
      if(self.display.displayElement(element)){
        $(this).addClass('selected');
      } else {
        $(this).removeClass('selected');
      }
    });
};
<|endoftext|>


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

    angular.module('ariaNg').factory('aria2SettingService', ['aria2AllOptions', 'aria2GlobalAvailableOptions', 'aria2TaskAvailableOptions', 'ariaNgCommonService', 'aria2RpcService', function (aria2AllOptions, aria2GlobalAvailableOptions, aria2TaskAvailableOptions, ariaNgCommonService, aria2RpcService) {
        var processStatResult = function (stat) {
            if (!stat) {
                return stat;
            }

            var activeCount = parseInt(stat.numActive);
            var waitingCount = parseInt(stat.numWaiting);
            var totalRunningCount = activeCount + waitingCount;

            stat.totalRunningCount = totalRunningCount;

            return stat;
        };

        return {
            getAvailableGlobalOptionsKeys: function (type) {
                if (type == 'basic') {
                    return aria2GlobalAvailableOptions.basicOptions;
                } else if (type == 'http-ftp-sftp') {
                    return aria2GlobalAvailableOptions.httpFtpSFtpOptions;
                } else if (type == 'http') {
                    return aria2GlobalAvailableOptions.httpOptions;
                } else if (type == 'ftp-sftp') {
                    return aria2GlobalAvailableOptions.ftpSFtpOptions;
                } else if (type == 'bt') {
                    return aria2GlobalAvailableOptions.btOptions;
                } else if (type == 'metalink') {
                    return aria2GlobalAvailableOptions.metalinkOptions;
                } else if (type == 'rpc') {
                    return aria2GlobalAvailableOptions.rpcOptions;
                } else if (type == 'advanced') {
                    return aria2GlobalAvailableOptions.advancedOptions;
                } else {
                    return false;
                }
            },
            getAvailableTaskOptionKeys: function (status, isBittorrent) {
                var allOptions = aria2TaskAvailableOptions.taskOptions;
                var availableOptions = [];

                for (var i = 0; i < allOptions.length; i++) {
                    var option = allOptions[i];
                    var optionKey = {
                        key: option.key
                    };

                    if (option.newOnly) {
                        continue;
                    }

                    if (option.httpOnly && isBittorrent) {
                        continue;
                    } else if (option.btOnly && !isBittorrent) {
                        continue;
                    }

                    if (option.activeReadonly && status == 'active') {
                        optionKey.readonly = true;
                    }

                    availableOptions.push(optionKey);
                }

                return availableOptions;
            },
            getNewTaskOptionKeys: function (isBittorrent) {
                var allOptions = aria2TaskAvailableOptions.taskOptions;
                var availableOptions = [];

                for (var i = 0; i < allOptions.length; i++) {
                    var option = allOptions[i];
                    var optionKey = {
                        key: option.key
                    };

                    availableOptions.push(optionKey);
                }

                return availableOptions;
            },
            getSpecifiedOptions: function (keys) {
                var options = [];

                for (var i = 0; i < keys.length; i++) {
                    var key = keys[i];
                    var readonly = false;

                    if (angular.isObject(key)) {
                        var optionKey = key;

                        key = optionKey.key;
                        readonly = !!optionKey.readonly;
                    }

                    var option = aria2AllOptions[key];

                    if (!option) {
                        continue;
                    }

                    option = angular.extend({
                        key: key,
                        nameKey: 'options.' + key + '.name',
                        descriptionKey: 'options.' + key + '.description'
                    }, option);

                    if (option.type == 'boolean') {
                        option.options = ['true', 'false'];
                    }

                    if (readonly) {
                        option.readonly = true;
                    }

                    if (option.options) {
                        var availableOptions = [];

                        for (var j = 0; j < option.options.length; j++) {
                            availableOptions.push({
                                name: 'options.' + option.options[j],
                                value: option.options[j]
                            });
                        }

                        option.options = availableOptions;
                    }

                    options.push(option);
                }

                return options;
            },
            getGlobalOption: function (callback, silent) {
                return aria2RpcService.getGlobalOption({
                    silent: !!silent,
                    callback: callback
                });
            },
            setGlobalOption: function (key, value, callback, silent) {
                var data = {};
                data[key] = value;

                return aria2RpcService.changeGlobalOption({
                    options: data,
                    silent: !!silent,
                    callback: callback
                });
            },
            getAria2Status: function (callback, silent) {
                return aria2RpcService.getVersion({
                    silent: !!silent,
                    callback: callback
                })
            },
            getGlobalStat: function (callback, silent) {
                return aria2RpcService.getGlobalStat({
                    silent: !!silent,
                    callback: function (result) {
                        if (!callback) {
                            return;
                        }

                        var stat = processStatResult(result);
                        callback(stat);
                    }
                });
            },
            saveSession: function (callback, silent) {
                return aria2RpcService.saveSession({
                    silent: !!silent,
                    callback: callback
                })
            },
            shutdown: function (callback, silent) {
                return aria2RpcService.shutdown({
                    silent: !!silent,
                    callback: callback
                })
            }
        };
    }]);
})();
<commit_msg>modify variable name<commit_after>(function () {
    'use strict';

    angular.module('ariaNg').factory('aria2SettingService', ['aria2AllOptions', 'aria2GlobalAvailableOptions', 'aria2TaskAvailableOptions', 'ariaNgCommonService', 'aria2RpcService', function (aria2AllOptions, aria2GlobalAvailableOptions, aria2TaskAvailableOptions, ariaNgCommonService, aria2RpcService) {
        var processStatResult = function (stat) {
            if (!stat) {
                return stat;
            }

            var activeCount = parseInt(stat.numActive);
            var waitingCount = parseInt(stat.numWaiting);
            var totalRunningCount = activeCount + waitingCount;

            stat.totalRunningCount = totalRunningCount;

            return stat;
        };

        return {
            getAvailableGlobalOptionsKeys: function (type) {
                if (type == 'basic') {
                    return aria2GlobalAvailableOptions.basicOptions;
                } else if (type == 'http-ftp-sftp') {
                    return aria2GlobalAvailableOptions.httpFtpSFtpOptions;
                } else if (type == 'http') {
                    return aria2GlobalAvailableOptions.httpOptions;
                } else if (type == 'ftp-sftp') {
                    return aria2GlobalAvailableOptions.ftpSFtpOptions;
                } else if (type == 'bt') {
                    return aria2GlobalAvailableOptions.btOptions;
                } else if (type == 'metalink') {
                    return aria2GlobalAvailableOptions.metalinkOptions;
                } else if (type == 'rpc') {
                    return aria2GlobalAvailableOptions.rpcOptions;
                } else if (type == 'advanced') {
                    return aria2GlobalAvailableOptions.advancedOptions;
                } else {
                    return false;
                }
            },
            getAvailableTaskOptionKeys: function (status, isBittorrent) {
                var allOptions = aria2TaskAvailableOptions.taskOptions;
                var availableOptions = [];

                for (var i = 0; i < allOptions.length; i++) {
                    var option = allOptions[i];
                    var optionKey = {
                        key: option.key
                    };

                    if (option.newOnly) {
                        continue;
                    }

                    if (option.httpOnly && isBittorrent) {
                        continue;
                    } else if (option.btOnly && !isBittorrent) {
                        continue;
                    }

                    if (option.activeReadonly && status == 'active') {
                        optionKey.readonly = true;
                    }

                    availableOptions.push(optionKey);
                }

                return availableOptions;
            },
            getNewTaskOptionKeys: function (isBittorrent) {
                var allOptions = aria2TaskAvailableOptions.taskOptions;
                var availableOptions = [];

                for (var i = 0; i < allOptions.length; i++) {
                    var option = allOptions[i];
                    var optionKey = {
                        key: option.key
                    };

                    availableOptions.push(optionKey);
                }

                return availableOptions;
            },
            getSpecifiedOptions: function (keys) {
                var options = [];

                for (var i = 0; i < keys.length; i++) {
                    var key = keys[i];
                    var readonly = false;

                    if (angular.isObject(key)) {
                        var optionKey = key;

                        key = optionKey.key;
                        readonly = !!optionKey.readonly;
                    }

                    var option = aria2AllOptions[key];

                    if (!option) {
                        continue;
                    }

                    option = angular.extend({
                        key: key,
                        nameKey: 'options.' + key + '.name',
                        descriptionKey: 'options.' + key + '.description'
                    }, option);

                    if (option.type == 'boolean') {
                        option.options = ['true', 'false'];
                    }

                    if (readonly) {
                        option.readonly = true;
                    }

                    if (option.options) {
                        var availableOptions = [];

                        for (var j = 0; j < option.options.length; j++) {
                            availableOptions.push({
                                name: 'options.' + option.options[j],
                                value: option.options[j]
                            });
                        }

                        option.options = availableOptions;
                    }

                    options.push(option);
                }

                return options;
            },
            getGlobalOption: function (callback, silent) {
                return aria2RpcService.getGlobalOption({
                    silent: !!silent,
                    callback: callback
                });
            },
            setGlobalOption: function (key, value, callback, silent) {
                var data = {};
                data[key] = value;

                return aria2RpcService.changeGlobalOption({
                    options: data,
                    silent: !!silent,
                    callback: callback
                });
            },
            getAria2Status: function (callback, silent) {
                return aria2RpcService.getVersion({
                    silent: !!silent,
                    callback: callback
                })
            },
            getGlobalStat: function (callback, silent) {
                return aria2RpcService.getGlobalStat({
                    silent: !!silent,
                    callback: function (response) {
                        if (!callback) {
                            return;
                        }

                        var stat = processStatResult(response);
                        callback(stat);
                    }
                });
            },
            saveSession: function (callback, silent) {
                return aria2RpcService.saveSession({
                    silent: !!silent,
                    callback: callback
                })
            },
            shutdown: function (callback, silent) {
                return aria2RpcService.shutdown({
                    silent: !!silent,
                    callback: callback
                })
            }
        };
    }]);
})();
<|endoftext|>


<commit_before>angular.module('patternfly.table').component('pfTableView', {
  bindings: {
    config: '<?',
    dtOptions: '<?',
    colummns: '<',
    items: '<',
    actionButtons: '<?',
    menuActions: '<?',
    emptyStateConfig: '=?'
  },
  templateUrl: 'table/tableview/table-view.html',
  controller: function (DTOptionsBuilder, DTColumnDefBuilder, $element, pfUtils, $log, $filter, $timeout) {
    'use strict';
    var ctrl = this, prevDtOptions, prevItems;

    // Once datatables is out of active development I'll remove log statements
    ctrl.debug = false;

    ctrl.selectAll = false;
    ctrl.dtInstance = {};

    ctrl.defaultDtOptions = {
      autoWidth: false,
      destroy: true,
      order: [[1, "asc"]],
      dom: "t",
      select: {
        selector: 'td:first-child input[type="checkbox"]',
        style: 'multi'
      }
    };

    ctrl.defaultConfig = {
      selectionMatchProp: 'uuid',
      onCheckBoxChange: null
    };

    ctrl.$onInit = function () {

      if (ctrl.debug) {
        $log.debug("$onInit");
      }

      if (angular.isUndefined(ctrl.dtOptions)) {
        ctrl.dtOptions = {};
      }
      if (angular.isUndefined(ctrl.config)) {
        ctrl.config = {};
      }

      ctrl.updateConfigOptions();

      setColumnDefs();
    };

    ctrl.updateConfigOptions = function () {
      var col, props = "";

      if (ctrl.debug) {
        $log.debug("  updateConfigOptions");
      }

      if (angular.isDefined(ctrl.dtOptions) && angular.isDefined(ctrl.dtOptions.displayLength)) {
        ctrl.dtOptions.displayLength = Number(ctrl.dtOptions.displayLength);
      }

      // Need to deep watch changes in dtOptions and items
      prevDtOptions = angular.copy(ctrl.dtOptions);
      prevItems = angular.copy(ctrl.items);

      // Setting bound variables to new variables loses it's one way binding
      //   ctrl.dtOptions = pfUtils.merge(ctrl.defaultDtOptions, ctrl.dtOptions);
      //   ctrl.config = pfUtils.merge(ctrl.defaultConfig, ctrl.config);

      // Instead, use _.defaults to update the existing variable
      _.defaults(ctrl.dtOptions, ctrl.defaultDtOptions);
      _.defaults(ctrl.config, ctrl.defaultConfig);
      // may need to use _.defaultsDeep, but not currently available in
      // lodash-amd a-pf is using

      if (!validSelectionMatchProp()) {
        angular.forEach(ctrl.colummns, function (col) {
          if (props.length === 0) {
            props = col.itemField;
          } else {
            props += ", " + col.itemField;
          }
        });
        throw new Error("pfTableView - " +
          "config.selectionMatchProp '" + ctrl.config.selectionMatchProp +
          "' does not match any property in 'config.colummns'! Please set config.selectionMatchProp " +
          "to one of these properties: " + props);
      }
    };

    ctrl.dtInstanceCallback = function (_dtInstance) {
      var oTable, rows;
      if (ctrl.debug) {
        $log.debug("--> dtInstanceCallback");
      }

      ctrl.dtInstance = _dtInstance;
      listenForDraw();
      selectRowsByChecked();
    };

    ctrl.$onChanges = function (changesObj) {
      if (ctrl.debug) {
        $log.debug("$onChanges");
      }
      if ((changesObj.config && !changesObj.config.isFirstChange()) ) {
        if (ctrl.debug) {
          $log.debug("...updateConfigOptions");
        }
        ctrl.updateConfigOptions();
      }
    };

    ctrl.$doCheck = function () {
      if (ctrl.debug) {
        $log.debug("$doCheck");
      }
      // do a deep compare on dtOptions and items
      if (!angular.equals(ctrl.dtOptions, prevDtOptions)) {
        if (ctrl.debug) {
          $log.debug("  dtOptions !== prevDtOptions");
        }
        ctrl.updateConfigOptions();
      }
      if (!angular.equals(ctrl.items, prevItems)) {
        if (ctrl.debug) {
          $log.debug("  items !== prevItems");
        }
        prevItems = angular.copy(ctrl.items);
        //$timeout(function () {
        selectRowsByChecked();
        //});
      }
    };

    ctrl.$postLink = function () {
      if (ctrl.debug) {
        $log.debug(" $postLink");
      }
    };

    ctrl.$onDestroy = function () {
      if (ctrl.debug) {
        $log.debug(" $onDestroy");
      }
      ctrl.dtInstance = {};
    };

    function setColumnDefs () {
      var i = 0, actnBtns = 1;
      var item, prop;

      // add checkbox col, not sortable
      ctrl.dtColumnDefs = [ DTColumnDefBuilder.newColumnDef(i++).notSortable() ];
      // add column def. for each property of an item
      item = ctrl.items[0];
      for (prop in item) {
        if (item.hasOwnProperty(prop)) {   //need this 'if' for eslint
          ctrl.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i++));
          // Determine selectionMatchProp column number
          if (ctrl.config.selectionMatchProp === prop) {
            ctrl.selectionMatchPropColNum = (i - 1);
          }
        }
      }
      // add actions col.
      if (ctrl.actionButtons && ctrl.actionButtons.length > 0) {
        for (actnBtns = 1; actnBtns <= ctrl.actionButtons.length; actnBtns++) {
          ctrl.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i++).notSortable());
        }
      }
      if (ctrl.menuActions && ctrl.menuActions.length > 0) {
        ctrl.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i++).notSortable());
      }
    }

    function listenForDraw () {
      var oTable;
      var dtInstance = ctrl.dtInstance;
      if (dtInstance && dtInstance.dataTable) {
        oTable = dtInstance.dataTable;
        ctrl.tableId = oTable[0].id;
        oTable.on('draw.dt', function () {
          if (ctrl.debug) {
            $log.debug("--> redraw");
          }
          selectRowsByChecked();
        });
      }
    }

    function validSelectionMatchProp () {
      var retVal = false, prop;
      var item = ctrl.items[0];
      for (prop in item) {
        if (item.hasOwnProperty(prop)) {   //need this 'if' for eslint
          if (ctrl.config.selectionMatchProp === prop) {
            retVal = true;
          }
        }
      }
      return retVal;
    }
    /*
     *   Checkbox Selections
     */

    ctrl.toggleAll = function () {
      var item;
      var visibleRows = getVisibleRows();
      angular.forEach(visibleRows, function (row) {
        item = getItemFromRow(row);
        if (item.selected !== ctrl.selectAll) {
          item.selected = ctrl.selectAll;
          if (ctrl.config && ctrl.config.onCheckBoxChange) {
            ctrl.config.onCheckBoxChange(item);
          }
        }
      });
    };

    ctrl.toggleOne = function (item) {
      if (ctrl.config && ctrl.config.onCheckBoxChange) {
        ctrl.config.onCheckBoxChange(item);
      }
    };

    function getItemFromRow (matchPropValue) {
      var item, retVals;
      var filterObj = {};
      filterObj[ctrl.config.selectionMatchProp] = matchPropValue;
      retVals = $filter('filter')(ctrl.items, filterObj);

      if (retVals && retVals.length === 1) {
        item = retVals[0];
      }

      return item;
    }

    function selectRowsByChecked () {
      $timeout(function () {
        var oTable, rows, checked;

        oTable = ctrl.dtInstance.DataTable;

        if (ctrl.debug) {
          $log.debug("  selectRowsByChecked");
        }

        if (angular.isUndefined(oTable)) {
          return;
        }

        if (ctrl.debug) {
          $log.debug("  ...oTable defined");
        }

        // deselect all
        rows = oTable.rows();
        rows.deselect();

        // select those with checked checkboxes
        rows = oTable.rows( function ( idx, data, node ) {
          //         row      td     input type=checkbox
          checked = node.children[0].children[0].checked;
          return checked;
        });

        if (ctrl.debug) {
          $log.debug("   ... #checkedRows = " + rows[0].length);
        }

        if (rows[0].length > 0) {
          rows.select();
        }
        setSelectAllCheckbox();
      });
    }

    function setSelectAllCheckbox () {
      var numVisibleRows, numCheckedRows;

      if (ctrl.debug) {
        $log.debug("  setSelectAllCheckbox");
      }

      numVisibleRows = getVisibleRows().length;
      numCheckedRows = document.querySelectorAll("#" + ctrl.tableId + " tbody tr.even.selected").length +
                       document.querySelectorAll("#" + ctrl.tableId + " tbody tr.odd.selected").length;
      ctrl.selectAll = (numVisibleRows === numCheckedRows);
    }

    function getVisibleRows () {
      // Returns an array of visible 'selectionMatchProp' values
      // Ex. if selectionMatchProp === 'name' & selectionMatchPropColNum === 1 &
      //        page length === 3
      //     returns ['Mary Jane', 'Fred Flinstone', 'Frank Livingston']
      //
      var i, rowData, visibleRows = new Array();
      var oTable = ctrl.dtInstance.dataTable;

      var anNodes = document.querySelectorAll("#" + ctrl.tableId + "  tbody tr");

      for (i = 0; i < anNodes.length; ++i) {
        rowData = oTable.fnGetData(anNodes[i]);
        if (rowData !== null) {
          visibleRows.push(rowData[ctrl.selectionMatchPropColNum]);
        }
      }

      if (ctrl.debug) {
        $log.debug("    getVisibleRows (" + visibleRows.length + ")");
      }

      return visibleRows;
    }

    /*
     *   Action Buttons and Menus
     */

    ctrl.handleButtonAction = function (action, item) {
      if (action && action.actionFn) {
        action.actionFn(action, item);
      }
    };

    ctrl.isColItemFld = function (key) {
      var retVal = false;
      var tableCol = $filter('filter')(ctrl.colummns, {itemField: key});

      if (tableCol && tableCol.length === 1) {
        retVal = true;
      }

      return retVal;
    };

    ctrl.areActions = function () {
      return (ctrl.actionButtons && ctrl.actionButtons.length > 0) ||
        (ctrl.menuActions && ctrl.menuActions.length > 0);
    };

    ctrl.calcActionsColspan = function () {
      var colspan = 0;

      if (ctrl.actionButtons && ctrl.actionButtons.length > 0) {
        colspan += ctrl.actionButtons.length;
      }

      if (ctrl.menuActions && ctrl.menuActions.length > 0) {
        colspan += 1;
      }

      return colspan;
    };

    ctrl.handleMenuAction = function (action, item) {
      if (!ctrl.checkDisabled(item) && action && action.actionFn && (action.isDisabled !== true)) {
        action.actionFn(action, item);
      }
    };

    ctrl.setupActions = function (item, event) {
      /* Ignore disabled items completely
       if (ctrl.checkDisabled(item)) {
       return;
       }*/

      // update the actions based on the current item
      // $scope.updateActions(item);

      $timeout(function () {
        var parentDiv = undefined;
        var nextElement;

        nextElement = event.target;
        while (nextElement && !parentDiv) {
          if (nextElement.className.indexOf('dropdown-kebab-pf') !== -1) {
            parentDiv = nextElement;
            if (nextElement.className.indexOf('open') !== -1) {
              setDropMenuLocation (parentDiv);
            }
          }
          nextElement = nextElement.parentElement;
        }
      });
    };

    ctrl.checkDisabled = function (item) {
      return false;
    };

    function setDropMenuLocation (parentDiv) {
      var dropButton = parentDiv.querySelector('.dropdown-toggle');
      var dropMenu =  parentDiv.querySelector('.dropdown-menu');
      var parentRect = $element[0].getBoundingClientRect();
      var buttonRect = dropButton.getBoundingClientRect();
      var menuRect = dropMenu.getBoundingClientRect();
      var menuTop = buttonRect.top - menuRect.height;
      var menuBottom = buttonRect.top + buttonRect.height + menuRect.height;

      if ((menuBottom <= parentRect.top + parentRect.height) || (menuTop < parentRect.top)) {
        ctrl.dropdownClass = 'dropdown';
      } else {
        ctrl.dropdownClass = 'dropup';
      }
    }
  }
});
<commit_msg>fixes #441: pfTableView: error when items have more properties than the defined columns<commit_after>angular.module('patternfly.table').component('pfTableView', {
  bindings: {
    config: '<?',
    dtOptions: '<?',
    colummns: '<',
    items: '<',
    actionButtons: '<?',
    menuActions: '<?',
    emptyStateConfig: '=?'
  },
  templateUrl: 'table/tableview/table-view.html',
  controller: function (DTOptionsBuilder, DTColumnDefBuilder, $element, pfUtils, $log, $filter, $timeout) {
    'use strict';
    var ctrl = this, prevDtOptions, prevItems;

    // Once datatables is out of active development I'll remove log statements
    ctrl.debug = false;

    ctrl.selectAll = false;
    ctrl.dtInstance = {};

    ctrl.defaultDtOptions = {
      autoWidth: false,
      destroy: true,
      order: [[1, "asc"]],
      dom: "t",
      select: {
        selector: 'td:first-child input[type="checkbox"]',
        style: 'multi'
      }
    };

    ctrl.defaultConfig = {
      selectionMatchProp: 'uuid',
      onCheckBoxChange: null
    };

    ctrl.$onInit = function () {

      if (ctrl.debug) {
        $log.debug("$onInit");
      }

      if (angular.isUndefined(ctrl.dtOptions)) {
        ctrl.dtOptions = {};
      }
      if (angular.isUndefined(ctrl.config)) {
        ctrl.config = {};
      }

      ctrl.updateConfigOptions();

      setColumnDefs();
    };

    ctrl.updateConfigOptions = function () {
      var col, props = "";

      if (ctrl.debug) {
        $log.debug("  updateConfigOptions");
      }

      if (angular.isDefined(ctrl.dtOptions) && angular.isDefined(ctrl.dtOptions.displayLength)) {
        ctrl.dtOptions.displayLength = Number(ctrl.dtOptions.displayLength);
      }

      // Need to deep watch changes in dtOptions and items
      prevDtOptions = angular.copy(ctrl.dtOptions);
      prevItems = angular.copy(ctrl.items);

      // Setting bound variables to new variables loses it's one way binding
      //   ctrl.dtOptions = pfUtils.merge(ctrl.defaultDtOptions, ctrl.dtOptions);
      //   ctrl.config = pfUtils.merge(ctrl.defaultConfig, ctrl.config);

      // Instead, use _.defaults to update the existing variable
      _.defaults(ctrl.dtOptions, ctrl.defaultDtOptions);
      _.defaults(ctrl.config, ctrl.defaultConfig);
      // may need to use _.defaultsDeep, but not currently available in
      // lodash-amd a-pf is using

      if (!validSelectionMatchProp()) {
        angular.forEach(ctrl.colummns, function (col) {
          if (props.length === 0) {
            props = col.itemField;
          } else {
            props += ", " + col.itemField;
          }
        });
        throw new Error("pfTableView - " +
          "config.selectionMatchProp '" + ctrl.config.selectionMatchProp +
          "' does not match any property in 'config.colummns'! Please set config.selectionMatchProp " +
          "to one of these properties: " + props);
      }
    };

    ctrl.dtInstanceCallback = function (_dtInstance) {
      var oTable, rows;
      if (ctrl.debug) {
        $log.debug("--> dtInstanceCallback");
      }

      ctrl.dtInstance = _dtInstance;
      listenForDraw();
      selectRowsByChecked();
    };

    ctrl.$onChanges = function (changesObj) {
      if (ctrl.debug) {
        $log.debug("$onChanges");
      }
      if ((changesObj.config && !changesObj.config.isFirstChange()) ) {
        if (ctrl.debug) {
          $log.debug("...updateConfigOptions");
        }
        ctrl.updateConfigOptions();
      }
    };

    ctrl.$doCheck = function () {
      if (ctrl.debug) {
        $log.debug("$doCheck");
      }
      // do a deep compare on dtOptions and items
      if (!angular.equals(ctrl.dtOptions, prevDtOptions)) {
        if (ctrl.debug) {
          $log.debug("  dtOptions !== prevDtOptions");
        }
        ctrl.updateConfigOptions();
      }
      if (!angular.equals(ctrl.items, prevItems)) {
        if (ctrl.debug) {
          $log.debug("  items !== prevItems");
        }
        prevItems = angular.copy(ctrl.items);
        //$timeout(function () {
        selectRowsByChecked();
        //});
      }
    };

    ctrl.$postLink = function () {
      if (ctrl.debug) {
        $log.debug(" $postLink");
      }
    };

    ctrl.$onDestroy = function () {
      if (ctrl.debug) {
        $log.debug(" $onDestroy");
      }
      ctrl.dtInstance = {};
    };

    function setColumnDefs () {
      var i = 0, actnBtns = 1;
      var item, prop;

      // add checkbox col, not sortable
      ctrl.dtColumnDefs = [ DTColumnDefBuilder.newColumnDef(i++).notSortable() ];
      // add column def. for each property of an item
      item = ctrl.items[0];
      for (prop in item) {
        if (item.hasOwnProperty(prop) && ctrl.isColItemFld(prop)) {
          ctrl.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i++));
          // Determine selectionMatchProp column number
          if (ctrl.config.selectionMatchProp === prop) {
            ctrl.selectionMatchPropColNum = (i - 1);
          }
        }
      }
      // add actions col.
      if (ctrl.actionButtons && ctrl.actionButtons.length > 0) {
        for (actnBtns = 1; actnBtns <= ctrl.actionButtons.length; actnBtns++) {
          ctrl.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i++).notSortable());
        }
      }
      if (ctrl.menuActions && ctrl.menuActions.length > 0) {
        ctrl.dtColumnDefs.push(DTColumnDefBuilder.newColumnDef(i++).notSortable());
      }
    }

    function listenForDraw () {
      var oTable;
      var dtInstance = ctrl.dtInstance;
      if (dtInstance && dtInstance.dataTable) {
        oTable = dtInstance.dataTable;
        ctrl.tableId = oTable[0].id;
        oTable.on('draw.dt', function () {
          if (ctrl.debug) {
            $log.debug("--> redraw");
          }
          selectRowsByChecked();
        });
      }
    }

    function validSelectionMatchProp () {
      var retVal = false, prop;
      var item = ctrl.items[0];
      for (prop in item) {
        if (item.hasOwnProperty(prop)) {   //need this 'if' for eslint
          if (ctrl.config.selectionMatchProp === prop) {
            retVal = true;
          }
        }
      }
      return retVal;
    }
    /*
     *   Checkbox Selections
     */

    ctrl.toggleAll = function () {
      var item;
      var visibleRows = getVisibleRows();
      angular.forEach(visibleRows, function (row) {
        item = getItemFromRow(row);
        if (item.selected !== ctrl.selectAll) {
          item.selected = ctrl.selectAll;
          if (ctrl.config && ctrl.config.onCheckBoxChange) {
            ctrl.config.onCheckBoxChange(item);
          }
        }
      });
    };

    ctrl.toggleOne = function (item) {
      if (ctrl.config && ctrl.config.onCheckBoxChange) {
        ctrl.config.onCheckBoxChange(item);
      }
    };

    function getItemFromRow (matchPropValue) {
      var item, retVals;
      var filterObj = {};
      filterObj[ctrl.config.selectionMatchProp] = matchPropValue;
      retVals = $filter('filter')(ctrl.items, filterObj);

      if (retVals && retVals.length === 1) {
        item = retVals[0];
      }

      return item;
    }

    function selectRowsByChecked () {
      $timeout(function () {
        var oTable, rows, checked;

        oTable = ctrl.dtInstance.DataTable;

        if (ctrl.debug) {
          $log.debug("  selectRowsByChecked");
        }

        if (angular.isUndefined(oTable)) {
          return;
        }

        if (ctrl.debug) {
          $log.debug("  ...oTable defined");
        }

        // deselect all
        rows = oTable.rows();
        rows.deselect();

        // select those with checked checkboxes
        rows = oTable.rows( function ( idx, data, node ) {
          //         row      td     input type=checkbox
          checked = node.children[0].children[0].checked;
          return checked;
        });

        if (ctrl.debug) {
          $log.debug("   ... #checkedRows = " + rows[0].length);
        }

        if (rows[0].length > 0) {
          rows.select();
        }
        setSelectAllCheckbox();
      });
    }

    function setSelectAllCheckbox () {
      var numVisibleRows, numCheckedRows;

      if (ctrl.debug) {
        $log.debug("  setSelectAllCheckbox");
      }

      numVisibleRows = getVisibleRows().length;
      numCheckedRows = document.querySelectorAll("#" + ctrl.tableId + " tbody tr.even.selected").length +
                       document.querySelectorAll("#" + ctrl.tableId + " tbody tr.odd.selected").length;
      ctrl.selectAll = (numVisibleRows === numCheckedRows);
    }

    function getVisibleRows () {
      // Returns an array of visible 'selectionMatchProp' values
      // Ex. if selectionMatchProp === 'name' & selectionMatchPropColNum === 1 &
      //        page length === 3
      //     returns ['Mary Jane', 'Fred Flinstone', 'Frank Livingston']
      //
      var i, rowData, visibleRows = new Array();
      var oTable = ctrl.dtInstance.dataTable;

      var anNodes = document.querySelectorAll("#" + ctrl.tableId + "  tbody tr");

      for (i = 0; i < anNodes.length; ++i) {
        rowData = oTable.fnGetData(anNodes[i]);
        if (rowData !== null) {
          visibleRows.push(rowData[ctrl.selectionMatchPropColNum]);
        }
      }

      if (ctrl.debug) {
        $log.debug("    getVisibleRows (" + visibleRows.length + ")");
      }

      return visibleRows;
    }

    /*
     *   Action Buttons and Menus
     */

    ctrl.handleButtonAction = function (action, item) {
      if (action && action.actionFn) {
        action.actionFn(action, item);
      }
    };

    ctrl.isColItemFld = function (key) {
      var retVal = false;
      var tableCol = $filter('filter')(ctrl.colummns, {itemField: key});

      if (tableCol && tableCol.length === 1) {
        retVal = true;
      }

      return retVal;
    };

    ctrl.areActions = function () {
      return (ctrl.actionButtons && ctrl.actionButtons.length > 0) ||
        (ctrl.menuActions && ctrl.menuActions.length > 0);
    };

    ctrl.calcActionsColspan = function () {
      var colspan = 0;

      if (ctrl.actionButtons && ctrl.actionButtons.length > 0) {
        colspan += ctrl.actionButtons.length;
      }

      if (ctrl.menuActions && ctrl.menuActions.length > 0) {
        colspan += 1;
      }

      return colspan;
    };

    ctrl.handleMenuAction = function (action, item) {
      if (!ctrl.checkDisabled(item) && action && action.actionFn && (action.isDisabled !== true)) {
        action.actionFn(action, item);
      }
    };

    ctrl.setupActions = function (item, event) {
      /* Ignore disabled items completely
       if (ctrl.checkDisabled(item)) {
       return;
       }*/

      // update the actions based on the current item
      // $scope.updateActions(item);

      $timeout(function () {
        var parentDiv = undefined;
        var nextElement;

        nextElement = event.target;
        while (nextElement && !parentDiv) {
          if (nextElement.className.indexOf('dropdown-kebab-pf') !== -1) {
            parentDiv = nextElement;
            if (nextElement.className.indexOf('open') !== -1) {
              setDropMenuLocation (parentDiv);
            }
          }
          nextElement = nextElement.parentElement;
        }
      });
    };

    ctrl.checkDisabled = function (item) {
      return false;
    };

    function setDropMenuLocation (parentDiv) {
      var dropButton = parentDiv.querySelector('.dropdown-toggle');
      var dropMenu =  parentDiv.querySelector('.dropdown-menu');
      var parentRect = $element[0].getBoundingClientRect();
      var buttonRect = dropButton.getBoundingClientRect();
      var menuRect = dropMenu.getBoundingClientRect();
      var menuTop = buttonRect.top - menuRect.height;
      var menuBottom = buttonRect.top + buttonRect.height + menuRect.height;

      if ((menuBottom <= parentRect.top + parentRect.height) || (menuTop < parentRect.top)) {
        ctrl.dropdownClass = 'dropdown';
      } else {
        ctrl.dropdownClass = 'dropup';
      }
    }
  }
});
<|endoftext|>


<commit_before>import React, {Component} from 'react';

import RaisedButton from 'src/RaisedButton';
import Toaster from 'src/Toaster';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import MaterialProvider from 'src/MaterialProvider';
import ButtonRadioGroup from 'src/ButtonRadioGroup';
import MaterialTextField from 'src/MaterialTextField';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Toast.json';

import 'sass/containers/app/modules/pop/PopExamples.scss';
import 'sass/containers/app/modules/pop/ToastExamples.scss';

export default class ToastExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            type: Toaster.Type.INFO,
            position: Toaster.Position.TOP,
            message: 'Message',
            toasts: []
        };

        this.Type = Object.keys(Toaster.Type).map(item => ({
            className: `type-${item.toLowerCase()}`,
            iconCls: 'fas fa-check',
            label: item,
            value: Toaster.Type[item]
        }));

        this.ToasterPosition = Object.keys(Toaster.Position).map(item => ({
            label: item,
            value: Toaster.Position[item]
        }));

        this.updateField = ::this.updateField;
        this.addToast = ::this.addToast;
        this.toastPopHandler = ::this.toastPopHandler;

    }

    updateField(key, value) {
        let state = {};
        state[key] = value;
        this.setState(state);
    }

    addToast(position) {

        const {type, message, toasts} = this.state;

        toasts.push({
            type,
            message
        });

        this.setState({
            toasts,
            position
        });

    }

    toastPopHandler() {
        this.setState({
            toasts: []
        });
    }

    render() {

        const {type, position, title, message, toasts} = this.state;

        return (

Toast

                    Toast is a global display notification alert information .

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                <ButtonRadioGroup data={this.Type}
                                                  value={type}
                                                  onChange={value => {
                                                      this.updateField('type', value);
                                                  }}/>

                                <MaterialTextField theme={MaterialTextField.Theme.HIGHLIGHT}
                                                   value={message}
                                                   onChange={value => {
                                                       this.updateField('message', value);
                                                   }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Top Left"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.TOP_LEFT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.TOP);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top right"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.TOP_RIGHT);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Top"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.RIGHT_TOP);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.RIGHT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Bottom"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.RIGHT_BOTTOM);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Left"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.BOTTOM_LEFT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.BOTTOM);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Right"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.BOTTOM_RIGHT);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Top"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.LEFT_TOP);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.LEFT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Bottom"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.LEFT_BOTTOM);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Center"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.CENTER);
                                                      }}/>

                                <Toaster toasts={toasts}
                                         position={position}
                                         onToastPop={this.toastPopHandler}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};<commit_msg>update ToastExamples<commit_after>import React, {Component} from 'react';

import RaisedButton from 'src/RaisedButton';
import Toaster from 'src/Toaster';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import ButtonRadioGroup from 'src/ButtonRadioGroup';
import MaterialTextField from 'src/MaterialTextField';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Toast.json';

import 'sass/containers/app/modules/pop/PopExamples.scss';
import 'sass/containers/app/modules/pop/ToastExamples.scss';

class ToastExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            type: Toaster.Type.INFO,
            position: Toaster.Position.TOP,
            message: 'Message',
            toasts: []
        };

        this.Type = Object.keys(Toaster.Type).map(item => ({
            className: `type-${item.toLowerCase()}`,
            iconCls: 'fas fa-check',
            label: item,
            value: Toaster.Type[item]
        }));

        this.ToasterPosition = Object.keys(Toaster.Position).map(item => ({
            label: item,
            value: Toaster.Position[item]
        }));

    }

    updateField = (key, value) => {
        let state = {};
        state[key] = value;
        this.setState(state);
    };

    addToast = position => {

        const {type, message, toasts} = this.state;

        toasts.push({
            type,
            message
        });

        this.setState({
            toasts,
            position
        });

    };

    toastPopHandler = () => {
        this.setState({
            toasts: []
        });
    };

    render() {

        const {type, position, title, message, toasts} = this.state;

        return (

Toast

                    Toast is a global display notification alert information .

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="Basic"/>

                                <ButtonRadioGroup data={this.Type}
                                                  value={type}
                                                  onChange={value => {
                                                      this.updateField('type', value);
                                                  }}/>

                                <MaterialTextField theme={MaterialTextField.Theme.HIGHLIGHT}
                                                   value={message}
                                                   onChange={value => {
                                                       this.updateField('message', value);
                                                   }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Top Left"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.TOP_LEFT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.TOP);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top right"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.TOP_RIGHT);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Top"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.RIGHT_TOP);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.RIGHT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Bottom"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.RIGHT_BOTTOM);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Left"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.BOTTOM_LEFT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.BOTTOM);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Right"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.BOTTOM_RIGHT);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Top"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.LEFT_TOP);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.LEFT);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Bottom"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.LEFT_BOTTOM);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Center"
                                                      onClick={() => {
                                                          this.addToast(Toaster.Position.CENTER);
                                                      }}/>

                                <Toaster toasts={toasts}
                                         position={position}
                                         onToastPop={this.toastPopHandler}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
};

export default ToastExamples;<|endoftext|>


<commit_before>import React, { Component } from 'react'
import firebase from 'firebase'
import 'isomorphic-unfetch'
import clientCredentials from '../credentials/client'

export default class Index extends Component {
  static async getInitialProps ({req, query}) {
    const user = req && req.session ? req.session.decodedToken : null
    // don't fetch anything from firebase if the user is not found
    const snap = user && await req.firebaseServer.database().ref('messages').once('value')
    const messages = snap && snap.val()
    return { user, messages }
  }

  constructor (props) {
    super(props)
    this.state = {
      user: this.props.user,
      value: '',
      messages: this.props.messages
    }

    this.addDbListener = this.addDbListener.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  componentDidMount () {
    firebase.initializeApp(clientCredentials)

    if (this.state.user) this.addDbListener()

    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ user: user })
        return user.getIdToken()
          .then((token) => {
            // eslint-disable-next-line no-undef
            return fetch('/api/login', {
              method: 'POST',
              // eslint-disable-next-line no-undef
              headers: new Headers({ 'Content-Type': 'application/json' }),
              credentials: 'same-origin',
              body: JSON.stringify({ token })
            })
          }).then((res) => this.addDbListener())
      } else {
        this.setState({ user: null })
        // eslint-disable-next-line no-undef
        fetch('/api/logout', {
          method: 'POST',
          credentials: 'same-origin'
        }).then(() => firebase.database().ref('messages').off())
      }
    })
  }

  addDbListener () {
    firebase.database().ref('messages').on('value', snap => {
      const messages = snap.val()
      if (messages) this.setState({ messages })
    }, (error) => {
      console.error(error)
    })
  }

  handleChange (event) {
    this.setState({ value: event.target.value })
  }

  handleSubmit (event) {
    event.preventDefault()
    const date = new Date().getTime()
    firebase.database().ref(`messages/${date}`).set({
      id: date,
      text: this.state.value
    })
    this.setState({ value: '' })
  }

  handleLogin () {
    firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider())
  }

  handleLogout () {
    firebase.auth().signOut()
  }

  render () {
    const { user, value, messages } = this.state

    return

      {
        user
          ? <button onClick={this.handleLogout}>Logout</button>
          : <button onClick={this.handleLogin}>Login</button>
      }
      {
        user &&

          <form onSubmit={this.handleSubmit}>
            <input
              type={'text'}
              onChange={this.handleChange}
              placeholder={'add message'}
              value={value}
            />
          </form>

            {
              messages &&
              Object.keys(messages).map(key =>
{messages[key].text}
)
            }

      }

  }
}
<commit_msg>Update for use with Firestore (#5793)<commit_after>import React, { Component } from 'react'
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
import 'isomorphic-unfetch'
import clientCredentials from '../credentials/client'

export default class Index extends Component {
  static async getInitialProps ({req, query}) {
    const user = req && req.session ? req.session.decodedToken : null
    // don't fetch anything from firebase if the user is not found
    // const snap = user && await req.firebaseServer.database().ref('messages').once('value')
    // const messages = snap && snap.val()
    const messages = null
    return { user, messages }
  }

  constructor (props) {
    super(props)
    this.state = {
      user: this.props.user,
      value: '',
      messages: this.props.messages
    }

    this.addDbListener = this.addDbListener.bind(this)
    this.removeDbListener = this.removeDbListener.bind(this)
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  componentDidMount () {
    firebase.initializeApp(clientCredentials)

    if (this.state.user) this.addDbListener()

    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ user: user })
        return user.getIdToken()
          .then((token) => {
            // eslint-disable-next-line no-undef
            return fetch('/api/login', {
              method: 'POST',
              // eslint-disable-next-line no-undef
              headers: new Headers({ 'Content-Type': 'application/json' }),
              credentials: 'same-origin',
              body: JSON.stringify({ token })
            })
          }).then((res) => this.addDbListener())
      } else {
        this.setState({ user: null })
        // eslint-disable-next-line no-undef
        fetch('/api/logout', {
          method: 'POST',
          credentials: 'same-origin'
        }).then(() => this.removeDbListener())
      }
    })
  }

  addDbListener () {
    var db = firebase.firestore()
    // Disable deprecated features
    db.settings({
      timestampsInSnapshots: true
    })
    let unsubscribe = db.collection('messages').onSnapshot(querySnapshot => {
      var messages = {}
      querySnapshot.forEach(function (doc) {
        messages[doc.id] = doc.data()
      })
      if (messages) this.setState({ messages })
    }, (error) => {
      console.error(error)
    })
    this.setState({ unsubscribe })
  }

  removeDbListener () {
    // firebase.database().ref('messages').off()
    if (this.state.unsubscribe) { this.state.unsubscribe() }
  }

  handleChange (event) {
    this.setState({ value: event.target.value })
  }

  handleSubmit (event) {
    event.preventDefault()
    var db = firebase.firestore()
    // Disable deprecated features
    db.settings({
      timestampsInSnapshots: true
    })
    const date = new Date().getTime()
    db.collection('messages').doc(`${date}`).set({
      id: date,
      text: this.state.value
    })
    this.setState({ value: '' })
  }

  handleLogin () {
    firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider())
  }

  handleLogout () {
    firebase.auth().signOut()
  }

  render () {
    const { user, value, messages } = this.state

    return

      {
        user
          ? <button onClick={this.handleLogout}>Logout</button>
          : <button onClick={this.handleLogin}>Login</button>
      }
      {
        user &&

          <form onSubmit={this.handleSubmit}>
            <input
              type={'text'}
              onChange={this.handleChange}
              placeholder={'add message...'}
              value={value}
            />
          </form>

            {
              messages &&
              Object.keys(messages).map(key =>
{messages[key].text}
)
            }

      }

  }
}
<|endoftext|>


<commit_before>var mainInt;
var execute = true;
try {
    var videoId = window.location.search.split('v=')[1];
    var ampersandPosition = videoId.indexOf('&');
    if(ampersandPosition != -1) videoId = videoId.substring(0, ampersandPosition);
} catch(err) {
    execute = false;
}

if (!window.jQuery) execute = false;

if (execute ) {
    var theatreButton =
        '
'+
        '
Theatre mode
'+
        '

'
        '
';
    var theatreButtonOld =
        '
' +
            '
' +
                '
Theatre mode
' +
            '
'
        '
';

    if($('#movie_player #ytp-main-menu-id').length) {
        if ($('#movie_player #ytp-main-menu-id #yt-theatre-button').length == 0) {
            $('#movie_player #ytp-main-menu-id').append(theatreButton);
            $('#yt-theatre-button').click(goFullWindow);
        }
    } else if($('#movie_player .ytp-menu-container').length) {
        var exists = $('#movie_player .ytp-menu-container #yt-theatre-button').length;
        if(exists == 0) {
            mainInt = setInterval(function() {
                exists = $('#movie_player .ytp-menu-container #yt-theatre-button').length;

                if(exists) {
                    clearInterval(mainInt);
                } else {
                    $('#movie_player .ytp-menu-container .ytp-menu .ytp-menu-content').append(theatreButtonOld);
                    $('#yt-theatre-button').click(goFullWindow);
                }
            }, 500);
        }
    }
}

function goFullWindow() {
    var closeCurrentTab = false;
    chrome.storage.sync.get(['closeCurrentTab'], function(items) {
        closeCurrentTab = items.closeCurrentTab;

        var isPaused = $('#player-api .html5-video-player').hasClass('paused-mode') ? true : false;
        if (!isPaused) {
            $('#movie_player .ytp-play-button.ytp-button').click();
        }

        var start;
        start = $('#player-api .ytp-time-display .ytp-time-current').text().split(':');
        start = start[0] * 1 > 0 ? ((start[0] * 1) * 60) + (start[1] * 1) : start[1] * 1;

        var url = "http://www.youtube.com/embed/"+videoId+"?html5=1&autoplay=1&start="+start;

        if (closeCurrentTab) {
            chrome.runtime.sendMessage({method: "changeCurrentTabUrl", url : url});
        } else {
            chrome.runtime.sendMessage({method: "openNewTab", url : url});
            //chrome.runtime.sendMessage({method: "changeUrl"});
        }
        //window.open();
    });
}
<commit_msg>Remove old player support<commit_after>var mainInt;
var execute = true;
try {
    var videoId = window.location.search.split('v=')[1];
    var ampersandPosition = videoId.indexOf('&');
    if(ampersandPosition != -1) videoId = videoId.substring(0, ampersandPosition);
} catch(err) {
    execute = false;
}

if (!window.jQuery) execute = false;

if (execute) {
    var buttonContainer = document.querySelector('#movie_player .ytp-settings-menu');

    var theatreButton = document.createElement('div');
    theatreButton.setAttribute('class', 'ytp-menuitem');
    theatreButton.setAttribute('id', 'yt-theatre-button');
    theatreButton.setAttribute('role', 'menuitem');
    theatreButton.innerHtml =
        '
Theatre Mode
'+
        '

';

    theatreButton.onclick = goFullWindow;

    /*var theatreButton =
        '
'+
            '
Theatre Mode
'+
            '

'
        '
';*/

    if(buttonContainer.length) {
        if(buttonContainer.querySelector('#yt-theatre-button').length == 0) {
            buttonContainer.appendChild(theatreButton);
        }

        /*if($('#movie_player #ytp-main-menu-id #yt-theatre-button').length == 0) {
            $('#movie_player #ytp-main-menu-id').append(theatreButton);
            $('#yt-theatre-button').click(goFullWindow);
        }*/
    }
}

function goFullWindow() {
    var closeCurrentTab = false;
    chrome.storage.sync.get(['closeCurrentTab'], function(items) {
        closeCurrentTab = items.closeCurrentTab;

        var isPaused = $('#player-api .html5-video-player').hasClass('paused-mode') ? true : false;
        if (!isPaused) {
            $('#movie_player .ytp-play-button.ytp-button').click();
        }

        var start;
        start = $('#player-api .ytp-time-display .ytp-time-current').text().split(':');
        start = start[0] * 1 > 0 ? ((start[0] * 1) * 60) + (start[1] * 1) : start[1] * 1;

        var url = "http://www.youtube.com/embed/"+videoId+"?html5=1&autoplay=1&start="+start;

        if (closeCurrentTab) {
            chrome.runtime.sendMessage({method: "changeCurrentTabUrl", url : url});
        } else {
            chrome.runtime.sendMessage({method: "openNewTab", url : url});
            //chrome.runtime.sendMessage({method: "changeUrl"});
        }
        //window.open();
    });
}
<|endoftext|>