<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/**
 * @fileoverview This library augments gadgets.window with functionality
 * to change the height of a gadget dynamically.
 */

/**
 * @static
 * @class Provides operations for getting information about the window the
 *        gadget is placed in.
 * @name gadgets.window
 */
gadgets.window = gadgets.window || {};

(function() {

  /**
   * Parse out the value (specified in px) for a CSS attribute of an element.
   *
   * @param {Element} elem the element with the attribute to look for.
   * @param {string} attr the CSS attribute name of interest.
   * @return {number} the value of the px attr of the elem.
   * @private
   */
  function parseIntFromElemPxAttribute(elem, attr) {
    var style = window.getComputedStyle(elem, '');
    var value = style.getPropertyValue(attr);
    value.match(/^([0-9]+)/);
    return parseInt(RegExp.$1, 10);
  }

  /**
   * For Webkit-based browsers, calculate the height of the gadget iframe by
   * iterating through all elements in the gadget, starting with the body tag.
   * It is not sufficient to only account body children elements, because
   * CSS style position "float" may place a child element outside of the
   * containing parent element. Not counting "float" elements may lead to
   * undercounting.
   *
   * @return {number} the height of the gadget.
   * @private
   */
  function getHeightForWebkit() {
    var result = 0;
    var queue = [document.body];

    while (queue.length > 0) {
      var elem = queue.shift();
      var children = elem.childNodes;

      /*
       * Here, we are checking if we are a container that clips its overflow wit h
       * a specific height, because if so, we should ignore children
       */

      // check that elem is actually an element, could be a text node otherwise
      if (typeof elem.style !== 'undefined') {
        // Get the overflowY value, looking in the computed style if necessary
        var overflowY = elem.style['overflowY'];
        if (!overflowY) {
          var css = document.defaultView.getComputedStyle(elem, null);
          overflowY = css ? css['overflowY'] : null;
        }

        // The only non-clipping values of overflow is 'visible'. We assume that 'inherit'
        // is also non-clipping at the moment, but should we check this?
        if (overflowY != 'visible' && overflowY != 'inherit') {
          // Make sure this element explicitly specifies a height
          var height = elem.style['height'];
          if (!height) {
            var css = document.defaultView.getComputedStyle(elem, null);
            height = css ? css['height'] : '';
          }
          if (height.length > 0 && height != 'auto') {
            // We can safely ignore the children of this element,
            // so move onto the next in the queue
            continue;
          }
        }
      }

      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (typeof child.offsetTop !== 'undefined' &&
            typeof child.offsetHeight !== 'undefined') {
          // offsetHeight already accounts for border-bottom, padding-bottom.
          var bottom = child.offsetTop + child.offsetHeight +
              parseIntFromElemPxAttribute(child, 'margin-bottom');
          result = Math.max(result, bottom);
        }
        queue.push(child);
      }
    }

    // Add border, padding and margin of the containing body.
    return result +
        parseIntFromElemPxAttribute(document.body, 'border-bottom') +
        parseIntFromElemPxAttribute(document.body, 'margin-bottom') +
        parseIntFromElemPxAttribute(document.body, 'padding-bottom');
  }

  /**
   * Adjusts the gadget height
   * @param {number=} opt_height An optional preferred height in pixels. If not
   *     specified, will attempt to fit the gadget to its content.
   * @member gadgets.window
   */

  /**
   * Calculate inner content height is hard and different between
   * browsers rendering in Strict vs. Quirks mode.  We use a combination of
   * three properties within document.body and document.documentElement:
   * - scrollHeight
   * - offsetHeight
   * - clientHeight
   * These values differ significantly between browsers and rendering modes.
   * But there are patterns.  It just takes a lot of time and persistence
   * to figure out.
   */
  gadgets.window.getHeight = function() {
    // Get the height of the viewport
    var vh = gadgets.window.getViewportDimensions().height;
    var body = document.body;
    var docEl = document.documentElement;
    if (document.compatMode === 'CSS1Compat' && docEl.scrollHeight) {
      // In Strict mode:
      // The inner content height is contained in either:
      //    document.documentElement.scrollHeight
      //    document.documentElement.offsetHeight
      // Based on studying the values output by different browsers,
      // use the value that's NOT equal to the viewport height found above.
      return docEl.scrollHeight !== vh ?
          docEl.scrollHeight : docEl.offsetHeight;
    } else if (navigator.userAgent.indexOf('AppleWebKit') >= 0) {
      // In Webkit:
      // Property scrollHeight and offsetHeight will only increase in value.
      // This will incorrectly calculate reduced height of a gadget
      // (ie: made smaller).
      return getHeightForWebkit();
    } else if (body && docEl) {
      // In Quirks mode:
      // documentElement.clientHeight is equal to documentElement.offsetHeight
      // except in IE.  In most browsers, document.documentElement can be used
      // to calculate the inner content height.
      // However, in other browsers (e.g. IE), document.body must be used
      // instead.  How do we know which one to use?
      // If document.documentElement.clientHeight does NOT equal
      // document.documentElement.offsetHeight, then use document.body.
      var sh = docEl.scrollHeight;
      var oh = docEl.offsetHeight;
      if (docEl.clientHeight !== oh) {
        sh = body.scrollHeight;
        oh = body.offsetHeight;
      }

      // Detect whether the inner content height is bigger or smaller
      // than the bounding box (viewport).  If bigger, take the larger
      // value.  If smaller, take the smaller value.
      if (sh > vh) {
        // Content is larger
        return sh > oh ? sh : oh;
      } else {
        // Content is smaller
        return sh < oh ? sh : oh;
      }
    }
  };

  /**
   * Parse out the value (specified in px) for a CSS attribute of an element.
   *
   * @param {Element} elem the element with the attribute to look for.
   * @param {string} attr the CSS attribute name of interest.
   * @return {number} the value of the px attr of the elem.
   * @private
   */
  function parseIntFromElemPxAttribute(elem, attr) {
    var style = window.getComputedStyle(elem, '');
    var value = style.getPropertyValue(attr);
    value.match(/^([0-9]+)/);
    return parseInt(RegExp.$1, 10);
  }

  /**
   * For Webkit-based browsers, calculate the height of the gadget iframe by
   * iterating through all elements in the gadget, starting with the body tag.
   * It is not sufficient to only account body children elements, because
   * CSS style position "float" may place a child element outside of the
   * containing parent element. Not counting "float" elements may lead to
   * undercounting.
   *
   * @return {number} the height of the gadget.
   * @private
   */
  function getHeightForWebkit() {
    var result = 0;
    var queue = [document.body];

    while (queue.length > 0) {
      var elem = queue.shift();
      var children = elem.childNodes;

      /*
       * Here, we are checking if we are a container that clips its overflow wit h
       * a specific height, because if so, we should ignore children
       */

      // check that elem is actually an element, could be a text node otherwise
      if (typeof elem.style !== 'undefined') {
        // Get the overflowY value, looking in the computed style if necessary
        var overflowY = elem.style['overflowY'];
        if (!overflowY) {
          var css = document.defaultView.getComputedStyle(elem, null);
          overflowY = css ? css['overflowY'] : null;
        }

        // The only non-clipping values of overflow is 'visible'. We assume that 'inherit'
        // is also non-clipping at the moment, but should we check this?
        if (overflowY != 'visible' && overflowY != 'inherit') {
          // Make sure this element explicitly specifies a height
          var height = elem.style['height'];
          if (!height) {
            var css = document.defaultView.getComputedStyle(elem, null);
            height = css ? css['height'] : '';
          }
          if (height.length > 0 && height != 'auto') {
            // We can safely ignore the children of this element,
            // so move onto the next in the queue
            continue;
          }
        }
      }

      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (typeof child.offsetTop !== 'undefined' &&
            typeof child.offsetHeight !== 'undefined') {
          // offsetHeight already accounts for border-bottom, padding-bottom.
          var bottom = child.offsetTop + child.offsetHeight +
              parseIntFromElemPxAttribute(child, 'margin-bottom');
          result = Math.max(result, bottom);
        }
        queue.push(child);
      }
    }

    // Add border, padding and margin of the containing body.
    return result +
        parseIntFromElemPxAttribute(document.body, 'border-bottom') +
        parseIntFromElemPxAttribute(document.body, 'margin-bottom') +
        parseIntFromElemPxAttribute(document.body, 'padding-bottom');
  }
}());
<commit_msg>SHINDIG-1583  | Remove duplicate code in features/src/main/javascript/features/dynamic-height.height/dynamic-height-height.js | Patch from Dan Dumont<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/**
 * @fileoverview This library augments gadgets.window with functionality
 * to change the height of a gadget dynamically.
 */

/**
 * @static
 * @class Provides operations for getting information about the window the
 *        gadget is placed in.
 * @name gadgets.window
 */
gadgets.window = gadgets.window || {};

