<commit_before>
var center =  {lat: -29.710173, lng: -53.716594};
var bufsmCurrentLocation =  {lat: -29.710173, lng: -53.716594};
var i;
var pointsRoute = [{lat: -29.710173, lng: -53.716594},
	{lat: -29.705787, lng: -53.715961},
	{lat: -29.705293, lng: -53.715718},
	{lat: -29.705244, lng: -53.716063},
	{lat: -29.705722, lng: -53.716054},
	{lat: -29.709991, lng: -53.716707},
	{lat: -29.710737, lng: -53.716693},
	{lat: -29.711810, lng: -53.716515},
	{lat: -29.712242, lng: -53.719246},
	{lat: -29.715677, lng: -53.718637},
	{lat: -29.715267, lng: -53.715848},
	{lat: -29.716060, lng: -53.715677},
	{lat: -29.719159, lng: -53.715061},
	{lat: -29.719554, lng: -53.717932},
	{lat: -29.721895, lng: -53.717508},
	{lat: -29.722654, lng: -53.723044},
	{lat: -29.729176, lng: -53.721712},
	{lat: -29.728947, lng: -53.719800},
	{lat: -29.730092, lng: -53.719642},
	{lat: -29.728939, lng: -53.719791},
	{lat: -29.728435, lng: -53.716317},
	{lat: -29.725455, lng: -53.716864},
	{lat: -29.725059, lng: -53.714266},
	{lat: -29.724784, lng: -53.712402},
	{lat: -29.724646, lng: -53.710987},
	{lat: -29.722872, lng: -53.711337},
	{lat: -29.720057, lng: -53.711882},
	{lat: -29.720684, lng: -53.716483},
	{lat: -29.719519, lng: -53.716707},
	{lat: -29.719269, lng: -53.715010},
	{lat: -29.716008, lng: -53.715652},
	{lat: -29.715818, lng: -53.715619},
	{lat: -29.712755, lng: -53.716135},
	{lat: -29.710173, lng: -53.716594}];

	var pointsStop = [{lat: -29.711392, lng: -53.716317},
		{lat: -29.709379, lng: -53.716468},
		{lat: -29.706658, lng: -53.716061},
		{lat: -29.706639, lng: -53.716211},
		{lat: -29.709398, lng: -53.716683}];

		var iconMarker;
		var iconBus;
		var busMarker;
		var urlAPI = "http://bufsm-dalmago.rhcloud.com/linha/1";

		//Iniatialize google maps API and go to the IoT portal to update List of things
		function initMap() {
			map = new google.maps.Map(document.getElementById('map'), {center: center, scrollwheel: false, zoom: 17, streetViewControl: false});
			var centerControlDiv = document.createElement('div');
			var centerControl = new CenterControl(centerControlDiv, map);

			centerControlDiv.index = 1;
			map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(centerControlDiv);

			var busPath = new google.maps.Polyline({
				path: pointsRoute,
				geodesic: true,
				strokeColor: '#0000FF',
				strokeOpacity: 1.0,
				strokeWeight: 2
			});
			iconBus = {
				url: "static/img/bufsm2.png", // url
				scaledSize: new google.maps.Size(25, 32), // scaled size
				origin: new google.maps.Point(0,0), // origin
				anchor: new google.maps.Point(0, 0) // anchor
			};
			iconMarker = {
				url: 'static/img/marker.png', // url
				scaledSize: new google.maps.Size(30, 35), // scaled size
				origin: new google.maps.Point(0,0), // origin
				anchor: new google.maps.Point(0, 0) // anchor
			};
			for(i = 0; i<5; i++){
				addBusStop(pointsStop[i]);
			}
			addBus(bufsmCurrentLocation);
			busPath.setMap(map);
			updatePosition();
		}

		function updatePosition(){
			i = 0;
			window.setInterval(function () {
				var data;
				$.get(urlAPI, function(data, status){
					bufsmCurrentLocation.lat = data.lat;
					bufsmCurrentLocation.lng = data.lng;
					console.log(center);
				});
				busMarker.setPosition(bufsmCurrentLocation);
			}, 1000); // repeat forever, polling every 3 seconds
		}
		function addBusStop(location) {
			marker = new google.maps.Marker({
				position: location,
				icon: iconMarker,
				map: map
			});
		}
		function addBus(location) {
			busMarker = new google.maps.Marker({
				position: location,
				icon: iconBus,
				map: map
			});
		}
		function CenterControl(controlDiv, map) {

			// Set CSS for the control border.
			var controlUI = document.createElement('div');
			controlUI.style.backgroundColor = '#fff';
			controlUI.style.border = '2px solid #fff';
			controlUI.style.borderRadius = '3px';
			controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
			controlUI.style.cursor = 'pointer';
			controlUI.style.marginBottom = '22px';
			controlUI.style.textAlign = 'center';
			controlUI.title = 'Click to recenter the map';
			controlDiv.appendChild(controlUI);

			// Set CSS for the control interior.
			var controlText = document.createElement('div');
			controlText.style.color = 'rgb(25,25,25)';
			controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
			controlText.style.fontSize = '16px';
			controlText.style.lineHeight = '38px';
			controlText.style.paddingLeft = '5px';
			controlText.style.paddingRight = '5px';
			controlText.innerHTML = 'BUFSM, cadê tu?';
			controlUI.appendChild(controlText);

			// Setup the click event listeners: simply set the map to Chicago.
			controlUI.addEventListener('click', function() {
				map.setCenter(bufsmCurrentLocation);
			});

		}
<commit_msg>Map Touch<commit_after>
var center =  {lat: -29.710173, lng: -53.716594};
var bufsmCurrentLocation =  {lat: -29.710173, lng: -53.716594};
var i;
var pointsRoute = [{lat: -29.710173, lng: -53.716594},
	{lat: -29.705787, lng: -53.715961},
	{lat: -29.705293, lng: -53.715718},
	{lat: -29.705244, lng: -53.716063},
	{lat: -29.705722, lng: -53.716054},
	{lat: -29.709991, lng: -53.716707},
	{lat: -29.710737, lng: -53.716693},
	{lat: -29.711810, lng: -53.716515},
	{lat: -29.712242, lng: -53.719246},
	{lat: -29.715677, lng: -53.718637},
	{lat: -29.715267, lng: -53.715848},
	{lat: -29.716060, lng: -53.715677},
	{lat: -29.719159, lng: -53.715061},
	{lat: -29.719554, lng: -53.717932},
	{lat: -29.721895, lng: -53.717508},
	{lat: -29.722654, lng: -53.723044},
	{lat: -29.729176, lng: -53.721712},
	{lat: -29.728947, lng: -53.719800},
	{lat: -29.730092, lng: -53.719642},
	{lat: -29.728939, lng: -53.719791},
	{lat: -29.728435, lng: -53.716317},
	{lat: -29.725455, lng: -53.716864},
	{lat: -29.725059, lng: -53.714266},
	{lat: -29.724784, lng: -53.712402},
	{lat: -29.724646, lng: -53.710987},
	{lat: -29.722872, lng: -53.711337},
	{lat: -29.720057, lng: -53.711882},
	{lat: -29.720684, lng: -53.716483},
	{lat: -29.719519, lng: -53.716707},
	{lat: -29.719269, lng: -53.715010},
	{lat: -29.716008, lng: -53.715652},
	{lat: -29.715818, lng: -53.715619},
	{lat: -29.712755, lng: -53.716135},
	{lat: -29.710173, lng: -53.716594}];

	var pointsStop = [{lat: -29.711392, lng: -53.716317},
		{lat: -29.709379, lng: -53.716468},
		{lat: -29.706658, lng: -53.716061},
		{lat: -29.706639, lng: -53.716211},
		{lat: -29.709398, lng: -53.716683}];

		var iconMarker;
		var iconBus;
		var busMarker;
		var urlAPI = "http://bufsm-dalmago.rhcloud.com/linha/1";

		//Iniatialize google maps API and go to the IoT portal to update List of things
		function initMap() {
			map = new google.maps.Map(document.getElementById('map'), {center: center,fullscreenControl: true, gestureHandling: 'greedy', scrollwheel: false, zoom: 17, streetViewControl: false});
			var centerControlDiv = document.createElement('div');
			var centerControl = new CenterControl(centerControlDiv, map);

			centerControlDiv.index = 1;
			map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(centerControlDiv);

			var busPath = new google.maps.Polyline({
				path: pointsRoute,
				geodesic: true,
				strokeColor: '#0000FF',
				strokeOpacity: 1.0,
				strokeWeight: 2
			});
			iconBus = {
				url: "static/img/bufsm2.png", // url
				scaledSize: new google.maps.Size(25, 32), // scaled size
				origin: new google.maps.Point(0,0), // origin
				anchor: new google.maps.Point(0, 0) // anchor
			};
			iconMarker = {
				url: 'static/img/marker.png', // url
				scaledSize: new google.maps.Size(30, 35), // scaled size
				origin: new google.maps.Point(0,0), // origin
				anchor: new google.maps.Point(0, 0) // anchor
			};
			for(i = 0; i<5; i++){
				addBusStop(pointsStop[i]);
			}
			addBus(bufsmCurrentLocation);
			busPath.setMap(map);
			updatePosition();
		}

		function updatePosition(){
			i = 0;
			window.setInterval(function () {
				var data;
				$.get(urlAPI, function(data, status){
					bufsmCurrentLocation.lat = data.lat;
					bufsmCurrentLocation.lng = data.lng;
					console.log(center);
				});
				busMarker.setPosition(bufsmCurrentLocation);
			}, 1000); // repeat forever, polling every 3 seconds
		}
		function addBusStop(location) {
			marker = new google.maps.Marker({
				position: location,
				icon: iconMarker,
				map: map
			});
		}
		function addBus(location) {
			busMarker = new google.maps.Marker({
				position: location,
				icon: iconBus,
				map: map
			});
		}
		function CenterControl(controlDiv, map) {

			// Set CSS for the control border.
			var controlUI = document.createElement('div');
			controlUI.style.backgroundColor = '#fff';
			controlUI.style.border = '2px solid #fff';
			controlUI.style.borderRadius = '3px';
			controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
			controlUI.style.cursor = 'pointer';
			controlUI.style.marginBottom = '22px';
			controlUI.style.textAlign = 'center';
			controlUI.title = 'Click to recenter the map';
			controlDiv.appendChild(controlUI);

			// Set CSS for the control interior.
			var controlText = document.createElement('div');
			controlText.style.color = 'rgb(25,25,25)';
			controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
			controlText.style.fontSize = '16px';
			controlText.style.lineHeight = '38px';
			controlText.style.paddingLeft = '5px';
			controlText.style.paddingRight = '5px';
			controlText.innerHTML = 'BUFSM, cadê tu?';
			controlUI.appendChild(controlText);

			// Setup the click event listeners: simply set the map to Chicago.
			controlUI.addEventListener('click', function() {
				map.setCenter(bufsmCurrentLocation);
			});

		}
