<commit_before>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Laura Schlimmer
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
var DropDownComponent = function() {

  this.createdCallback = function() {
    var base = this;

    // dropdown items
    var items = this.querySelector("z-dropdown-items");
    if (items) {
      var item_nodes = items.querySelectorAll("z-dropdown-item");
      for (var i = 0; i < item_nodes.length; i++) {
        item_nodes[i].addEventListener('click', function(e) {
          e.stopPropagation;
          base.__onItemClick(this);
        }, false);
      }
    }

    // header
    var header_elem = this.querySelector("z-dropdown-header");
    if (!header_elem) {
      header_elem = document.createElement("z-dropdown-header");
      this.insertBefore(header_elem, this.firstChild);
    }

    //render header value
    if (!header_elem.querySelector("z-dropdown-header-value")) {
      header_elem.appendChild(document.createElement(
        "z-dropdown-header-value"));
    }

    //render header icon
    if (!header_elem.querySelector("z-dropdown-header-icon")) {
      var icon = document.createElement("z-dropdown-header-icon");
      icon.innerHTML = "";
      header_elem.appendChild(icon);
    }

    //render apply button
    if (this.hasAttribute("data-multiselect")) {
      var button_container = document.createElement("z-dropdown-button");
      var button = document.createElement("button");
      button.className = "z-button primary"
      button.innerHTML = "Apply";
      button_container.appendChild(button);
      this.querySelector("z-dropdown-flyout").insertBefore(
        button_container,
        items);

      button.addEventListener("click", base.hideDropdown.bind(base), false);
    }

    header_elem.addEventListener('click', function(e) {
      e.stopPropagation();
      base.toggleDropdown();
    }, false);

    if (this.hasAttribute('data-hover')) {
      this.addEventListener(
        'mouseover',
        base.showDropdown.bind(base),
        false);

      this.addEventListener(
        'mouseout',
        base.hideDropdown.bind(base),
        false);
    }

    //close dropdown only if click event is outside
    this.addEventListener('click', function(e) {
      e.stopPropagation();
    }, false);

    this.__applyAttributes();
  };

  this.detachedCallback = function() {
    this.hideDropdown();
  }

  this.attributeChangedCallback = function(attr, old_val, new_val) {
    this.__applyAttributes();
  };

  /**
    * Returns either the selected items data-value attr or text content
    *
    * @return {String} csv
    */
  this.getValue = function() {
    var items = this.querySelectorAll("z-dropdown-item[data-selected]");
    var value = [];

    for (var i = 0; i < items.length; i++) {
      if (items[i].hasAttribute('data-value')) {
        value.push(items[i].getAttribute('data-value'));
      } else {
        value.push(items[i].textContent);
      }
    }

    return value.join(",");
  };

  /**
    * Marks for each value the matching dropdown-item as selected
    *
    * @param {Array} values
    */
  this.setValue = function(values) {
    var _this = this;

    values.forEach(function(v) {
      var item = _this.querySelector("z-dropdown-item[data-value='" + v + "']");

      if (item) {
        item.setAttribute('data-selected', 'selected');

        var checkbox = item.querySelector("z-checkbox");

        if (checkbox) {
          checkbox.setAttribute('data-active', 'active');
        }
      }
    });

    this.__setHeaderValue();
  }

  this.setDropdownItems = function(items) {
    var base = this;
    var elem = this.querySelector("z-dropdown-items");
    elem.innerHTML = "";

    for (var i = 0; i < items.length; i++) {
      items[i].addEventListener('click', function(e) {
        e.stopPropagation;
        base.__onItemClick(this);
      }, false);

      elem.appendChild(items[i]);
    }
  };

  this.unselectItem = function(item) {
    if (!item) {return;}
    item.removeAttribute('data-selected');
    var checkbox = item.querySelector("z-checkbox");
    if (checkbox) {
      checkbox.removeAttribute('data-active');
    }
  };

  this.selectItem = function(item) {
    if (!item) {return;}
    item.setAttribute('data-selected', 'selected');
    var checkbox = item.querySelector("z-checkbox");
    if (checkbox) {
      checkbox.setAttribute('data-active', 'active');
    }
  };

  this.toggleDropdown = function() {
    if (this.hasAttribute('data-active')) {
     this.hideDropdown();
    } else {
      this.showDropdown();
    }
  };

  this.showDropdown = function() {
    if (this.classList.contains("disabled")) {
      return;
    }

    if (this.getAttribute('data-active') == 'active') {
      return;
    }

    this.closeAllDropdowns();
    this.setAttribute('data-active', 'active');
    //this.setXValue();

    this.__setKeyNavigation();
  };

  this.hideDropdown = function() {
    if (this.getAttribute('data-active') != 'active') {
      return;
    }

    this.__unsetKeyNavigation();
    this.removeAttribute('data-active');

    var ev = new CustomEvent('z-dropdown-close', {
      bubbles: true,
      cancelable: true
    });

    this.dispatchEvent(ev);
    if (this.hasAttribute("data-multiselect")) {
      this.__fireChangeEvent();
    }
  };

  /**
    * Close all open dropdowns
    */
  this.closeAllDropdowns = function(callback) {
    var active_items = document.querySelectorAll("z-dropdown[data-active]");

    for (var i = 0; i < active_items.length; i++) {
      if (typeof active_items[i].hideDropdown == 'function') {
        active_items[i].hideDropdown();
      }
    }

    if (callback) callback();
  };

  this.findItemByValue = function(value) {
    return (this.querySelector("z-dropdown-item[data-value='" + value + "']"));
  };

  /*************************** PRIVATE **********************************/

  this.__applyAttributes = function() {
    this.__setHeaderValue();
  }

  // Copies the selected items html to the header_elem
  this.__setHeaderValue = function() {
    var header = this.querySelector("z-dropdown-header-value");

    if (header.hasAttribute('data-static')) {
      return;
    }

    var innerHTML = "";

    var selected_items = this.querySelectorAll("z-dropdown-item[data-selected]");
    if (selected_items.length == 0) {
      var preselection = this.getAttribute('data-preselected');
      //set preselected item
      if (preselection) {
        var preselected_item = this.findItemByValue(preselection);

        preselected_item.setAttribute('data-selected', 'selected');
        innerHTML = preselected_item.innerHTML;

      } else {
        //z-dropdown has initial not selectable header
        if (header.innerHTML.length > 0) {
          return;
        }

        //set first z-dropdown-item as header value
        var first_item = this.querySelector("z-dropdown-item");
        if (first_item) {
          innerHTML = first_item.innerHTML;
        }
      }
    }

    if (selected_items.length == 1) {
      var selected_item = selected_items[0];
      if (!selected_item) {
      } else {
        //set items input value as html header
        if (selected_item.hasAttribute('data-input-select')) {
          var input = selected_item.querySelector("input");
          innerHTML = input.value;

        } else {
          //set selected_item's html as header (standard case)
          innerHTML = selected_item.innerHTML;
        }
      }
    }

    if (selected_items.length > 1) {
      for (var i = 0; i < selected_items.length; i++) {
        if (i > 0) {
          innerHTML += ", ";
        }

        innerHTML += selected_items[i].innerText || selected_items[i].textContent;
      }
    }

    header.innerHTML = innerHTML;
    var checkbox = header.querySelector("z-checkbox");
    if (checkbox) checkbox.remove();
  };

  this.__forceSelect = function() {
    var default_selection =
      this.querySelector('z-dropdown-item[data-default]') ||
      this.querySelector('z-dropdown-item');

    this.selectItem(default_selection);
    this.__fireItemChangedEvent({selected: false}, default_selection);
  }

  this.__onItemClick = function(item) {
    if (!item) {
      return;
    }

    var selected = true;
    var checkbox =
      item.querySelector("z-checkbox") || item.querySelector("[data-check]");

    //multi-selectable dropdown with checkboxes
    if (checkbox != null) {
      //unselect item
      if (item.hasAttribute('data-selected')) {
        selected = false;
        this.unselectItem(item);
      }
    } else {
      //unselect previously selected item
      this.unselectItem(this.querySelector("z-dropdown-item[data-selected]"));
    }

    if (selected) {
      this.selectItem(item);
    }

    this.__fireItemChangedEvent({selected: selected}, item);

    // don't check it previously to maintain correct item-change event order
    if (!selected &&
        !this.hasAttribute("data-allow-empty") &&
        !this.querySelector('z-dropdown-item[data-selected]')) {
          this.__forceSelect();
    }

    if (this.hasAttribute("data-multiselect")) {
      return;
    }

    this.hideDropdown();
    this.__fireChangeEvent();
  };

  this.__fireItemChangedEvent = function(detail, item) {
    var click_ev = new CustomEvent("item-change", {
      detail: detail,
      bubbles: true,
      cancelable: true
    });

    item.dispatchEvent(click_ev);
  };

  this.__fireChangeEvent = function() {
    var change_ev = new CustomEvent("change", {
      detail : {value: this.getValue()},
      bubbles: true,
      cancelable: true
    });

    this.dispatchEvent(change_ev);
  };

  this.__setKeyNavigation = function() {
    var base = this;
    this.__unsetKeyNavigation();

    this.keydown_handler = function(e) {
      switch (e.keyCode) {
        case 38:
          base.__keyNavigation('up');
          e.preventDefault();
          return false;

        case 40:
          base.__keyNavigation('down');
          e.preventDefault();
          return false;

        case 13:
          base.__onItemClick(base.querySelector("z-dropdown-item.hover"), true);
          e.preventDefault();
          return false;

        case 27:
          base.hideDropdown();
          e.preventDefault();
          return false;

        default:
          return true;
      }
    };

    window.addEventListener('keydown', this.keydown_handler, false);

    this.click_handler = function(e) {
      base.hideDropdown();
    };

    window.addEventListener('click', this.click_handler, false);
  };

  this.__unsetKeyNavigation = function() {
    window.removeEventListener('keydown', this.keydown_handler, false);
    window.removeEventListener('click', this.click_handler, false);
  };

  this.__keyNavigation = function(direction) {
    var items = this.querySelector("z-dropdown-items");
    var visibleScrollbar = items.scrollHeight > items.offsetHeight;

    var hover_elem = this.querySelector("z-dropdown-item.hover");
    var ref_elem;
    var elem = null;
    var items = this.querySelectorAll("z-dropdown-item");

    if (!hover_elem) {
      if (direction == 'down') {
        //filtered Dropdown can contain hidden items
        if (items[0].classList.contains('hidden')) {
          hover_elem = items[0];
        } else {
          items[0].classList.add('hover');
          return;
        }
      }
    }

    ref_elem = hover_elem;
    for (var i = 0; i < items.length; i++) {

      //down
      if (direction == 'down') {
        elem = ref_elem.nextElementSibling;

        //wrap around and mark first item
        if (!elem) {
          elem = items[0];

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = 0;
          }

        } else {

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = d_items.scrollTop + (d_items.offsetHeight / items.length);
          }
        }

      //up
      } else {
        elem = ref_elem.previousElementSibling;

        //wrap around and mark last item
        if (!elem) {
          elem = items[items.length - 1];

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = d_items.scrollHeight;
          }

        } else {

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = d_items.scrollTop - (d_items.offsetHeight / items.length);
          }

        }
      }

      if (elem.classList.contains('hidden')) {
        ref_elem = elem;
      } else {
        elem.classList.add('hover');
        hover_elem.classList.remove('hover');
        return;
      }
    }
  };

 };