(function() {

  /**
   * Parse out the value (specified in px) for a CSS attribute of an element.
   *
   * @param {Element} elem the element with the attribute to look for.
   * @param {string} attr the CSS attribute name of interest.
   * @return {number} the value of the px attr of the elem.
   * @private
   */
  function parseIntFromElemPxAttribute(elem, attr) {
    var style = window.getComputedStyle(elem, '');
    var value = style.getPropertyValue(attr);
    value.match(/^([0-9]+)/);
    return parseInt(RegExp.$1, 10);
  }

  /**
   * For Webkit-based browsers, calculate the height of the gadget iframe by
   * iterating through all elements in the gadget, starting with the body tag.
   * It is not sufficient to only account body children elements, because
   * CSS style position "float" may place a child element outside of the
   * containing parent element. Not counting "float" elements may lead to
   * undercounting.
   *
   * @return {number} the height of the gadget.
   * @private
   */
  function getHeightForWebkit() {
    var result = 0;
    var queue = [document.body];

    while (queue.length > 0) {
      var elem = queue.shift();
      var children = elem.childNodes;

      /*
       * Here, we are checking if we are a container that clips its overflow wit h
       * a specific height, because if so, we should ignore children
       */

      // check that elem is actually an element, could be a text node otherwise
      if (typeof elem.style !== 'undefined') {
        // Get the overflowY value, looking in the computed style if necessary
        var overflowY = elem.style['overflowY'];
        if (!overflowY) {
          var css = document.defaultView.getComputedStyle(elem, null);
          overflowY = css ? css['overflowY'] : null;
        }

        // The only non-clipping values of overflow is 'visible'. We assume that 'inherit'
        // is also non-clipping at the moment, but should we check this?
        if (overflowY != 'visible' && overflowY != 'inherit') {
          // Make sure this element explicitly specifies a height
          var height = elem.style['height'];
          if (!height) {
            var css = document.defaultView.getComputedStyle(elem, null);
            height = css ? css['height'] : '';
          }
          if (height.length > 0 && height != 'auto') {
            // We can safely ignore the children of this element,
            // so move onto the next in the queue
            continue;
          }
        }
      }

      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (typeof child.offsetTop !== 'undefined' &&
            typeof child.offsetHeight !== 'undefined') {
          // offsetHeight already accounts for border-bottom, padding-bottom.
          var bottom = child.offsetTop + child.offsetHeight +
              parseIntFromElemPxAttribute(child, 'margin-bottom');
          result = Math.max(result, bottom);
        }
        queue.push(child);
      }
    }

    // Add border, padding and margin of the containing body.
    return result +
        parseIntFromElemPxAttribute(document.body, 'border-bottom') +
        parseIntFromElemPxAttribute(document.body, 'margin-bottom') +
        parseIntFromElemPxAttribute(document.body, 'padding-bottom');
  }

  /**
   * Adjusts the gadget height
   * @param {number=} opt_height An optional preferred height in pixels. If not
   *     specified, will attempt to fit the gadget to its content.
   * @member gadgets.window
   */

  /**
   * Calculate inner content height is hard and different between
   * browsers rendering in Strict vs. Quirks mode.  We use a combination of
   * three properties within document.body and document.documentElement:
   * - scrollHeight
   * - offsetHeight
   * - clientHeight
   * These values differ significantly between browsers and rendering modes.
   * But there are patterns.  It just takes a lot of time and persistence
   * to figure out.
   */
  gadgets.window.getHeight = function() {
    // Get the height of the viewport
    var vh = gadgets.window.getViewportDimensions().height;
    var body = document.body;
    var docEl = document.documentElement;
    if (document.compatMode === 'CSS1Compat' && docEl.scrollHeight) {
      // In Strict mode:
      // The inner content height is contained in either:
      //    document.documentElement.scrollHeight
      //    document.documentElement.offsetHeight
      // Based on studying the values output by different browsers,
      // use the value that's NOT equal to the viewport height found above.
      return docEl.scrollHeight !== vh ?
          docEl.scrollHeight : docEl.offsetHeight;
    } else if (navigator.userAgent.indexOf('AppleWebKit') >= 0) {
      // In Webkit:
      // Property scrollHeight and offsetHeight will only increase in value.
      // This will incorrectly calculate reduced height of a gadget
      // (ie: made smaller).
      return getHeightForWebkit();
    } else if (body && docEl) {
      // In Quirks mode:
      // documentElement.clientHeight is equal to documentElement.offsetHeight
      // except in IE.  In most browsers, document.documentElement can be used
      // to calculate the inner content height.
      // However, in other browsers (e.g. IE), document.body must be used
      // instead.  How do we know which one to use?
      // If document.documentElement.clientHeight does NOT equal
      // document.documentElement.offsetHeight, then use document.body.
      var sh = docEl.scrollHeight;
      var oh = docEl.offsetHeight;
      if (docEl.clientHeight !== oh) {
        sh = body.scrollHeight;
        oh = body.offsetHeight;
      }

      // Detect whether the inner content height is bigger or smaller
      // than the bounding box (viewport).  If bigger, take the larger
      // value.  If smaller, take the smaller value.
      if (sh > vh) {
        // Content is larger
        return sh > oh ? sh : oh;
      } else {
        // Content is smaller
        return sh < oh ? sh : oh;
      }
    }
  };
}());
<|endoftext|>


<commit_before>'use strict';

angular.module('<%=angularAppName%>')
    .component('jhAlert',  {
            template: '
' +
                            '
' +
                                '<uib-alert ng-cloak="" type="{{alert.type}}" close="alert.close()">
{{ alert.msg }}
</uib-alert>' +
                            '
' +
                      '
',
            controller: ['$scope','AlertService',
                function($scope, AlertService) {
                    $scope.alerts = AlertService.get();
                    $scope.$on('$destroy', function () {
                        $scope.alerts = [];
                    });
                }
            ]
    })
    .component('jhAlertError',  {
            template: '
' +
                            '
' +
                                '<uib-alert ng-cloak="" type="{{alert.type}}" close="alert.close(alerts)">
{{ alert.msg }}
</uib-alert>' +
                            '
' +
                      '
',
            controller: ['$scope', 'AlertService', '$rootScope'<% if (enableTranslation) { %>, '$translate'<% } %>,
                function($scope, AlertService, $rootScope<% if (enableTranslation) { %>, $translate<% } %>) {

                    $scope.alerts = [];

                    var addErrorAlert = function (message, key, data) {
                        <%_ if (enableTranslation) { _%>
                        key = key && key !== null ? key : message;
                            $scope.alerts.push(
                            AlertService.add(
                        {
                            type: 'danger',
                            msg: key,
                            params: data,
                            timeout: 5000,
                            toast: AlertService.isToast(),
                            scoped: true
                        },
                            $scope.alerts
                            )
                            );
                            <%_ } else { _%>
                        $scope.alerts.push(
                            AlertService.add(
                                {
                                    type: 'danger',
                                    msg: message,
                                    timeout: 5000,
                                    toast: AlertService.isToast(),
                                    scoped: true
                                },
                                $scope.alerts
                            )
                        );
                        <%_ } _%>
                    };

                    var cleanHttpErrorListener = $rootScope.$on('<%=angularAppName%>.httpError', function (event, httpResponse) {
                        var i;
                        event.stopPropagation();
                        switch (httpResponse.status) {
                            // connection refused, server not reachable
                            case 0:
                                addErrorAlert('Server not reachable','error.server.not.reachable');
                                break;

                            case 400:
                                var errorHeader = httpResponse.headers('X-<%=angularAppName%>-error');
                                var entityKey = httpResponse.headers('X-<%=angularAppName%>-params');
                                if (errorHeader) {
                                    var entityName = <% if (enableTranslation) { %>$translate.instant('global.menu.entities.' + entityKey)<% }else{ %>entityKey<% } %>;
                                    addErrorAlert(errorHeader, errorHeader, {entityName: entityName});
                                } else if (httpResponse.data && httpResponse.data.fieldErrors) {
                                    for (i = 0; i < httpResponse.data.fieldErrors.length; i++) {
                                        var fieldError = httpResponse.data.fieldErrors[i];
                                        // convert 'something[14].other[4].id' to 'something[].other[].id' so translations can be written to it
                                        var convertedField = fieldError.field.replace(/\[\d*\]/g, '[]');
                                        var fieldName = <% if (enableTranslation) { %>$translate.instant('<%= angularAppName %>.' + fieldError.objectName + '.' + convertedField)<% }else{ %>convertedField.charAt(0).toUpperCase() + convertedField.slice(1)<% } %>;
                                        addErrorAlert('Field ' + fieldName + ' cannot be empty', 'error.' + fieldError.message, {fieldName: fieldName});
                                    }
                                } else if (httpResponse.data && httpResponse.data.message) {
                                    addErrorAlert(httpResponse.data.message, httpResponse.data.message, httpResponse.data);
                                } else {
                                    addErrorAlert(httpResponse.data);
                                }
                                break;

                            default:
                                if (httpResponse.data && httpResponse.data.message) {
                                    addErrorAlert(httpResponse.data.message);
                                } else {
                                    addErrorAlert(JSON.stringify(httpResponse));
                                }
                        }
                    });

                    $scope.$on('$destroy', function () {
                        if(cleanHttpErrorListener !== undefined && cleanHttpErrorListener !== null){
                            cleanHttpErrorListener();
                            $scope.alerts = [];
                        }
                    });
                }
            ]
    });
<commit_msg>refactoring alert directives<commit_after>(function() {
    'use strict';

    angular
        .module('<%=angularAppName%>')
        .component('jhAlert', jhAlert);

    var jhAlert = {
        template: '
' +
                        '
' +
                            '<uib-alert ng-cloak="" type="{{alert.type}}" close="alert.close()">
{{ alert.msg }}
</uib-alert>' +
                        '
' +
                  '
',
        controller: jhAlertController,
        controllerAs: 'vm'
    };

    jhAlertController.$inject = ['$scope', 'AlertService'];

    function jhAlertController($scope, AlertService) {
        var vm = this;

        vm.alerts = AlertService.get();
        $scope.$on('$destroy', function () {
            vm.alerts = [];
        });
    }
})();
<|endoftext|>