<|endoftext|>


<commit_before>var searchify_controller;

function searchify(facets) {
  searchify_controller = new Searchify(facets);
}

function searchify_submit() {
  $('#searchify select.searchify_facets').attr('disabled', 'disabled');
  return true;
}

function searchify_change_facet(element) {
  searchify_controller.change_facet(element);
}

function searchify_add_row() {
  searchify_controller.add_row();
}

function searchify_remove_row(index) {
  searchify_controller.remove_row(index);
}

var Searchify = function(facets) {
  this.init(facets);
}
$.extend(Searchify.prototype, {
  init: function(facets) {
    this.facets = facets;
    this.rows = new Array();
    this.build_initial_rows();
    $('#searchify').html(this.to_html());
  },

  to_html: function() {
    return "
" + $.map(this.rows, function(row, i) { return row.to_html() }).join('') + "
add";
  },

  get_params: function() {
    var result = new Array();
    var pairs = top.location.search.substring(1).split(/\&/);
    var self = this;
    $.each(pairs, function(index, pair) {
      var name_value = pair.split(/\=/);
      if (name_value.length == 2) {
        result.push([self.decode_url(name_value[0]), self.decode_url(name_value[1])]);
      }
    });
    return result;
  },

  decode_url: function(string) {
    return unescape(string.replace(/\+/g,"%20"));
  },

  build_initial_rows: function() {
    this.build_rows_from_params();
    if (this.rows.length == 0) {
      this.rows.push(this.default_row());
    }
  },

  default_row: function() {
    return new SearchifyRow(this, this.facets[0], false);
  },

  build_rows_from_params: function() {
    var self = this;
    $.each(this.get_params(), function(index, param) {
      facet = self.facet_with_name(param[0]);
      if (facet) {
        row = self.row_from_facet(facet);
        row.add_value(param[0], param[1]);
      }
    });
  },

  row_from_facet: function(facet) {
    for (var i=0; i<this.rows.length; ++i ) {
      if (this.rows[i].facet.name == facet.name) {
        return this.rows[i];
      }
    };
    var row = new SearchifyRow(this, facet);
    this.rows.push(row)
    return row;
  },

  index_of_row: function(row) {
    return this.rows.indexOf(row);
  },

  change_facet: function(element) {
    var index = element.id.split('_')[2];
    this.rows[index].change_facet(this.facet_with_name(element.value));
  },

  facet_with_name: function(name) {
    for (var i=0; i<this.facets.length; ++i ) {
      if (this.facets[i].name == name || name.indexOf(this.facets[i].name + '_') == 0) {
        return this.facets[i];
      }
    }
  },

  add_row: function() {
    var row = this.default_row();
    this.rows.push(row);
    $('#searchify_rows').append(row.to_html());
  },

  remove_row: function(index) {
    this.rows.splice(index, 1);
    $('#searchify_row_' + index).remove();
  }
});