var proto = Object.create(HTMLElement.prototype);
DropDownComponent.apply(proto);
document.registerElement("z-dropdown", { prototype: proto });
<commit_msg>z-dropdown fixed setValue<commit_after>/**
 * This file is part of the "FnordMetric" project
 *   Copyright (c) 2014 Laura Schlimmer
 *   Copyright (c) 2014 Paul Asmuth, Google Inc.
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
var DropDownComponent = function() {

  this.createdCallback = function() {
    var base = this;

    // dropdown items
    var items = this.querySelector("z-dropdown-items");
    if (items) {
      var item_nodes = items.querySelectorAll("z-dropdown-item");
      for (var i = 0; i < item_nodes.length; i++) {
        item_nodes[i].addEventListener('click', function(e) {
          e.stopPropagation;
          base.__onItemClick(this);
        }, false);
      }
    }

    // header
    var header_elem = this.querySelector("z-dropdown-header");
    if (!header_elem) {
      header_elem = document.createElement("z-dropdown-header");
      this.insertBefore(header_elem, this.firstChild);
    }

    //render header value
    if (!header_elem.querySelector("z-dropdown-header-value")) {
      header_elem.appendChild(document.createElement(
        "z-dropdown-header-value"));
    }

    //render header icon
    if (!header_elem.querySelector("z-dropdown-header-icon")) {
      var icon = document.createElement("z-dropdown-header-icon");
      icon.innerHTML = "";
      header_elem.appendChild(icon);
    }

    //render apply button
    if (this.hasAttribute("data-multiselect")) {
      var button_container = document.createElement("z-dropdown-button");
      var button = document.createElement("button");
      button.className = "z-button primary"
      button.innerHTML = "Apply";
      button_container.appendChild(button);
      this.querySelector("z-dropdown-flyout").insertBefore(
        button_container,
        items);

      button.addEventListener("click", base.hideDropdown.bind(base), false);
    }

    header_elem.addEventListener('click', function(e) {
      e.stopPropagation();
      base.toggleDropdown();
    }, false);

    if (this.hasAttribute('data-hover')) {
      this.addEventListener(
        'mouseover',
        base.showDropdown.bind(base),
        false);

      this.addEventListener(
        'mouseout',
        base.hideDropdown.bind(base),
        false);
    }

    //close dropdown only if click event is outside
    this.addEventListener('click', function(e) {
      e.stopPropagation();
    }, false);

    this.__applyAttributes();
  };

  this.detachedCallback = function() {
    this.hideDropdown();
  }

  this.attributeChangedCallback = function(attr, old_val, new_val) {
    this.__applyAttributes();
  };

  /**
    * Returns either the selected items data-value attr or text content
    *
    * @return {String} csv
    */
  this.getValue = function() {
    var items = this.querySelectorAll("z-dropdown-item[data-selected]");
    var value = [];

    for (var i = 0; i < items.length; i++) {
      if (items[i].hasAttribute('data-value')) {
        value.push(items[i].getAttribute('data-value'));
      } else {
        value.push(items[i].textContent);
      }
    }

    return value.join(",");
  };

  /**
    * Marks for each value the matching dropdown-item as selected
    *
    * @param {Array} values
    */
  this.setValue = function(values) {
    var _this = this;

    var selected_items = this.querySelectorAll("z-dropdown-item[data-selected");
    for (var i = 0; i < selected_items.length; i++) {
      this.unselectItem(selected_items[i]);
    }

    values.forEach(function(v) {
      _this.selectItem(
          _this.querySelector("z-dropdown-item[data-value='" + v + "']"));
    });

    this.__setHeaderValue();
  }

  this.setDropdownItems = function(items) {
    var base = this;
    var elem = this.querySelector("z-dropdown-items");
    elem.innerHTML = "";

    for (var i = 0; i < items.length; i++) {
      items[i].addEventListener('click', function(e) {
        e.stopPropagation;
        base.__onItemClick(this);
      }, false);

      elem.appendChild(items[i]);
    }
  };

  this.unselectItem = function(item) {
    if (!item) {return;}
    item.removeAttribute('data-selected');
    var checkbox = item.querySelector("z-checkbox");
    if (checkbox) {
      checkbox.removeAttribute('data-active');
    }
  };

  this.selectItem = function(item) {
    if (!item) {return;}
    item.setAttribute('data-selected', 'selected');
    var checkbox = item.querySelector("z-checkbox");
    if (checkbox) {
      checkbox.setAttribute('data-active', 'active');
    }
  };

  this.toggleDropdown = function() {
    if (this.hasAttribute('data-active')) {
     this.hideDropdown();
    } else {
      this.showDropdown();
    }
  };

  this.showDropdown = function() {
    if (this.classList.contains("disabled")) {
      return;
    }

    if (this.getAttribute('data-active') == 'active') {
      return;
    }

    this.closeAllDropdowns();
    this.setAttribute('data-active', 'active');
    //this.setXValue();

    this.__setKeyNavigation();
  };

  this.hideDropdown = function() {
    if (this.getAttribute('data-active') != 'active') {
      return;
    }

    this.__unsetKeyNavigation();
    this.removeAttribute('data-active');

    var ev = new CustomEvent('z-dropdown-close', {
      bubbles: true,
      cancelable: true
    });

    this.dispatchEvent(ev);
    if (this.hasAttribute("data-multiselect")) {
      this.__fireChangeEvent();
    }
  };

  /**
    * Close all open dropdowns
    */
  this.closeAllDropdowns = function(callback) {
    var active_items = document.querySelectorAll("z-dropdown[data-active]");

    for (var i = 0; i < active_items.length; i++) {
      if (typeof active_items[i].hideDropdown == 'function') {
        active_items[i].hideDropdown();
      }
    }

    if (callback) callback();
  };

  this.findItemByValue = function(value) {
    return (this.querySelector("z-dropdown-item[data-value='" + value + "']"));
  };

  /*************************** PRIVATE **********************************/

  this.__applyAttributes = function() {
    this.__setHeaderValue();
  }

  // Copies the selected items html to the header_elem
  this.__setHeaderValue = function() {
    var header = this.querySelector("z-dropdown-header-value");

    if (header.hasAttribute('data-static')) {
      return;
    }

    var innerHTML = "";

    var selected_items = this.querySelectorAll("z-dropdown-item[data-selected]");
    if (selected_items.length == 0) {
      var preselection = this.getAttribute('data-preselected');
      //set preselected item
      if (preselection) {
        var preselected_item = this.findItemByValue(preselection);

        preselected_item.setAttribute('data-selected', 'selected');
        innerHTML = preselected_item.innerHTML;

      } else {
        //z-dropdown has initial not selectable header
        if (header.innerHTML.length > 0) {
          return;
        }

        //set first z-dropdown-item as header value
        var first_item = this.querySelector("z-dropdown-item");
        if (first_item) {
          innerHTML = first_item.innerHTML;
        }
      }
    }

    if (selected_items.length == 1) {
      var selected_item = selected_items[0];
      if (!selected_item) {
      } else {
        //set items input value as html header
        if (selected_item.hasAttribute('data-input-select')) {
          var input = selected_item.querySelector("input");
          innerHTML = input.value;

        } else {
          //set selected_item's html as header (standard case)
          innerHTML = selected_item.innerHTML;
        }
      }
    }

    if (selected_items.length > 1) {
      for (var i = 0; i < selected_items.length; i++) {
        if (i > 0) {
          innerHTML += ", ";
        }

        innerHTML += selected_items[i].innerText || selected_items[i].textContent;
      }
    }

    header.innerHTML = innerHTML;
    var checkbox = header.querySelector("z-checkbox");
    if (checkbox) checkbox.remove();
  };

  this.__forceSelect = function() {
    var default_selection =
      this.querySelector('z-dropdown-item[data-default]') ||
      this.querySelector('z-dropdown-item');

    this.selectItem(default_selection);
    this.__fireItemChangedEvent({selected: false}, default_selection);
  }

  this.__onItemClick = function(item) {
    if (!item) {
      return;
    }

    var selected = true;
    var checkbox =
      item.querySelector("z-checkbox") || item.querySelector("[data-check]");

    //multi-selectable dropdown with checkboxes
    if (checkbox != null) {
      //unselect item
      if (item.hasAttribute('data-selected')) {
        selected = false;
        this.unselectItem(item);
      }
    } else {
      //unselect previously selected item
      this.unselectItem(this.querySelector("z-dropdown-item[data-selected]"));
    }

    if (selected) {
      this.selectItem(item);
    }

    this.__fireItemChangedEvent({selected: selected}, item);

    // don't check it previously to maintain correct item-change event order
    if (!selected &&
        !this.hasAttribute("data-allow-empty") &&
        !this.querySelector('z-dropdown-item[data-selected]')) {
          this.__forceSelect();
    }

    if (this.hasAttribute("data-multiselect")) {
      return;
    }

    this.hideDropdown();
    this.__fireChangeEvent();
  };

  this.__fireItemChangedEvent = function(detail, item) {
    var click_ev = new CustomEvent("item-change", {
      detail: detail,
      bubbles: true,
      cancelable: true
    });

    item.dispatchEvent(click_ev);
  };

  this.__fireChangeEvent = function() {
    var change_ev = new CustomEvent("change", {
      detail : {value: this.getValue()},
      bubbles: true,
      cancelable: true
    });

    this.dispatchEvent(change_ev);
  };

  this.__setKeyNavigation = function() {
    var base = this;
    this.__unsetKeyNavigation();

    this.keydown_handler = function(e) {
      switch (e.keyCode) {
        case 38:
          base.__keyNavigation('up');
          e.preventDefault();
          return false;

        case 40:
          base.__keyNavigation('down');
          e.preventDefault();
          return false;

        case 13:
          base.__onItemClick(base.querySelector("z-dropdown-item.hover"), true);
          e.preventDefault();
          return false;

        case 27:
          base.hideDropdown();
          e.preventDefault();
          return false;

        default:
          return true;
      }
    };

    window.addEventListener('keydown', this.keydown_handler, false);

    this.click_handler = function(e) {
      base.hideDropdown();
    };

    window.addEventListener('click', this.click_handler, false);
  };

  this.__unsetKeyNavigation = function() {
    window.removeEventListener('keydown', this.keydown_handler, false);
    window.removeEventListener('click', this.click_handler, false);
  };

  this.__keyNavigation = function(direction) {
    var items = this.querySelector("z-dropdown-items");
    var visibleScrollbar = items.scrollHeight > items.offsetHeight;

    var hover_elem = this.querySelector("z-dropdown-item.hover");
    var ref_elem;
    var elem = null;
    var items = this.querySelectorAll("z-dropdown-item");

    if (!hover_elem) {
      if (direction == 'down') {
        //filtered Dropdown can contain hidden items
        if (items[0].classList.contains('hidden')) {
          hover_elem = items[0];
        } else {
          items[0].classList.add('hover');
          return;
        }
      }
    }

    ref_elem = hover_elem;
    for (var i = 0; i < items.length; i++) {

      //down
      if (direction == 'down') {
        elem = ref_elem.nextElementSibling;

        //wrap around and mark first item
        if (!elem) {
          elem = items[0];

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = 0;
          }

        } else {

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = d_items.scrollTop + (d_items.offsetHeight / items.length);
          }
        }

      //up
      } else {
        elem = ref_elem.previousElementSibling;

        //wrap around and mark last item
        if (!elem) {
          elem = items[items.length - 1];

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = d_items.scrollHeight;
          }

        } else {

          if (visibleScrollbar) {
            var d_items = this.querySelector("z-dropdown-items");
            d_items.scrollTop = d_items.scrollTop - (d_items.offsetHeight / items.length);
          }

        }
      }

      if (elem.classList.contains('hidden')) {
        ref_elem = elem;
      } else {
        elem.classList.add('hover');
        hover_elem.classList.remove('hover');
        return;
      }
    }
  };

 };