<commit_before>$(document).ready(function() {

    $("#duplicateStudy").click(function () {

        console.log(contextPath);
        var listTags = {};
        var studyId = $('#studyId').val();
        var action = contextPath + "studies/"+studyId+"/duplicate";
        var inputs= $('#study-duplications-form-container').find('.studyItemFormInput');
        inputs.each(function(j, input) {
            listTags[input.name] = input.value;
        });

        if (listTags != {}) {
            var dataJSON = JSON.stringify(listTags);
            console.log("if ");
            $.ajax({
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                dataType: 'json',
                type: "POST",
                url: action,
                data: dataJSON,
                success: function (data, textStatus, jqXHR) {
                    if ("failed" in data) {
                       alert(data["failed"]);
                    }
                    else {
                        window.location.href = contextPath+data.success;
                    }

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Something went wrong. Please, contact the helpdesk.");
                }
            });
        }
        else alert("You must add at least a study.");
    });

});<commit_msg>disable form<commit_after>$(document).ready(function() {

    function disableForm() {
        var inputs= $('#study-duplications-form-container').find('.studyItemFormInput');
        inputs.each(function(j, input) {
            $(input).prop('disabled', true);
        });

        var removes= $('#study-duplications-form-container').find('.remove-study-duplications');
        removes.each(function(j, remove) {
            $(remove).attr("disabled", "disabled");
        });
        $('#multi-add-study-duplications').attr("disabled", "disabled");
        $('#multi-add-study-duplications-button').attr("disabled", "disabled");
        $('#duplicateStudy').attr("disabled", "disabled");

    }

    function enableForm() {
        var inputs= $('#study-duplications-form-container').find('.studyItemFormInput');
        inputs.each(function(j, input) {
            $(input).prop('disabled', false);
        });

        var removes= $('#study-duplications-form-container').find('.remove-study-duplications');
        removes.each(function(j, remove) {
            $(remove).removeAttr("disabled");
        });
        $('#multi-add-study-duplications').removeAttr("disabled");
        $('#multi-add-study-duplications-button').removeAttr("disabled");
        $('#duplicateStudy').removeAttr("disabled");
    }

    $("#duplicateStudy").click(function () {

        //console.log(contextPath);
        var listTags = {};
        var studyId = $('#studyId').val();
        var action = contextPath + "studies/"+studyId+"/duplicate";
        var inputs= $('#study-duplications-form-container').find('.studyItemFormInput');
        inputs.each(function(j, input) {
            listTags[input.name] = input.value;
        });

        if (listTags != {}) {
            var dataJSON = JSON.stringify(listTags);
            console.log("if ");
            $.ajax({
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                dataType: 'json',
                type: "POST",
                url: action,
                data: dataJSON,
                beforeSend: function() {
                    disableForm();
                },
                success: function (data, textStatus, jqXHR) {
                    if ("failed" in data) {
                       alert(data["failed"]);
                       enableForm();
                    }
                    else {
                        window.location.href = contextPath+data.success;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Something went wrong. Please, contact the helpdesk.");
                }
            });
        }
        else alert("You must add at least a study.");
    });

});<|endoftext|>


<commit_before>if (typeof(XCoLab) == 'undefined')
	throw new "XCoLab isn't defined";
if (typeof(XCoLab.modeling) == 'undefined')
	throw new "XCoLab.modeling isn't defined";

(function() {
	/**
	 * A header renderer for modeling widget
	 */
	function DefaultHeaderRenderer(modelingWidget) {
		this.modelingWidget = modelingWidget;
		this.render(modelingWidget.container);
		var that = this;

		jQuery(modelingWidget).on("valueChanged", function() {
			that.container.find(".runSimulationButtonHighlight").effect("highlight", {}, 2000);
		});

		jQuery(modelingWidget).on('scenarioFetched', function(event) {
			that.updateNameDescription(event.scenario);
		});

		jQuery(modelingWidget).on('modelFetched', function(event) {
			that.updateNameDescription(event.model);
		});
	}

	DefaultHeaderRenderer.prototype = new XCoLab.modeling.BaseXCoLabModelingRenderer();
	DefaultHeaderRenderer.prototype.constructor = DefaultHeaderRenderer.prototype;

	DefaultHeaderRenderer.prototype.containerHtml = "

";

	DefaultHeaderRenderer.prototype.renderEdit = function(container) {

		var that = this;
		this.container = container;

		container.append('

' +
			'
Actions
' +
			'
 ' +
			'
' +
			'
' +
			'Impacts' +
			'

' +
			'
' +
			'RUN the model' +
			'
' +
			'

 ' +
			'

' +
			"

");

		container.find(".runmodel").click(function() { that.modelingWidget.runTheModel(); });
	};

	DefaultHeaderRenderer.prototype.renderView = function(container) {
		this.container = container;
		container.append("

Actions

" +
			"

Impacts

" +
			"

" +
			"

");
	};

	DefaultHeaderRenderer.prototype.updateNameDescription = function(model) {
		console.log(this, this.container);
		this.container.find('.model_name').text(model.modelName);
		this.container.find('.model_description').text(model.modelDescription);
		this.container.find(".model_description .brand").remove();
		var brand = $("

");
		brand.addClass(model.modelName);
		this.container.find(".model_description").append(brand);

	}

	XCoLab.modeling.headerRenderers.push(function (modelingWidget) {
		return new DefaultHeaderRenderer(modelingWidget);
	});
}());<commit_msg>Added link to climateinteractive-logo<commit_after>if (typeof(XCoLab) == 'undefined')
	throw new "XCoLab isn't defined";
if (typeof(XCoLab.modeling) == 'undefined')
	throw new "XCoLab.modeling isn't defined";

(function() {
	/**
	 * A header renderer for modeling widget
	 */
	function DefaultHeaderRenderer(modelingWidget) {
		this.modelingWidget = modelingWidget;
		this.render(modelingWidget.container);
		var that = this;

		jQuery(modelingWidget).on("valueChanged", function() {
			that.container.find(".runSimulationButtonHighlight").effect("highlight", {}, 2000);
		});

		jQuery(modelingWidget).on('scenarioFetched', function(event) {
			that.updateNameDescription(event.scenario);
		});

		jQuery(modelingWidget).on('modelFetched', function(event) {
			that.updateNameDescription(event.model);
		});
	}

	DefaultHeaderRenderer.prototype = new XCoLab.modeling.BaseXCoLabModelingRenderer();
	DefaultHeaderRenderer.prototype.constructor = DefaultHeaderRenderer.prototype;

	DefaultHeaderRenderer.prototype.containerHtml = "

";

	DefaultHeaderRenderer.prototype.renderEdit = function(container) {

		var that = this;
		this.container = container;

		container.append('

' +
			'
Actions
' +
			'
 ' +
			'
' +
			'
' +
			'Impacts' +
			'

' +
			'
' +
			'RUN the model' +
			'
' +
			'

 ' +
			'

' +
			"

");

		container.find(".runmodel").click(function() { that.modelingWidget.runTheModel(); });
	};

	DefaultHeaderRenderer.prototype.renderView = function(container) {
		this.container = container;
		container.append("

Actions

" +
			"

Impacts

" +
			"

" +
			"

");
	};

	DefaultHeaderRenderer.prototype.updateNameDescription = function(model) {
		console.log(this, this.container);
		this.container.find('.model_name').text(model.modelName);
		this.container.find('.model_description').text(model.modelDescription);
		this.container.find(".model_description .brand").remove();
		var brand = $("<div class='brand' onclick='location.href='http://www.climateinteractive.org''
");
		brand.addClass(model.modelName);
		this.container.find(".model_description").append(brand);

	}

	XCoLab.modeling.headerRenderers.push(function (modelingWidget) {
		return new DefaultHeaderRenderer(modelingWidget);
	});
}());<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright 2015 - 2016 France Labs
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/

AjaxFranceLabs.SearchBarWidget = AjaxFranceLabs.AbstractWidget
		.extend({

			// Variables

			autocomplete : false,

			noRequest : false,

			autocompleteOptions : {
				optionsExtend : true,
				render : null,
				field : null,
				valueSelectFormat : function(value) {
					return value;
				},
				singleValue : false,
				openOnFieldFocus : false
			},

			updateBrowserAddressBar : true,

			removeContentButton : false,

			type : 'searchBar',

			activateAdvancedSearchLink : false,

			// Methods

			updateAddressBar : function() {
				if (this.updateBrowserAddressBar == true) {
					var searchType = 'allWords';
					var radios = $('#searchBar').find(
							'.searchMode input[type=radio]');
					$.each(radios, function(key, radio) {
						if (radio.checked) {
							searchType = radio.value;
						}
					});
					var query = $('.searchBar input[type=text]').val();

					window.history.pushState('Object', 'Title',
							window.location.pathname + '?searchType='
									+ searchType + '&query=' + query + '&lang='
									+ window.i18n.language);

					Manager.store.addByValue("id", UUID.generate());
				}
			},

			clean : function() {
				this.manager.store.remove('start');
				this.manager.store.remove('fq');
				$.each(this.manager.widgets, function(index, widget) {
					if (typeof widget.pagination !== "undefined") {
						widget.pagination.pageSelected = 0;
					}
				});

			},

			buildWidget : function() {
				var self = this, elm = $(this.elm);
				$("#basicSearchLink").html(window.i18n.msgStore['search']);
				$("#basicSearchLink").click(function() {self.initBasicSearchUI();});
				$("#basicSearchLink").addClass("active");

				if ($(window).width() > 800) {
					elm.addClass('searchBarWidget').addClass('widget').append(
							'

').append(
							'

');
					elm.find('#searchBarContent').append(
							'

');
				} else {
					elm.addClass('searchBarWidget').addClass('widget').append(
							'

').append(
							'

');
				}
				elm
						.find('.searchBar')
						.append(
								'<input type="text" autocorrect="off" autocapitalize="off"/>')
						.append(
								'

');
				if (this.removeContentButton)
					elm.find('.searchBar').append(
							'').find(
							'.removeContent').css('display', 'none').append(
							'X').click(function() {
						elm.find('.searchBar input[type=text]').val('');
						$(this).css('display', 'none');
						self.makeRequest();
					});

				elm.find('.searchMode').append('

').append(
						'

').append('

').append(
						'

');
				elm
						.find('.searchMode div')
						.attr('style', 'display: inline')
						.append(
								'<input type="radio" name="searchType" class="radio" />')
						.append('');
				elm.find('.searchMode div:eq(0)').find('input').attr('value',
						'allWords').attr('checked', 'true').attr('id',
						'allWords').parent().find('label').attr('for',
						'allWords').append(' ').append(
						window.i18n.msgStore['allWords']);
				elm.find('.searchMode div:eq(1)').find('input').attr('value',
						'atLeastOneWord').attr('id', 'atLeastOneWord').parent()
						.find('label').attr('for', 'atLeastOneWord').append(
								' ').append(
								window.i18n.msgStore['atLeastOneWord']);
				elm.find('.searchMode div:eq(2)').find('input').attr('value',
						'exactExpression').attr('id', 'exactExpression')
						.parent().find('label').attr('for', 'exactExpression')
						.append(' ').append(
								window.i18n.msgStore['exactExpression']);

				elm
						.find('.searchBar input[type=text]')
						.keypress(
								function(event) {
									if (event.keyCode === 13) {
										if (self.autocomplete)
											self.elm
													.find(
															'.searchBar input[type=text]')
													.autocomplete("close");
										self.makeRequest();
									}
								})
						.keyup(
								function() {
									if (self.removeContentButton) {
										if (AjaxFranceLabs.empty(elm.find(
												'.searchBar input[type=text]')
												.val()))
											elm
													.find(
															'.searchBar .removeContent:visible')
													.css('display', 'none');
										else
											elm
													.find(
															'.searchBar .removeContent:hidden')
													.css('display', 'block');
									}
								});
				elm.find('.searchBar .search').click(function() {
					self.makeRequest();

				});
				if (this.autocomplete === true) {
					this.autocompleteOptions.elm = elm
							.find('.searchBar input[type=text]');
					this.autocomplete = new AjaxFranceLabs.AutocompleteModule(
							this.autocompleteOptions);
					this.autocomplete.manager = this.manager;
					this.autocomplete.init();
				} else if (this.autocomplete) {
					this.autocomplete.elm = elm
							.find('.searchBar input[type=text]');
					this.autocomplete.manager = this.manager;
					this.autocomplete.init();
				}
				var sortModeDiv = document.getElementById("sortMode");
				var textSort = document
						.createTextNode(window.i18n.msgStore['sortType']);
				sortModeDiv.appendChild(textSort);
				var selectList = document.createElement("select");
				selectList.id = "mySelect";
				selectList.onchange = function() {
					self.makeRequest();
				};
				sortModeDiv.appendChild(selectList);

				var optionScore = document.createElement("option");
				optionScore.setAttribute("value", "score");
				optionScore.setAttribute("selected", "");
				optionScore.text = window.i18n.msgStore['score'];

				selectList.appendChild(optionScore);

				var optionDate = document.createElement("option");
				optionDate.setAttribute("value", "date");
				optionDate.text = window.i18n.msgStore['date'];
				selectList.appendChild(optionDate);

				if (this.activateAdvancedSearchLink){

					$('#advancedSearchLink').click(function(event){

						destroyDatatables();

						// Hide other UIs
						$("#parametersUi").hide();
						$("#favoritesUi").hide();
						$("#loginDatafariLinks").find(".active").removeClass("active");

						// Make the link active
						$(this).addClass('active');

						// Hide the basic search
						elm.hide();

						// Hide the results UI
						$("#results_div").hide();

						// Reset the widget status (radios, entered text, ...)
						self.manager.getWidgetByID('advancedSearch').reset();

						// Initialize the advancedSearch UI
						self.manager.getWidgetByID('advancedSearch').buildStartingUI();

						// Display the advanced search
						$('#advancedSearch').show();

						// Perform a "select all" request: *:*
						//self.manager.makeDefaultRequest();

						// Prevent page reload
						event.preventDefault();
					});
				}
			},

			beforeRequest : function() {

				/*
				 * Check if we are executing a synthetic request, built by
				 * spellChecker widget after a misspelled search term or not. If
				 * it is a "normal" request, update the Q parameter with the
				 * value from searchBar and do other useful stuff. Else, it is a
				 * "synthetic" request; do nothing as the spellchecker itself
				 * has already replaced the Q parameter with the corrected
				 * search term.
				 */
				if (this.manager.store.isParamDefined('original_query') !== true) {

					var search = (AjaxFranceLabs.empty(AjaxFranceLabs.trim($(
							this.elm).find('.searchBar input').val()))) ? '*:*'
							: AjaxFranceLabs.trim($(this.elm).find(
									'.searchBar input').val());
					// Make spellchecker case insensitive
					// Manager.store.addByValue("spellcheck.q", search);
					var testSelect = document.getElementById("mySelect");
					if (testSelect.options[testSelect.selectedIndex].value == 'date') {
						Manager.store.addByValue("sort", 'last_modified desc');
					} else {
						Manager.store.addByValue("sort", 'score desc');
					}

					if (this.autocomplete)
						search = search.replace(/\u200c/g, '');
					switch ($(this.elm).find('input[name=searchType]:checked')
							.val()) {
					case "allWords":
						Manager.store.addByValue("q.op", 'AND');
						Manager.store.addByValue("spellcheck.collateParam.q.op", 'AND');
						break;
					case "atLeastOneWord":
						Manager.store.addByValue("q.op", 'OR');
						Manager.store.addByValue("spellcheck.collateParam.q.op", 'OR');
						break;
					case 'exactExpression':
						search = '"' + search + '"';
						break;
					default:
						Manager.store.addByValue("q.op", 'AND');
						Manager.store.addByValue("spellcheck.collateParam.q.op", 'AND');
						break
					}

					this.manager.store.get('q').val(search);

				}

			},

			afterRequest : function() {
				/*
				 * It appeared that sometimes when making a request, the
				 * autocomplete was displayed, this part of the code has been
				 * made to counter this little glitch, after a request, we close
				 * the autocomplete
				 */
				if (this.autocomplete) {
					this.elm.find('.searchBar input[type=text]').autocomplete(
							"close");
				}
			},

			makeRequest : function() {
				if (!this.noRequest) {
					this.initBasicSearchUI();
					this.clean();
					this.updateAddressBar();
					this.manager.makeRequest();
					$("#results .doc_list").empty();
				}

			},

			initBasicSearchUI: function() {
				if(typeof destroyDatatables !== "undefined") {
					destroyDatatables();
				}
				$('#searchBar').show();
				$("#results_div").show();
				$("#search_information").show();
				$("#sortMode").show();
				$("#advancedSearch").hide();
				$("#parametersUi").hide();
				$("#favoritesUi").hide();
				$("#loginDatafariLinks").find(".active").removeClass("active");
				$("#basicSearchLink").addClass("active");
			},

			/**
			 * Resets the inputs of the widget
			 */
			reset : function() {
				var elm = $(this.elm);
				elm.find('input[type="text"]').val('');
				elm.find('input#allWords').prop('checked', true);
			}

		});
<commit_msg>Keep facets when sort mode is changed<commit_after>/*******************************************************************************
 * Copyright 2015 - 2016 France Labs
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/

AjaxFranceLabs.SearchBarWidget = AjaxFranceLabs.AbstractWidget
		.extend({

			// Variables

			autocomplete : false,

			noRequest : false,

			autocompleteOptions : {
				optionsExtend : true,
				render : null,
				field : null,
				valueSelectFormat : function(value) {
					return value;
				},
				singleValue : false,
				openOnFieldFocus : false
			},

			updateBrowserAddressBar : true,

			removeContentButton : false,

			type : 'searchBar',

			activateAdvancedSearchLink : false,

			// Methods

			updateAddressBar : function() {
				if (this.updateBrowserAddressBar == true) {
					var searchType = 'allWords';
					var radios = $('#searchBar').find(
							'.searchMode input[type=radio]');
					$.each(radios, function(key, radio) {
						if (radio.checked) {
							searchType = radio.value;
						}
					});
					var query = $('.searchBar input[type=text]').val();

					window.history.pushState('Object', 'Title',
							window.location.pathname + '?searchType='
									+ searchType + '&query=' + query + '&lang='
									+ window.i18n.language);

					Manager.store.addByValue("id", UUID.generate());
				}
			},

			clean : function() {
				this.manager.store.remove('start');
				this.manager.store.remove('fq');
				$.each(this.manager.widgets, function(index, widget) {
					if (typeof widget.pagination !== "undefined") {
						widget.pagination.pageSelected = 0;
					}
				});

			},

			buildWidget : function() {
				var self = this, elm = $(this.elm);
				$("#basicSearchLink").html(window.i18n.msgStore['search']);
				$("#basicSearchLink").click(function() {self.initBasicSearchUI();});
				$("#basicSearchLink").addClass("active");

				if ($(window).width() > 800) {
					elm.addClass('searchBarWidget').addClass('widget').append(
							'

').append(
							'

');
					elm.find('#searchBarContent').append(
							'

');
				} else {
					elm.addClass('searchBarWidget').addClass('widget').append(
							'

').append(
							'

');
				}
				elm
						.find('.searchBar')
						.append(
								'<input type="text" autocorrect="off" autocapitalize="off"/>')
						.append(
								'

');
				if (this.removeContentButton)
					elm.find('.searchBar').append(
							'').find(
							'.removeContent').css('display', 'none').append(
							'X').click(function() {
						elm.find('.searchBar input[type=text]').val('');
						$(this).css('display', 'none');
						self.makeRequest();
					});

				elm.find('.searchMode').append('

').append(
						'

').append('

').append(
						'

');
				elm
						.find('.searchMode div')
						.attr('style', 'display: inline')
						.append(
								'<input type="radio" name="searchType" class="radio" />')
						.append('');
				elm.find('.searchMode div:eq(0)').find('input').attr('value',
						'allWords').attr('checked', 'true').attr('id',
						'allWords').parent().find('label').attr('for',
						'allWords').append(' ').append(
						window.i18n.msgStore['allWords']);
				elm.find('.searchMode div:eq(1)').find('input').attr('value',
						'atLeastOneWord').attr('id', 'atLeastOneWord').parent()
						.find('label').attr('for', 'atLeastOneWord').append(
								' ').append(
								window.i18n.msgStore['atLeastOneWord']);
				elm.find('.searchMode div:eq(2)').find('input').attr('value',
						'exactExpression').attr('id', 'exactExpression')
						.parent().find('label').attr('for', 'exactExpression')
						.append(' ').append(
								window.i18n.msgStore['exactExpression']);

				elm
						.find('.searchBar input[type=text]')
						.keypress(
								function(event) {
									if (event.keyCode === 13) {
										if (self.autocomplete)
											self.elm
													.find(
															'.searchBar input[type=text]')
													.autocomplete("close");
										self.makeRequest();
									}
								})
						.keyup(
								function() {
									if (self.removeContentButton) {
										if (AjaxFranceLabs.empty(elm.find(
												'.searchBar input[type=text]')
												.val()))
											elm
													.find(
															'.searchBar .removeContent:visible')
													.css('display', 'none');
										else
											elm
													.find(
															'.searchBar .removeContent:hidden')
													.css('display', 'block');
									}
								});
				elm.find('.searchBar .search').click(function() {
					self.makeRequest();

				});
				if (this.autocomplete === true) {
					this.autocompleteOptions.elm = elm
							.find('.searchBar input[type=text]');
					this.autocomplete = new AjaxFranceLabs.AutocompleteModule(
							this.autocompleteOptions);
					this.autocomplete.manager = this.manager;
					this.autocomplete.init();
				} else if (this.autocomplete) {
					this.autocomplete.elm = elm
							.find('.searchBar input[type=text]');
					this.autocomplete.manager = this.manager;
					this.autocomplete.init();
				}
				var sortModeDiv = document.getElementById("sortMode");
				var textSort = document
						.createTextNode(window.i18n.msgStore['sortType']);
				sortModeDiv.appendChild(textSort);
				var selectList = document.createElement("select");
				selectList.id = "mySelect";
				selectList.onchange = function() {
					self.manager.makeRequest();
				};
				sortModeDiv.appendChild(selectList);

				var optionScore = document.createElement("option");
				optionScore.setAttribute("value", "score");
				optionScore.setAttribute("selected", "");
				optionScore.text = window.i18n.msgStore['score'];

				selectList.appendChild(optionScore);

				var optionDate = document.createElement("option");
				optionDate.setAttribute("value", "date");
				optionDate.text = window.i18n.msgStore['date'];
				selectList.appendChild(optionDate);

				if (this.activateAdvancedSearchLink){

					$('#advancedSearchLink').click(function(event){

						destroyDatatables();

						// Hide other UIs
						$("#parametersUi").hide();
						$("#favoritesUi").hide();
						$("#loginDatafariLinks").find(".active").removeClass("active");

						// Make the link active
						$(this).addClass('active');

						// Hide the basic search
						elm.hide();

						// Hide the results UI
						$("#results_div").hide();

						// Reset the widget status (radios, entered text, ...)
						self.manager.getWidgetByID('advancedSearch').reset();

						// Initialize the advancedSearch UI
						self.manager.getWidgetByID('advancedSearch').buildStartingUI();

						// Display the advanced search
						$('#advancedSearch').show();

						// Perform a "select all" request: *:*
						//self.manager.makeDefaultRequest();

						// Prevent page reload
						event.preventDefault();
					});
				}
			},

			beforeRequest : function() {

				/*
				 * Check if we are executing a synthetic request, built by
				 * spellChecker widget after a misspelled search term or not. If
				 * it is a "normal" request, update the Q parameter with the
				 * value from searchBar and do other useful stuff. Else, it is a
				 * "synthetic" request; do nothing as the spellchecker itself
				 * has already replaced the Q parameter with the corrected
				 * search term.
				 */
				if (this.manager.store.isParamDefined('original_query') !== true) {

					var search = (AjaxFranceLabs.empty(AjaxFranceLabs.trim($(
							this.elm).find('.searchBar input').val()))) ? '*:*'
							: AjaxFranceLabs.trim($(this.elm).find(
									'.searchBar input').val());
					// Make spellchecker case insensitive
					// Manager.store.addByValue("spellcheck.q", search);
					var testSelect = document.getElementById("mySelect");
					if (testSelect.options[testSelect.selectedIndex].value == 'date') {
						Manager.store.addByValue("sort", 'last_modified desc');
					} else {
						Manager.store.addByValue("sort", 'score desc');
					}

					if (this.autocomplete)
						search = search.replace(/\u200c/g, '');
					switch ($(this.elm).find('input[name=searchType]:checked')
							.val()) {
					case "allWords":
						Manager.store.addByValue("q.op", 'AND');
						Manager.store.addByValue("spellcheck.collateParam.q.op", 'AND');
						break;
					case "atLeastOneWord":
						Manager.store.addByValue("q.op", 'OR');
						Manager.store.addByValue("spellcheck.collateParam.q.op", 'OR');
						break;
					case 'exactExpression':
						search = '"' + search + '"';
						break;
					default:
						Manager.store.addByValue("q.op", 'AND');
						Manager.store.addByValue("spellcheck.collateParam.q.op", 'AND');
						break
					}

					this.manager.store.get('q').val(search);

				}

			},

			afterRequest : function() {
				/*
				 * It appeared that sometimes when making a request, the
				 * autocomplete was displayed, this part of the code has been
				 * made to counter this little glitch, after a request, we close
				 * the autocomplete
				 */
				if (this.autocomplete) {
					this.elm.find('.searchBar input[type=text]').autocomplete(
							"close");
				}
			},

			makeRequest : function() {
				if (!this.noRequest) {
					this.initBasicSearchUI();
					this.clean();
					this.updateAddressBar();
					this.manager.makeRequest();
					$("#results .doc_list").empty();
				}

			},

			initBasicSearchUI: function() {
				if(typeof destroyDatatables !== "undefined") {
					destroyDatatables();
				}
				$('#searchBar').show();
				$("#results_div").show();
				$("#search_information").show();
				$("#sortMode").show();
				$("#advancedSearch").hide();
				$("#parametersUi").hide();
				$("#favoritesUi").hide();
				$("#loginDatafariLinks").find(".active").removeClass("active");
				$("#basicSearchLink").addClass("active");
			},

			/**
			 * Resets the inputs of the widget
			 */
			reset : function() {
				var elm = $(this.elm);
				elm.find('input[type="text"]').val('');
				elm.find('input#allWords').prop('checked', true);
			}

		});
<|endoftext|>


<commit_before>/**
 * PageSpeedInsightsDashboardWidgetHomepageSpeedColumn component.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import withData from 'GoogleComponents/higherorder/withdata';
import { TYPE_MODULES } from 'GoogleComponents/data';
import { getTimeInSeconds } from 'GoogleUtil';
import {
	getDataTableFromData,
	TableOverflowContainer,
} from 'GoogleComponents/data-table';
/**
 * Internal dependencies
 */
import {
	getScoreCategoryLabel,
	PageSpeedReportScoreCategoryWrapper,
	PageSpeedReportScoreGauge,
} from './util';

const { Component } = wp.element;
const { __ } = wp.i18n;

class PageSpeedInsightsDashboardWidgetHomepageSpeedColumn extends Component {
	componentDidMount() {
		const {
			data,
			handleDataLoaded,
		} = this.props;

		if ( data && handleDataLoaded ) {
			handleDataLoaded();
		}
	}
	render() {
		const { data } = this.props;

		// Waiting for withData resolution.
		if ( ! data || data.error ) {
			return null;
		}

		const headers = [];
		const options = {
			hideHeader: true,
			disableListMode: true,
			chartsEnabled: false,
			links: [],
		};

		const title = 'mobile' === data.configSettings.emulatedFormFactor ? __( 'Mobile', 'google-site-kit' ) : __( 'Desktop', 'google-site-kit' );

		const score = data.categories.performance.score;
		const scoreCategory = getScoreCategoryLabel( score );
		const interactive = data.audits.interactive.displayValue;

		const dataTable = getDataTableFromData(
			[
				[
					__( 'Real user speed data', 'google-site-kit' ),
					<PageSpeedReportScoreCategoryWrapper key="0" score={ score }>{ scoreCategory }</PageSpeedReportScoreCategoryWrapper>,
				],
				[
					__( 'Time to become fully interactive', 'google-site-kit' ),
					<PageSpeedReportScoreCategoryWrapper key="0" score={ score }>{ interactive }</PageSpeedReportScoreCategoryWrapper>,
				],
			],
			headers,
			options
		);

		return (

						{ title }

					<PageSpeedReportScoreGauge score={ score } />

				<TableOverflowContainer>
					{ dataTable }
				</TableOverflowContainer>

		);
	}
}

export const PageSpeedInsightsDashboardWidgetHomepageSpeedMobile = withData(
	PageSpeedInsightsDashboardWidgetHomepageSpeedColumn,
	[
		{
			type: TYPE_MODULES,
			identifier: 'pagespeed-insights',
			datapoint: 'site-pagespeed-mobile',
			data: {
				permaLink: googlesitekit.permaLink,
			},
			priority: 10,
			maxAge: getTimeInSeconds( 'day' ),
			context: [ 'Single', 'Dashboard' ],
		},
	],
	null,
	{
		inGrid: true,
	},
);

export const PageSpeedInsightsDashboardWidgetHomepageSpeedDesktop = withData(
	PageSpeedInsightsDashboardWidgetHomepageSpeedColumn,
	[
		{
			type: TYPE_MODULES,
			identifier: 'pagespeed-insights',
			datapoint: 'site-pagespeed-desktop',
			permaLink: googlesitekit.permaLink,
			priority: 10,
			maxAge: getTimeInSeconds( 'day' ),
			context: [ 'Single', 'Dashboard' ],
		},
	],
	null,
	{
		inGrid: true,
	},
);
<commit_msg>Fix withData call previously missed.<commit_after>/**
 * PageSpeedInsightsDashboardWidgetHomepageSpeedColumn component.
 *
 * Site Kit by Google, Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import withData from 'GoogleComponents/higherorder/withdata';
import { TYPE_MODULES } from 'GoogleComponents/data';
import { getTimeInSeconds } from 'GoogleUtil';
import {
	getDataTableFromData,
	TableOverflowContainer,
} from 'GoogleComponents/data-table';
/**
 * Internal dependencies
 */
import {
	getScoreCategoryLabel,
	PageSpeedReportScoreCategoryWrapper,
	PageSpeedReportScoreGauge,
} from './util';

const { Component } = wp.element;
const { __ } = wp.i18n;

class PageSpeedInsightsDashboardWidgetHomepageSpeedColumn extends Component {
	componentDidMount() {
		const {
			data,
			handleDataLoaded,
		} = this.props;

		if ( data && handleDataLoaded ) {
			handleDataLoaded();
		}
	}
	render() {
		const { data } = this.props;

		// Waiting for withData resolution.
		if ( ! data || data.error ) {
			return null;
		}

		const headers = [];
		const options = {
			hideHeader: true,
			disableListMode: true,
			chartsEnabled: false,
			links: [],
		};

		const title = 'mobile' === data.configSettings.emulatedFormFactor ? __( 'Mobile', 'google-site-kit' ) : __( 'Desktop', 'google-site-kit' );

		const score = data.categories.performance.score;
		const scoreCategory = getScoreCategoryLabel( score );
		const interactive = data.audits.interactive.displayValue;

		const dataTable = getDataTableFromData(
			[
				[
					__( 'Real user speed data', 'google-site-kit' ),
					<PageSpeedReportScoreCategoryWrapper key="0" score={ score }>{ scoreCategory }</PageSpeedReportScoreCategoryWrapper>,
				],
				[
					__( 'Time to become fully interactive', 'google-site-kit' ),
					<PageSpeedReportScoreCategoryWrapper key="0" score={ score }>{ interactive }</PageSpeedReportScoreCategoryWrapper>,
				],
			],
			headers,
			options
		);

		return (

						{ title }

					<PageSpeedReportScoreGauge score={ score } />

				<TableOverflowContainer>
					{ dataTable }
				</TableOverflowContainer>

		);
	}
}

export const PageSpeedInsightsDashboardWidgetHomepageSpeedMobile = withData(
	PageSpeedInsightsDashboardWidgetHomepageSpeedColumn,
	[
		{
			type: TYPE_MODULES,
			identifier: 'pagespeed-insights',
			datapoint: 'site-pagespeed-mobile',
			data: {
				permaLink: googlesitekit.permaLink,
			},
			priority: 10,
			maxAge: getTimeInSeconds( 'day' ),
			context: [ 'Single', 'Dashboard' ],
		},
	],
	null,
	{
		inGrid: true,
	},
);

export const PageSpeedInsightsDashboardWidgetHomepageSpeedDesktop = withData(
	PageSpeedInsightsDashboardWidgetHomepageSpeedColumn,
	[
		{
			type: TYPE_MODULES,
			identifier: 'pagespeed-insights',
			datapoint: 'site-pagespeed-desktop',
			data: {
				permaLink: googlesitekit.permaLink,
			},
			priority: 10,
			maxAge: getTimeInSeconds( 'day' ),
			context: [ 'Single', 'Dashboard' ],
		},
	],
	null,
	{
		inGrid: true,
	},
);
<|endoftext|>


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

    //// JavaScript Code  ////
    function projectStatusCtrl($scope,$rootScope,$log,$filter,$location,SelectedNodesService,Constants,AlertService,$routeParams,ProjectsRepository) {
        $scope.projectName = $scope.projectConfiguration.name;
        $scope.tabName = $routeParams.tab_name;
        $scope.allNodesCount = 0;
        //$log.debug('projectStatusCtrl: projectConfiguration = ' + angular.toJson($scope.projectConfiguration));
        //$log.debug('projectStatusCtrl: projectStatus = ' + angular.toJson($scope.projectStatus));

        //$scope.projectStatus = {};
        $scope.projectStatus.nodes_for_version = [];
        $scope.maxNodeAliasLengthForSmallCol = 30;
        $scope.maxNodeAliasLength = 0;
        for (var i12=0 ; i12 < $scope.projectStatusImmutable.nodes_for_version.length; i12++) {
            var nodeForVersion = {nodes:[],immutable:$scope.projectStatusImmutable.nodes_for_version[i12]};
            $scope.projectStatus.nodes_for_version.push(nodeForVersion);
            for (var j12=0 ; j12 < $scope.projectStatusImmutable.nodes_for_version[i12].nodes.length; j12++) {
                nodeForVersion.nodes.push({immutable:$scope.projectStatusImmutable.nodes_for_version[i12].nodes[j12]});
                if ($scope.projectStatusImmutable.nodes_for_version[i12].nodes[j12].alias.length > $scope.maxNodeAliasLength) {
                    $scope.maxNodeAliasLength = $scope.projectStatusImmutable.nodes_for_version[i12].nodes[j12].alias.length;
                }
            }
        }
        $scope.maxNodesToShow = 2;
        $scope.versionIsOpen = [];
        for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
            $scope.versionIsOpen[i] = true;
        }
        $scope.collapseAll = function() {
            for (var i=0 ; i < $scope.versionIsOpen.length; i++) {
                $scope.versionIsOpen[i] = false;
            }
        };
        $scope.expandAll = function() {
            for (var i=0 ; i < $scope.versionIsOpen.length; i++) {
                $scope.versionIsOpen[i] = true;
            }
        };
        $scope.shouldShowClearFilters = function() {
            var search = $location.search();
            var noTagsOn = ((!angular.isDefined(search.tagsOn) || search.tagsOn.length === 0));
            var noTagsOff = ((!angular.isDefined(search.tagsOff) || search.tagsOff.length === 0));
            var noTags = noTagsOn && noTagsOff;
            return !(($scope.selectedMonitor === 'All Nodes') && ($scope.nodesFilter === '') && (noTags));
        };

        $scope.initValues = function() {
            $scope.selectedMonitor = 'All Nodes';
            $scope.nodesFilter = '';
        };

        $scope.clearFilters = function() {
            $location.search({});
            $scope.initValues();
            for (var j=0; j < $scope.projectStatus.tag_info.length ; j++) {
                $scope.projectStatus.tag_info[j].state = 0;
            }
            $scope.refreshFilters();
        };

        $scope.initValues();

        $scope.initFromQueryString = function() {
            var queryStringObject = $location.search();
            var shouldRefresh = false;
            if (angular.isDefined(queryStringObject.monitorFilter)) {
                shouldRefresh = true;
                $log.debug('projectStatusCtrl: Monitor filter init from query string - ' + queryStringObject.monitorFilter);
                $scope.selectedMonitor = queryStringObject.monitorFilter;
            }
            if (angular.isDefined(queryStringObject.tagsOn)) {
                shouldRefresh = true;
            }
            if (angular.isDefined(queryStringObject.tagsOff)) {
                shouldRefresh = true;
            }
            return shouldRefresh;
        };

        var tagsChangedHandler = $rootScope.$on(Constants.EVENTS.TAGS_CHANGED, function() {
            $scope.refreshFilters();
        });

        // Returns true if the node should be in the filtered array (Displayed)
        var isNodeFiltered = function(node) {
            return $filter('nodeFilter')(node.immutable,$scope.nodesFilter,$scope.selectedMonitor,$scope.projectStatus.tag_info);
        };

        var moveNodeToVisible = function(versionItem,node) {
            node.visible = true;
            if (!versionItem.visibleNodes) {
                versionItem.visibleNodes = [];
            }
            versionItem.visibleNodes.push(node);
        };

        for (var i1=0 ; i1 < $scope.projectStatus.nodes_for_version.length; i1++) {
            $scope.projectStatus.nodes_for_version[i1].filteredNodes = $scope.projectStatus.nodes_for_version[i1].nodes.slice();
            var maxNodesToShowHere = $scope.maxNodesToShow;
            if (maxNodesToShowHere > $scope.projectStatus.nodes_for_version[i1].filteredNodes.length || !$scope.projectStatusImmutable.more_nodes_enabled) {
                maxNodesToShowHere = $scope.projectStatus.nodes_for_version[i1].filteredNodes.length;
            }
            for (var j=0; j < maxNodesToShowHere; j++) {
                moveNodeToVisible($scope.projectStatus.nodes_for_version[i1],$scope.projectStatus.nodes_for_version[i1].filteredNodes[j]);
            }
            $scope.allNodesCount += $scope.projectStatus.nodes_for_version[i1].filteredNodes.length;
        }

        $scope.$watch("selectedMonitor",function( newName, oldName ) {
                if ( newName === oldName ) {
                    return;
                }
                $log.debug('projectStatusCtrl: selectedMonitor was changed');
                $location.search('monitorFilter',newName);
                $scope.refreshFilters();
            }
        );

        $scope.$watch("nodesFilter",function( newName, oldName ) {
                if ( newName === oldName ) {
                    return;
                }
                $log.debug('projectStatusCtrl: nodesFilter was changed');
                $scope.refreshFilters();
            }
        );

        $scope.showMore = function(count) {
            if ($scope.projectStatusImmutable.more_nodes_enabled) {
                return count < $scope.maxNodesToShow;
            }
            else {
                return true;
            }
        };
        $scope.refreshFilters = function() {
            $log.debug("refreshFilters");
            var count = 0;
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                $scope.projectStatus.nodes_for_version[i].filteredNodes.splice(0,$scope.projectStatus.nodes_for_version[i].filteredNodes.length);
                $scope.projectStatus.nodes_for_version[i].visibleNodes.splice(0,$scope.projectStatus.nodes_for_version[i].visibleNodes.length);
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].nodes.length; j++) {
                    $scope.projectStatus.nodes_for_version[i].nodes[j].visible = false;
                    if (isNodeFiltered($scope.projectStatus.nodes_for_version[i].nodes[j])) {
                        $scope.projectStatus.nodes_for_version[i].filteredNodes.push($scope.projectStatus.nodes_for_version[i].nodes[j]);
                        count++;
                    }
                }
                if ($scope.projectStatus.nodes_for_version[i].filteredNodes.length > 0) {
                    for (var k=0; $scope.showMore(k) && k < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; k++) {
                        moveNodeToVisible($scope.projectStatus.nodes_for_version[i],$scope.projectStatus.nodes_for_version[i].filteredNodes[k]);
                    }
                }
            }
            $scope.allNodesCount = count;
        };

        if ($scope.initFromQueryString()) {
            $scope.refreshFilters();
        }

        $scope.loadMoreNodes = function(index) {
            var j = 0;
            if ($scope.projectStatus.nodes_for_version[index].filteredNodes.length === $scope.projectStatus.nodes_for_version[index].visibleNodes.length) {
                return;
            }
            for (var i=0; (i < $scope.projectStatus.nodes_for_version[index].filteredNodes.length) && (j < 10); i++) {
                if (!$scope.projectStatus.nodes_for_version[index].filteredNodes[i].visible) {
                    moveNodeToVisible($scope.projectStatus.nodes_for_version[index],$scope.projectStatus.nodes_for_version[index].filteredNodes[i]);
                    j++;
                }
            }
        };

        $scope.selectMonitor = function(monitor) {
            $scope.selectedMonitor = monitor;
        };

        $scope.runCommand = function(command) {
            $log.debug('projectStatusCtrl: will run command ' + command);
            if (!$scope.isAnyNodeChecked()) {
                $log.debug('projectStatusCtrl: no nodes selected, will do nothing');
                AlertService.addAlert('danger','No nodes selected to run the command.<br/>Please select nodes first.',6000);
                return;
            }
            var url = '/codeine/view/' + $scope.tabName + '/project/' + $scope.projectName + '/command/' + command + '/setup';
            SelectedNodesService.setSelectedNodes($scope.getAllSelectedNodesToRun(),url);
            $location.path(url);
        };

        $scope.selectedCount = function(){
            var count = 0;
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if ($scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked){
                        count++;
                    }
                }
            }
            return count;
        };
        $scope.checkboxClick = function(versionItem, event) {
            event.stopPropagation();
            angular.forEach(versionItem.filteredNodes, function(item) {
                item.checked = event.target.checked && item.immutable.user_can_command;
            });
        };

        $scope.hasFailingCollectors = function(collectors_info) {
            for (var i=0 ; i < collectors_info.length; i++) {
                if (collectors_info[i].exit_status !== 0) {
                    return true;
                }
            }
            return false;
        };

        $scope.isAnyNodeChecked = function() {
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if ($scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked) {
                        return true;
                    }
                }
            }
            return false;
        };

        $scope.getAllSelectedNodesToRun = function() {
            var res = [];
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if ($scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked) {
                        res.push($scope.projectStatus.nodes_for_version[i].filteredNodes[j].immutable);
                    }
                }
            }
            return res;
        };

        $scope.isAllNodesChecked = function() {
            if ($scope.allNodesCount === 0) {
                return false;
            }
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if (!$scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked) {
                        return false;
                    }
                }
            }
            return true;
        };

        $scope.isVersionChecked = function(versionItem) {
            for (var i=0 ; i < versionItem.filteredNodes.length; i++) {
                if (!versionItem.filteredNodes[i].checked) {
                    return false;
                }

            }
            return true;
        };

        $scope.doSelectAllNodes = function(event) {
            event.stopPropagation();
            angular.forEach($scope.projectStatus.nodes_for_version, function(versionItem) {
                angular.forEach(versionItem.filteredNodes, function(node) {
                    node.checked = event.target.checked && node.immutable.user_can_command;
                });
            });
        };

        $scope.isNodeDisabled = function(node){
            return !node.immutable.user_can_command;
        };
        var unRegisterFunction = $rootScope.$on(Constants.EVENTS.BREADCRUMB_CLICKED, function () {
            $scope.clearFilters();
        });

        $scope.$on('$destroy',function() {
            $location.search({});
            unRegisterFunction();
            tagsChangedHandler();
        });

        $scope.refreshProjectStatus = function() {
            $scope.refreshStatusPromise = ProjectsRepository.getProject($scope.projectConfiguration.name, [ 'status' ], true);
        };
    }

    //// Angular Code ////
    angular.module('codeine').controller('projectStatusCtrl', projectStatusCtrl);

})(angular);<commit_msg>fix node url for internal project<commit_after>(function (angular) {
    'use strict';

    //// JavaScript Code  ////
    function projectStatusCtrl($scope,$rootScope,$log,$filter,$location,SelectedNodesService,Constants,AlertService,$routeParams,ProjectsRepository) {
        $scope.projectName = $scope.projectConfiguration.name;
        if ($location.path() === '/codeine/nodes/status') {
            $scope.projectName = Constants.CODEINE_NODES_PROJECT_NAME;
        }
        $scope.tabName = $routeParams.tab_name;
        if (typeof $scope.tabName === 'undefined') {
            $scope.tabName = 'main';
        }
        $scope.allNodesCount = 0;
        //$log.debug('projectStatusCtrl: projectConfiguration = ' + angular.toJson($scope.projectConfiguration));
        //$log.debug('projectStatusCtrl: projectStatus = ' + angular.toJson($scope.projectStatus));

        //$scope.projectStatus = {};
        $scope.projectStatus.nodes_for_version = [];
        $scope.maxNodeAliasLengthForSmallCol = 30;
        $scope.maxNodeAliasLength = 0;
        for (var i12=0 ; i12 < $scope.projectStatusImmutable.nodes_for_version.length; i12++) {
            var nodeForVersion = {nodes:[],immutable:$scope.projectStatusImmutable.nodes_for_version[i12]};
            $scope.projectStatus.nodes_for_version.push(nodeForVersion);
            for (var j12=0 ; j12 < $scope.projectStatusImmutable.nodes_for_version[i12].nodes.length; j12++) {
                nodeForVersion.nodes.push({immutable:$scope.projectStatusImmutable.nodes_for_version[i12].nodes[j12]});
                if ($scope.projectStatusImmutable.nodes_for_version[i12].nodes[j12].alias.length > $scope.maxNodeAliasLength) {
                    $scope.maxNodeAliasLength = $scope.projectStatusImmutable.nodes_for_version[i12].nodes[j12].alias.length;
                }
            }
        }
        $scope.maxNodesToShow = 2;
        $scope.versionIsOpen = [];
        for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
            $scope.versionIsOpen[i] = true;
        }
        $scope.collapseAll = function() {
            for (var i=0 ; i < $scope.versionIsOpen.length; i++) {
                $scope.versionIsOpen[i] = false;
            }
        };
        $scope.expandAll = function() {
            for (var i=0 ; i < $scope.versionIsOpen.length; i++) {
                $scope.versionIsOpen[i] = true;
            }
        };
        $scope.shouldShowClearFilters = function() {
            var search = $location.search();
            var noTagsOn = ((!angular.isDefined(search.tagsOn) || search.tagsOn.length === 0));
            var noTagsOff = ((!angular.isDefined(search.tagsOff) || search.tagsOff.length === 0));
            var noTags = noTagsOn && noTagsOff;
            return !(($scope.selectedMonitor === 'All Nodes') && ($scope.nodesFilter === '') && (noTags));
        };

        $scope.initValues = function() {
            $scope.selectedMonitor = 'All Nodes';
            $scope.nodesFilter = '';
        };

        $scope.clearFilters = function() {
            $location.search({});
            $scope.initValues();
            for (var j=0; j < $scope.projectStatus.tag_info.length ; j++) {
                $scope.projectStatus.tag_info[j].state = 0;
            }
            $scope.refreshFilters();
        };

        $scope.initValues();

        $scope.initFromQueryString = function() {
            var queryStringObject = $location.search();
            var shouldRefresh = false;
            if (angular.isDefined(queryStringObject.monitorFilter)) {
                shouldRefresh = true;
                $log.debug('projectStatusCtrl: Monitor filter init from query string - ' + queryStringObject.monitorFilter);
                $scope.selectedMonitor = queryStringObject.monitorFilter;
            }
            if (angular.isDefined(queryStringObject.tagsOn)) {
                shouldRefresh = true;
            }
            if (angular.isDefined(queryStringObject.tagsOff)) {
                shouldRefresh = true;
            }
            return shouldRefresh;
        };

        var tagsChangedHandler = $rootScope.$on(Constants.EVENTS.TAGS_CHANGED, function() {
            $scope.refreshFilters();
        });

        // Returns true if the node should be in the filtered array (Displayed)
        var isNodeFiltered = function(node) {
            return $filter('nodeFilter')(node.immutable,$scope.nodesFilter,$scope.selectedMonitor,$scope.projectStatus.tag_info);
        };

        var moveNodeToVisible = function(versionItem,node) {
            node.visible = true;
            if (!versionItem.visibleNodes) {
                versionItem.visibleNodes = [];
            }
            versionItem.visibleNodes.push(node);
        };

        for (var i1=0 ; i1 < $scope.projectStatus.nodes_for_version.length; i1++) {
            $scope.projectStatus.nodes_for_version[i1].filteredNodes = $scope.projectStatus.nodes_for_version[i1].nodes.slice();
            var maxNodesToShowHere = $scope.maxNodesToShow;
            if (maxNodesToShowHere > $scope.projectStatus.nodes_for_version[i1].filteredNodes.length || !$scope.projectStatusImmutable.more_nodes_enabled) {
                maxNodesToShowHere = $scope.projectStatus.nodes_for_version[i1].filteredNodes.length;
            }
            for (var j=0; j < maxNodesToShowHere; j++) {
                moveNodeToVisible($scope.projectStatus.nodes_for_version[i1],$scope.projectStatus.nodes_for_version[i1].filteredNodes[j]);
            }
            $scope.allNodesCount += $scope.projectStatus.nodes_for_version[i1].filteredNodes.length;
        }

        $scope.$watch("selectedMonitor",function( newName, oldName ) {
                if ( newName === oldName ) {
                    return;
                }
                $log.debug('projectStatusCtrl: selectedMonitor was changed');
                $location.search('monitorFilter',newName);
                $scope.refreshFilters();
            }
        );

        $scope.$watch("nodesFilter",function( newName, oldName ) {
                if ( newName === oldName ) {
                    return;
                }
                $log.debug('projectStatusCtrl: nodesFilter was changed');
                $scope.refreshFilters();
            }
        );

        $scope.showMore = function(count) {
            if ($scope.projectStatusImmutable.more_nodes_enabled) {
                return count < $scope.maxNodesToShow;
            }
            else {
                return true;
            }
        };
        $scope.refreshFilters = function() {
            $log.debug("refreshFilters");
            var count = 0;
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                $scope.projectStatus.nodes_for_version[i].filteredNodes.splice(0,$scope.projectStatus.nodes_for_version[i].filteredNodes.length);
                $scope.projectStatus.nodes_for_version[i].visibleNodes.splice(0,$scope.projectStatus.nodes_for_version[i].visibleNodes.length);
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].nodes.length; j++) {
                    $scope.projectStatus.nodes_for_version[i].nodes[j].visible = false;
                    if (isNodeFiltered($scope.projectStatus.nodes_for_version[i].nodes[j])) {
                        $scope.projectStatus.nodes_for_version[i].filteredNodes.push($scope.projectStatus.nodes_for_version[i].nodes[j]);
                        count++;
                    }
                }
                if ($scope.projectStatus.nodes_for_version[i].filteredNodes.length > 0) {
                    for (var k=0; $scope.showMore(k) && k < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; k++) {
                        moveNodeToVisible($scope.projectStatus.nodes_for_version[i],$scope.projectStatus.nodes_for_version[i].filteredNodes[k]);
                    }
                }
            }
            $scope.allNodesCount = count;
        };

        if ($scope.initFromQueryString()) {
            $scope.refreshFilters();
        }

        $scope.loadMoreNodes = function(index) {
            var j = 0;
            if ($scope.projectStatus.nodes_for_version[index].filteredNodes.length === $scope.projectStatus.nodes_for_version[index].visibleNodes.length) {
                return;
            }
            for (var i=0; (i < $scope.projectStatus.nodes_for_version[index].filteredNodes.length) && (j < 10); i++) {
                if (!$scope.projectStatus.nodes_for_version[index].filteredNodes[i].visible) {
                    moveNodeToVisible($scope.projectStatus.nodes_for_version[index],$scope.projectStatus.nodes_for_version[index].filteredNodes[i]);
                    j++;
                }
            }
        };

        $scope.selectMonitor = function(monitor) {
            $scope.selectedMonitor = monitor;
        };

        $scope.runCommand = function(command) {
            $log.debug('projectStatusCtrl: will run command ' + command);
            if (!$scope.isAnyNodeChecked()) {
                $log.debug('projectStatusCtrl: no nodes selected, will do nothing');
                AlertService.addAlert('danger','No nodes selected to run the command.<br/>Please select nodes first.',6000);
                return;
            }
            var url = '/codeine/view/' + $scope.tabName + '/project/' + $scope.projectName + '/command/' + command + '/setup';
            SelectedNodesService.setSelectedNodes($scope.getAllSelectedNodesToRun(),url);
            $location.path(url);
        };

        $scope.selectedCount = function(){
            var count = 0;
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if ($scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked){
                        count++;
                    }
                }
            }
            return count;
        };
        $scope.checkboxClick = function(versionItem, event) {
            event.stopPropagation();
            angular.forEach(versionItem.filteredNodes, function(item) {
                item.checked = event.target.checked && item.immutable.user_can_command;
            });
        };

        $scope.hasFailingCollectors = function(collectors_info) {
            for (var i=0 ; i < collectors_info.length; i++) {
                if (collectors_info[i].exit_status !== 0) {
                    return true;
                }
            }
            return false;
        };

        $scope.isAnyNodeChecked = function() {
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if ($scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked) {
                        return true;
                    }
                }
            }
            return false;
        };

        $scope.getAllSelectedNodesToRun = function() {
            var res = [];
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if ($scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked) {
                        res.push($scope.projectStatus.nodes_for_version[i].filteredNodes[j].immutable);
                    }
                }
            }
            return res;
        };

        $scope.isAllNodesChecked = function() {
            if ($scope.allNodesCount === 0) {
                return false;
            }
            for (var i=0 ; i < $scope.projectStatus.nodes_for_version.length; i++) {
                for (var j=0 ; j < $scope.projectStatus.nodes_for_version[i].filteredNodes.length; j++) {
                    if (!$scope.projectStatus.nodes_for_version[i].filteredNodes[j].checked) {
                        return false;
                    }
                }
            }
            return true;
        };

        $scope.isVersionChecked = function(versionItem) {
            for (var i=0 ; i < versionItem.filteredNodes.length; i++) {
                if (!versionItem.filteredNodes[i].checked) {
                    return false;
                }

            }
            return true;
        };

        $scope.doSelectAllNodes = function(event) {
            event.stopPropagation();
            angular.forEach($scope.projectStatus.nodes_for_version, function(versionItem) {
                angular.forEach(versionItem.filteredNodes, function(node) {
                    node.checked = event.target.checked && node.immutable.user_can_command;
                });
            });
        };

        $scope.isNodeDisabled = function(node){
            return !node.immutable.user_can_command;
        };
        var unRegisterFunction = $rootScope.$on(Constants.EVENTS.BREADCRUMB_CLICKED, function () {
            $scope.clearFilters();
        });

        $scope.$on('$destroy',function() {
            $location.search({});
            unRegisterFunction();
            tagsChangedHandler();
        });

        $scope.refreshProjectStatus = function() {
            $scope.refreshStatusPromise = ProjectsRepository.getProject($scope.projectConfiguration.name, [ 'status' ], true);
        };
    }

    //// Angular Code ////
    angular.module('codeine').controller('projectStatusCtrl', projectStatusCtrl);

})(angular);<|endoftext|>