var SearchifyRow = function(owner, facet) {
  this.init(owner, facet);
}
$.extend(SearchifyRow.prototype, {
  init: function(owner, facet) {
    this.owner = owner;
    this.facet = facet;
    this.values = {};
  },

  add_value: function(name, value) {
    this.values[this.strip_name(name)] = value;
  },

  strip_name: function(name) {
    if (name == this.facet.name) {
      return '';
    } else {
      return name.replace(this.facet.name + '_', '');
    }
  },

  to_html: function() {
    return "
" + this.facets_field() + " " + this.value_field()+ " " + this.remove_link() + "
";
  },

  remove_link: function() {
    return "remove";
  },

  facets_field: function() {
    return "<select class='searchify_facets' size='1' id='" + this.facets_field_id() + "' onchange='searchify_change_facet(this)'>" + this.facet_options() + "</select>";
  },

  facets_field_id: function() {
    return "searchify_facets_" + this.index();
  },

  value_field_id: function() {
    return "searchify_value_" + this.index();
  },

  facet_options: function() {
    var options = this.owner.facets.map(function(facet) {
      console.log(facet)
      return [facet.display, facet.name];
    });
    return this.select_menu_options(options, this.facet.name);
  },

  value_field: function() {
    return "" + this.value_field_for_type(this.facet.type) + "";
  },

  value_field_for_type: function(type) {
    if (type == "text" || type == "string") {
      return this.text_field('', 24);
    } else if (type == "date" || type == "datetime") {
      return this.text_field('from', 10) + " - " + this.text_field('to', 10);
    } else if (type == "integer" || type == "float" || type == "decimal") {
      return this.operator_menu() + " " + this.text_field('', 8);
    } else if (type == "boolean") {
      return this.boolean_menu();
    }
  },

  text_field: function(name, size) {
    return "<input type='text' name='" + this.make_name(name) + "' value='" + this.escaped_value(name) + "' size='" + size + "' />";
  },

  boolean_menu: function() {
    return this.select_menu('', [['Any', '%'], ['Yes', '1'], ['No', '0']]);
  },

  operator_menu: function() {
    return this.select_menu('operator', [['Equal', '='], ['Less Than', '<='], ['Greater Than', '>=']]);
  },

  select_menu: function(name, options) {
    return "<select size='1' name='" + this.make_name(name) + "'>" + this.select_menu_options(options, this.escaped_value(name)) + "</select>";
  },

  select_menu_options: function(options, selected) {
    var self = this;
    return $.map(options, function(option, index) {
      return "<option value='" + option[1] + "'" + self.selected_option(option[1], selected) + ">" + option[0] + "</option>";
    }).join('');
  },

  selected_option: function(option_value, selected_value) {
    if (option_value == selected_value) {
      return " selected='selected'";
    } else {
      return '';
    }
  },

  make_name: function(suffix) {
    if (suffix == '') {
      return this.facet.name;
    } else {
      return this.facet.name + '_' + suffix;
    }
  },

  index: function() {
    return this.owner.index_of_row(this);
  },

  change_facet: function(new_facet) {
    this.facet = new_facet;
    $("#" + this.value_field_id()).html(this.value_field());
  },

  escaped_value: function(name) {
    var value = this.values[name] || '';
    return value.replace(/\"/g, '"').replace(/\'/g, "'");
  }
});
<commit_msg>removing console.log statement<commit_after>var searchify_controller;

function searchify(facets) {
  searchify_controller = new Searchify(facets);
}

function searchify_submit() {
  $('#searchify select.searchify_facets').attr('disabled', 'disabled');
  return true;
}

function searchify_change_facet(element) {
  searchify_controller.change_facet(element);
}

function searchify_add_row() {
  searchify_controller.add_row();
}

function searchify_remove_row(index) {
  searchify_controller.remove_row(index);
}

var Searchify = function(facets) {
  this.init(facets);
}
$.extend(Searchify.prototype, {
  init: function(facets) {
    this.facets = facets;
    this.rows = new Array();
    this.build_initial_rows();
    $('#searchify').html(this.to_html());
  },

  to_html: function() {
    return "
" + $.map(this.rows, function(row, i) { return row.to_html() }).join('') + "
add";
  },

  get_params: function() {
    var result = new Array();
    var pairs = top.location.search.substring(1).split(/\&/);
    var self = this;
    $.each(pairs, function(index, pair) {
      var name_value = pair.split(/\=/);
      if (name_value.length == 2) {
        result.push([self.decode_url(name_value[0]), self.decode_url(name_value[1])]);
      }
    });
    return result;
  },

  decode_url: function(string) {
    return unescape(string.replace(/\+/g,"%20"));
  },

  build_initial_rows: function() {
    this.build_rows_from_params();
    if (this.rows.length == 0) {
      this.rows.push(this.default_row());
    }
  },

  default_row: function() {
    return new SearchifyRow(this, this.facets[0], false);
  },

  build_rows_from_params: function() {
    var self = this;
    $.each(this.get_params(), function(index, param) {
      facet = self.facet_with_name(param[0]);
      if (facet) {
        row = self.row_from_facet(facet);
        row.add_value(param[0], param[1]);
      }
    });
  },

  row_from_facet: function(facet) {
    for (var i=0; i<this.rows.length; ++i ) {
      if (this.rows[i].facet.name == facet.name) {
        return this.rows[i];
      }
    };
    var row = new SearchifyRow(this, facet);
    this.rows.push(row)
    return row;
  },

  index_of_row: function(row) {
    return this.rows.indexOf(row);
  },

  change_facet: function(element) {
    var index = element.id.split('_')[2];
    this.rows[index].change_facet(this.facet_with_name(element.value));
  },

  facet_with_name: function(name) {
    for (var i=0; i<this.facets.length; ++i ) {
      if (this.facets[i].name == name || name.indexOf(this.facets[i].name + '_') == 0) {
        return this.facets[i];
      }
    }
  },

  add_row: function() {
    var row = this.default_row();
    this.rows.push(row);
    $('#searchify_rows').append(row.to_html());
  },

  remove_row: function(index) {
    this.rows.splice(index, 1);
    $('#searchify_row_' + index).remove();
  }
});

var SearchifyRow = function(owner, facet) {
  this.init(owner, facet);
}
$.extend(SearchifyRow.prototype, {
  init: function(owner, facet) {
    this.owner = owner;
    this.facet = facet;
    this.values = {};
  },

  add_value: function(name, value) {
    this.values[this.strip_name(name)] = value;
  },

  strip_name: function(name) {
    if (name == this.facet.name) {
      return '';
    } else {
      return name.replace(this.facet.name + '_', '');
    }
  },

  to_html: function() {
    return "
" + this.facets_field() + " " + this.value_field()+ " " + this.remove_link() + "
";
  },

  remove_link: function() {
    return "remove";
  },

  facets_field: function() {
    return "<select class='searchify_facets' size='1' id='" + this.facets_field_id() + "' onchange='searchify_change_facet(this)'>" + this.facet_options() + "</select>";
  },

  facets_field_id: function() {
    return "searchify_facets_" + this.index();
  },

  value_field_id: function() {
    return "searchify_value_" + this.index();
  },

  facet_options: function() {
    var options = this.owner.facets.map(function(facet) {
      return [facet.display, facet.name];
    });
    return this.select_menu_options(options, this.facet.name);
  },

  value_field: function() {
    return "" + this.value_field_for_type(this.facet.type) + "";
  },

  value_field_for_type: function(type) {
    if (type == "text" || type == "string") {
      return this.text_field('', 24);
    } else if (type == "date" || type == "datetime") {
      return this.text_field('from', 10) + " - " + this.text_field('to', 10);
    } else if (type == "integer" || type == "float" || type == "decimal") {
      return this.operator_menu() + " " + this.text_field('', 8);
    } else if (type == "boolean") {
      return this.boolean_menu();
    }
  },

  text_field: function(name, size) {
    return "<input type='text' name='" + this.make_name(name) + "' value='" + this.escaped_value(name) + "' size='" + size + "' />";
  },

  boolean_menu: function() {
    return this.select_menu('', [['Any', '%'], ['Yes', '1'], ['No', '0']]);
  },

  operator_menu: function() {
    return this.select_menu('operator', [['Equal', '='], ['Less Than', '<='], ['Greater Than', '>=']]);
  },

  select_menu: function(name, options) {
    return "<select size='1' name='" + this.make_name(name) + "'>" + this.select_menu_options(options, this.escaped_value(name)) + "</select>";
  },

  select_menu_options: function(options, selected) {
    var self = this;
    return $.map(options, function(option, index) {
      return "<option value='" + option[1] + "'" + self.selected_option(option[1], selected) + ">" + option[0] + "</option>";
    }).join('');
  },

  selected_option: function(option_value, selected_value) {
    if (option_value == selected_value) {
      return " selected='selected'";
    } else {
      return '';
    }
  },

  make_name: function(suffix) {
    if (suffix == '') {
      return this.facet.name;
    } else {
      return this.facet.name + '_' + suffix;
    }
  },

  index: function() {
    return this.owner.index_of_row(this);
  },

  change_facet: function(new_facet) {
    this.facet = new_facet;
    $("#" + this.value_field_id()).html(this.value_field());
  },

  escaped_value: function(name) {
    var value = this.values[name] || '';
    return value.replace(/\"/g, '"').replace(/\'/g, "'");
  }
});
<|endoftext|>


<commit_before>import React from 'react'
import { findDOMNode } from 'react-dom'
import cx from 'classnames'
import { isEmpty } from 'lodash'
import { VelocityTransitionGroup } from 'velocity-react'
import { position } from '../util/scrolling'
import { findChildLink, dispatchEvent } from '../util'
import { KeyControlledList } from './KeyControlledList'
const { array, bool, func, object, string } = React.PropTypes

const DROPDOWN_OPENED = 'dropdown-opened'

export default class Dropdown extends React.Component {
  constructor (props) {
    super(props)
    this.state = {neverOpened: true}
  }

  static propTypes = {
    children: array,
    id: string,
    className: string,
    alignRight: bool,
    toggleChildren: object.isRequired,
    onFirstOpen: func,
    backdrop: bool,
    triangle: bool,
    openOnHover: bool,
    rivalrous: string,
    keyControlled: bool
  }

  static contextTypes = {
    isMobile: bool
  }

  toggle = (event, context) => {
    const { active } = this.state
    this.setState({active: !active})
    if (active) {
      this.setState({hoverOpened: false})
    } else {
      this.refs.parent.focus()
      if (context === 'hover') {
        this.setState({hoverOpened: true})
      }
      if (this.state.neverOpened) {
        this.setState({neverOpened: false})
        if (this.props.onFirstOpen) this.props.onFirstOpen()
      }
      if (this.props.rivalrous) {
        window.dispatchEvent(new window.CustomEvent(DROPDOWN_OPENED, {
          detail: {name: this.props.rivalrous}
        }))
      }
    }
    if (event) {
      event.stopPropagation()
      event.preventDefault()
    }
  }

  hide = () => {
    if (this.state.active) this.setState({active: false})
    return true
  }

  rivalrousHide = event => {
    if (event.detail.name === this.props.rivalrous) {
      return this.hide()
    }
  }

  componentDidMount () {
    window.addEventListener('click', this.hide)
    if (this.props.rivalrous) {
      window.addEventListener(DROPDOWN_OPENED, this.rivalrousHide)
    }
  }

  componentWillUnmount () {
    window.removeEventListener('click', this.hide)
    if (this.props.rivalrous) {
      window.removeEventListener(DROPDOWN_OPENED, this.rivalrousHide)
    }
  }

  handleKeys = event => {
    if (this.refs.list) this.refs.list.handleKeys(event)
  }

  chooseChild = choice => {
    const link = findChildLink(findDOMNode(this.refs[choice.ref]))
    dispatchEvent(link, 'click')
  }

  render () {
    const {
      toggleChildren, children, alignRight, backdrop, triangle, openOnHover, id,
      keyControlled
    } = this.props
    const { hoverOpened } = this.state
    const { isMobile } = this.context
    const active = this.state.active && !isEmpty(children)
    const className = cx('dropdown', this.props.className,
      {active, 'has-triangle': triangle})
    const ulProps = {
      className: cx('dropdown-menu', {'dropdown-menu-right': alignRight}),
      style: mobileMenuStyle(isMobile && active, this.refs.parent),
      onClick: () => this.toggle(),
      onMouseLeave: () => hoverOpened && this.toggle()
    }

    // adding refs to the children so that we can get the node in chooseChild above
    const childrenWithRefs = React.Children.map(children,
      (element, idx) => {
        return element && element.props
          ? React.cloneElement(element, {ref: idx})
          : element
      })

    const items = triangle
      ? [
]
        .concat(childrenWithRefs)
      : childrenWithRefs

    return

       openOnHover && this.toggle(ev, 'hover')}>
        {toggleChildren}

      {keyControlled
        ? <KeyControlledList ref='list' {...ulProps} onChange={this.chooseChild}>
            {items}
          </KeyControlledList>
        :

            {active && items}

      }
      <VelocityTransitionGroup
        enter={{animation: 'fadeIn', duration: 100}}
        leave={{animation: 'fadeOut', duration: 100}}>
        {(backdrop || isMobile) && active && }
      </VelocityTransitionGroup>

  }
}

const margin = 10

const mobileMenuStyle = (shouldUse, parent) => {
  if (!shouldUse) return {}
  return {
    left: findLeftPos(parent) + margin,
    width: document.documentElement.clientWidth - margin * 2
  }
}

const findLeftPos = parent => parent ? -position(parent).x : null

const findTriangleLeftPos = (isMobile, parent) => {
  if (!isMobile || !parent) return
  return position(parent).x + parent.offsetWidth / 2 - margin - 1
}
<commit_msg>make tabIndex settable<commit_after>import React from 'react'
import { findDOMNode } from 'react-dom'
import cx from 'classnames'
import { isEmpty } from 'lodash'
import { VelocityTransitionGroup } from 'velocity-react'
import { position } from '../util/scrolling'
import { findChildLink, dispatchEvent } from '../util'
import { KeyControlledList } from './KeyControlledList'
const { array, bool, func, object, string, number } = React.PropTypes

const DROPDOWN_OPENED = 'dropdown-opened'

export default class Dropdown extends React.Component {
  constructor (props) {
    super(props)
    this.state = {neverOpened: true}
  }

  static propTypes = {
    children: array,
    id: string,
    className: string,
    alignRight: bool,
    toggleChildren: object.isRequired,
    onFirstOpen: func,
    backdrop: bool,
    triangle: bool,
    openOnHover: bool,
    rivalrous: string,
    keyControlled: bool,
    tabIndex: number
  }

  static defaultProps = {
    tabIndex: 99
  }

  static contextTypes = {
    isMobile: bool
  }

  toggle = (event, context) => {
    const { active } = this.state
    this.setState({active: !active})
    if (active) {
      this.setState({hoverOpened: false})
    } else {
      this.refs.parent.focus()
      if (context === 'hover') {
        this.setState({hoverOpened: true})
      }
      if (this.state.neverOpened) {
        this.setState({neverOpened: false})
        if (this.props.onFirstOpen) this.props.onFirstOpen()
      }
      if (this.props.rivalrous) {
        window.dispatchEvent(new window.CustomEvent(DROPDOWN_OPENED, {
          detail: {name: this.props.rivalrous}
        }))
      }
    }
    if (event) {
      event.stopPropagation()
      event.preventDefault()
    }
  }

  hide = () => {
    if (this.state.active) this.setState({active: false})
    return true
  }

  rivalrousHide = event => {
    if (event.detail.name === this.props.rivalrous) {
      return this.hide()
    }
  }

  componentDidMount () {
    window.addEventListener('click', this.hide)
    if (this.props.rivalrous) {
      window.addEventListener(DROPDOWN_OPENED, this.rivalrousHide)
    }
  }

  componentWillUnmount () {
    window.removeEventListener('click', this.hide)
    if (this.props.rivalrous) {
      window.removeEventListener(DROPDOWN_OPENED, this.rivalrousHide)
    }
  }

  handleKeys = event => {
    if (this.refs.list) this.refs.list.handleKeys(event)
  }

  chooseChild = choice => {
    const link = findChildLink(findDOMNode(this.refs[choice.ref]))
    dispatchEvent(link, 'click')
  }

  render () {
    const {
      toggleChildren, children, alignRight, backdrop, triangle, openOnHover, id,
      keyControlled, tabIndex
    } = this.props
    const { hoverOpened } = this.state
    const { isMobile } = this.context
    const active = this.state.active && !isEmpty(children)
    const className = cx('dropdown', this.props.className,
      {active, 'has-triangle': triangle})
    const ulProps = {
      className: cx('dropdown-menu', {'dropdown-menu-right': alignRight}),
      style: mobileMenuStyle(isMobile && active, this.refs.parent),
      onClick: () => this.toggle(),
      onMouseLeave: () => hoverOpened && this.toggle()
    }

    // adding refs to the children so that we can get the node in chooseChild above
    const childrenWithRefs = keyControlled
      ? React.Children.map(children,
        (element, idx) => {
          return element && element.props
            ? React.cloneElement(element, {ref: idx})
            : element
        })
      : children

    const items = triangle
      ? [
]
        .concat(childrenWithRefs)
      : childrenWithRefs

    return

       openOnHover && this.toggle(ev, 'hover')}>
        {toggleChildren}

      {keyControlled
        ? <KeyControlledList ref='list' {...ulProps} onChange={this.chooseChild}>
            {items}
          </KeyControlledList>
        :

            {active && items}

      }
      <VelocityTransitionGroup
        enter={{animation: 'fadeIn', duration: 100}}
        leave={{animation: 'fadeOut', duration: 100}}>
        {(backdrop || isMobile) && active && }
      </VelocityTransitionGroup>

  }
}