var proto = Object.create(HTMLElement.prototype);
DropDownComponent.apply(proto);
document.registerElement("z-dropdown", { prototype: proto });
<|endoftext|>


<commit_before>/**
* HomeController
* @namespace afya360.layout.controllers
*/
(function () {
  'use strict';

  angular
  .module('afya360.layout.controllers')
  .controller('HomeController', HomeController)

  HomeController.$inject = ['$scope', '$location', 'Restangular', 'Meta'];

  /**
  * @namespace HomeController
  */
  function HomeController($scope, $location, Restangular, Meta) {
    var vm = this;
    vm.next = next;
    vm.back = back;

    Restangular.setDefaultRequestParams('get', {limit: 20, format: 'json'});

    activate();

    function activate() {
      Restangular.all('health-facilities/').getList({offset:0}).then(homeSuccessFn, homeErrorFn);
    }

    function next() {
      vm.offset += 20;
      vm.facilities = Restangular.all('health-facilities/').getList({offset:vm.offset}).$object;
    }

    function back() {
      vm.offset = vm.offset - 20;
      vm.facilities = Restangular.all('health-facilities/').getList({offset:vm.offset}).$object;
    }

    function homeSuccessFn(data, status, headers, config) {
      vm.facilities = data;
      vm.offset = 0;
      Meta.setTitle("Afy360 | Buzz");
    }

    function homeErrorFn(data, status, headers, config) {
      $location.url('/');
      console.log('Errrrrror.');
    }
  }
})();<commit_msg>change home default title<commit_after>/**
* HomeController
* @namespace afya360.layout.controllers
*/
(function () {
  'use strict';

  angular
  .module('afya360.layout.controllers')
  .controller('HomeController', HomeController)

  HomeController.$inject = ['$scope', '$location', 'Restangular', 'Meta'];

  /**
  * @namespace HomeController
  */
  function HomeController($scope, $location, Restangular, Meta) {
    var vm = this;
    vm.next = next;
    vm.back = back;

    Restangular.setDefaultRequestParams('get', {limit: 20, format: 'json'});

    activate();

    function activate() {
      Restangular.all('health-facilities/').getList({offset:0}).then(homeSuccessFn, homeErrorFn);
    }

    function next() {
      vm.offset += 20;
      vm.facilities = Restangular.all('health-facilities/').getList({offset:vm.offset}).$object;
    }

    function back() {
      vm.offset = vm.offset - 20;
      vm.facilities = Restangular.all('health-facilities/').getList({offset:vm.offset}).$object;
    }

    function homeSuccessFn(data, status, headers, config) {
      vm.facilities = data;
      vm.offset = 0;
      Meta.setTitle("Afy360 | Kenya Directory of Health Centers");
    }

    function homeErrorFn(data, status, headers, config) {
      $location.url('/');
      console.log('Error.');
    }
  }
})();<|endoftext|>


<commit_before>/*
Copyright (C) 2008  Alina Friedrichsen <x-alina@gmx.net>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/

function initDropdowns() {
	var aSelects = XHTML1.getElementsByTagName("select");
	var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

	function showPlaceholder(sel) {
		if( ! sel._ph ) {
			var box = sel.getBoundingClientRect();
			sel._dm = sel.currentStyle.display;
			sel._ph = document.createElement('input');
			sel.parentNode.insertBefore(sel._ph, sel);
			sel._ph.style.width  = ( box.right - box.left ) + 'px';
			sel._ph.style.height = ( box.bottom - box.top ) + 'px';
			sel._ph.style.margin = sel.currentStyle.margin;
		}

		sel._ph.value = sel.options[sel.selectedIndex].text;
		sel._ph.style.display = sel._dm;
		sel.style.display = 'none';
	}

	function hidePlaceholder(sel) {
		if( sel._ph ) sel._ph.style.display = 'none';
		sel.style.display = sel._dm;
	}

	function hideSelects() {
		for(var i = 0; i < aSelects.length; i++) {
			showPlaceholder(aSelects[i]);
		}
	}

	function showSelects() {
		for(var i = 0; i < aSelects.length; i++) {
			hidePlaceholder(aSelects[i]);
		}
	}

	function isEmptyObject(obj) {
		for(var i in obj) {
			return false;
		}
		return true;
	}

	var nextUniqueID = 1;
	var elementsNeeded = {};
	var menusShown = {};
	var menusToHide = {};
	var delayHideTimerId;
	var delayHideAllTime = 1000;
	var delayHideTime = 400;
	function delayHide() {
		for(var i in menusToHide) {
			XHTML1.removeClass(menusToHide[i], "focus");
		}
		delayHideTimerId = null;
	}

	function updatePopup() {
		if(isIE6) {
			if(isEmptyObject(elementsNeeded)) {
				showSelects();
			}
			else{
				hideSelects();
			}
		}

		var menusShownOld = menusShown;
		menusShown = {};
		for(var id in elementsNeeded) {
			var element = elementsNeeded[id];
			for(element = findLi(element); element; element = findLi(element.parentNode)) {
				XHTML1.addClass(element, "focus");
				if(!element.uniqueID) {
					element.uniqueID = nextUniqueID++;
				}
				element.style.zIndex = 1000;
				menusShown[element.uniqueID] = element;
				delete menusToHide[element.uniqueID];
			}
		}
		for(var id in menusShownOld) {
			if(!menusShown[id]) {
				if(delayHideTimerId) {
					clearTimeout(delayHideTimerId);
					delayHideTimerId = 0;
					delayHide();
				}
				menusToHide[id] = menusShownOld[id];
				menusToHide[id].style.zIndex = 999;
			}
		}
		if(menusToHide || isEmptyObject(elementsNeeded)) {
			if(delayHideTimerId) {
				clearTimeout(delayHideTimerId);
			}
			delayHideTimerId = setTimeout(delayHide, isEmptyObject(elementsNeeded) ? delayHideAllTime : delayHideTime);
		}
	}

	function findLi(element) {
		for(; element; element = element.parentNode) {
			if(XHTML1.isElement(element, "li")) {
				return element;
			}
		}
	}

	function onmouseover(evt) {
		var li = findLi(evt.currentTarget);
		if(li && !li.focused) {
			if(!li.uniqueID) {
				li.uniqueID = nextUniqueID++;
			}
			elementsNeeded[li.uniqueID] = li;
		}
		XHTML1.addClass(evt.currentTarget, "over");
		updatePopup();
	}

	function onmouseout(evt) {
		var li = findLi(evt.currentTarget);
		if(li && !li.focused && li.uniqueID) {
			delete elementsNeeded[li.uniqueID];
		}
		XHTML1.removeClass(evt.currentTarget, "over");
		updatePopup();
	}

	function onfocus(evt) {
		var li = findLi(evt.currentTarget);
		if(li) {
			li.focused = true;
			if(!li.uniqueID) {
				li.uniqueID = nextUniqueID++;
			}
			elementsNeeded[li.uniqueID] = li;
		}
		updatePopup();
	}

	function onblur(evt) {
		var li = findLi(evt.currentTarget);
		if(li) {
			li.focused = false;
			delete elementsNeeded[li.uniqueID];
		}
		updatePopup();
	}

	var aElements = XHTML1.getElementsByTagName("a");
	for(var i = 0; i < aElements.length; i++) {
		var a = aElements[i];
		for(var element = a.parentNode; element; element = element.parentNode) {
			if(XHTML1.isElement(element, "ul") && XHTML1.containsClass(element, "dropdowns")) {
				XHTML1.addEventListener(a, "focus", onfocus);
				XHTML1.addEventListener(a, "blur", onblur);
				XHTML1.addEventListener(a, "mouseover", onmouseover);
				XHTML1.addEventListener(a, "mouseout", onmouseout);
				break;
			}
		}
	}
}

if(XHTML1.isDOMSupported()) {
	XHTML1.addEventListener(window, "load", initDropdowns);
}
<commit_msg>themes/base: allow closing menus by clicking into the body (#97)<commit_after>/*
Copyright (C) 2008  Alina Friedrichsen <x-alina@gmx.net>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/

function initDropdowns() {
	var aSelects = XHTML1.getElementsByTagName("select");
	var isIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

	function showPlaceholder(sel) {
		if( ! sel._ph ) {
			var box = sel.getBoundingClientRect();
			sel._dm = sel.currentStyle.display;
			sel._ph = document.createElement('input');
			sel.parentNode.insertBefore(sel._ph, sel);
			sel._ph.style.width  = ( box.right - box.left ) + 'px';
			sel._ph.style.height = ( box.bottom - box.top ) + 'px';
			sel._ph.style.margin = sel.currentStyle.margin;
		}

		sel._ph.value = sel.options[sel.selectedIndex].text;
		sel._ph.style.display = sel._dm;
		sel.style.display = 'none';
	}

	function hidePlaceholder(sel) {
		if( sel._ph ) sel._ph.style.display = 'none';
		sel.style.display = sel._dm;
	}

	function hideSelects() {
		for(var i = 0; i < aSelects.length; i++) {
			showPlaceholder(aSelects[i]);
		}
	}

	function showSelects() {
		for(var i = 0; i < aSelects.length; i++) {
			hidePlaceholder(aSelects[i]);
		}
	}

	function isEmptyObject(obj) {
		for(var i in obj) {
			return false;
		}
		return true;
	}

	var nextUniqueID = 1;
	var elementsNeeded = {};
	var menusShown = {};
	var menusToHide = {};
	var delayHideTimerId;
	var delayHideAllTime = 1000;
	var delayHideTime = 400;
	function delayHide() {
		for(var i in menusToHide) {
			XHTML1.removeClass(menusToHide[i], "focus");
		}
		delayHideTimerId = null;
	}

	function updatePopup() {
		if(isIE6) {
			if(isEmptyObject(elementsNeeded)) {
				showSelects();
			}
			else{
				hideSelects();
			}
		}

		var menusShownOld = menusShown;
		menusShown = {};
		for(var id in elementsNeeded) {
			var element = elementsNeeded[id];
			for(element = findLi(element); element; element = findLi(element.parentNode)) {
				XHTML1.addClass(element, "focus");
				if(!element.uniqueID) {
					element.uniqueID = nextUniqueID++;
				}
				element.style.zIndex = 1000;
				menusShown[element.uniqueID] = element;
				delete menusToHide[element.uniqueID];
			}
		}
		for(var id in menusShownOld) {
			if(!menusShown[id]) {
				if(delayHideTimerId) {
					clearTimeout(delayHideTimerId);
					delayHideTimerId = 0;
					delayHide();
				}
				menusToHide[id] = menusShownOld[id];
				menusToHide[id].style.zIndex = 999;
			}
		}
		if(menusToHide || isEmptyObject(elementsNeeded)) {
			if(delayHideTimerId) {
				clearTimeout(delayHideTimerId);
			}
			delayHideTimerId = setTimeout(delayHide, isEmptyObject(elementsNeeded) ? delayHideAllTime : delayHideTime);
		}
	}

	function findLi(element) {
		for(; element; element = element.parentNode) {
			if(XHTML1.isElement(element, "li")) {
				return element;
			}
		}
	}

	function onmouseover(evt) {
		var li = findLi(evt.currentTarget);
		if(li && !li.focused) {
			if(!li.uniqueID) {
				li.uniqueID = nextUniqueID++;
			}
			elementsNeeded[li.uniqueID] = li;
		}
		XHTML1.addClass(evt.currentTarget, "over");
		updatePopup();
	}

	function onmouseout(evt) {
		var li = findLi(evt.currentTarget);
		if(li && !li.focused && li.uniqueID) {
			delete elementsNeeded[li.uniqueID];
		}
		XHTML1.removeClass(evt.currentTarget, "over");
		updatePopup();
	}

	function onfocus(evt) {
		var li = findLi(evt.currentTarget);
		if(li) {
			li.focused = true;
			if(!li.uniqueID) {
				li.uniqueID = nextUniqueID++;
			}
			elementsNeeded[li.uniqueID] = li;
		}
		updatePopup();
	}

	function onblur(evt) {
		var li = findLi(evt.currentTarget);
		if(li) {
			li.focused = false;
			delete elementsNeeded[li.uniqueID];
		}
		updatePopup();
	}

	var aElements = XHTML1.getElementsByTagName("a");
	for(var i = 0; i < aElements.length; i++) {
		var a = aElements[i];
		for(var element = a.parentNode; element; element = element.parentNode) {
			if(XHTML1.isElement(element, "ul") && XHTML1.containsClass(element, "dropdowns")) {
				XHTML1.addEventListener(a, "focus", onfocus);
				XHTML1.addEventListener(a, "blur", onblur);
				XHTML1.addEventListener(a, "mouseover", onmouseover);
				XHTML1.addEventListener(a, "mouseout", onmouseout);
				break;
			}
		}
	}

	XHTML1.addEventListener(document, "click", function() {
		if (delayHideTimerId) {
			clearTimeout(delayHideTimerId);
			delayHideTimerId = 0;
			delayHide();
		}
	});
}

if(XHTML1.isDOMSupported()) {
	XHTML1.addEventListener(window, "load", initDropdowns);
}
<|endoftext|>


<commit_before>var SquareType = require('./tiles').SquareType;
var utils = require('../utils');
var _ = utils.getLodash();

var TILE_SHAPES = {
  'log':             [0, 0],
  'lily1':           [1, 0],
  'land1':           [2, 0],
  'island_start':    [0, 1],
  'island_topRight': [1, 1],
  'island_botLeft':  [0, 2],
  'island_botRight': [1, 2],
  'water': [4, 0],

  'lily2': [2, 1],
  'lily3': [3, 1],
  'lily4': [2, 2],
  'lily5': [3, 2],

  'ice': [3, 0],

  'empty': [4, 0]
};

// Returns true if the tile at x,y is either a wall or out of bounds
function isWallOrOutOfBounds (x, y) {
  return Maze.map[y] === undefined || Maze.map[y][x] === undefined ||
    Maze.map[y][x] === SquareType.WALL;
}

// Returns true if the tile at x,y is a wall that is in bounds.
function isWall (x, y) {
  return Maze.map[y] !== undefined && Maze.map[y][x] === SquareType.WALL;
}

/**
 * Override maze's drawMapTiles
 */