<commit_before>'use strict';

function Visibility() {

    // States.
    this.currently_visible = true;
    // If this variable is set to to 'true' then calls to 'display_all_attachments_recursively' will not affect this Visibility object.
    this.manual_visibility = false;

    this.is_visible = function() {
        return this.currently_visible;
    };

    this.set_to_visible = function() {
        this.currently_visible = true;
        // Thanks to : https://stackoverflow.com/questions/42609602/how-to-hide-and-show-an-object-on-scene-in-three-js
        this.object3D.visible = true;
        this.object3D.traverse (function(child) {
            if (child instanceof THREE.Mesh) {
                child.visible = true;
            }
        });
    };

    this.set_to_invisible = function() {
        this.currently_visible = false;
        // Thanks to : https://stackoverflow.com/questions/42609602/how-to-hide-and-show-an-object-on-scene-in-three-js
        this.object3D.visible = false;
        this.object3D.traverse (function(child) {
            if (child instanceof THREE.Mesh) {
                child.visible = false;
            }
        });
    };

    /*__   ___  __          __   ___  __          ___ ___       __              ___      ___  __
     |__) |__  /  \ |  | | |__) |__  /__`     /\   |   |   /\  /  ` |__|  |\/| |__  |\ |  |  /__`
     |  \ |___ \__X \__/ | |  \ |___ .__/    /~~\  |   |  /~~\ \__, |  |  |  | |___ | \|  |  .__/ */

    this.display_self_and_all_child_attachments_recursively = function() {
        this.set_to_visible();
        var all_attachments = this._get_all_attachments_recursively();
        for (var a = 0; a < all_attachments.length; a++) {
            if (!all_attachments[a].manual_visibility) {
                all_attachments[a].set_to_visible();
            }
        }
    };

    this.hide_self_and_all_child_attachments_recursively = function() {
        this.set_to_invisible();
        var all_attachments = this._get_all_attachments_recursively();
        for (var a = 0; a < all_attachments.length; a++) {
            if (!all_attachments[a].manual_visibility) {
                all_attachments[a].set_to_invisible();
            }
        }
    };

    this.display_all_child_attachments_with_name = function(n) {
        for (var a = 0; a < this.attachments.length; a++) {
            if (this.attachments.relative_name === n) {
                this.attachments[a].set_to_visible();
            }
        }
    };

    this.hide_all_child_attachments_with_name = function(n) {
        for (var a = 0; a < this.attachments.length; a++) {
            if (this.attachments.relative_name === n) {
                this.attachments[a].set_to_visible();
            }
        }
    };

}
<commit_msg>broad refactoring 74<commit_after>'use strict';