const margin = 10

const mobileMenuStyle = (shouldUse, parent) => {
  if (!shouldUse) return {}
  return {
    left: findLeftPos(parent) + margin,
    width: document.documentElement.clientWidth - margin * 2
  }
}

const findLeftPos = parent => parent ? -position(parent).x : null

const findTriangleLeftPos = (isMobile, parent) => {
  if (!isMobile || !parent) return
  return position(parent).x + parent.offsetWidth / 2 - margin - 1
}
<|endoftext|>


<commit_before>'use strict';

var SETS = 'dataType';
var LABELS = 'bindingsCount';
var VALUES = 'scriptTime';
var FILTERS = [{
  key: 'dataSize',
  value: function (val) {
    return val === 5;
  }
}];
var DIR_NAME = './log/';
var CHART_DIR = './charts/';
var RenderData = require('./RenderData');
var Filter = require('./Filter');
var FilterRule = require('./FilterRule');
var ChartRenderer = require('./ChartRenderer');

var dataFilter = new Filter(FILTERS.map(function (f) {
  return new FilterRule(f.key, f.value);
}));

var fs = require('fs');
var path = require('path');
var files = fs.readdirSync(DIR_NAME);

files = files.filter(function (f) {
  return fs.statSync(path.join(DIR_NAME, f)).isFile();
});

// Elegant but not efficient, requires memory...
var logs = files.map(function (file) {
  return require('./' + path.join(DIR_NAME, file));
}).filter(function (data) {
  return dataFilter.filter(data.description.description);
});

var renderData = new RenderData(SETS, LABELS, VALUES);
renderData.process(logs);
var data = renderData.aggregate();
var labels = data[0].labels;

var chart = ChartRenderer.generate(labels, data);
var filters = FILTERS.map(function (f) {
  return f.key;
}).join('-');

ChartRenderer.save(chart, path.join(CHART_DIR) + filters + '.png');
<commit_msg>Update the log parser<commit_after>'use strict';

var SETS = 'dataType';
var LABELS = 'bindingsCount';
var VALUES = 'scriptTime';
var FILTERS = [{
  key: 'dataSize',
  value: function (val) {
    return val === 5;
  }
}];
var DIR_NAME = './log/';
var CHART_DIR = './charts/';
var RenderData = require('./lib/RenderData');
var Filter = require('./lib/Filter');
var FilterRule = require('./lib/FilterRule');
var ChartRenderer = require('./lib/ChartRenderer');

var dataFilter = new Filter(FILTERS.map(function (f) {
  return new FilterRule(f.key, f.value);
}));

var fs = require('fs');
var path = require('path');
var files = fs.readdirSync(DIR_NAME);

files = files.filter(function (f) {
  return fs.statSync(path.join(DIR_NAME, f)).isFile();
});

// Elegant but not efficient, requires memory...
var logs = files.map(function (file) {
  return require('./' + path.join(DIR_NAME, file));
}).filter(function (data) {
  return dataFilter.filter(data.description.description);
});

var renderData = new RenderData(SETS, LABELS, VALUES);
renderData.process(logs);
var data = renderData.aggregate();
var labels = data[0].labels;

var chart = ChartRenderer.generate(labels, data);
var filters = FILTERS.map(function (f) {
  return f.key;
}).join('-');

ChartRenderer.save(chart, path.join(CHART_DIR) + filters + '.png');
<|endoftext|>


<commit_before>Package.describe({
  summary: "Simple templates to add login widgets to an app."
});

Package.on_use(function (api) {
  api.use('accounts-ui-unstyled', 'client');
  api.use('less', 'server');

  api.add_files(['login_buttons.less'], 'client');
});
<commit_msg>accounts-ui: use correct 'where' in package.js.<commit_after>Package.describe({
  summary: "Simple templates to add login widgets to an app."
});

Package.on_use(function (api) {
  api.use('accounts-ui-unstyled', 'client');
  api.use('less', 'client');

  api.add_files(['login_buttons.less'], 'client');
});
<|endoftext|>


<commit_before>const config = require("../../config.json");
const { isMod } = require("../../util");

exports.run = async function (message, args, bot, db, showOnlyNew) {
  db.query(
    "SELECT * FROM trivia_questions WHERE id = ?",
    [args],
    function (err, rows) {
      if (rows[0] == null) {
        message.reply("That question does not exist.");
        return;
      }
      if (
        rows[0].user !== message.author.id &&
        message.author.id !== config.botAdminUserId
      ) {
        message.reply("You do not have permission to view these answers.");
        return;
      }
      getAnswerList(message, rows[0], showOnlyNew, bot, db);
    }
  );
};