module.exports.drawMapTiles = function (svg) {
  var island = null;

  var tileId = 0;
  var tile;
  for (var row = 0; row < Maze.ROWS; row++) {
    for (var col = 0; col < Maze.COLS; col++) {
      if (!isWallOrOutOfBounds(col, row)) {
        tile = 'ice';
      } else {
        var adjacentToPath = !isWallOrOutOfBounds(col, row - 1) ||
          !isWallOrOutOfBounds(col + 1, row) ||
          !isWallOrOutOfBounds(col, row + 1) ||
          !isWallOrOutOfBounds(col - 1, row);

        // if next to the path, always just have water. otherwise, there's
        // a chance of one of our other tiles
        tile = 'water';
        tile = _.sample(['empty', 'empty', 'empty', 'empty', 'empty', 'lily2',
          'lily3', 'lily4', 'lily5', 'lily1', 'log', 'lily1', 'land1']);

        if (island !== null) {
          if (island.col === col - 1 && island.row === row) {
            tile = 'island_topRight';
          } else  if (island.col === col && island.row === row - 1) {
            tile = 'island_botLeft';
          } else  if (island.col === col - 1 && island.row === row - 1) {
            tile = 'island_botRight';
          }
        } else if (Math.random() < 1/20 &&
            isWall(col + 1, row + 0) && isWallOrOutOfBounds(col + 2, row) &&
            isWall(col + 0, row + 1) && isWallOrOutOfBounds(col, row + 2) &&
            isWall(col + 1, row + 1)) {
          island = { col: col, row: row};
          tile = 'island_start';
        }

        if (adjacentToPath && tile === 'land1') {
          tile = 'empty';
        }
      }
      Maze.drawTile(svg, TILE_SHAPES[tile], row, col, tileId);
      tileId++;
    }
  }
};

/**
 * Schedule the animations for Scrat dancing.
 * @param {integer} timeAlloted How much time we have for our animations
 */
module.exports.scheduleDance = function (victoryDance, timeAlloted) {
  var finishIcon = document.getElementById('finish');
  if (finishIcon) {
    finishIcon.setAttribute('visibility', 'hidden');
  }

  var numFrames = skin.celebratePegmanRow;
  var timePerFrame = timeAlloted / numFrames;
  var start = {x: Maze.pegmanX, y: Maze.pegmanY};

  scheduleSheetedMovement({x: start.x, y: start.y}, {x: 0, y: 0 },
    numFrames, timePerFrame, 'celebrate', Direction.NORTH, true);
};
<commit_msg>always have an island<commit_after>var SquareType = require('./tiles').SquareType;
var utils = require('../utils');
var _ = utils.getLodash();

var TILE_SHAPES = {
  'log':             [0, 0],
  'lily1':           [1, 0],
  'land1':           [2, 0],
  'island_start':    [0, 1],
  'island_topRight': [1, 1],
  'island_botLeft':  [0, 2],
  'island_botRight': [1, 2],
  'water': [4, 0],

  'lily2': [2, 1],
  'lily3': [3, 1],
  'lily4': [2, 2],
  'lily5': [3, 2],

  'ice': [3, 0],

  'empty': [4, 0]
};

// Returns true if the tile at x,y is either a water tile or out of bounds
function isWaterOrOutOfBounds (x, y) {
  return Maze.map[y] === undefined || Maze.map[y][x] === undefined ||
    Maze.map[y][x] === SquareType.WALL;
}

// Returns true if the tile at x,y is a water tile that is in bounds.
function isWater (x, y) {
  return Maze.map[y] !== undefined && Maze.map[y][x] === SquareType.WALL;
}

/**
 * Override maze's drawMapTiles
 */
module.exports.drawMapTiles = function (svg) {
  var row, col;

  // first figure out where we want to put the island
  var possibleIslandLocations = [];
  for (row = 0; row < Maze.ROWS; row++) {
    for (col = 0; col < Maze.COLS; col++) {
      if (!isWater(col, row) || !isWater(col + 1, row) ||
        !isWater(col, row + 1) || !isWater(col + 1, row + 1)) {
        continue;
      }
      possibleIslandLocations.push({row: row, col: col});
    }
  }
  var island = _.sample(possibleIslandLocations);
  var preFilled = {};
  if (island) {
    preFilled[(island.row + 0) + "_" + (island.col + 0)] = 'island_start';
    preFilled[(island.row + 1) + "_" + (island.col + 0)] = 'island_botLeft';
    preFilled[(island.row + 0) + "_" + (island.col + 1)] = 'island_topRight';
    preFilled[(island.row + 1) + "_" + (island.col + 1)] = 'island_botRight';
  }

  var tileId = 0;
  var tile;
  for (row = 0; row < Maze.ROWS; row++) {
    for (col = 0; col < Maze.COLS; col++) {
      if (!isWaterOrOutOfBounds(col, row)) {
        tile = 'ice';
      } else {
        var adjacentToPath = !isWaterOrOutOfBounds(col, row - 1) ||
          !isWaterOrOutOfBounds(col + 1, row) ||
          !isWaterOrOutOfBounds(col, row + 1) ||
          !isWaterOrOutOfBounds(col - 1, row);

        // if next to the path, always just have water. otherwise, there's
        // a chance of one of our other tiles
        tile = 'water';

        tile = preFilled[row + "_" + col];
        if (!tile) {
          tile = _.sample(['empty', 'empty', 'empty', 'empty', 'empty', 'lily2',
            'lily3', 'lily4', 'lily5', 'lily1', 'log', 'lily1', 'land1']);
        }

        if (adjacentToPath && tile === 'land1') {
          tile = 'empty';
        }
      }
      Maze.drawTile(svg, TILE_SHAPES[tile], row, col, tileId);
      tileId++;
    }
  }
};

/**
 * Schedule the animations for Scrat dancing.
 * @param {integer} timeAlloted How much time we have for our animations
 */