function Visibility() {

    // States.
    this.currently_visible = true;
    // If this variable is set to to 'true' then calls to 'display_all_attachments_recursively' will not affect this Visibility object.
    this.manual_visibility = false;

    this.is_visible = function() {
        return this.currently_visible;
    };

    this.set_to_visible = function() {
        this.currently_visible = true;
        // Thanks to : https://stackoverflow.com/questions/42609602/how-to-hide-and-show-an-object-on-scene-in-three-js
        this.object3D.visible = true;
        this.object3D.traverse (function(child) {
            if (child instanceof THREE.Mesh) {
                child.visible = true;
            }
        });
    };

    this.set_to_invisible = function() {
        this.currently_visible = false;
        // Thanks to : https://stackoverflow.com/questions/42609602/how-to-hide-and-show-an-object-on-scene-in-three-js
        this.object3D.visible = false;
        this.object3D.traverse (function(child) {
            if (child instanceof THREE.Mesh) {
                child.visible = false;
            }
        });
    };

    /*__   ___  __          __   ___  __          ___ ___       __              ___      ___  __
     |__) |__  /  \ |  | | |__) |__  /__`     /\   |   |   /\  /  ` |__|  |\/| |__  |\ |  |  /__`
     |  \ |___ \__X \__/ | |  \ |___ .__/    /~~\  |   |  /~~\ \__, |  |  |  | |___ | \|  |  .__/ */

    this.display_self_and_all_child_attachments_recursively = function() {
        this.set_to_visible();
        var all_attachments = this._get_all_attachments_recursively();
        for (var a = 0; a < all_attachments.length; a++) {
            if (!all_attachments[a].manual_visibility) {
                all_attachments[a].set_to_visible();
            }
        }
    };

    this.hide_self_and_all_child_attachments_recursively = function() {
        this.set_to_invisible();
        var all_attachments = this._get_all_attachments_recursively();
        for (var a = 0; a < all_attachments.length; a++) {
            if (!all_attachments[a].manual_visibility) {
                all_attachments[a].set_to_invisible();
            }
        }
    };

    this.display_all_child_attachments_with_name = function(n) {
        for (var a = 0; a < this.attachments.length; a++) {
            if (this.attachments[a].relative_name === n) {
                this.attachments[a].set_to_visible();
            }
        }
    };

    this.hide_all_child_attachments_with_name = function(n) {
        for (var a = 0; a < this.attachments.length; a++) {
            if (this.attachments[a].relative_name === n) {
                this.attachments[a].set_to_visible();
            }
        }
    };

}
<|endoftext|>