async function getAnswerList(message, questionRow, showOnlyNew, bot, db) {
  let id = questionRow.id;
  let question = questionRow.question;
  let questionAsker = questionRow.user;
  let query =
    "SELECT user, answer FROM trivia_answers WHERE questionid = ? ORDER BY id";
  if (showOnlyNew) {
    query =
      "SELECT user, answer FROM trivia_answers WHERE questionid = ? AND viewed = 0 ORDER BY id";
  }
  const questionStatus = questionRow.isopen ? "Open" : "Closed";
  db.query(query, [id], async function (err, rows) {
    let responseMessages = [];
    let response =
      "**Answers for question #" +
      id +
      ": " +
      question +
      " (" +
      questionStatus +
      ")**\n";
    for (let i = 0; i < rows.length; i++) {
      let answer = rows[i].answer;
      let user = await bot.users.fetch(rows[i].user);
      let username = user ? "@" + user.tag : "Unknown " + rows[i].user;
      let answerEntry = "**" + username + "**\n" + answer + "\n\n";
      if (response.length + answerEntry > 4000) {
        responseMessages.push(response);
        response = "";
      }
      response += answerEntry;
    }
    responseMessages.push(response);
    const url = config.baseUrl + "question_tool.php?key=" + questionRow.web_key;
    if (message.author.id === questionAsker) {
      db.query("UPDATE trivia_answers SET viewed=1 WHERE questionid = ?", [id]);
    }
    const total = responseMessages.length;
    for (let i = 0; i < responseMessages.length; i++) {
      const part = i + 1;
      message.channel.send({
        embeds: [
          {
            title: "Answers part" + part + "/" + total,
            url: url,
            description: responseMessages[i],
          },
        ],
      });
    }
  });
}
<commit_msg>award tool link label<commit_after>const config = require("../../config.json");
const { isMod } = require("../../util");

exports.run = async function (message, args, bot, db, showOnlyNew) {
  db.query(
    "SELECT * FROM trivia_questions WHERE id = ?",
    [args],
    function (err, rows) {
      if (rows[0] == null) {
        message.reply("That question does not exist.");
        return;
      }
      if (
        rows[0].user !== message.author.id &&
        message.author.id !== config.botAdminUserId
      ) {
        message.reply("You do not have permission to view these answers.");
        return;
      }
      getAnswerList(message, rows[0], showOnlyNew, bot, db);
    }
  );
};

async function getAnswerList(message, questionRow, showOnlyNew, bot, db) {
  let id = questionRow.id;
  let question = questionRow.question;
  let questionAsker = questionRow.user;
  let query =
    "SELECT user, answer FROM trivia_answers WHERE questionid = ? ORDER BY id";
  if (showOnlyNew) {
    query =
      "SELECT user, answer FROM trivia_answers WHERE questionid = ? AND viewed = 0 ORDER BY id";
  }
  const questionStatus = questionRow.isopen ? "Open" : "Closed";
  db.query(query, [id], async function (err, rows) {
    let responseMessages = [];
    let response =
      "**Answers for question #" +
      id +
      ": " +
      question +
      " (" +
      questionStatus +
      ")**\n";
    for (let i = 0; i < rows.length; i++) {
      let answer = rows[i].answer;
      let user = await bot.users.fetch(rows[i].user);
      let username = user ? "@" + user.tag : "Unknown " + rows[i].user;
      let answerEntry = "**" + username + "**\n" + answer + "\n\n";
      if (response.length + answerEntry > 4000) {
        responseMessages.push(response);
        response = "";
      }
      response += answerEntry;
    }
    responseMessages.push(response);
    const url = config.baseUrl + "question_tool.php?key=" + questionRow.web_key;
    if (message.author.id === questionAsker) {
      db.query("UPDATE trivia_answers SET viewed=1 WHERE questionid = ?", [id]);
    }
    const total = responseMessages.length;
    for (let i = 0; i < responseMessages.length; i++) {
      const part = i + 1;
      message.channel.send({
        embeds: [
          {
            title:
              "Answers part " + part + "/" + total + " (click for award tool)",
            url: url,
            description: responseMessages[i],
          },
        ],
      });
    }
  });
}
<|endoftext|>


<commit_before>// For an introduction to the Navigation template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232506
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var nav = WinJS.Navigation;

    app.addEventListener("activated", function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }

            if (app.sessionState.history) {
                nav.history = app.sessionState.history;
            }
            args.setPromise(WinJS.UI.processAll().then(function () {
                if (nav.location) {
                    nav.history.current.initialPlaceholder = true;
                    return nav.navigate(nav.location, nav.state);
                } else {
                    return nav.navigate(Application.navigator.home);
                }
            }));
        }
    });

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. If you need to
        // complete an asynchronous operation before your application is
        // suspended, call args.setPromise().
        app.sessionState.history = nav.history;
    };

    app.start();
})();
<commit_msg>Small bug<commit_after>// For an introduction to the Navigation template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232506
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
    var nav = WinJS.Navigation;

    app.addEventListener("activated", function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }

            var shareImageHandler = function (event) {
                var dataRequest = event.request;

                dataRequest.data.properties.title = "Duck Enterprises Logo";
                dataRequest.data.properties.description = "The Logo of Duck Enterprises";
                dataRequest.data.properties.thumbnail =
                    Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(
                        new Windows.Foundation.Uri("ms-appx:///images/duck-logo-thumbnail.bmp")
                    );

                var bitmapStream =
                    Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(
                        new Windows.Foundation.Uri("ms-appx:///images/duck-logo.bmp")
                    );

                dataRequest.data.setBitmap(bitmapStream);
            };

            dataTransferManager.addEventListener("datarequested", shareImageHandler);

            if (app.sessionState.history) {
                nav.history = app.sessionState.history;
            }
            args.setPromise(WinJS.UI.processAll().then(function () {
                WinJS.Application.onsettings = function(e) {
                    e.detail.applicationcommands = {
                         "searchOptions": {
                             title: "Search Options",
                             href: "/pages/settings/searchOptions.html"
                         }
                    };
                    WinJS.UI.SettingsFlyout.populateSettings(e);
                };

                if (nav.location) {
                    nav.history.current.initialPlaceholder = true;
                    return nav.navigate(nav.location, nav.state);
                } else {
                    return nav.navigate(Application.navigator.home);
                }
            }));
        }
    });

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. If you need to
        // complete an asynchronous operation before your application is
        // suspended, call args.setPromise().
        app.sessionState.history = nav.history;
    };

    app.start();
})();
<|endoftext|>


<commit_before>import R from 'ramda';
import fs from 'fs-extra';
import fsPath from 'path';
import jsYaml from 'js-yaml';
import { isBlank } from 'js-util';
import { rootModulePath } from './paths';

const ROOT_PATH = rootModulePath();

const formatPath = (path) => {
  if (!R.is(String, path)) { return path; }
  return path.startsWith('.')
    ? fsPath.join(ROOT_PATH, path)
    : path;
};

/**
 * Parses the given YAML text into a config object.
 * @param {String} text: The raw YAML to parse.
 * @return {Object} config.
 */
export const parse = (text) => {
  // Parse the YAML.
  let yaml;
  try {
    yaml = jsYaml.safeLoad(text) || {};
  } catch (err) {
    throw new Error(`The [.uiharness.yml] file is invalid. ${ err.message }`);
  }

  // Format paths.
  yaml.entry = R.is(String, yaml.entry) ? yaml.entry : "./src/specs";
  yaml.entry = formatPath(yaml.entry);
  if (yaml.graphqlSchema) {
    yaml.graphqlSchema = formatPath(yaml.graphqlSchema);
  }

  // Finish up.
  return yaml;
};

/**
 * Loads and parses the YAML file at the given location.
 *
 * @param {String} path:  Optional. The path to the YAML config file to load.
 *                        If not specified a path to [.uiharness.yml] in the root
 *                        of the project is used.
 *
 * @return {Object} config OR undefined if the file does not exist.
 */
export const load = (path) => {
  // Setup initial conditions.
  path = isBlank(path) ? fsPath.join(ROOT_PATH, '.uiharness.yml') : path
  path = path.startsWith('.') ? fsPath.resolve(path) : path;

  // Ensure the path exists.
  if (!fs.existsSync(path)) { return; }

  // Load and parse the file.
  const yaml = fs.readFileSync(path, 'utf8');
  return parse(yaml);
};
<commit_msg>Fix lint<commit_after>
import R from 'ramda';
import fs from 'fs-extra';
import fsPath from 'path';
import jsYaml from 'js-yaml';
import { isBlank } from 'js-util';
import { rootModulePath } from './paths';

const ROOT_PATH = rootModulePath();

const formatPath = (path) => {
  if (!R.is(String, path)) { return path; }
  return path.startsWith('.')
    ? fsPath.join(ROOT_PATH, path)
    : path;
};

/**
 * Parses the given YAML text into a config object.
 * @param {String} text: The raw YAML to parse.
 * @return {Object} config.
 */