module.exports.scheduleDance = function (victoryDance, timeAlloted) {
  var finishIcon = document.getElementById('finish');
  if (finishIcon) {
    finishIcon.setAttribute('visibility', 'hidden');
  }

  var numFrames = skin.celebratePegmanRow;
  var timePerFrame = timeAlloted / numFrames;
  var start = {x: Maze.pegmanX, y: Maze.pegmanY};

  scheduleSheetedMovement({x: start.x, y: start.y}, {x: 0, y: 0 },
    numFrames, timePerFrame, 'celebrate', Direction.NORTH, true);
};
<|endoftext|>


<commit_before>import React from 'react';
import Control from '../Control';

class TextInput extends Control {
    constructor(props) {
        super(props);

        this.state.value = props.value;

        this.onClearClick = this.onClearClick.bind(this);
        this.onInputChange = this.onInputChange.bind(this);
    }

    render() {
        var type = this.props.type || 'text';

        var hasClear;
        if (this.props.hasClear && this.state.value) {
            hasClear = (

            );
        }

        return (

                    <input ref="control" className="input__control" type={type} placeholder={this.props.placeholder} value={this.state.value}
                        onChange={this.onInputChange}
                    />
                    {hasClear}

        );
    }

    className() {
        var className = 'input';

        if (this.props.theme) {
            className += ' input_theme_' + this.props.theme;
        }
        if (this.props.size) {
            className += ' input_size_' + this.props.size;
        }
        if (this.props.disabled) {
            className += ' input_disabled';
        }
        if (this.state.hovered) {
            className += ' input_hovered';
        }
        if (this.state.focused) {
            className += ' input_focused';
        }
        if (this.props.hasClear) {
            className += ' input_has-clear';
        }

        if (this.props.className) {
            className += ' ' + this.props.className;
        }

        return className;
    }

    onInputChange(e) {
        this.setState({ value: e.target.value });
        this.props.onChange();
    }

    onClearClick() {
        this.setState({ value: '', focused: true });
        //  FIXME: А неплохо бы на focused тут реагировать, а не явно ставить фокус?
        this.refs.control.focus();
        this.props.onChange({ source: 'clear' });
    }

}

TextInput.defaultProps = {
    onChange() {}
};

export default TextInput;
<commit_msg>hasClear не всегда имеет модификатор _visible<commit_after>import React from 'react';
import Control from '../Control';

class TextInput extends Control {
    constructor(props) {
        super(props);

        this.state.value = props.value;

        this.onClearClick = this.onClearClick.bind(this);
        this.onInputChange = this.onInputChange.bind(this);
    }

    render() {
        var type = this.props.type || 'text';

        var hasClear;
        if (this.props.hasClear) {
            var hasClearClassName = 'input__clear';
            if (this.state.value) {
                hasClearClassName += ' input__clear_visible';
            }

            hasClear = (

            );
        }

        return (

                    <input ref="control" className="input__control" type={type} placeholder={this.props.placeholder} value={this.state.value}
                        onChange={this.onInputChange}
                    />
                    {hasClear}

        );
    }

    className() {
        var className = 'input';

        if (this.props.theme) {
            className += ' input_theme_' + this.props.theme;
        }
        if (this.props.size) {
            className += ' input_size_' + this.props.size;
        }
        if (this.props.disabled) {
            className += ' input_disabled';
        }
        if (this.state.hovered) {
            className += ' input_hovered';
        }
        if (this.state.focused) {
            className += ' input_focused';
        }
        if (this.props.hasClear) {
            className += ' input_has-clear';
        }

        if (this.props.className) {
            className += ' ' + this.props.className;
        }

        return className;
    }

    onInputChange(e) {
        this.setState({ value: e.target.value });
        this.props.onChange();
    }

    onClearClick() {
        this.setState({ value: '', focused: true });
        //  FIXME: А неплохо бы на focused тут реагировать, а не явно ставить фокус?
        this.refs.control.focus();
        this.props.onChange({ source: 'clear' });
    }

}

TextInput.defaultProps = {
    onChange() {}
};

export default TextInput;
<|endoftext|>


<commit_before>(function(Vis) {
"use strict";

var busyDelay = 2500;

Vis.blocks['i-chart'] = {
    init: function(params) {
        var _this = this;

        _this.dimensions = {
            width: 0,
            height: 0
        };

        params = params || {};

        var colorScheme = params.colorScheme || {};
        _this.colorScheme = Vis.create(
            colorScheme,
            colorScheme.name || 'i-tango-color-scheme'
        );

        _this.content = {
            tAxes: params.tAxes || [],
            xAxes: params.xAxes || [],
            yAxes: params.yAxes || [],
            items: params.items || [],
            overlays: params.overlays || [],
            layers: []
        };
        _this._initContent();

        // _this.applySize();
        // _this.initResize();
    },

    initTAxis: function(tAxisNo) { /* override me */ },
    _initTAxis: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo];

        tAxis.rangeProvider = Vis.create(
            tAxis.rangeProvider,
            tAxis.rangeProvider.name || 'undefined-t-range-provider'
        );

        _this.initTAxis(tAxisNo);

        tAxis.rangeProvider.on('update', function() {
            _this._updateTAxisRange(tAxisNo);
        });
        _this._updateTAxisRange(tAxisNo);
    },

    updateTAxisRange: function(tAxisNo) { /* override me */ },
    _updateTAxisRange: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo],
            range = tAxis.rangeProvider.get(),
            scale = tAxis.scale || {},
            items = _this.content.items;

        _this.updateTAxisRange(tAxisNo);

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        tAxis.scale = {
            inputMin: range.min,
            inputMax: range.max
        };

        _this.updateTAxisRange(tAxisNo);
    },

    initTAxes: function() { /* override me */ },
    _initTAxes: function() {
        var _this = this,
            tAxes = _this.content.tAxes;

        for (var tAxisNo = 0, l = tAxes.length; tAxisNo < l; ++tAxisNo) {
            _this._initTAxis(tAxisNo);
        }

        _this.initTAxes();
    },

    initXAxis: function(xAxisNo) { /* override me */ },
    _initXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            tAxes = _this.content.tAxes;

        var scale = xAxis.scale || {};
        xAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof xAxis.units === 'undefined') {
            xAxis.units = "";
        }

        if (xAxis.pos !== 'top' && xAxis.pos !== 'bottom') {
            xAxis.pos = 'bottom';
        }

        xAxis.tAxis = tAxes[xAxis.tAxisNo || 0] || Vis.error("No t-axis for x-axis #" + xAxisNo);

        if (typeof xAxis.rangeProvider.timeRangeProvider === 'undefined') {
            xAxis.rangeProvider.timeRangeProvider = xAxis.tAxis.rangeProvider;
        }
        xAxis.rangeProvider = Vis.create(
            xAxis.rangeProvider,
            xAxis.rangeProvider.name || 'undefined-x-range-provider'
        );

        if (typeof xAxis.processors === 'undefined') {
            xAxis.processors = [];
        }
        for (var i = 0, l = xAxis.processors.length; i < l; ++i) {
            var processor = xAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            xAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(xAxisNo);

        xAxis.rangeProvider.on('update', function() {
            _this._updateXAxisRange(xAxisNo);
        });
        _this._updateXAxisRange(xAxisNo);
    },

    updateXAxisRange: function(xAxisNo) { /* override me */ },
    _updateXAxisRange: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            range = xAxis.rangeProvider.get(),
            scale = xAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateXAxisRange(xAxisNo);

        _this._renderXAxis(xAxisNo);
    },

    renderXAxis: function(xAxisNo, ticks) { /* override me */ },
    _renderXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = this.content.xAxes[xAxisNo];

        xAxis.ticks = xAxis.scale.ticks(Math.floor(_this.dimensions.width / 65), xAxis.units);

        var ticks = Units.formatTicks(xAxis.ticks, xAxis.units, xAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = Math.round(xAxis.scale.f(tick.tickValue));
        }

        _this.renderXAxis(xAxisNo, ticks);
    },

    initXAxes: function() { /* override me */ },
    _initXAxes: function() {
        var _this = this,
            xAxes = _this.content.xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }

        _this.initXAxes();
    },

    initYAxis: function(yAxisNo) { /* override me */ },
    _initYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo];

        var scale = yAxis.scale || {};
        yAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof yAxis.units === 'undefined') {
            yAxis.units = "";
        }

        if (yAxis.pos !== 'left' && yAxis.pos !== 'right') {
            yAxis.pos = 'right';
        }

        yAxis.rangeProvider = Vis.create(
            yAxis.rangeProvider,
            yAxis.rangeProvider.name || 'undefined-y-range-provider'
        );

        if (typeof yAxis.processors === 'undefined') {
            yAxis.processors = [];
        }
        for (var i = 0, l = yAxis.processors.length; i < l; ++i) {
            var processor = yAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            yAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(yAxisNo);

        yAxis.rangeProvider.on('update', function() {
            _this._updateYAxisRange(yAxisNo);
        });
        _this._updateYAxisRange(yAxisNo);
    },

    updateYAxisRange: function(yAxisNo) { /* override me */ },
    _updateYAxisRange: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo],
            range = yAxis.rangeProvider.get(),
            scale = yAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateYAxisRange(yAxisNo);

        _this._renderYAxis(yAxisNo);
    },

    renderYAxis: function(yAxisNo, ticks) { /* override me */ },
    _renderYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = this.content.yAxes[yAxisNo];

        yAxis.ticks = yAxis.scale.ticks(Math.floor(_this.dimensions.height / 40), yAxis.units);

        var ticks = Units.formatTicks(yAxis.ticks, yAxis.units, yAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = _this.dimensions.height - Math.round(yAxis.scale.f(tick.tickValue)) - 1;
        }

        _this.renderYAxis(yAxisNo, ticks);
    },

    initYAxes: function() { /* override me */ },
    _initYAxes: function() {
        var _this = this,
            yAxes = _this.content.yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }

        _this.initYAxes();
    },

    _initItem: function(itemNo) {
        var _this = this,
            tAxes = _this.content.tAxes,
            item = _this.content.items[itemNo];

        item.tAxis = tAxes[item.tAxisNo || 0] || Vis.error("No t-axis for item #" + itemNo);

        if (typeof item.dataProvider.timeRangeProvider === 'undefined') {
            item.dataProvider.timeRangeProvider = item.tAxis.rangeProvider;
        }
        item.dataProvider = Vis.create(
            item.dataProvider,
            item.dataProvider.name || 'undefined-item-data-provider'
        );
        item.dataProvider.on('update', function(e) {
            _this._updateItemData(itemNo);
        });

        if (!item.filters) {
            item.filters = [];
        }
        for (var i = 0, l = item.filters.length; i < l; ++i) {
            item.filters[i] = Vis.create(
                item.filters[i],
                item.filters[i].name
            );
        }

        if (typeof item.color === 'undefined') {
            item.color = _this.colorScheme.get(itemNo);
        }

        if (typeof item.units === 'undefined') {
            item.units = "";
        }

        item.renderData = {};

        _this._updateItemData(itemNo);
        // _requestItemData?
    },

    _updateItemData: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo],
            filters = item.filters;

        item.rawData = item.dataProvider.get();

        var data = {};
        $.each(item.rawData, function(name, arr) {
            data[name] = arr.slice();
        });
        for (var i = 0, l = filters.length; i < l; ++i) {
            data = filters[i].run(item, data);
        }
        item.data = data;

        // override me
        this.render();
    },

    _initItems: function() {
        var _this = this,
            items = _this.content.items;

        for (var itemNo = 0, l = items.length; itemNo < l; ++itemNo) {
            _this._initItem(itemNo);
        }
    },

    initOverlay: function(overlayNo) { /* override me */ },
    _initOverlay: function(overlayNo) {
        var _this = this,
            overlays = _this.content.overlays,
            overlay = overlays[overlayNo];

        overlay.dimensions = _this.dimensions;
        overlay.content = _this.content;
        overlays[overlayNo] = Vis.create(
            overlay,
            overlay.name || 'undefined-overlay'
        );

        _this.initOverlay(overlayNo);
    },

    _initOverlays: function() {
        var _this = this,
            overlays = _this.content.overlays;

        for (var i = 0, l = overlays.length; i < l; ++i) {
            _this._initOverlay(i);
        }
    },

    initContent: function () { /* override me */ },
    _initContent: function () {
        this._initTAxes();
        this._initXAxes();
        this._initYAxes();
        this._initItems();
        this._initOverlays();

        this.initContent();
    },

    applySize: function () { /* override me */ },
    _applySize: function() {
        var _this = this,
            dim = _this.dimensions,
            xAxes = _this.content.xAxes,
            yAxes = _this.content.yAxes,
            i, l;

        for (i = 0, l = xAxes.length; i < l; ++i) {
            xAxes[i].scale.output(0, dim.width - 1);
        }

        for (i = 0, l = yAxes.length; i < l; ++i) {
            yAxes[i].scale.output(0, dim.height - 1);
        }

        _this.applySize();
    },

    initResize: function() {
        // override me
    },

    setYAxes: function(yAxes) {
        var _this = this;

        _this._destroyYAxes();
        _this.content.yAxes = yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }
        _this._initYAxes();

        _this._initState.yAxes = true;
        _this._updateInit();
    },

    setXAxes: function(xAxes) {
        var _this = this;

        _this._destroyXAxes();
        _this.content.xAxes = xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }
        _this._initXAxes();

        _this._initState.xAxes = true;
        _this._updateInit();
    },

    _updateItem: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo];

        _this._updateItemData(item);
        item.ready = true;
        _this.renderItem(itemNo);
    },

    _requestItemData: function(item) {
        var _this = this,
            xAxis = _this.content.xAxes[item.xAxis || 0] || _this.content.xAxes[0];

        item.ready = false;
        item.dataProvider.range(xAxis.scale.inputMin, xAxis.scale.inputMax);
    },

    _runProcessors: function() {
        var _this = this,
            yAxes = _this.content.yAxes,
            items = _this.content.items;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            var yAxis = yAxes[yAxisNo];

            var axisItems = [];
            for (var i = 0, m = items.length; i < m; ++i) {
                var item = items[i];
                if (item.yAxis != yAxisNo) continue;

                item.renderData = item.data;
                axisItems.push(item);
            }

            for (var i = 0, m = yAxis.processors.length; i < m; ++i) {
                yAxis.processors[i].run(axisItems);
            }

            var range = yAxis.rangeProvider.get(axisItems);
            _this._updateYAxisRange(yAxisNo, range);
        }
    },

    beforeRender: function() {
        this._runProcessors();

        // override me
    },

    afterRender: function() {
        // override me
    },

    renderItem: function(itemNo) {
        if (this._init != -1) {
            return;
        }

        this.render();
    }
};

})(Vis);
<commit_msg>Set default values for item axisNo<commit_after>(function(Vis) {
"use strict";

var busyDelay = 2500;

Vis.blocks['i-chart'] = {
    init: function(params) {
        var _this = this;

        _this.dimensions = {
            width: 0,
            height: 0
        };

        params = params || {};

        var colorScheme = params.colorScheme || {};
        _this.colorScheme = Vis.create(
            colorScheme,
            colorScheme.name || 'i-tango-color-scheme'
        );

        _this.content = {
            tAxes: params.tAxes || [],
            xAxes: params.xAxes || [],
            yAxes: params.yAxes || [],
            items: params.items || [],
            overlays: params.overlays || [],
            layers: []
        };
        _this._initContent();

        // _this.applySize();
        // _this.initResize();
    },

    initTAxis: function(tAxisNo) { /* override me */ },
    _initTAxis: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo];

        tAxis.rangeProvider = Vis.create(
            tAxis.rangeProvider,
            tAxis.rangeProvider.name || 'undefined-t-range-provider'
        );

        _this.initTAxis(tAxisNo);

        tAxis.rangeProvider.on('update', function() {
            _this._updateTAxisRange(tAxisNo);
        });
        _this._updateTAxisRange(tAxisNo);
    },

    updateTAxisRange: function(tAxisNo) { /* override me */ },
    _updateTAxisRange: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo],
            range = tAxis.rangeProvider.get(),
            scale = tAxis.scale || {},
            items = _this.content.items;

        _this.updateTAxisRange(tAxisNo);

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        tAxis.scale = {
            inputMin: range.min,
            inputMax: range.max
        };

        _this.updateTAxisRange(tAxisNo);
    },

    initTAxes: function() { /* override me */ },
    _initTAxes: function() {
        var _this = this,
            tAxes = _this.content.tAxes;

        for (var tAxisNo = 0, l = tAxes.length; tAxisNo < l; ++tAxisNo) {
            _this._initTAxis(tAxisNo);
        }

        _this.initTAxes();
    },

    initXAxis: function(xAxisNo) { /* override me */ },
    _initXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            tAxes = _this.content.tAxes;

        var scale = xAxis.scale || {};
        xAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof xAxis.units === 'undefined') {
            xAxis.units = "";
        }

        if (xAxis.pos !== 'top' && xAxis.pos !== 'bottom') {
            xAxis.pos = 'bottom';
        }

        xAxis.tAxis = tAxes[xAxis.tAxisNo || 0] || Vis.error("No t-axis for x-axis #" + xAxisNo);

        if (typeof xAxis.rangeProvider.timeRangeProvider === 'undefined') {
            xAxis.rangeProvider.timeRangeProvider = xAxis.tAxis.rangeProvider;
        }
        xAxis.rangeProvider = Vis.create(
            xAxis.rangeProvider,
            xAxis.rangeProvider.name || 'undefined-x-range-provider'
        );

        if (typeof xAxis.processors === 'undefined') {
            xAxis.processors = [];
        }
        for (var i = 0, l = xAxis.processors.length; i < l; ++i) {
            var processor = xAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            xAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(xAxisNo);

        xAxis.rangeProvider.on('update', function() {
            _this._updateXAxisRange(xAxisNo);
        });
        _this._updateXAxisRange(xAxisNo);
    },

    updateXAxisRange: function(xAxisNo) { /* override me */ },
    _updateXAxisRange: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            range = xAxis.rangeProvider.get(),
            scale = xAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateXAxisRange(xAxisNo);

        _this._renderXAxis(xAxisNo);
    },

    renderXAxis: function(xAxisNo, ticks) { /* override me */ },
    _renderXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = this.content.xAxes[xAxisNo];

        xAxis.ticks = xAxis.scale.ticks(Math.floor(_this.dimensions.width / 65), xAxis.units);

        var ticks = Units.formatTicks(xAxis.ticks, xAxis.units, xAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = Math.round(xAxis.scale.f(tick.tickValue));
        }

        _this.renderXAxis(xAxisNo, ticks);
    },

    initXAxes: function() { /* override me */ },
    _initXAxes: function() {
        var _this = this,
            xAxes = _this.content.xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }

        _this.initXAxes();
    },

    initYAxis: function(yAxisNo) { /* override me */ },
    _initYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo];

        var scale = yAxis.scale || {};
        yAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof yAxis.units === 'undefined') {
            yAxis.units = "";
        }

        if (yAxis.pos !== 'left' && yAxis.pos !== 'right') {
            yAxis.pos = 'right';
        }

        yAxis.rangeProvider = Vis.create(
            yAxis.rangeProvider,
            yAxis.rangeProvider.name || 'undefined-y-range-provider'
        );

        if (typeof yAxis.processors === 'undefined') {
            yAxis.processors = [];
        }
        for (var i = 0, l = yAxis.processors.length; i < l; ++i) {
            var processor = yAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            yAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(yAxisNo);

        yAxis.rangeProvider.on('update', function() {
            _this._updateYAxisRange(yAxisNo);
        });
        _this._updateYAxisRange(yAxisNo);
    },

    updateYAxisRange: function(yAxisNo) { /* override me */ },
    _updateYAxisRange: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo],
            range = yAxis.rangeProvider.get(),
            scale = yAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateYAxisRange(yAxisNo);

        _this._renderYAxis(yAxisNo);
    },

    renderYAxis: function(yAxisNo, ticks) { /* override me */ },
    _renderYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = this.content.yAxes[yAxisNo];

        yAxis.ticks = yAxis.scale.ticks(Math.floor(_this.dimensions.height / 40), yAxis.units);

        var ticks = Units.formatTicks(yAxis.ticks, yAxis.units, yAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = _this.dimensions.height - Math.round(yAxis.scale.f(tick.tickValue)) - 1;
        }

        _this.renderYAxis(yAxisNo, ticks);
    },

    initYAxes: function() { /* override me */ },
    _initYAxes: function() {
        var _this = this,
            yAxes = _this.content.yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }

        _this.initYAxes();
    },

    _initItem: function(itemNo) {
        var _this = this,
            tAxes = _this.content.tAxes,
            xAxes = _this.content.xAxes,
            yAxes = _this.content.yAxes,
            item = _this.content.items[itemNo];

        if (typeof item.tAxisNo === 'undefined') {
            item.tAxisNo = 0;
        }
        item.tAxis = tAxes[item.tAxisNo] || Vis.error("No t-axis for item #" + itemNo);

        if (typeof item.xAxisNo === 'undefined') {
            item.xAxisNo = 0;
        }
        item.xAxis = xAxes[item.xAxisNo] || Vis.error("No x-axis for item #" + itemNo);

        if (typeof item.yAxisNo === 'undefined') {
            item.yAxisNo = 0;
        }
        item.yAxis = yAxes[item.yAxisNo] || Vis.error("No y-axis for item #" + itemNo);

        if (typeof item.color === 'undefined') {
            item.color = _this.colorScheme.get(itemNo);
        }

        if (typeof item.units === 'undefined') {
            item.units = "";
        }

        if (typeof item.dataProvider.timeRangeProvider === 'undefined') {
            item.dataProvider.timeRangeProvider = item.tAxis.rangeProvider;
        }
        item.dataProvider = Vis.create(
            item.dataProvider,
            item.dataProvider.name || 'undefined-item-data-provider'
        );
        item.dataProvider.on('update', function(e) {
            _this._updateItemData(itemNo);
        });

        if (!item.filters) {
            item.filters = [];
        }
        for (var i = 0, l = item.filters.length; i < l; ++i) {
            item.filters[i] = Vis.create(
                item.filters[i],
                item.filters[i].name
            );
        }

        item.renderData = {};

        _this._updateItemData(itemNo);
        // _requestItemData?
    },

    _updateItemData: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo],
            filters = item.filters;

        item.rawData = item.dataProvider.get();

        var data = {};
        $.each(item.rawData, function(name, arr) {
            data[name] = arr.slice();
        });
        for (var i = 0, l = filters.length; i < l; ++i) {
            data = filters[i].run(item, data);
        }
        item.data = data;

        // override me
        this.render();
    },

    _initItems: function() {
        var _this = this,
            items = _this.content.items;

        for (var itemNo = 0, l = items.length; itemNo < l; ++itemNo) {
            _this._initItem(itemNo);
        }
    },

    initOverlay: function(overlayNo) { /* override me */ },
    _initOverlay: function(overlayNo) {
        var _this = this,
            overlays = _this.content.overlays,
            overlay = overlays[overlayNo];

        overlay.dimensions = _this.dimensions;
        overlay.content = _this.content;
        overlays[overlayNo] = Vis.create(
            overlay,
            overlay.name || 'undefined-overlay'
        );

        _this.initOverlay(overlayNo);
    },

    _initOverlays: function() {
        var _this = this,
            overlays = _this.content.overlays;

        for (var i = 0, l = overlays.length; i < l; ++i) {
            _this._initOverlay(i);
        }
    },

    initContent: function () { /* override me */ },
    _initContent: function () {
        this._initTAxes();
        this._initXAxes();
        this._initYAxes();
        this._initItems();
        this._initOverlays();

        this.initContent();
    },

    applySize: function () { /* override me */ },
    _applySize: function() {
        var _this = this,
            dim = _this.dimensions,
            xAxes = _this.content.xAxes,
            yAxes = _this.content.yAxes,
            i, l;

        for (i = 0, l = xAxes.length; i < l; ++i) {
            xAxes[i].scale.output(0, dim.width - 1);
        }

        for (i = 0, l = yAxes.length; i < l; ++i) {
            yAxes[i].scale.output(0, dim.height - 1);
        }

        _this.applySize();
    },

    initResize: function() {
        // override me
    },

    setYAxes: function(yAxes) {
        var _this = this;

        _this._destroyYAxes();
        _this.content.yAxes = yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }
        _this._initYAxes();

        _this._initState.yAxes = true;
        _this._updateInit();
    },

    setXAxes: function(xAxes) {
        var _this = this;

        _this._destroyXAxes();
        _this.content.xAxes = xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }
        _this._initXAxes();

        _this._initState.xAxes = true;
        _this._updateInit();
    },

    _updateItem: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo];

        _this._updateItemData(item);
        item.ready = true;
        _this.renderItem(itemNo);
    },

    _requestItemData: function(item) {
        var _this = this,
            xAxis = _this.content.xAxes[item.xAxis || 0] || _this.content.xAxes[0];

        item.ready = false;
        item.dataProvider.range(xAxis.scale.inputMin, xAxis.scale.inputMax);
    },

    _runProcessors: function() {
        var _this = this,
            yAxes = _this.content.yAxes,
            items = _this.content.items;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            var yAxis = yAxes[yAxisNo];

            var axisItems = [];
            for (var i = 0, m = items.length; i < m; ++i) {
                var item = items[i];
                if (item.yAxis != yAxisNo) continue;

                item.renderData = item.data;
                axisItems.push(item);
            }

            for (var i = 0, m = yAxis.processors.length; i < m; ++i) {
                yAxis.processors[i].run(axisItems);
            }

            var range = yAxis.rangeProvider.get(axisItems);
            _this._updateYAxisRange(yAxisNo, range);
        }
    },

    beforeRender: function() {
        this._runProcessors();

        // override me
    },

    afterRender: function() {
        // override me
    },

    renderItem: function(itemNo) {
        if (this._init != -1) {
            return;
        }

        this.render();
    }
};

})(Vis);
<|endoftext|>