export const parse = (text) => {
  // Parse the YAML.
  let yaml;
  try {
    yaml = jsYaml.safeLoad(text) || {};
  } catch (err) {
    throw new Error(`The [.uiharness.yml] file is invalid. ${ err.message }`);
  }

  // Format paths.
  yaml.entry = R.is(String, yaml.entry) ? yaml.entry : './src/specs';
  yaml.entry = formatPath(yaml.entry);
  if (yaml.graphqlSchema) {
    yaml.graphqlSchema = formatPath(yaml.graphqlSchema);
  }

  // Finish up.
  return yaml;
};

/**
 * Loads and parses the YAML file at the given location.
 *
 * @param {String} path:  Optional. The path to the YAML config file to load.
 *                        If not specified a path to [.uiharness.yml] in the root
 *                        of the project is used.
 *
 * @return {Object} config OR undefined if the file does not exist.
 */
export const load = (path) => {
  // Setup initial conditions.
  path = isBlank(path) ? fsPath.join(ROOT_PATH, '.uiharness.yml') : path;
  path = path.startsWith('.') ? fsPath.resolve(path) : path;

  // Ensure the path exists.
  if (!fs.existsSync(path)) { return undefined; }

  // Load and parse the file.
  const yaml = fs.readFileSync(path, 'utf8');
  return parse(yaml);
};
<|endoftext|>


<commit_before>/**
@module ember
@submodule ember-application
*/

import { assign } from 'ember-utils';
import { deprecate } from 'ember-debug';
import { get, set, run, computed } from 'ember-metal';
import {
  buildFakeRegistryWithDeprecations,
  RSVP
} from 'ember-runtime';
import { environment } from 'ember-environment';
import { jQuery } from 'ember-views';
import EngineInstance from './engine-instance';

let BootOptions;

/**
  The `ApplicationInstance` encapsulates all of the stateful aspects of a
  running `Application`.

  At a high-level, we break application boot into two distinct phases:

  * Definition time, where all of the classes, templates, and other
    dependencies are loaded (typically in the browser).
  * Run time, where we begin executing the application once everything
    has loaded.

  Definition time can be expensive and only needs to happen once since it is
  an idempotent operation. For example, between test runs and FastBoot
  requests, the application stays the same. It is only the state that we want
  to reset.

  That state is what the `ApplicationInstance` manages: it is responsible for
  creating the container that contains all application state, and disposing of
  it once the particular test run or FastBoot request has finished.

  @public
  @class Ember.ApplicationInstance
  @extends Ember.EngineInstance
*/

const ApplicationInstance = EngineInstance.extend({
  /**
    The `Application` for which this is an instance.

    @property {Ember.Application} application
    @private
  */
  application: null,

  /**
    The DOM events for which the event dispatcher should listen.

    By default, the application's `Ember.EventDispatcher` listens
    for a set of standard DOM events, such as `mousedown` and
    `keyup`, and delegates them to your application's `Ember.View`
    instances.

    @private
    @property {Object} customEvents
  */
  customEvents: null,

  /**
    The root DOM element of the Application as an element or a
    [jQuery-compatible selector
    string](http://api.jquery.com/category/selectors/).

    @private
    @property {String|DOMElement} rootElement
  */
  rootElement: null,

  init() {
    this._super(...arguments);

    // Register this instance in the per-instance registry.
    //
    // Why do we need to register the instance in the first place?
    // Because we need a good way for the root route (a.k.a ApplicationRoute)
    // to notify us when it has created the root-most view. That view is then
    // appended to the rootElement, in the case of apps, to the fixture harness
    // in tests, or rendered to a string in the case of FastBoot.
    this.register('-application-instance:main', this, { instantiate: false });
  },

  /**
    Overrides the base `EngineInstance._bootSync` method with concerns relevant
    to booting application (instead of engine) instances.

    This method should only contain synchronous boot concerns. Asynchronous
    boot concerns should eventually be moved to the `boot` method, which
    returns a promise.

    Until all boot code has been made asynchronous, we need to continue to
    expose this method for use *internally* in places where we need to boot an
    instance synchronously.

    @private
  */
  _bootSync(options) {
    if (this._booted) { return this; }

    options = new BootOptions(options);

    this.setupRegistry(options);

    if (options.rootElement) {
      this.rootElement = options.rootElement;
    } else {
      this.rootElement = this.application.rootElement;
    }

    if (options.location) {
      let router = get(this, 'router');
      set(router, 'location', options.location);
    }

    this.application.runInstanceInitializers(this);

    if (options.isInteractive) {
      this.setupEventDispatcher();
    }

    this._booted = true;

    return this;
  },

  setupRegistry(options) {
    this.constructor.setupRegistry(this.__registry__, options);
  },

  router: computed(function() {
    return this.lookup('router:main');
  }).readOnly(),

  /**
    This hook is called by the root-most Route (a.k.a. the ApplicationRoute)
    when it has finished creating the root View. By default, we simply take the
    view and append it to the `rootElement` specified on the Application.

    In cases like FastBoot and testing, we can override this hook and implement
    custom behavior, such as serializing to a string and sending over an HTTP
    socket rather than appending to DOM.

    @param view {Ember.View} the root-most view
    @private
  */
  didCreateRootView(view) {
    view.appendTo(this.rootElement);
  },

  /**
    Tells the router to start routing. The router will ask the location for the
    current URL of the page to determine the initial URL to start routing to.
    To start the app at a specific URL, call `handleURL` instead.

    @private
  */
  startRouting() {
    let router = get(this, 'router');
    router.startRouting();
    this._didSetupRouter = true;
  },

  /**
    @private

    Sets up the router, initializing the child router and configuring the
    location before routing begins.

    Because setup should only occur once, multiple calls to `setupRouter`
    beyond the first call have no effect.
  */
  setupRouter() {
    if (this._didSetupRouter) { return; }
    this._didSetupRouter = true;

    let router = get(this, 'router');
    router.setupRouter();
  },

  /**
    Directs the router to route to a particular URL. This is useful in tests,
    for example, to tell the app to start at a particular URL.

    @param url {String} the URL the router should route to
    @private
  */
  handleURL(url) {
    let router = get(this, 'router');

    this.setupRouter();
    return router.handleURL(url);
  },

  /**
    @private
  */
  setupEventDispatcher() {
    let dispatcher = this.lookup('event_dispatcher:main');
    let applicationCustomEvents = get(this.application, 'customEvents');
    let instanceCustomEvents = get(this, 'customEvents');

    let customEvents = assign({}, applicationCustomEvents, instanceCustomEvents);
    dispatcher.setup(customEvents, this.rootElement);

    return dispatcher;
  },

  /**
    Returns the current URL of the app instance. This is useful when your
    app does not update the browsers URL bar (i.e. it uses the `'none'`
    location adapter).

    @public
    @return {String} the current URL
  */
  getURL() {
    let router = get(this, 'router');
    return get(router, 'url');
  },

  // `instance.visit(url)` should eventually replace `instance.handleURL()`;
  // the test helpers can probably be switched to use this implementation too

  /**
    Navigate the instance to a particular URL. This is useful in tests, for
    example, or to tell the app to start at a particular URL. This method
    returns a promise that resolves with the app instance when the transition
    is complete, or rejects if the transion was aborted due to an error.

    @public
    @param url {String} the destination URL
    @return {Promise<Ember.ApplicationInstance>}
  */
  visit(url) {
    this.setupRouter();

    let bootOptions = this.__container__.lookup('-environment:main');

    let router = get(this, 'router');

    let handleTransitionResolve = () => {
      if (!bootOptions.options.shouldRender) {
        // No rendering is needed, and routing has completed, simply return.
        return this;
      } else {
        return new RSVP.Promise((resolve) => {
          // Resolve once rendering is completed. `router.handleURL` returns the transition (as a thennable)
          // which resolves once the transition is completed, but the transition completion only queues up
          // a scheduled revalidation (into the `render` queue) in the Renderer.
          //
          // This uses `run.schedule('afterRender', ....)` to resolve after that rendering has completed.
          run.schedule('afterRender', null, resolve, this);
        });
      }
    };

    let handleTransitionReject = (error) => {
      if (error.error) {
        throw error.error;
      } else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) {
        return router._routerMicrolib.activeTransition.then(handleTransitionResolve, handleTransitionReject);
      } else if (error.name === 'TransitionAborted') {
        throw new Error(error.message);
      } else {
        throw error;
      }
    };

    let location = get(router, 'location');

    // Keeps the location adapter's internal URL in-sync
    location.setURL(url);

    // getURL returns the set url with the rootURL stripped off
    return router.handleURL(location.getURL()).then(handleTransitionResolve, handleTransitionReject);
  }
});

ApplicationInstance.reopenClass({
  /**
   @private
   @method setupRegistry
   @param {Registry} registry
   @param {BootOptions} options
  */
  setupRegistry(registry, options = {}) {
    if (!options.toEnvironment) {
      options = new BootOptions(options);
    }

    registry.register('-environment:main', options.toEnvironment(), { instantiate: false });
    registry.register('service:-document', options.document, { instantiate: false });

    this._super(registry, options);
  }
});