<commit_before>define("ace/snippets/curly",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText =undefined;
exports.scope = "curly";

});
<commit_msg>Update tmp/bower_components/ace-builds/src/snippets/curly.js<commit_after><|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  description: 'Choose which addons to install',

  normalizeEntityName: function() {
  },

  afterInstall: function(options) {
    return this._chooseAddonsToInstall()
      .then((addons) => {
        return this.addAddonsToProject({
          packages: addons
        });
      });
  },
  /**
   * Uses inquirer to prompt the user to select which addons to install
   * @returns {Promise} Resolves into array of selected addons
   * @private
   */
  _chooseAddonsToInstall: function() {
    // Ask which ember addons to install
    return this.ui.prompt({
      type: 'checkbox',
      name: 'addonsToInstall',
      message: 'Which addons would you like to install?',
      choices: [
        {
          checked: true,
          name: 'flexi-default-styles',
          value: { name: 'flexi-default-styles' }
        },
        {
          checked: true,
          name: 'flexi-dsl',
          value: { name: 'flexi-dsl' }
        },
        {
          checked: true,
          name: 'flexi-layouts',
          value: { name: 'flexi-layouts' }
        },
        {
          checked: false,
          name: 'flexi-sustain',
          value: { name: 'flexi-sustain' }
        },
      ]
    })
      .then((selected) => {
        return selected.addonsToInstall;
      });
  }
};
<commit_msg>Add validate, and some separators with descriptions<commit_after>var inquirer = require('inquirer');

/*jshint node:true*/
module.exports = {
  description: 'Choose which addons to install',

  normalizeEntityName: function() {
  },

  afterInstall: function(options) {
    return this._chooseAddonsToInstall()
      .then((addons) => {
        return this.addAddonsToProject({
          packages: addons
        });
      });
  },
  /**
   * Uses inquirer to prompt the user to select which addons to install
   * @returns {Promise} Resolves into array of selected addons
   * @private
   */
  _chooseAddonsToInstall: function() {
    // Ask which ember addons to install
    return this.ui.prompt({
      type: 'checkbox',
      name: 'addonsToInstall',
      message: 'Which addons would you like to install?',
      choices: [
        new inquirer.Separator('flexi-default-styles - Default flexi styles'),
        {
          checked: true,
          name: 'flexi-default-styles',
          value: { name: 'flexi-default-styles' }
        },
        new inquirer.Separator('flexi-dsl - Converts attributes to classes'),
        {
          checked: true,
          name: 'flexi-dsl',
          value: { name: 'flexi-dsl' }
        },
        new inquirer.Separator('flexi-layouts - Layout service and grids'),
        {
          checked: true,
          name: 'flexi-layouts',
          value: { name: 'flexi-layouts' }
        },
        new inquirer.Separator('flexi-sustain - Recyclable components (Ember <= 2.9)'),
        {
          checked: false,
          message: '',
          name: 'flexi-sustain',
          value: { name: 'flexi-sustain' }
        },
      ],
      validate: (answer) => {
        if (answer.length < 1) {
          return 'You must choose at least one addon.';
        }
        return true;
      }
    })
      .then((selected) => {
        return selected.addonsToInstall;
      });
  }
};
<|endoftext|>


<commit_before>/**
 * Created by ziv on 15/03/2017.
 */

var ScrapedProduct = require('../../../models/Scrapedprodcut');

const cheerioReq = require("cheerio-req");
const URL = 'https://www.whatsinproducts.com/types/index/TypeLanguage.search:search/TypeLanguage.filter:%LETTER%/TypeLanguage.lang_id:1';
const letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
exports.whatsInProductScraper = class WhatsInProductScraper {
    constructor() {
    }

    addProductsToQueue(letter) {
        var products = [];
        // for(let letterIndex = 0; letterIndex < letters.length; letterIndex++){
        //     let urlToCheck = URL.replace('%LETTER%',letters[letterIndex]);
        let urlToCheck = URL.replace('%LETTER%', letter);
        console.log(urlToCheck);
        cheerioReq(urlToCheck, (err, $) => {
            var results = $('.rslt_prd_hldr .brnd_srch_brnd_name a');
            for (let itemIndex = 0; itemIndex < results.length; itemIndex++) {
                let scrapeProduct = new ScrapedProduct({
                    product_url: "https://www.whatsinproducts.com" + results[itemIndex].attribs.href,
                    scraper_strategy:"whatsinproducts",
                    name:$(results[itemIndex]).text().replace(/(\s\s\s*)/g, ''),
                    ingredients : []
                });
                // scrapeProduct.product_url = "https://www.whatsinproducts.com" + results[itemIndex].attribs.href;
                // scrapeProduct.scraper_strategy = "whatsinproducts";
                // products.push(scrapeProduct);
                scrapeProduct.save().then(function(res){
                    // console.log(res);
                },function(err){
                    // console.log(err);
                });
            }
            console.log('finished');
        });
    }

    scrapeProductsFromQueue(){
        return setInterval(function() {
            // ScrapedProduct.findOne({$and:[{"scrape_result" : { $exists : false }}, { "ingredients":  {$size: 0}}]}, function(err, productToScrape) {
            ScrapedProduct.findOne({ "ingredients":  {$size: 0}}, function(err, productToScrape) {
                if(productToScrape) {
                    console.log('start scrape - ' + productToScrape.name);
                    cheerioReq(productToScrape.product_url, (err, $) => {
                        var ingredientsHtml = $('.rslt_prd_hldr .brnd_srch_chem_name');
                        if(ingredientsHtml.length === 0){
                            ingredientsHtml = $('.rslt_prd_hldr .eu_othr_feild1_name.eu_chemical_name a');
                        }
                        for( let ingredientIndex = 0 ; ingredientIndex < ingredientsHtml.length;ingredientIndex++ ){
                            productToScrape.ingredients.push($($(ingredientsHtml)[ingredientIndex]).text().trim())
                        }
                        productToScrape.image_url = $('.big_img_hldr img').attr('src');
                        productToScrape.number_of_searches = 0;
                        productToScrape.scraper_strategy = 'whatsInProductScraper';
                        productToScrape.scraped_time = new Date();
                        productToScrape.scrape_result = 'FOUND';
                        productToScrape.category = $($('.breadcrumbs')[1]).text().split('::')[0].trim();
                        // productToScrape.
                        productToScrape.save();
                    });
                }
            });
        }, 10000);
    }
};