/**
  A list of boot-time configuration options for customizing the behavior of
  an `Ember.ApplicationInstance`.

  This is an interface class that exists purely to document the available
  options; you do not need to construct it manually. Simply pass a regular
  JavaScript object containing the desired options into methods that require
  one of these options object:

  ```javascript
  MyApp.visit("/", { location: "none", rootElement: "#container" });
  ```

  Not all combinations of the supported options are valid. See the documentation
  on `Ember.Application#visit` for the supported configurations.

  Internal, experimental or otherwise unstable flags are marked as private.

  @class BootOptions
  @namespace Ember.ApplicationInstance
  @public
*/
BootOptions = function BootOptions(options = {}) {
  /**
    Provide a specific instance of jQuery. This is useful in conjunction with
    the `document` option, as it allows you to use a copy of `jQuery` that is
    appropriately bound to the foreign `document` (e.g. a jsdom).

    This is highly experimental and support very incomplete at the moment.

    @property jQuery
    @type Object
    @default auto-detected
    @private
  */
  this.jQuery = jQuery; // This default is overridable below

  /**
    Interactive mode: whether we need to set up event delegation and invoke
    lifecycle callbacks on Components.

    @property isInteractive
    @type boolean
    @default auto-detected
    @private
  */
  this.isInteractive = environment.hasDOM; // This default is overridable below

  /**
    Run in a full browser environment.

    When this flag is set to `false`, it will disable most browser-specific
    and interactive features. Specifically:

    * It does not use `jQuery` to append the root view; the `rootElement`
      (either specified as a subsequent option or on the application itself)
      must already be an `Element` in the given `document` (as opposed to a
      string selector).

    * It does not set up an `EventDispatcher`.

    * It does not run any `Component` lifecycle hooks (such as `didInsertElement`).

    * It sets the `location` option to `"none"`. (If you would like to use
      the location adapter specified in the app's router instead, you can also
      specify `{ location: null }` to specifically opt-out.)

    @property isBrowser
    @type boolean
    @default auto-detected
    @public
  */
  if (options.isBrowser !== undefined) {
    this.isBrowser = !!options.isBrowser;
  } else {
    this.isBrowser = environment.hasDOM;
  }

  if (!this.isBrowser) {
    this.jQuery = null;
    this.isInteractive = false;
    this.location = 'none';
  }

  /**
    Disable rendering completely.

    When this flag is set to `true`, it will disable the entire rendering
    pipeline. Essentially, this puts the app into "routing-only" mode. No
    templates will be rendered, and no Components will be created.

    @property shouldRender
    @type boolean
    @default true
    @public
  */
  if (options.shouldRender !== undefined) {
    this.shouldRender = !!options.shouldRender;
  } else {
    this.shouldRender = true;
  }

  if (!this.shouldRender) {
    this.jQuery = null;
    this.isInteractive = false;
  }

  /**
    If present, render into the given `Document` object instead of the
    global `window.document` object.

    In practice, this is only useful in non-browser environment or in
    non-interactive mode, because Ember's `jQuery` dependency is
    implicitly bound to the current document, causing event delegation
    to not work properly when the app is rendered into a foreign
    document object (such as an iframe's `contentDocument`).

    In non-browser mode, this could be a "`Document`-like" object as
    Ember only interact with a small subset of the DOM API in non-
    interactive mode. While the exact requirements have not yet been
    formalized, the `SimpleDOM` library's implementation is known to
    work.

    @property document
    @type Document
    @default the global `document` object
    @public
  */
  if (options.document) {
    this.document = options.document;
  } else {
    this.document = (typeof document !== 'undefined') ? document : null;
  }

  /**
    If present, overrides the application's `rootElement` property on
    the instance. This is useful for testing environment, where you
    might want to append the root view to a fixture area.

    In non-browser mode, because Ember does not have access to jQuery,
    this options must be specified as a DOM `Element` object instead of
    a selector string.

    See the documentation on `Ember.Applications`'s `rootElement` for
    details.

    @property rootElement
    @type String|Element
    @default null
    @public
   */
  if (options.rootElement) {
    this.rootElement = options.rootElement;
  }

  // Set these options last to give the user a chance to override the
  // defaults from the "combo" options like `isBrowser` (although in
  // practice, the resulting combination is probably invalid)

  /**
    If present, overrides the router's `location` property with this
    value. This is useful for environments where trying to modify the
    URL would be inappropriate.

    @property location
    @type string
    @default null
    @public
  */
  if (options.location !== undefined) {
    this.location = options.location;
  }

  if (options.jQuery !== undefined) {
    this.jQuery = options.jQuery;
  }

  if (options.isInteractive !== undefined) {
    this.isInteractive = !!options.isInteractive;
  }
};

BootOptions.prototype.toEnvironment = function() {
  let env = assign({}, environment);
  // For compatibility with existing code
  env.hasDOM = this.isBrowser;
  env.isInteractive = this.isInteractive;
  env.options = this;
  return env;
};

Object.defineProperty(ApplicationInstance.prototype, 'registry', {
  configurable: true,
  enumerable: false,
  get() {
    return buildFakeRegistryWithDeprecations(this, 'ApplicationInstance');
  }
});

export default ApplicationInstance;
<commit_msg>remove redundant `BootOptions` variable<commit_after>/**
@module ember
@submodule ember-application
*/

import { assign } from 'ember-utils';
import { get, set, run, computed } from 'ember-metal';
import {
  buildFakeRegistryWithDeprecations,
  RSVP
} from 'ember-runtime';
import { environment } from 'ember-environment';
import { jQuery } from 'ember-views';
import EngineInstance from './engine-instance';

/**
  The `ApplicationInstance` encapsulates all of the stateful aspects of a
  running `Application`.

  At a high-level, we break application boot into two distinct phases:

  * Definition time, where all of the classes, templates, and other
    dependencies are loaded (typically in the browser).
  * Run time, where we begin executing the application once everything
    has loaded.

  Definition time can be expensive and only needs to happen once since it is
  an idempotent operation. For example, between test runs and FastBoot
  requests, the application stays the same. It is only the state that we want
  to reset.

  That state is what the `ApplicationInstance` manages: it is responsible for
  creating the container that contains all application state, and disposing of
  it once the particular test run or FastBoot request has finished.

  @public
  @class Ember.ApplicationInstance
  @extends Ember.EngineInstance
*/

const ApplicationInstance = EngineInstance.extend({
  /**
    The `Application` for which this is an instance.

    @property {Ember.Application} application
    @private
  */
  application: null,

  /**
    The DOM events for which the event dispatcher should listen.

    By default, the application's `Ember.EventDispatcher` listens
    for a set of standard DOM events, such as `mousedown` and
    `keyup`, and delegates them to your application's `Ember.View`
    instances.

    @private
    @property {Object} customEvents
  */
  customEvents: null,

  /**
    The root DOM element of the Application as an element or a
    [jQuery-compatible selector
    string](http://api.jquery.com/category/selectors/).

    @private
    @property {String|DOMElement} rootElement
  */
  rootElement: null,

  init() {
    this._super(...arguments);

    // Register this instance in the per-instance registry.
    //
    // Why do we need to register the instance in the first place?
    // Because we need a good way for the root route (a.k.a ApplicationRoute)
    // to notify us when it has created the root-most view. That view is then
    // appended to the rootElement, in the case of apps, to the fixture harness
    // in tests, or rendered to a string in the case of FastBoot.
    this.register('-application-instance:main', this, { instantiate: false });
  },

  /**
    Overrides the base `EngineInstance._bootSync` method with concerns relevant
    to booting application (instead of engine) instances.

    This method should only contain synchronous boot concerns. Asynchronous
    boot concerns should eventually be moved to the `boot` method, which
    returns a promise.

    Until all boot code has been made asynchronous, we need to continue to
    expose this method for use *internally* in places where we need to boot an
    instance synchronously.

    @private
  */
  _bootSync(options) {
    if (this._booted) { return this; }

    options = new BootOptions(options);

    this.setupRegistry(options);

    if (options.rootElement) {
      this.rootElement = options.rootElement;
    } else {
      this.rootElement = this.application.rootElement;
    }

    if (options.location) {
      let router = get(this, 'router');
      set(router, 'location', options.location);
    }

    this.application.runInstanceInitializers(this);

    if (options.isInteractive) {
      this.setupEventDispatcher();
    }

    this._booted = true;

    return this;
  },

  setupRegistry(options) {
    this.constructor.setupRegistry(this.__registry__, options);
  },

  router: computed(function() {
    return this.lookup('router:main');
  }).readOnly(),

  /**
    This hook is called by the root-most Route (a.k.a. the ApplicationRoute)
    when it has finished creating the root View. By default, we simply take the
    view and append it to the `rootElement` specified on the Application.

    In cases like FastBoot and testing, we can override this hook and implement
    custom behavior, such as serializing to a string and sending over an HTTP
    socket rather than appending to DOM.

    @param view {Ember.View} the root-most view
    @private
  */
  didCreateRootView(view) {
    view.appendTo(this.rootElement);
  },

  /**
    Tells the router to start routing. The router will ask the location for the
    current URL of the page to determine the initial URL to start routing to.
    To start the app at a specific URL, call `handleURL` instead.

    @private
  */
  startRouting() {
    let router = get(this, 'router');
    router.startRouting();
    this._didSetupRouter = true;
  },

  /**
    @private

    Sets up the router, initializing the child router and configuring the
    location before routing begins.

    Because setup should only occur once, multiple calls to `setupRouter`
    beyond the first call have no effect.
  */
  setupRouter() {
    if (this._didSetupRouter) { return; }
    this._didSetupRouter = true;

    let router = get(this, 'router');
    router.setupRouter();
  },

  /**
    Directs the router to route to a particular URL. This is useful in tests,
    for example, to tell the app to start at a particular URL.

    @param url {String} the URL the router should route to
    @private
  */
  handleURL(url) {
    let router = get(this, 'router');

    this.setupRouter();
    return router.handleURL(url);
  },

  /**
    @private
  */
  setupEventDispatcher() {
    let dispatcher = this.lookup('event_dispatcher:main');
    let applicationCustomEvents = get(this.application, 'customEvents');
    let instanceCustomEvents = get(this, 'customEvents');

    let customEvents = assign({}, applicationCustomEvents, instanceCustomEvents);
    dispatcher.setup(customEvents, this.rootElement);

    return dispatcher;
  },

  /**
    Returns the current URL of the app instance. This is useful when your
    app does not update the browsers URL bar (i.e. it uses the `'none'`
    location adapter).

    @public
    @return {String} the current URL
  */
  getURL() {
    return get(this, 'router.url');
  },

  // `instance.visit(url)` should eventually replace `instance.handleURL()`;
  // the test helpers can probably be switched to use this implementation too

  /**
    Navigate the instance to a particular URL. This is useful in tests, for
    example, or to tell the app to start at a particular URL. This method
    returns a promise that resolves with the app instance when the transition
    is complete, or rejects if the transion was aborted due to an error.

    @public
    @param url {String} the destination URL
    @return {Promise<Ember.ApplicationInstance>}
  */
  visit(url) {
    this.setupRouter();

    let bootOptions = this.__container__.lookup('-environment:main');

    let router = get(this, 'router');

    let handleTransitionResolve = () => {
      if (!bootOptions.options.shouldRender) {
        // No rendering is needed, and routing has completed, simply return.
        return this;
      } else {
        return new RSVP.Promise((resolve) => {
          // Resolve once rendering is completed. `router.handleURL` returns the transition (as a thennable)
          // which resolves once the transition is completed, but the transition completion only queues up
          // a scheduled revalidation (into the `render` queue) in the Renderer.
          //
          // This uses `run.schedule('afterRender', ....)` to resolve after that rendering has completed.
          run.schedule('afterRender', null, resolve, this);
        });
      }
    };

    let handleTransitionReject = (error) => {
      if (error.error) {
        throw error.error;
      } else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) {
        return router._routerMicrolib.activeTransition.then(handleTransitionResolve, handleTransitionReject);
      } else if (error.name === 'TransitionAborted') {
        throw new Error(error.message);
      } else {
        throw error;
      }
    };

    let location = get(router, 'location');

    // Keeps the location adapter's internal URL in-sync
    location.setURL(url);

    // getURL returns the set url with the rootURL stripped off
    return router.handleURL(location.getURL()).then(handleTransitionResolve, handleTransitionReject);
  }
});

ApplicationInstance.reopenClass({
  /**
   @private
   @method setupRegistry
   @param {Registry} registry
   @param {BootOptions} options
  */
  setupRegistry(registry, options = {}) {
    if (!options.toEnvironment) {
      options = new BootOptions(options);
    }

    registry.register('-environment:main', options.toEnvironment(), { instantiate: false });
    registry.register('service:-document', options.document, { instantiate: false });

    this._super(registry, options);
  }
});

/**
  A list of boot-time configuration options for customizing the behavior of
  an `Ember.ApplicationInstance`.

  This is an interface class that exists purely to document the available
  options; you do not need to construct it manually. Simply pass a regular
  JavaScript object containing the desired options into methods that require
  one of these options object:

  ```javascript
  MyApp.visit("/", { location: "none", rootElement: "#container" });
  ```

  Not all combinations of the supported options are valid. See the documentation
  on `Ember.Application#visit` for the supported configurations.

  Internal, experimental or otherwise unstable flags are marked as private.

  @class BootOptions
  @namespace Ember.ApplicationInstance
  @public
*/
function BootOptions(options = {}) {
  /**
    Provide a specific instance of jQuery. This is useful in conjunction with
    the `document` option, as it allows you to use a copy of `jQuery` that is
    appropriately bound to the foreign `document` (e.g. a jsdom).

    This is highly experimental and support very incomplete at the moment.

    @property jQuery
    @type Object
    @default auto-detected
    @private
  */
  this.jQuery = jQuery; // This default is overridable below

  /**
    Interactive mode: whether we need to set up event delegation and invoke
    lifecycle callbacks on Components.

    @property isInteractive
    @type boolean
    @default auto-detected
    @private
  */
  this.isInteractive = environment.hasDOM; // This default is overridable below

  /**
    Run in a full browser environment.

    When this flag is set to `false`, it will disable most browser-specific
    and interactive features. Specifically:

    * It does not use `jQuery` to append the root view; the `rootElement`
      (either specified as a subsequent option or on the application itself)
      must already be an `Element` in the given `document` (as opposed to a
      string selector).

    * It does not set up an `EventDispatcher`.

    * It does not run any `Component` lifecycle hooks (such as `didInsertElement`).

    * It sets the `location` option to `"none"`. (If you would like to use
      the location adapter specified in the app's router instead, you can also
      specify `{ location: null }` to specifically opt-out.)

    @property isBrowser
    @type boolean
    @default auto-detected
    @public
  */
  if (options.isBrowser !== undefined) {
    this.isBrowser = !!options.isBrowser;
  } else {
    this.isBrowser = environment.hasDOM;
  }

  if (!this.isBrowser) {
    this.jQuery = null;
    this.isInteractive = false;
    this.location = 'none';
  }

  /**
    Disable rendering completely.

    When this flag is set to `true`, it will disable the entire rendering
    pipeline. Essentially, this puts the app into "routing-only" mode. No
    templates will be rendered, and no Components will be created.

    @property shouldRender
    @type boolean
    @default true
    @public
  */
  if (options.shouldRender !== undefined) {
    this.shouldRender = !!options.shouldRender;
  } else {
    this.shouldRender = true;
  }

  if (!this.shouldRender) {
    this.jQuery = null;
    this.isInteractive = false;
  }

  /**
    If present, render into the given `Document` object instead of the
    global `window.document` object.

    In practice, this is only useful in non-browser environment or in
    non-interactive mode, because Ember's `jQuery` dependency is
    implicitly bound to the current document, causing event delegation
    to not work properly when the app is rendered into a foreign
    document object (such as an iframe's `contentDocument`).

    In non-browser mode, this could be a "`Document`-like" object as
    Ember only interact with a small subset of the DOM API in non-
    interactive mode. While the exact requirements have not yet been
    formalized, the `SimpleDOM` library's implementation is known to
    work.

    @property document
    @type Document
    @default the global `document` object
    @public
  */
  if (options.document) {
    this.document = options.document;
  } else {
    this.document = (typeof document !== 'undefined') ? document : null;
  }

  /**
    If present, overrides the application's `rootElement` property on
    the instance. This is useful for testing environment, where you
    might want to append the root view to a fixture area.

    In non-browser mode, because Ember does not have access to jQuery,
    this options must be specified as a DOM `Element` object instead of
    a selector string.

    See the documentation on `Ember.Applications`'s `rootElement` for
    details.

    @property rootElement
    @type String|Element
    @default null
    @public
   */
  if (options.rootElement) {
    this.rootElement = options.rootElement;
  }

  // Set these options last to give the user a chance to override the
  // defaults from the "combo" options like `isBrowser` (although in
  // practice, the resulting combination is probably invalid)

  /**
    If present, overrides the router's `location` property with this
    value. This is useful for environments where trying to modify the
    URL would be inappropriate.

    @property location
    @type string
    @default null
    @public
  */
  if (options.location !== undefined) {
    this.location = options.location;
  }

  if (options.jQuery !== undefined) {
    this.jQuery = options.jQuery;
  }

  if (options.isInteractive !== undefined) {
    this.isInteractive = !!options.isInteractive;
  }
}

BootOptions.prototype.toEnvironment = function() {
  let env = assign({}, environment);
  // For compatibility with existing code
  env.hasDOM = this.isBrowser;
  env.isInteractive = this.isInteractive;
  env.options = this;
  return env;
};

Object.defineProperty(ApplicationInstance.prototype, 'registry', {
  configurable: true,
  enumerable: false,
  get() {
    return buildFakeRegistryWithDeprecations(this, 'ApplicationInstance');
  }
});

export default ApplicationInstance;
<|endoftext|>