<commit_msg>improve logs<commit_after>/**
 * Created by ziv on 15/03/2017.
 */

var ScrapedProduct = require('../../../models/Scrapedprodcut');

const cheerioReq = require("cheerio-req");
const URL = 'https://www.whatsinproducts.com/types/index/TypeLanguage.search:search/TypeLanguage.filter:%LETTER%/TypeLanguage.lang_id:1';
const letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
exports.whatsInProductScraper = class WhatsInProductScraper {
    constructor() {
    }

    addProductsToQueue(letter) {
        var products = [];
        // for(let letterIndex = 0; letterIndex < letters.length; letterIndex++){
        //     let urlToCheck = URL.replace('%LETTER%',letters[letterIndex]);
        let urlToCheck = URL.replace('%LETTER%', letter);
        console.log(urlToCheck);
        cheerioReq(urlToCheck, (err, $) => {
            var results = $('.rslt_prd_hldr .brnd_srch_brnd_name a');
            for (let itemIndex = 0; itemIndex < results.length; itemIndex++) {
                let scrapeProduct = new ScrapedProduct({
                    product_url: "https://www.whatsinproducts.com" + results[itemIndex].attribs.href,
                    scraper_strategy:"whatsinproducts",
                    name:$(results[itemIndex]).text().replace(/(\s\s\s*)/g, ''),
                    ingredients : []
                });
                // scrapeProduct.product_url = "https://www.whatsinproducts.com" + results[itemIndex].attribs.href;
                // scrapeProduct.scraper_strategy = "whatsinproducts";
                // products.push(scrapeProduct);
                scrapeProduct.save().then(function(res){
                    // console.log(res);
                },function(err){
                    // console.log(err);
                });
            }
            console.log('finished');
        });
    }

    scrapeProductsFromQueue(){
        return setInterval(function() {
            // ScrapedProduct.findOne({$and:[{"scrape_result" : { $exists : false }}, { "ingredients":  {$size: 0}}]}, function(err, productToScrape) {
            ScrapedProduct.findOne({ "ingredients":  {$size: 0}}, function(err, productToScrape) {
                if(productToScrape) {
                    console.log('start scrape - ' + productToScrape.name);
                    cheerioReq(productToScrape.product_url, (err, $) => {
                        var ingredientsHtml = $('.rslt_prd_hldr .brnd_srch_chem_name');
                        if(ingredientsHtml.length === 0){
                            ingredientsHtml = $('.rslt_prd_hldr .eu_othr_feild1_name.eu_chemical_name a');
                        }
                        for( let ingredientIndex = 0 ; ingredientIndex < ingredientsHtml.length;ingredientIndex++ ){
                            productToScrape.ingredients.push($($(ingredientsHtml)[ingredientIndex]).text().trim())
                        }
                        productToScrape.image_url = $('.big_img_hldr img').attr('src');
                        productToScrape.number_of_searches = 0;
                        productToScrape.scraper_strategy = 'whatsInProductScraper';
                        productToScrape.scraped_time = new Date();
                        productToScrape.scrape_result = 'FOUND';
                        productToScrape.category = $($('.breadcrumbs')[1]).text().split('::')[0].trim();
                        // productToScrape.
                        productToScrape.save();
                    });
                }else{
                    console.log('no products');
                }
            });
        }, 10000);
    }
};

<|endoftext|>


<commit_before>/**
 * 相对路径转为绝对路径，并且添加CDN域名
 * Created by damujiangr on 2016/10/15.
 */
'use strict';

var path = require('path');
var url = require('url');

var gulp = require('gulp');
var gutil = require('gulp-util');
var through = require('through2');
var _ = require('lodash');

var config = require('./../config.json');
var projectName = config['deploy']['projectName'] || process.cwd().split(path.sep).pop();
var basePath = config['deploy']['basePath'];

/**
 *
 * @param options
 *  asset 资源的根路径
 *  remotePath 远程部署路径
 *  domain 域名
 */
function transformPath(options) {
    var contents, mainPath, reg, asset, assetAbsolute, domain, remotePath;

    //资源的路径
    asset = options.asset || process.cwd();
    //远程部署路径的相对路径
    remotePath = options.remotePath || '/';
    //域名
    //1. 为String '/'时，所有相对路径妆化为绝对路径
    //2. 值为Object 时，按照文件类型赋值不同的CDN域名
    domain = options.domain || '/';

    assetAbsolute = path.resolve(asset);

    //匹配正则
    reg = new RegExp('["\'\\(]\\s*([\\w\\_\/\\.\\-]*\\.(jpg|jpeg|png|gif|eot|svg|ttf|woff|js|css))[^\\)"\']*\\s*[\\)"\']', 'gim');

    return through.obj(function (file, enc, callback) {
        if (file.isNull()) {
            this.push(file);
            return callback();
        }

        if (file.isStream()) {
            this.emit('error', gutil.log('Streams are not supported!'));
            return callback();
        }

        mainPath = path.dirname(file.path);

        contents = file.contents.toString().replace(reg, function (content, filePath) {
            var relative;

            if (/^\//.test(filePath)) {
                relative = filePath.replace(/^\//, '');
            } else {
                if (mainPath.indexOf(assetAbsolute) !== -1) {
                    relative = path.relative(asset, path.resolve(asset, mainPath, filePath));
                }
            }
            return relative ? (function () {
                var prefix = '';
                //根据文件后缀划分资源类型
                var ext = path.extname(relative);
                if (domain == '/') {
                    prefix = domain;
                } else if (_.indexOf(['.js'], ext) > -1) {
                    prefix = domain['js'] || '/';
                } else if (_.indexOf(['.css'], ext) > -1) {
                    prefix = domain['css'] || '/';
                } else if (_.indexOf(['.jpg', '.jpeg', '.png', '.gif'], ext) > -1) {
                    prefix = domain['img'] || '/';
                } else if (_.indexOf(['eot', 'svg', 'ttf', 'woff'], ext) > -1) {
                    prefix = domain['font'] || '/';
                }
                return content.replace(filePath, url.resolve(prefix, path.join(remotePath, relative)));
            })() : content;
        });

        file.contents = new Buffer(contents);

        this.push(file);
        return callback();
    });
}

/**
 * 路径转化
 * @returns {*}
 */
function absoluteAndDomain() {
    var remotePath = path.join(basePath, projectName);

    var sourceCss = path.join(config.tmp.dir, '/**/*.css');
    var sourceHtml = path.join(config.tmp.dir, '/**/*.html');

    return gulp.src([sourceHtml, sourceCss], {base: config.tmp.dir})
        .pipe(transformPath({
            asset: config.tmp.dir,
            remotePath: remotePath,
            domain: {
                'js': '//j1.58cdn.com.cn',
                'css': '//c.58cdn.com.cn',
                'img': '//img.58cdn.com.cn',
                'font': '//img.58cdn.com.cn/webfonts'
            }
        }))
        .pipe(gulp.dest(config.tmp.dir));
}

exports.absoluteAndDomain = absoluteAndDomain;<commit_msg>fix bug:webfonts transformPath<commit_after>/**
 * 相对路径转为绝对路径，并且添加CDN域名
 * Created by damujiangr on 2016/10/15.
 */
'use strict';

var path = require('path');
var url = require('url');

var gulp = require('gulp');
var gutil = require('gulp-util');
var through = require('through2');
var _ = require('lodash');

var config = require('./../config.json');
var projectName = config['deploy']['projectName'] || process.cwd().split(path.sep).pop();
var basePath = config['deploy']['basePath'];

/**
 *
 * @param options
 *  asset 资源的根路径
 *  remotePath 远程部署路径
 *  domain 域名
 */
function transformPath(options) {
    var contents, mainPath, reg, asset, assetAbsolute, domain, remotePath;

    //资源的路径
    asset = options.asset || process.cwd();
    //远程部署路径的相对路径
    remotePath = options.remotePath || '/';
    //域名
    //1. 为String '/'时，所有相对路径妆化为绝对路径
    //2. 值为Object 时，按照文件类型赋值不同的CDN域名
    domain = options.domain || '/';

    assetAbsolute = path.resolve(asset);

    //匹配正则
    reg = new RegExp('["\'\\(]\\s*([\\w\\_\/\\.\\-]*\\.(jpg|jpeg|png|gif|eot|svg|ttf|woff|js|css))[^\\)"\']*\\s*[\\)"\']', 'gim');

    return through.obj(function (file, enc, callback) {
        if (file.isNull()) {
            this.push(file);
            return callback();
        }

        if (file.isStream()) {
            this.emit('error', gutil.log('Streams are not supported!'));
            return callback();
        }

        mainPath = path.dirname(file.path);

        contents = file.contents.toString().replace(reg, function (content, filePath) {
            var relative;

            if (/^\//.test(filePath)) {
                relative = filePath.replace(/^\//, '');
            } else {
                if (mainPath.indexOf(assetAbsolute) !== -1) {
                    relative = path.relative(asset, path.resolve(asset, mainPath, filePath));
                }
            }
            return relative ? (function () {
                var prefix = '';
                //根据文件后缀划分资源类型
                var ext = path.extname(relative);
                if (domain == '/') {
                    prefix = domain;
                } else if (_.indexOf(['.js'], ext) > -1) {
                    prefix = domain['js'] || '/';
                } else if (_.indexOf(['.css'], ext) > -1) {
                    prefix = domain['css'] || '/';
                } else if (_.indexOf(['.jpg', '.jpeg', '.png', '.gif'], ext) > -1) {
                    prefix = domain['img'] || '/';
                } else if (_.indexOf(['.eot', '.svg', '.ttf', '.woff'], ext) > -1) {
                    prefix = domain['font'] || '/';
                }
                return content.replace(filePath, url.resolve(prefix, path.join(remotePath, relative)));
            })() : content;
        });

        file.contents = new Buffer(contents);

        this.push(file);
        return callback();
    });
}

/**
 * 路径转化
 * @returns {*}
 */
function absoluteAndDomain() {
    var remotePath = path.join(basePath, projectName);

    var sourceCss = path.join(config.tmp.dir, '/**/*.css');
    var sourceHtml = path.join(config.tmp.dir, '/**/*.html');

    return gulp.src([sourceHtml, sourceCss], {base: config.tmp.dir})
        .pipe(transformPath({
            asset: config.tmp.dir,
            remotePath: remotePath,
            domain: {
                'js': '//j1.58cdn.com.cn/',
                'css': '//c.58cdn.com.cn/',
                'img': '//img.58cdn.com.cn/',
                'font': '//img.58cdn.com.cn/webfonts/'
            }
        }))
        .pipe(gulp.dest(config.tmp.dir));
}

exports.absoluteAndDomain = absoluteAndDomain;<|endoftext|>