<commit_before>var Endpoint = require('../entities/endpoint'),
    Exporter = require('./exporter'),
    YAML = require('json2yaml')

//TODO right now, no hiearachy support yet
//SL doesn't contain those info anyway

function RAMLDefinition(title, env) {
  this.title = title
  //TODO anyway to know version?
  this.version = "v1"
  this.baseUri = env.Host + env.BasePath
  this.mediaType = env.DefaultResponseType || ""
  this.protocols = mapProtocols(env.Protocols)

  //TODO any way to get the SL documentation
  //this.documentation = []
}

function RAML() {
  this.metadata = null
}

RAML.prototype = new Exporter()

function mapBody(bodyData){
  var body = {}
  if (bodyData.body) {
    //TODO default as applicaiton/json, is it OK?
    var mimeType = bodyData.mimeType || 'application/json'
    body[mimeType] = {
      example: bodyData.example || '',
      schema: bodyData.body
    }
  }
  return body
}

function mapHeaders(headerData){
  var headers = {}
  headers = headerData.properties
  return headers
}

function mapResponses(responseData){
  var responses = {}
  for(var i=0; i< responseData.length; i++) {
    resBody = responseData[i]
    if(resBody.codes.length>0) {
      var code = resBody.codes[0]
      responses[code] = {
        body: {}
      }

      var type = resBody.mimeType || 'application/json'
      responses[code]['body'][type] = {
        'schema': resBody.body,
        'example': resBody.example
      }
    }
  }
  return responses
}

function mapQueryParams(queryParams) {
  var queryString = {}
  for(var key in queryParams.properties) {
    queryString[key] = queryParams.properties[key]
    if(queryParams.required.indexOf(key) > -1){
      queryString[key].required = true
    }
  }
  return queryString
}

function mapPathParams(pathParamData) {
  var pathParams = {}
  for(var key in pathParamData) {
    pathParams[key] = {}
    if(pathParamData[key].description) {
      pathParams[key].description = pathParamData[key].description
    }
    if(pathParamData[key].type) {
      pathParams[key].type = pathParamData[key].type
    }
  }
  return pathParams
}

function mapProtocols(protocols) {
  var validProtocols = []
  for(var i=0; i<protocols.length; i++) {
    if ((protocols[i].toLowerCase() != 'http') && (protocols[i].toLowerCase() != 'https')) {
      //RAML incompatible formats( 'ws' etc)
      continue
    }
    validProtocols.push(protocols[i])
  }
  return validProtocols
}

RAML.prototype.map = function () {
  var env = this.project.Environment
  ramlDef = new RAMLDefinition(this.project.Name, env)

  var endpoints = this.project.Endpoints
  for(var i in endpoints) {

    var endpoint = endpoints[i], parameters = []

    var method = {
      displayName: endpoint.Name,
      description: endpoint.Description
    }

    if (endpoint.Method.toLowerCase() === "post" || endpoint.Method.toLowerCase() === "put") {
      method.body = mapBody(endpoint.Body)
    }

    method.headers = mapHeaders(endpoint.Headers)

    method.responses = mapResponses(endpoint.Responses)

    method.queryParameters = mapQueryParams(endpoint.QueryString)

    if(!ramlDef.hasOwnProperty(endpoint.Path)) {
      //Not found, create new resource
      var resource = {
        displayName: endpoint.Path, //TODO we don't have name in group wise
      }
      resource[endpoint.Method] = method
      resource.uriParameters = mapPathParams(endpoint.PathParams)
      ramlDef[endpoint.Path] = resource
    }
    else {
      //add to existing resource
      var res = ramlDef[endpoint.Path]
      res[endpoint.Method] = method
    }
  }

  this.data = ramlDef
}

RAML.prototype.getData = function(format) {
  switch (format) {
    case 'yaml':
      return "#%RAML 0.8\n"+YAML.stringify(this.data)
    default:
      throw Error('RAML doesn not support '+format+' format')
  }
}

module.exports = RAML
<commit_msg>- added resources as nested uris<commit_after>var Endpoint = require('../entities/endpoint'),
    Exporter = require('./exporter'),
    YAML = require('json2yaml')

//TODO right now, no hiearachy support yet
//SL doesn't contain those info anyway

function RAMLDefinition(title, env) {
  this.title = title
  //TODO anyway to know version?
  this.version = "v1"
  this.baseUri = env.Host + env.BasePath
  this.mediaType = env.DefaultResponseType || ""
  this.protocols = mapProtocols(env.Protocols)

  //TODO any way to get the SL documentation
  //this.documentation = []
}

RAMLDefinition.prototype.addMethod = function(resource, methodURIs, methodKey, method) {
  if (methodURIs.length <= 0) {
    //reach the leaf of tree
    //TODO optional: check same method existence
    resource[methodKey] = method
  }
  else {
    var currentURI = "/" + methodURIs[0]
    if (!resource[currentURI]) {
      resource[currentURI] = {
        "displayName": methodURIs[0],
        "description": ""
      }
      //TODO uriParams?!?
    }
    methodURIs.splice(0, 1)
    this.addMethod(resource[currentURI], methodURIs, methodKey, method)
  }
}

function RAML() {
  this.metadata = null
}

RAML.prototype = new Exporter()

function mapBody(bodyData){
  var body = {}
  if (bodyData.body) {
    //TODO default as applicaiton/json, is it OK?
    var mimeType = bodyData.mimeType || 'application/json'
    body[mimeType] = {
      example: bodyData.example || '',
      schema: bodyData.body
    }
  }
  return body
}

function mapHeaders(headerData){
  var headers = {}
  headers = headerData.properties
  return headers
}

function mapResponses(responseData){
  var responses = {}
  for(var i=0; i< responseData.length; i++) {
    resBody = responseData[i]
    if(resBody.codes.length>0) {
      var code = resBody.codes[0]
      responses[code] = {
        body: {}
      }

      var type = resBody.mimeType || 'application/json'
      responses[code]['body'][type] = {
        'schema': resBody.body,
        'example': resBody.example
      }
    }
  }
  return responses
}

function mapQueryParams(queryParams) {
  var queryString = {}
  for(var key in queryParams.properties) {
    queryString[key] = queryParams.properties[key]
    if(queryParams.required.indexOf(key) > -1){
      queryString[key].required = true
    }
  }
  return queryString
}

function mapPathParams(pathParamData) {
  var pathParams = {}
  for(var key in pathParamData) {
    pathParams[key] = {}
    if(pathParamData[key].description) {
      pathParams[key].description = pathParamData[key].description
    }
    if(pathParamData[key].type) {
      pathParams[key].type = pathParamData[key].type
    }
  }
  return pathParams
}

function mapProtocols(protocols) {
  var validProtocols = []
  for(var i=0; i<protocols.length; i++) {
    if ((protocols[i].toLowerCase() != 'http') && (protocols[i].toLowerCase() != 'https')) {
      //RAML incompatible formats( 'ws' etc)
      continue
    }
    validProtocols.push(protocols[i])
  }
  return validProtocols
}

RAML.prototype.map = function () {
  var env = this.project.Environment
  var ramlDef = new RAMLDefinition(this.project.Name, env)

  var endpoints = this.project.Endpoints
  for(var i in endpoints) {

    var endpoint = endpoints[i], parameters = []

    var method = {
      displayName: endpoint.Name,
      description: endpoint.Description
    }

    if (endpoint.Method.toLowerCase() === "post" || endpoint.Method.toLowerCase() === "put") {
      method.body = mapBody(endpoint.Body)
    }

    method.headers = mapHeaders(endpoint.Headers)

    method.responses = mapResponses(endpoint.Responses)

    method.queryParameters = mapQueryParams(endpoint.QueryString)

    var uriParts = endpoint.Path.split("/")
    uriParts.splice(0, 1)
    ramlDef.addMethod(ramlDef, uriParts, endpoint.Method, method)
  }

  this.data = ramlDef
}

RAML.prototype.getData = function(format) {
  switch (format) {
    case 'yaml':
      return "#%RAML 0.8\n"+YAML.stringify(this.data)
    default:
      throw Error('RAML doesn not support '+format+' format')
  }
}

module.exports = RAML
<|endoftext|>


<commit_before>/**
 * @license
 * Youbora Plugin Kaltura player
 * Copyright NicePopleAtWork & Kaltura
 * @author Jordi Aguilar & Dan Ziv
 */

var VERSION = '1.0.0';

$YB.plugins.KalturaV2 = function (player, options) {
  try {
    /** Name and platform of the plugin.*/
    this.pluginName = 'kaltura-js';

    /** Version of the plugin. ie: 5.1.0-name */
    this.pluginVersion = '5.4.5-' + VERSION + '-kaltura-js';

    /* Initialize YouboraJS */
    this.startMonitoring(player, options);

    this.bitrate = -1;

    // Start listening
    this.registerListeners();
  } catch (err) {
    $YB.error(err);
  }
};

/** Inherit from generic plugin */
$YB.plugins.KalturaV2.prototype = new $YB.plugins.Generic;

$YB.plugins.KalturaV2.prototype.getPlayhead = function () {
  return this.player.getPlayer().currentTime;
};

$YB.plugins.KalturaV2.prototype.getBitrate = function () {
  if (this.player.getPlayer().isMulticast &&
    $.isFunction(this.player.getPlayer().getMulticastBitrate)
  ) {
    this.bitrate = this.player.getPlayer().getMulticastBitrate();
  }

  var bitrate = this.player.getPlayer().mediaElement.selectedSource.getBitrate();
  if (this.bitrate === -1 && bitrate > 0) {
    this.bitrate = bitrate
  }

  return (this.bitrate !== -1) ? (this.bitrate * 1024) : -1
};

$YB.plugins.KalturaV2.prototype.getMediaDuration = function () {
  return this.player.getPlayer().evaluate("{mediaProxy.entry.duration}");
};

$YB.plugins.KalturaV2.prototype.getTitle = function () {
  return this.player.getPlayer().evaluate("{mediaProxy.entry.name}");
};

$YB.plugins.KalturaV2.prototype.getRendition = function () {
  var source = this.player.getPlayer().mediaElement.selectedSource;
  if (source && source.height && source.width) {
    return $YB.utils.buildRenditionString(source.width, source.height, source.bandwidth)
  }
};

$YB.plugins.KalturaV2.prototype.getResource = function () {
  return this.player.getPlayer().getSrc()
};

$YB.plugins.KalturaV2.prototype.getIsLive = function () {
  return this.player.getPlayer().isLive()
};

$YB.plugins.KalturaV2.prototype.getPlayerVersion = function () {
  return 'kaltura-player-v' + MWEMBED_VERSION;
};

/** Register Listeners */
$YB.plugins.KalturaV2.prototype.registerListeners = function () {
  // save context
  var context = this;

  this.player.bind('onChangeMedia', function () {
    // dispatch stop if changing media during playback in order to close the session at Youbora
    if (context.player.getPlayer().currentState !== 'end') {
      context.endedHandler();
      context.reset();
    }
  });

  this.player.bind('playerReady', function () {
    // Set ContentId
    context.setMetadata();

    // Set bitrate
    var kalturaContextData = context.player.getPlayer().kalturaContextData;
    if (kalturaContextData && kalturaContextData.flavorAssets) {
      if (kalturaContextData.flavorAssets.length === 1) {
        context.bitrate = kalturaContextData.flavorAssets[0].bitrate;
      } else {
        context.bitrate = -1;
      }
    }
  });

  this.player.bind('postEnded', function () {
    context.endedHandler();
    context.reset();
  });

  this.player.bind('playerError', function (e, errorObj) {
    var errorMsg = errorObj ? errorObj.message : context.player.getPlayer().getErrorMessage();
    var errorCode = errorObj && errorObj.key ? errorObj.key : context.player.getPlayer().getErrorCode();
    context.setMetadata();
    context.errorHandler(errorCode, errorMsg);
  });

  this.player.bind('bitrateChange', function (e, newBitrate) {
    context.bitrate = newBitrate;
  });

  this.player.bind('SourceSelected', function (e, source) {
    if (source.getBitrate()) {
      context.bitrate = source.getBitrate();
    }
  });

  this.player.bind('sourceSwitchingEnd', function (e, source) {
    if (source.newBitrate) {
      context.bitrate = source.newBitrate;
    }
  });

  this.player.bind('onpause', function () {
    context.pauseHandler();
  });

  this.player.bind('onplay', function () {
    context.resumeHandler();
  });

  this.player.bind('bufferStartEvent', function () {
    context.bufferingHandler();
  });

  this.player.bind('bufferEndEvent', function () {
    context.bufferedHandler();
  });

  this.player.bind('AdSupport_PreSequence firstPlay replayEvent', function () {
    context.setMetadata();
    context.playHandler();
  });

  this.player.bind('playing', function () {
    if ( context.player.getPlayer().isInSequence ) {
      return;
    }
    context.playingHandler();
  });

  this.player.bind('seeking', function () {
    if (!context.viewManager.isBuffering) {
      context.seekingHandler();
    }
  });

  this.player.bind('seeked', function () {
      context.seekedHandler();
  });

  // Adnalyzer start
  this.adnalyzer = new $YB.adnalyzers.KalturaAds(this)
};

$YB.plugins.KalturaV2.prototype.unregisterListeners = function () {
  this.player.unbind(this.eventSuffix)
};

$YB.plugins.KalturaV2.prototype.reset = function () {
  this.viewManager.comm.view++;
};

$YB.plugins.KalturaV2.prototype.setMetadata = function () {
    //Set default kaltura properties
	this.setOptions({
		properties: {
			kalturaInfo: {
				entryId: this.player.getPlayer().evaluate("{mediaProxy.entry.id}"),
				sessionId: this.player.getPlayer().evaluate("{configProxy.sessionId}"),
				uiConfigId: this.player.getPlayer().evaluate("{configProxy.kw.uiConfId}")
			}
		}
	});
	//Set new youbora media config
	var player = this.player.getPlayer();
	var config = player.getKalturaConfig("youbora");
	this.setOptions(config);
};<commit_msg> fix youbora error code handler<commit_after>/**
 * @license
 * Youbora Plugin Kaltura player
 * Copyright NicePopleAtWork & Kaltura
 * @author Jordi Aguilar & Dan Ziv
 */

var VERSION = '1.0.0';

$YB.plugins.KalturaV2 = function (player, options) {
  try {
    /** Name and platform of the plugin.*/
    this.pluginName = 'kaltura-js';

    /** Version of the plugin. ie: 5.1.0-name */
    this.pluginVersion = '5.4.5-' + VERSION + '-kaltura-js';

    /* Initialize YouboraJS */
    this.startMonitoring(player, options);

    this.bitrate = -1;

    // Start listening
    this.registerListeners();
  } catch (err) {
    $YB.error(err);
  }
};

/** Inherit from generic plugin */
$YB.plugins.KalturaV2.prototype = new $YB.plugins.Generic;

$YB.plugins.KalturaV2.prototype.getPlayhead = function () {
  return this.player.getPlayer().currentTime;
};

$YB.plugins.KalturaV2.prototype.getBitrate = function () {
  if (this.player.getPlayer().isMulticast &&
    $.isFunction(this.player.getPlayer().getMulticastBitrate)
  ) {
    this.bitrate = this.player.getPlayer().getMulticastBitrate();
  }

  var bitrate = this.player.getPlayer().mediaElement.selectedSource.getBitrate();
  if (this.bitrate === -1 && bitrate > 0) {
    this.bitrate = bitrate
  }

  return (this.bitrate !== -1) ? (this.bitrate * 1024) : -1
};

$YB.plugins.KalturaV2.prototype.getMediaDuration = function () {
  return this.player.getPlayer().evaluate("{mediaProxy.entry.duration}");
};

$YB.plugins.KalturaV2.prototype.getTitle = function () {
  return this.player.getPlayer().evaluate("{mediaProxy.entry.name}");
};

$YB.plugins.KalturaV2.prototype.getRendition = function () {
  var source = this.player.getPlayer().mediaElement.selectedSource;
  if (source && source.height && source.width) {
    return $YB.utils.buildRenditionString(source.width, source.height, source.bandwidth)
  }
};

$YB.plugins.KalturaV2.prototype.getResource = function () {
  return this.player.getPlayer().getSrc()
};

$YB.plugins.KalturaV2.prototype.getIsLive = function () {
  return this.player.getPlayer().isLive()
};

$YB.plugins.KalturaV2.prototype.getPlayerVersion = function () {
  return 'kaltura-player-v' + MWEMBED_VERSION;
};

/** Register Listeners */
$YB.plugins.KalturaV2.prototype.registerListeners = function () {
  // save context
  var context = this;

  this.player.bind('onChangeMedia', function () {
    // dispatch stop if changing media during playback in order to close the session at Youbora
    if (context.player.getPlayer().currentState !== 'end') {
      context.endedHandler();
      context.reset();
    }
  });

  this.player.bind('playerReady', function () {
    // Set ContentId
    context.setMetadata();

    // Set bitrate
    var kalturaContextData = context.player.getPlayer().kalturaContextData;
    if (kalturaContextData && kalturaContextData.flavorAssets) {
      if (kalturaContextData.flavorAssets.length === 1) {
        context.bitrate = kalturaContextData.flavorAssets[0].bitrate;
      } else {
        context.bitrate = -1;
      }
    }
  });

  this.player.bind('postEnded', function () {
    context.endedHandler();
    context.reset();
  });

  this.player.bind('playerError', function (e, errorObj) {
    var errorMsg = errorObj ? errorObj.message : context.player.getPlayer().getErrorMessage();
    var errorCode = errorObj && errorObj.key ? errorObj.key : context.player.getPlayer().getErrorCode(errorObj);
    context.setMetadata();
    context.errorHandler(errorCode, errorMsg);
  });

  this.player.bind('bitrateChange', function (e, newBitrate) {
    context.bitrate = newBitrate;
  });

  this.player.bind('SourceSelected', function (e, source) {
    if (source.getBitrate()) {
      context.bitrate = source.getBitrate();
    }
  });

  this.player.bind('sourceSwitchingEnd', function (e, source) {
    if (source.newBitrate) {
      context.bitrate = source.newBitrate;
    }
  });

  this.player.bind('onpause', function () {
    context.pauseHandler();
  });

  this.player.bind('onplay', function () {
    context.resumeHandler();
  });

  this.player.bind('bufferStartEvent', function () {
    context.bufferingHandler();
  });

  this.player.bind('bufferEndEvent', function () {
    context.bufferedHandler();
  });

  this.player.bind('AdSupport_PreSequence firstPlay replayEvent', function () {
    context.setMetadata();
    context.playHandler();
  });

  this.player.bind('playing', function () {
    if ( context.player.getPlayer().isInSequence ) {
      return;
    }
    context.playingHandler();
  });

  this.player.bind('seeking', function () {
    if (!context.viewManager.isBuffering) {
      context.seekingHandler();
    }
  });

  this.player.bind('seeked', function () {
      context.seekedHandler();
  });

  // Adnalyzer start
  this.adnalyzer = new $YB.adnalyzers.KalturaAds(this)
};

$YB.plugins.KalturaV2.prototype.unregisterListeners = function () {
  this.player.unbind(this.eventSuffix)
};

$YB.plugins.KalturaV2.prototype.reset = function () {
  this.viewManager.comm.view++;
};

$YB.plugins.KalturaV2.prototype.setMetadata = function () {
    //Set default kaltura properties
	this.setOptions({
		properties: {
			kalturaInfo: {
				entryId: this.player.getPlayer().evaluate("{mediaProxy.entry.id}"),
				sessionId: this.player.getPlayer().evaluate("{configProxy.sessionId}"),
				uiConfigId: this.player.getPlayer().evaluate("{configProxy.kw.uiConfId}")
			}
		}
	});
	//Set new youbora media config
	var player = this.player.getPlayer();
	var config = player.getKalturaConfig("youbora");
	this.setOptions(config);
};<|endoftext|>


<commit_before>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();
    $.getJSON( "https://api.github.com/users/exilesas/repos", function(data){
    	var model = $("#product-model");
    	$.each(data, function(index, value){
    		console.log(index, value);
    		var clone = model.clone();
    		clone.appendTo("#products-container");
    		clone.removeAttr("id");
    		clone.find("h4").html(value.name);
    		if(value.language==null){
    			value.language = "Software"
    		}
    		clone.find("h5").html(value.language);
    		clone.find("p").html(value.description);
    	});
    	model.remove();
    });
  }); // end of document ready
})(jQuery); // end of jQuery name space<commit_msg>Cambio por direccion exildev<commit_after>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();
    $.getJSON( "https://api.github.com/users/exildev/repos", function(data){
    	var model = $("#product-model");
    	$.each(data, function(index, value){
    		console.log(index, value);
    		var clone = model.clone();
    		clone.appendTo("#products-container");
    		clone.removeAttr("id");
    		clone.find("h4").html(value.name);
    		if(value.language==null){
    			value.language = "Software"
    		}
    		clone.find("h5").html(value.language);
    		clone.find("p").html(value.description);
    	});
    	model.remove();
    });
  }); // end of document ready
})(jQuery); // end of jQuery name space
<|endoftext|>


<commit_before>/**
 * Create and send a change event to the parent
 */
'use strict';
export default function dispatch(el, fn) {
  // Generate a change event to let the parent know
  let customEvent = new window.MouseEvent('change');

  // Calls parent change function with the custom event and the right target
  let handler = function(ev) {
    // Clean up
    el.removeEventListener('change', handler);

    if (typeof fn === 'function'){
      // Call
      fn.call(ev, ev);
    }
  };

  // Attach
  el.addEventListener('change', handler);

  // Trigger
  el.dispatchEvent(customEvent);
}
<commit_msg>Fixes the bug where in IE mouse event is not recognized<commit_after>/**
 * Create and send a change event to the parent
 */
'use strict';
export default function dispatch(el, fn) {

  // Generate a change event to let the parent know
  let customEvent = null;

  // Internet Explorer 6-11
  if(/*@cc_on!@*/false || !!document.documentMode) {
    customEvent = document.createEvent('MouseEvent');
    customEvent.initMouseEvent('change',true,true,window,0,0,0,0,0,false,false,false,false,0,null);
  } else {
    // Other browsers
    customEvent = new window.MouseEvent('change');
  }

  // Calls parent change function with the custom event and the right target
  let handler = function(ev) {
    // Clean up
    el.removeEventListener('change', handler);

    if (typeof fn === 'function'){
      // Call
      fn.call(ev, ev);
    }
  };

  // Attach
  el.addEventListener('change', handler);

  // Trigger
  el.dispatchEvent(customEvent);
}
<|endoftext|>


<commit_before>var oldCreate = Factory._create;

if (Meteor.isClient) {
  var lastRecord;

  Factory._create = function(name, doc) {
    Meteor.call('factoryInsert', name, doc);
    var record = lastRecord;
    return record;
  };

  // XXX: Document what this is used for
  flushWrites = function(fn) {
    Meteor.call('flush', function() {
      fn.apply(this);
    });
  };
}

Meteor.methods({
  factoryInsert: function(name, doc) {
    var record = oldCreate(name, doc);

    // XXX: this is a nasty hack because Meteor doesn't give us a way of
    // getting the return value of a stub.
    if (Meteor.isClient) {
      lastRecord = record;
    }

    return record;
  },
  flush: function() {
    // do nothing
  }
});
<commit_msg>Explain `flushWrites`<commit_after>var oldCreate = Factory._create;

if (Meteor.isClient) {
  var lastRecord;

  Factory._create = function(name, doc) {
    Meteor.call('factoryInsert', name, doc);
    var record = lastRecord;
    return record;
  };

  // use this function to ensure that all the client-side factory creates you've written are in the DB on the server.
  //
  // The way this works is using the fact that by default Meteor Methods block each other per-user.
  // So if we wait for a 'null' write method to complete, this will guarantee that all earlier method's we called
  // (namely inserts) have finished before the callback is executed.
  flushWrites = function(fn) {
    Meteor.call('flush', function() {
      fn.apply(this);
    });
  };
}

Meteor.methods({
  factoryInsert: function(name, doc) {
    var record = oldCreate(name, doc);

    // XXX: this is a nasty hack because Meteor doesn't give us a way of
    // getting the return value of a stub.
    if (Meteor.isClient) {
      lastRecord = record;
    }

    return record;
  },
  flush: function() {
    // do nothing
  }
});
<|endoftext|>


<commit_before><commit_msg>Update abChess-0.1.js<commit_after><|endoftext|>


<commit_before>
	var UP = UP || {};
	window.UP = UP;

	/*
	 * What the framework calls 'Views' are actually 'Controllers'
	 * so we rename the module by creating an object Controller that inherits every property of View
	 */
	Backbone.Controller = Backbone.View.extend({});

	/* Constants */
	UP.constants = {
		ACTIVITY_SPEED   : 700,
		DISABLED_OPACITY : 0.5,
		FADE_SPEED       : 700,
		MAX_WEIGHT_VALUE : 5,
		SLIDE_SPEED      : 300,
		STAGES_SPEED     : 500,
		VALUE            : [ "strongly recommended", "neutral", "slightly recommended", "not recommended" ]
	};<commit_msg>2 new UP constants: initial slider value and the method's height (to perform the fix of the method-info animation)<commit_after>
	var UP = UP || {};
	window.UP = UP;

	/*
	 * What the framework calls 'Views' are actually 'Controllers'
	 * so we rename the module by creating an object Controller that inherits every property of View
	 */
	Backbone.Controller = Backbone.View.extend({});

	/* Constants */
	UP.constants = {
		ACTIVITY_SPEED   : 700,
		DISABLED_OPACITY : 0.5,
		FADE_SPEED       : 700,
		MAX_WEIGHT_VALUE : 5,
		METHOD_HEIGHT    : 25,
		SLIDE_SPEED      : 300,
		SLIDER_VALUE     : 1,
		STAGES_SPEED     : 500,
		VALUE            : [ "strongly recommended", "neutral", "slightly recommended", "not recommended" ]
	};
<|endoftext|>


<commit_before><commit_msg>adjusts in contatoCtrl correct the location of redirect after submit.<commit_after><|endoftext|>


<commit_before>define([
  "lodash",
  "bluebird",
  "./errors",
  "./util"
], function (_, Promise, Errors, util) {

  var IndexedDB, IDBKeyRange;

  IndexedDB = window.indexedDB ||
              window.webkitIndexedDB ||
              window.mozIndexedDB ||
              window.oIndexedDB ||
              window.msIndexedDB;
  IDBKeyRange = window.IDBKeyRange ||
                window.webkitIDBKeyRange;

  if (_.isUndefined(IndexedDB)) {
    throw new Errors.IndexedDbNotFound();
  }

  var getCursor = function (store) {
    var keyRange = IDBKeyRange.lowerBound(0);
    return store.openCursor(keyRange);
  };

  var getIndexedCursor = function (store, indexedField, indexedValue) {
    var keyRange = IDBKeyRange.only(indexedValue);
    return store.index(indexedField).openCursor(keyRange);
  };

  var accumulateResults = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || util.validate(query, cursor)) {
      records.push(cursor);
    }
    cursor.continue();
  };

  var oneResult = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || util.validate(query, cursor)) {
      records.push(cursor);
      return;
    }
    cursor.continue();
  };

  var indexField = function (dsName, fieldName, isArray) {
    var connection = IndexedDB.open(dsName);
    connection.onsuccess(function (e) {
      var db = e.target.result;
      db.objectStore.createIndex(fieldName, fieldName, {
        unique: false,
        multiEntry: isArray && true || false
      });
    });
  };

  var _createDatastore = function (db, options) {
    var datastore = db.createObjectStore(options.name, {
      autoIncrement: options.autoIncrement,
      keyPath: options.keyPath
    });

    _.each(options.indexes, function (fieldOptions, fieldName) {
      datastore.createIndex(fieldName, fieldName, fieldOptions);
    });

    return datastore;
  };

  var createDatastore = function (options) {
    options = options || {};

    var connection = IndexedDB.open(options.databaseName);

    return new Promise(function (resolve, reject) {
      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      connection.onsuccess = function (e) {
        resolve(_createDatastore(e.target.result, options));
        e.target.result.close();
      };

      // connection.onupgradeneeded = function (e) {
      //   var db = e.target.result;
      //   // if (!db.objectStoreNames.contains(dsName)) {
      //   db.createObjectStore(dsName, {
      //     keyPath: "_id",
      //     autoIncrement: true
      //   });
      //   // }
      // };
    });
  };

  var get = function (options) {
    options = options || {};
    var connection = IndexedDB.open(options.dbName);

    return new Promise(function (resolve, reject) {
      connection.onsuccess = function (e) {
        var db, transaction, store, request;

        db = e.target.result;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);
        request = store.get(options._id);

        request.onsuccess = function (e) {
          resolve(e.target.result);
        };

        request.onerror = function (e) {
          reject(new Errors.CursorError(e));
        };

        transaction.oncomplete = function (/* e */) {
          db.close();
        };

        transaction.onerror = function (e) {
          reject(new Errors.TransactionError(e));
        };
      };

      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      // connection.onupgradeneeded = _.partial(reconfigureStore, options.dsName);
    });
  };

  var getMany = function (options) {
    options = options || {};
    var connection = IndexedDB.open(options.dbName);

    return new Promise(function (resolve, reject) {
      connection.onsuccess = function (e) {
        var db, transaction, store, cursor, records;

        db = e.target.result;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);

        cursor = options.indexedFieldName ?
          getIndexedCursor(store, options.indexedFieldName, options.indexedValue) :
          getCursor(store);

        records = [];

        cursor.onsuccess = options.findMany ?
          _.partial(accumulateResults, records, options.query) :
          _.partial(oneResult, records, options.query);

        cursor.onerror = function (e) {
          reject(new Errors.CursorError(e));
        };

        transaction.oncomplete = function (/* e */) {
          db.close();
          resolve(records);
        };

        transaction.onerror = function (e) {
          reject(new Errors.TransactionError(e));
        };

      };

      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      // connection.onupgradeneeded = _.partial(reconfigureStore, options.dsName);
    });
  };

  var addMany = function (options) {
    options = options || {};
    var connection = IndexedDB.open(options.dbName);

    return new Promise(function (resolve, reject) {
      connection.onsuccess = function (e) {
        var db, transaction, store;

        db = e.target.result;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);

        var ids = [];

        _.each(options.records, function (record) {
          var request = store.add(record);
          request.onsuccess = function (e) {
            ids.push(e.target.result);
          };
        });

        transaction.oncomplete = function (/* e */) {
          db.close();
          resolve(ids);
        };

        transaction.onerror = function (e) {
          reject(new Errors.TransactionError(e));
        };
      };

      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      // connection.onupgradeneeded = _.partial(reconfigureStore, options.dsName);
    });
  };

  var update = function (objUpdates, record) {
    var value = record.value;
    _.extend(value, objUpdates);
    var request = record.update(value);

    return new Promise(function (resolve, reject) {
      request.onsuccess = function (e) {
        resolve(e.target.result);
      };
      request.onerror = function (e) {
        reject(new Errors.UpdateError(e));
      };
    });
  };

  var del = function (records) {
    var values = _.map(records, function (record) {
      return record.value;
    });

    return new Promise(function (resolve, reject) {
      var request = _.each(records, function (record) {
        record.delete(record.value);
      });
      request.onsuccess = function () {
        resolve(values);
      };
      request.onerror = function (e) {
        reject(new Errors.DeletionError(e));
      };
    });
  };

  return {
    get: get,
    getMany: getMany,
    addMany: addMany,
    update: update,
    del: del,
    indexField: indexField,
    createDatastore: createDatastore
  };
});
<commit_msg>use build-once use-many Query for checking cursor values<commit_after>define([
  "lodash",
  "bluebird",
  "./errors",
  "./query"
], function (_, Promise, Errors, Query) {

  var IndexedDB, IDBKeyRange;

  IndexedDB = window.indexedDB ||
              window.webkitIndexedDB ||
              window.mozIndexedDB ||
              window.oIndexedDB ||
              window.msIndexedDB;
  IDBKeyRange = window.IDBKeyRange ||
                window.webkitIDBKeyRange;

  if (_.isUndefined(IndexedDB)) {
    throw new Errors.IndexedDbNotFound();
  }

  var getCursor = function (store) {
    var keyRange = IDBKeyRange.lowerBound(0);
    return store.openCursor(keyRange);
  };

  var getIndexedCursor = function (store, indexedField, indexedValue) {
    var keyRange = IDBKeyRange.only(indexedValue);
    return store.index(indexedField).openCursor(keyRange);
  };

  var accumulateResults = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      records.push(cursor);
    }
    cursor.continue();
  };

  var oneResult = function (records, query, e) {
    var cursor = e.target.result;
    if (!cursor) { return; }
    if (!query || query.isMatch(cursor.value)) {
      records.push(cursor);
      return;
    }
    cursor.continue();
  };

  var indexField = function (dsName, fieldName, isArray) {
    var connection = IndexedDB.open(dsName);
    connection.onsuccess(function (e) {
      var db = e.target.result;
      db.objectStore.createIndex(fieldName, fieldName, {
        unique: false,
        multiEntry: isArray && true || false
      });
    });
  };

  var _createDatastore = function (db, options) {
    var datastore = db.createObjectStore(options.name, {
      autoIncrement: options.autoIncrement,
      keyPath: options.keyPath
    });

    _.each(options.indexes, function (fieldOptions, fieldName) {
      datastore.createIndex(fieldName, fieldName, fieldOptions);
    });

    return datastore;
  };

  var createDatastore = function (options) {
    options = options || {};

    var connection = IndexedDB.open(options.databaseName);

    return new Promise(function (resolve, reject) {
      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      connection.onsuccess = function (e) {
        resolve(_createDatastore(e.target.result, options));
        e.target.result.close();
      };

      // connection.onupgradeneeded = function (e) {
      //   var db = e.target.result;
      //   // if (!db.objectStoreNames.contains(dsName)) {
      //   db.createObjectStore(dsName, {
      //     keyPath: "_id",
      //     autoIncrement: true
      //   });
      //   // }
      // };
    });
  };

  var get = function (options) {
    options = options || {};
    var connection = IndexedDB.open(options.dbName);

    return new Promise(function (resolve, reject) {
      connection.onsuccess = function (e) {
        var db, transaction, store, request;

        db = e.target.result;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);
        request = store.get(options._id);

        request.onsuccess = function (e) {
          resolve(e.target.result);
        };

        request.onerror = function (e) {
          reject(new Errors.CursorError(e));
        };

        transaction.oncomplete = function (/* e */) {
          db.close();
        };

        transaction.onerror = function (e) {
          reject(new Errors.TransactionError(e));
        };
      };

      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      // connection.onupgradeneeded = _.partial(reconfigureStore, options.dsName);
    });
  };

  var getMany = function (options) {
    options = options || {};

    var
      connection = IndexedDB.open(options.dbName),
      query = new Query(options.query);

    return new Promise(function (resolve, reject) {
      connection.onsuccess = function (e) {
        var db, transaction, store, cursor, records;

        db = e.target.result;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);

        cursor = options.indexedFieldName ?
          getIndexedCursor(store, options.indexedFieldName, options.indexedValue) :
          getCursor(store);

        records = [];

        cursor.onsuccess = options.findMany ?
          _.partial(accumulateResults, records, query) :
          _.partial(oneResult, records, query);

        cursor.onerror = function (e) {
          reject(new Errors.CursorError(e));
        };

        transaction.oncomplete = function (/* e */) {
          db.close();
          resolve(records);
        };

        transaction.onerror = function (e) {
          reject(new Errors.TransactionError(e));
        };

      };

      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      // connection.onupgradeneeded = _.partial(reconfigureStore, options.dsName);
    });
  };

  var addMany = function (options) {
    options = options || {};
    var connection = IndexedDB.open(options.dbName);

    return new Promise(function (resolve, reject) {
      connection.onsuccess = function (e) {
        var db, transaction, store;

        db = e.target.result;
        transaction = db.transaction([options.dsName], "readwrite");
        store = transaction.objectStore(options.dsName);

        var ids = [];

        _.each(options.records, function (record) {
          var request = store.add(record);
          request.onsuccess = function (e) {
            ids.push(e.target.result);
          };
        });

        transaction.oncomplete = function (/* e */) {
          db.close();
          resolve(ids);
        };

        transaction.onerror = function (e) {
          reject(new Errors.TransactionError(e));
        };
      };

      connection.onerror = function (e) {
        reject(new Errors.ConnectionError(e));
      };

      // connection.onupgradeneeded = _.partial(reconfigureStore, options.dsName);
    });
  };

  var update = function (objUpdates, record) {
    var value = record.value;
    _.extend(value, objUpdates);
    var request = record.update(value);

    return new Promise(function (resolve, reject) {
      request.onsuccess = function (e) {
        resolve(e.target.result);
      };
      request.onerror = function (e) {
        reject(new Errors.UpdateError(e));
      };
    });
  };

  var del = function (records) {
    var values = _.map(records, function (record) {
      return record.value;
    });

    return new Promise(function (resolve, reject) {
      var request = _.each(records, function (record) {
        record.delete(record.value);
      });
      request.onsuccess = function () {
        resolve(values);
      };
      request.onerror = function (e) {
        reject(new Errors.DeletionError(e));
      };
    });
  };

  return {
    get: get,
    getMany: getMany,
    addMany: addMany,
    update: update,
    del: del,
    indexField: indexField,
    createDatastore: createDatastore
  };
});
<|endoftext|>


<commit_before><commit_msg>Delete jquery.mobile-1.4.2.min.js<commit_after><|endoftext|>


<commit_before><commit_msg>fixed issue with energy chunks created during preload, see #137<commit_after><|endoftext|>


<commit_before>function like_add(post_id){
	$.post('classes/like_add.php', {post_id:post_id}, function(data) {
		like_get(post_id);
	}).done(function() {
		changeText(post_id);
	});
}

function like_get(post_id) {
	$.post('classes/like_get.php', {post_id:post_id}, function(data) {
		$('#post_'+post_id+'_likes').text(data);
	});
}

function changeText(post_id) {
    var element = document.getElementById('like_'+post_id);
    if (element.innerHTML != 'Unlike')
	{
    	element.innerHTML = 'Unlike';
		addName(post_id);
    }
    else
	{
        element.innerHTML = 'Like';
		removeName(post_id);
    }
}

function addName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("like") > -1) {
		element.innerHTML = "You, " + html;
	} else {
		element.innerHTML = "You like this.";
	}
}

function removeName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("likes") > -1) {
		element.innerHTML = "";
	} else {
		var i = html.indexOf("You")
		element.innerHTML = html.substring(0,i) + html.substring(i,i+6) + html.substring(i+7);
	}
}

<commit_msg>Testing JS<commit_after>function like_add(post_id){
	$.post('classes/like_add.php', {post_id:post_id}, function(data) {
		like_get(post_id);
	}).done(function() {
		changeText(post_id);
	});
}

function like_get(post_id) {
	$.post('classes/like_get.php', {post_id:post_id}, function(data) {
		$('#post_'+post_id+'_likes').text(data);
	});
}

function changeText(post_id) {
    var element = document.getElementById('like_'+post_id);
    if (element.innerHTML != 'Unlike')
	{
    	element.innerHTML = 'Unlike';
		addName(post_id);
    }
    else
	{
        element.innerHTML = 'Like';
		removeName(post_id);
    }
}

function addName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("like") > -1) {
		element.innerHTML = "You, " + html;
	} else {
		element.innerHTML = "You like this.";
	}
}

function removeName(post_id) {
	var element = document.getElementById('likes_'+post_id);
	var html = element.innerHTML;
	if(html.indexOf("likes") > -1) {
		element.innerHTML = "";
	} else {
		var i = html.indexOf("You")
		element.innerHTML = html.substring(0,i-3) + html.substring(i-3,i+7) + html.substring(i+7);
	}
}

<|endoftext|>


<commit_before><commit_msg>Added templateUrl support and fixed a few bugs in inline completions<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

var Anissia = require('../lib/anissia');
var AniONDB = require('../model/aniondb');
var config = require('../config');
var Q = require('q');

var aniondb = new AniONDB(config.database);

function callback (db) {
  return function (newlist, dblist) {
    newlist.forEach(function (ani) {
      var genres = ani.genres.slice(0); // copy array;
      ani.genre = ani.genres.join();
      delete ani.genres;
      db.Ani.upsert(ani).then(function () {
        genres.forEach(function (genre) {
          aniondb.Genre.create({
            ani_id: ani.id,
            genre: genre,
          });
        });
      });
    });
  };
}

aniondb.seq.query('DELETE FROM ani_genres')
.then(function () {
  function crawlOneWeekday (weekday) {
    return Q.all([
      Anissia.getAnilist(weekday),
      aniondb.Ani.findAll({
        ended: false,
        weekday: weekday,
      }),
    ]).spread(callback(aniondb));
  }
  var result = Q();
  for (var weekday = 0; weekday <= 8; weekday++) {
    result = result.then(crawlOneWeekday.bind(null, weekday));
  }
  return result;
})
.then(function () {
  function crawlEndedOnePage (page) {
    return Q.all([
      Anissia.getEndedAnilist(page),
      aniondb.Ani.findAll({
        ended: true,
      }),
    ]).spread(callback(aniondb));
  }
  var result = Q();
  for (var page = 0; page <= 10; page++) {
    result = result.then(crawlEndedOnePage.bind(null, page));
  }
  return result;
});
<commit_msg>crawler.js 재작성<commit_after>#!/usr/bin/env node

const Anissia = require('../lib/anissia')
const AniONDB = require('../model/aniondb')
const config = require('../config')
const Q = require('q')
const _ = require('lodash')

const aniondb = new AniONDB(config.database)

async function updateAni(ani) {
  const genres = ani.genres.slice(0)
  ani.genre = ani.genres.join()
  delete ani.genres
  await aniondb.Ani.upsert(ani)
  return aniondb.Genre.bulkCreate(
    genres.map(genre => ({
      genre,
      ani_id: ani.id,
    }))
  )
}

async function main() {
  await aniondb.seq.query('DELETE FROM ani_genres')
  // _.range is exclusive-range
  for (const weekday of _.range(9)) {
    const anissiaAnis = await Anissia.getAnilist(weekday)
    const dbAnis = await aniondb.Ani.findAll({
      where: {
        weekday,
        ended: false,
      },
    })
    for (const ani of anissiaAnis) {
      await updateAni(ani)
    }
  }
  for (const page of _.range(15)) {
    const anissiaAnis = await Anissia.getEndedAnilist(page)
    const dbAnis = await aniondb.Ani.findAll({
      where: {
        ended: true,
      },
    })
    for (const ani of anissiaAnis) {
      await updateAni(ani)
    }
  }
}

main()
<|endoftext|>


<commit_before>// @flow

const React = require("react");
const { DOM: dom, PropTypes, createFactory } = React;
const { findDOMNode } = require("react-dom");
const { isEnabled } = require("devtools-config");
const { filter } = require("fuzzaldrin-plus");
const Svg = require("../shared/Svg");
const {
  find,
  findNext,
  findPrev,
  removeOverlay,
  countMatches,
  clearIndex
} = require("../../utils/editor");
const { getSymbols } = require("../../utils/parser");
const { scrollList } = require("../../utils/result-list");
const classnames = require("classnames");
const debounce = require("lodash/debounce");
const SearchInput = createFactory(require("../shared/SearchInput"));
const ResultList = createFactory(require("../shared/ResultList"));
const ImPropTypes = require("react-immutable-proptypes");

import type { FormattedSymbolDeclaration } from "../../utils/parser";

function getShortcuts() {
  const searchAgainKey = L10N.getStr("sourceSearch.search.again.key");
  const fnSearchKey = L10N.getStr("symbolSearch.search.key");

  return {
    shiftSearchAgainShortcut: `CmdOrCtrl+Shift+${searchAgainKey}`,
    searchAgainShortcut: `CmdOrCtrl+${searchAgainKey}`,
    symbolSearchShortcut: `CmdOrCtrl+Shift+${fnSearchKey}`,
    searchShortcut: `CmdOrCtrl+${L10N.getStr("sourceSearch.search.key")}`
  };
}

type ToggleSymbolSearchOpts = {
  toggle: boolean,
  searchType: string
}

require("./SearchBar.css");

const SearchBar = React.createClass({

  propTypes: {
    editor: PropTypes.object,
    sourceText: ImPropTypes.map,
    selectSource: PropTypes.func.isRequired,
    selectedSource: ImPropTypes.map,
    searchResults: PropTypes.object.isRequired,
    modifiers: PropTypes.object.isRequired,
    toggleModifier: PropTypes.func.isRequired,
    query: PropTypes.string.isRequired,
    updateQuery: PropTypes.func.isRequired,
    updateSearchResults: PropTypes.func.isRequired
  },

  displayName: "SearchBar",

  getInitialState() {
    return {
      enabled: false,
      symbolSearchEnabled: false,
      selectedSymbolType: "functions",
      symbolSearchResults: [],
      selectedResultIndex: 0,
      count: 0,
      index: -1
    };
  },

  contextTypes: {
    shortcuts: PropTypes.object
  },

  componentWillUnmount() {
    const shortcuts = this.context.shortcuts;
    const {
      searchShortcut, searchAgainShortcut,
      shiftSearchAgainShortcut, symbolSearchShortcut
    } = getShortcuts();

    shortcuts.off(searchShortcut);
    shortcuts.off("Escape");
    shortcuts.off(searchAgainShortcut);
    shortcuts.off(shiftSearchAgainShortcut);
    shortcuts.off(symbolSearchShortcut);
  },

  componentDidMount() {
    const shortcuts = this.context.shortcuts;
    const {
      searchShortcut, searchAgainShortcut,
      shiftSearchAgainShortcut, symbolSearchShortcut
    } = getShortcuts();

    shortcuts.on(searchShortcut, (_, e) => this.toggleSearch(e));
    shortcuts.on("Escape", (_, e) => this.onEscape(e));

    shortcuts.on(
      shiftSearchAgainShortcut,
      (_, e) => this.traverseResults(e, true)
    );

    shortcuts.on(
      searchAgainShortcut,
      (_, e) => this.traverseResults(e, false)
    );

    if (isEnabled("symbolSearch")) {
      shortcuts.on(
        symbolSearchShortcut,
        (_, e) => this.toggleSymbolSearch(e, {
          toggle: false,
          searchType: "functions"
        })
      );
    }
  },

  componentDidUpdate(prevProps: any) {
    const { sourceText, selectedSource, query, modifiers } = this.props;

    if (this.searchInput()) {
      this.searchInput().focus();
    }

    if (this.refs.resultList && this.refs.resultList.refs) {
      scrollList(this.refs.resultList.refs, this.state.selectedResultIndex);
    }

    const hasLoaded = sourceText && !sourceText.get("loading");
    const wasLoading = prevProps.sourceText
                        && prevProps.sourceText.get("loading");

    const doneLoading = wasLoading && hasLoaded;
    const changedFiles = selectedSource != prevProps.selectedSource
                          && hasLoaded;
    const modifiersUpdated = modifiers != prevProps.modifiers;

    const isOpen = this.state.enabled || this.state.symbolSearchEnabled;

    if (isOpen && (doneLoading || changedFiles || modifiersUpdated)) {
      this.doSearch(query);
    }
  },

  onEscape(e: SyntheticKeyboardEvent) {
    this.closeSearch(e);
  },

  clearSearch() {
    const { editor: ed, query, modifiers } = this.props;
    if (ed) {
      const ctx = { ed, cm: ed.codeMirror };
      this.props.updateQuery("");
      removeOverlay(ctx, query, modifiers);
    }
  },

  closeSearch(e: SyntheticEvent) {
    const { editor: ed } = this.props;

    if (this.state.enabled && ed) {
      this.clearSearch();
      this.setState({
        enabled: false,
        symbolSearchEnabled: false,
        selectedSymbolType: "functions"
      });
      e.stopPropagation();
      e.preventDefault();
    }
  },

  toggleSearch(e: SyntheticKeyboardEvent) {
    e.stopPropagation();
    e.preventDefault();
    const { editor } = this.props;

    if (!this.state.enabled) {
      this.setState({ enabled: true });
    }

    if (this.state.symbolSearchEnabled) {
      this.clearSearch();
      this.setState({
        symbolSearchEnabled: false, selectedSymbolType: "functions" });
    }

    if (this.state.enabled && editor) {
      const selection = editor.codeMirror.getSelection();
      this.setSearchValue(selection);
      this.doSearch(selection);
      this.selectSearchInput();
    }
  },

  toggleSymbolSearch(e: SyntheticKeyboardEvent,
    { toggle, searchType }: ToggleSymbolSearchOpts = {}) {
    const { sourceText } = this.props;

    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }

    if (!sourceText) {
      return;
    }

    if (!this.state.enabled) {
      this.setState({ enabled: true });
    }

    if (this.state.symbolSearchEnabled) {
      if (toggle) {
        this.setState({ symbolSearchEnabled: false });
      } else {
        this.setState({ selectedSymbolType: searchType });
      }
      return;
    }

    if (this.props.selectedSource) {
      this.clearSearch();
      this.setState({
        symbolSearchEnabled: true, selectedSymbolType: searchType });
    }
  },

  setSearchValue(value: string) {
    if (value == "") {
      return;
    }

    this.searchInput().value = value;
  },

  selectSearchInput() {
    const node = this.searchInput();
    if (node) {
      node.setSelectionRange(0, node.value.length);
    }
  },

  searchInput() {
    return findDOMNode(this).querySelector("input");
  },

  updateSymbolSearchResults(query: string) {
    const {
      sourceText,
      updateSearchResults
    } = this.props;
    const { selectedSymbolType } = this.state;

    if (query == "" || !sourceText) {
      return;
    }

    const symbolDeclarations = getSymbols(
      sourceText.toJS())[selectedSymbolType];

    const symbolSearchResults = filter(
      symbolDeclarations,
      query,
      { key: "value" }
    );

    updateSearchResults({ count: symbolSearchResults.length });
    return this.setState({ symbolSearchResults });
  },

  doSearch(query: string) {
    const {
      sourceText,
      modifiers,
      updateQuery,
      editor: ed,
      searchResults: { index }
    } = this.props;
    if (!sourceText || !sourceText.get("text")) {
      return;
    }

    updateQuery(query);

    if (this.state.symbolSearchEnabled) {
      return this.updateSymbolSearchResults(query);
    }

    if (!ed) {
      return;
    }

    const ctx = { ed, cm: ed.codeMirror };

    const newCount = countMatches(query, sourceText.get("text"), modifiers);

    if (index == -1) {
      clearIndex(ctx, query, modifiers);
    }

    const newIndex = find(ctx, query, true, modifiers);

    debounce(
      () => this.props.updateSearchResults({
        count: newCount,
        index: newIndex
      }),
      100
    )();
  },

  traverseResults(e: SyntheticEvent, rev: boolean) {
    e.stopPropagation();
    e.preventDefault();

    const ed = this.props.editor;

    if (!ed) {
      return;
    }

    const ctx = { ed, cm: ed.codeMirror };

    const {
      query,
      modifiers,
      updateSearchResults,
      searchResults: { count, index }
    } = this.props;

    if (query === "") {
      this.setState({ enabled: true });
    }

    if (index == -1) {
      clearIndex(ctx, query, modifiers);
    }

    const findFnc = rev ? findPrev : findNext;
    const newIndex = findFnc(ctx, query, true, modifiers);
    updateSearchResults({
      index: newIndex,
      count
    });
  },

  // Handlers
  selectResultItem(item: FormattedSymbolDeclaration) {
    const { selectSource, selectedSource } = this.props;
    if (selectedSource) {
      selectSource(
        selectedSource.get("id"), { line: item.location.start.line });
    }
  },

  onSelectResultItem(item: FormattedSymbolDeclaration) {
    const { selectSource, selectedSource } = this.props;
    if (selectedSource) {
      selectSource(
        selectedSource.get("id"), { line: item.location.start.line });
    }
  },

  onChange(e: any) {
    return this.doSearch(e.target.value);
  },

  onKeyUp(e: SyntheticKeyboardEvent) {
    if (e.key != "Enter") {
      return;
    }

    this.traverseResults(e, e.shiftKey);
  },

  onKeyDown(e: SyntheticKeyboardEvent) {
    if (!this.state.symbolSearchEnabled || this.props.query == "") {
      return;
    }

    const searchResults = this.state.symbolSearchResults,
      resultCount = searchResults.length;

    if (e.key === "ArrowUp") {
      const selectedResultIndex = Math
        .max(0, this.state.selectedResultIndex - 1);
      this.setState({ selectedResultIndex });
      this.onSelectResultItem(searchResults[selectedResultIndex]);
      e.preventDefault();
    } else if (e.key === "ArrowDown") {
      const selectedResultIndex = Math
        .min(resultCount - 1, this.state.selectedResultIndex + 1);
      this.setState({ selectedResultIndex });
      this.onSelectResultItem(searchResults[selectedResultIndex]);
      e.preventDefault();
    } else if (e.key === "Enter") {
      if (searchResults.length) {
        this.selectResultItem(searchResults[this.state.selectedResultIndex]);
      }
      this.closeSearch(e);
      e.preventDefault();
    } else if (e.key === "Tab") {
      this.closeSearch(e);
      e.preventDefault();
    }
  },

  // Renderers
  buildSummaryMsg() {
    if (this.state.symbolSearchEnabled) {
      return L10N.getFormatStr("sourceSearch.resultsSummary1",
        this.state.symbolSearchResults.length);
    }
    const { searchResults: { count, index }, query } = this.props;

    if (query.trim() == "") {
      return "";
    }

    if (count == 0) {
      return L10N.getStr("editor.noResults");
    }

    if (index == -1) {
      return L10N.getFormatStr("sourceSearch.resultsSummary1", count);
    }

    return L10N.getFormatStr("editor.searchResults", index + 1, count);
  },

  buildPlaceHolder() {
    const { symbolSearchEnabled, selectedSymbolType } = this.state;
    if (symbolSearchEnabled) {
      return L10N
        .getFormatStr(`symbolSearch.search.${selectedSymbolType}Placeholder`);
    }

    return L10N.getStr("sourceSearch.search.placeholder");
  },

  renderSearchModifiers() {
    if (!isEnabled("searchModifiers")) {
      return;
    }

    const {
      modifiers: { caseSensitive, wholeWord, regexMatch },
      toggleModifier } = this.props;
    const { symbolSearchEnabled } = this.state;

    function searchModBtn(modVal, className, svgName) {
      const defaultMods = { caseSensitive, wholeWord, regexMatch };
      return dom.button({
        className: classnames(className, {
          active: !symbolSearchEnabled && !Object.values(modVal)[0],
          disabled: symbolSearchEnabled
        }),
        onClick: () => !symbolSearchEnabled ?
        toggleModifier(Object.assign(defaultMods, modVal)) : null
      }, Svg(svgName));
    }

    return dom.div(
      { className: "search-modifiers" },
      searchModBtn({
        regexMatch: !regexMatch }, "regex-match-btn", "regex-match"),
      searchModBtn({
        caseSensitive: !caseSensitive }, "case-sensitive-btn", "case-match"),
      searchModBtn({
        wholeWord: !wholeWord }, "whole-word-btn", "whole-word-match")
    );
  },

  renderSearchTypeToggle() {
    if (!isEnabled("symbolSearch")) {
      return;
    }
    const { toggleSymbolSearch } = this;
    const { symbolSearchEnabled, selectedSymbolType } = this.state;
    const { sourceText } = this.props;

    function searchTypeBtn(searchType) {
      return dom.button({
        className: classnames("search-type-btn", {
          active: symbolSearchEnabled && selectedSymbolType == searchType
        }),
        onClick: e => {
          if (selectedSymbolType == searchType) {
            toggleSymbolSearch(e, { toggle: true, searchType });
            return;
          }
          toggleSymbolSearch(e, { toggle: false, searchType });
        }
      }, L10N.getStr(`symbolSearch.search.${searchType}Placeholder`));
    }

    let classSearchBtn;
    if (sourceText) {
      const symbolDeclarations = getSymbols(sourceText.toJS());
      if (symbolDeclarations.classes.length) {
        classSearchBtn = searchTypeBtn("classes");
      }
    }

    return dom.section(
      { className: "search-type-toggles" },
      dom.h1(
        { className: "search-toggle-title" },
        "Search for:"
      ),
      searchTypeBtn("functions"),
      searchTypeBtn("variables"),
      classSearchBtn
    );
  },

  renderBottomBar() {
    if (!isEnabled("searchModifiers") || !isEnabled("symbolSearch")) {
      return;
    }

    return dom.div(
      { className: "search-bottom-bar" },
      this.renderSearchTypeToggle(),
      this.renderSearchModifiers()
    );
  },

  renderResults() {
    const {
      symbolSearchEnabled, symbolSearchResults, selectedResultIndex
    } = this.state;
    const { query } = this.props;
    if (query == "" ||
      !symbolSearchEnabled || !symbolSearchResults.length) {
      return;
    }

    return ResultList({
      items: symbolSearchResults,
      selected: selectedResultIndex,
      selectItem: this.selectResultItem,
      ref: "resultList"
    });
  },

  render() {
    const {
      searchResults: { count },
      query,
    } = this.props;

    if (!this.state.enabled) {
      return dom.div();
    }

    return dom.div(
      { className: "search-bar" },
      SearchInput({
        query,
        count,
        placeholder: this.buildPlaceHolder(),
        summaryMsg: this.buildSummaryMsg(),
        onChange: this.onChange,
        onKeyUp: this.onKeyUp,
        onKeyDown: this.onKeyDown,
        handleClose: this.closeSearch
      }),
      this.renderResults(),
      this.renderBottomBar()
    );
  }
});

module.exports = SearchBar;
<commit_msg>Accidentally used the placeholder L10N strings in place of the button labels.<commit_after>// @flow

const React = require("react");
const { DOM: dom, PropTypes, createFactory } = React;
const { findDOMNode } = require("react-dom");
const { isEnabled } = require("devtools-config");
const { filter } = require("fuzzaldrin-plus");
const Svg = require("../shared/Svg");
const {
  find,
  findNext,
  findPrev,
  removeOverlay,
  countMatches,
  clearIndex
} = require("../../utils/editor");
const { getSymbols } = require("../../utils/parser");
const { scrollList } = require("../../utils/result-list");
const classnames = require("classnames");
const debounce = require("lodash/debounce");
const SearchInput = createFactory(require("../shared/SearchInput"));
const ResultList = createFactory(require("../shared/ResultList"));
const ImPropTypes = require("react-immutable-proptypes");

import type { FormattedSymbolDeclaration } from "../../utils/parser";

function getShortcuts() {
  const searchAgainKey = L10N.getStr("sourceSearch.search.again.key");
  const fnSearchKey = L10N.getStr("symbolSearch.search.key");

  return {
    shiftSearchAgainShortcut: `CmdOrCtrl+Shift+${searchAgainKey}`,
    searchAgainShortcut: `CmdOrCtrl+${searchAgainKey}`,
    symbolSearchShortcut: `CmdOrCtrl+Shift+${fnSearchKey}`,
    searchShortcut: `CmdOrCtrl+${L10N.getStr("sourceSearch.search.key")}`
  };
}

type ToggleSymbolSearchOpts = {
  toggle: boolean,
  searchType: string
}

require("./SearchBar.css");

const SearchBar = React.createClass({

  propTypes: {
    editor: PropTypes.object,
    sourceText: ImPropTypes.map,
    selectSource: PropTypes.func.isRequired,
    selectedSource: ImPropTypes.map,
    searchResults: PropTypes.object.isRequired,
    modifiers: PropTypes.object.isRequired,
    toggleModifier: PropTypes.func.isRequired,
    query: PropTypes.string.isRequired,
    updateQuery: PropTypes.func.isRequired,
    updateSearchResults: PropTypes.func.isRequired
  },

  displayName: "SearchBar",

  getInitialState() {
    return {
      enabled: false,
      symbolSearchEnabled: false,
      selectedSymbolType: "functions",
      symbolSearchResults: [],
      selectedResultIndex: 0,
      count: 0,
      index: -1
    };
  },

  contextTypes: {
    shortcuts: PropTypes.object
  },

  componentWillUnmount() {
    const shortcuts = this.context.shortcuts;
    const {
      searchShortcut, searchAgainShortcut,
      shiftSearchAgainShortcut, symbolSearchShortcut
    } = getShortcuts();

    shortcuts.off(searchShortcut);
    shortcuts.off("Escape");
    shortcuts.off(searchAgainShortcut);
    shortcuts.off(shiftSearchAgainShortcut);
    shortcuts.off(symbolSearchShortcut);
  },

  componentDidMount() {
    const shortcuts = this.context.shortcuts;
    const {
      searchShortcut, searchAgainShortcut,
      shiftSearchAgainShortcut, symbolSearchShortcut
    } = getShortcuts();

    shortcuts.on(searchShortcut, (_, e) => this.toggleSearch(e));
    shortcuts.on("Escape", (_, e) => this.onEscape(e));

    shortcuts.on(
      shiftSearchAgainShortcut,
      (_, e) => this.traverseResults(e, true)
    );

    shortcuts.on(
      searchAgainShortcut,
      (_, e) => this.traverseResults(e, false)
    );

    if (isEnabled("symbolSearch")) {
      shortcuts.on(
        symbolSearchShortcut,
        (_, e) => this.toggleSymbolSearch(e, {
          toggle: false,
          searchType: "functions"
        })
      );
    }
  },

  componentDidUpdate(prevProps: any) {
    const { sourceText, selectedSource, query, modifiers } = this.props;

    if (this.searchInput()) {
      this.searchInput().focus();
    }

    if (this.refs.resultList && this.refs.resultList.refs) {
      scrollList(this.refs.resultList.refs, this.state.selectedResultIndex);
    }

    const hasLoaded = sourceText && !sourceText.get("loading");
    const wasLoading = prevProps.sourceText
                        && prevProps.sourceText.get("loading");

    const doneLoading = wasLoading && hasLoaded;
    const changedFiles = selectedSource != prevProps.selectedSource
                          && hasLoaded;
    const modifiersUpdated = modifiers != prevProps.modifiers;

    const isOpen = this.state.enabled || this.state.symbolSearchEnabled;

    if (isOpen && (doneLoading || changedFiles || modifiersUpdated)) {
      this.doSearch(query);
    }
  },

  onEscape(e: SyntheticKeyboardEvent) {
    this.closeSearch(e);
  },

  clearSearch() {
    const { editor: ed, query, modifiers } = this.props;
    if (ed) {
      const ctx = { ed, cm: ed.codeMirror };
      this.props.updateQuery("");
      removeOverlay(ctx, query, modifiers);
    }
  },

  closeSearch(e: SyntheticEvent) {
    const { editor: ed } = this.props;

    if (this.state.enabled && ed) {
      this.clearSearch();
      this.setState({
        enabled: false,
        symbolSearchEnabled: false,
        selectedSymbolType: "functions"
      });
      e.stopPropagation();
      e.preventDefault();
    }
  },

  toggleSearch(e: SyntheticKeyboardEvent) {
    e.stopPropagation();
    e.preventDefault();
    const { editor } = this.props;

    if (!this.state.enabled) {
      this.setState({ enabled: true });
    }

    if (this.state.symbolSearchEnabled) {
      this.clearSearch();
      this.setState({
        symbolSearchEnabled: false, selectedSymbolType: "functions" });
    }

    if (this.state.enabled && editor) {
      const selection = editor.codeMirror.getSelection();
      this.setSearchValue(selection);
      this.doSearch(selection);
      this.selectSearchInput();
    }
  },

  toggleSymbolSearch(e: SyntheticKeyboardEvent,
    { toggle, searchType }: ToggleSymbolSearchOpts = {}) {
    const { sourceText } = this.props;

    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }

    if (!sourceText) {
      return;
    }

    if (!this.state.enabled) {
      this.setState({ enabled: true });
    }

    if (this.state.symbolSearchEnabled) {
      if (toggle) {
        this.setState({ symbolSearchEnabled: false });
      } else {
        this.setState({ selectedSymbolType: searchType });
      }
      return;
    }

    if (this.props.selectedSource) {
      this.clearSearch();
      this.setState({
        symbolSearchEnabled: true, selectedSymbolType: searchType });
    }
  },

  setSearchValue(value: string) {
    if (value == "") {
      return;
    }

    this.searchInput().value = value;
  },

  selectSearchInput() {
    const node = this.searchInput();
    if (node) {
      node.setSelectionRange(0, node.value.length);
    }
  },

  searchInput() {
    return findDOMNode(this).querySelector("input");
  },

  updateSymbolSearchResults(query: string) {
    const {
      sourceText,
      updateSearchResults
    } = this.props;
    const { selectedSymbolType } = this.state;

    if (query == "" || !sourceText) {
      return;
    }

    const symbolDeclarations = getSymbols(
      sourceText.toJS())[selectedSymbolType];

    const symbolSearchResults = filter(
      symbolDeclarations,
      query,
      { key: "value" }
    );

    updateSearchResults({ count: symbolSearchResults.length });
    return this.setState({ symbolSearchResults });
  },

  doSearch(query: string) {
    const {
      sourceText,
      modifiers,
      updateQuery,
      editor: ed,
      searchResults: { index }
    } = this.props;
    if (!sourceText || !sourceText.get("text")) {
      return;
    }

    updateQuery(query);

    if (this.state.symbolSearchEnabled) {
      return this.updateSymbolSearchResults(query);
    }

    if (!ed) {
      return;
    }

    const ctx = { ed, cm: ed.codeMirror };

    const newCount = countMatches(query, sourceText.get("text"), modifiers);

    if (index == -1) {
      clearIndex(ctx, query, modifiers);
    }

    const newIndex = find(ctx, query, true, modifiers);

    debounce(
      () => this.props.updateSearchResults({
        count: newCount,
        index: newIndex
      }),
      100
    )();
  },

  traverseResults(e: SyntheticEvent, rev: boolean) {
    e.stopPropagation();
    e.preventDefault();

    const ed = this.props.editor;

    if (!ed) {
      return;
    }

    const ctx = { ed, cm: ed.codeMirror };

    const {
      query,
      modifiers,
      updateSearchResults,
      searchResults: { count, index }
    } = this.props;

    if (query === "") {
      this.setState({ enabled: true });
    }

    if (index == -1) {
      clearIndex(ctx, query, modifiers);
    }

    const findFnc = rev ? findPrev : findNext;
    const newIndex = findFnc(ctx, query, true, modifiers);
    updateSearchResults({
      index: newIndex,
      count
    });
  },

  // Handlers
  selectResultItem(item: FormattedSymbolDeclaration) {
    const { selectSource, selectedSource } = this.props;
    if (selectedSource) {
      selectSource(
        selectedSource.get("id"), { line: item.location.start.line });
    }
  },

  onSelectResultItem(item: FormattedSymbolDeclaration) {
    const { selectSource, selectedSource } = this.props;
    if (selectedSource) {
      selectSource(
        selectedSource.get("id"), { line: item.location.start.line });
    }
  },

  onChange(e: any) {
    return this.doSearch(e.target.value);
  },

  onKeyUp(e: SyntheticKeyboardEvent) {
    if (e.key != "Enter") {
      return;
    }

    this.traverseResults(e, e.shiftKey);
  },

  onKeyDown(e: SyntheticKeyboardEvent) {
    if (!this.state.symbolSearchEnabled || this.props.query == "") {
      return;
    }

    const searchResults = this.state.symbolSearchResults,
      resultCount = searchResults.length;

    if (e.key === "ArrowUp") {
      const selectedResultIndex = Math
        .max(0, this.state.selectedResultIndex - 1);
      this.setState({ selectedResultIndex });
      this.onSelectResultItem(searchResults[selectedResultIndex]);
      e.preventDefault();
    } else if (e.key === "ArrowDown") {
      const selectedResultIndex = Math
        .min(resultCount - 1, this.state.selectedResultIndex + 1);
      this.setState({ selectedResultIndex });
      this.onSelectResultItem(searchResults[selectedResultIndex]);
      e.preventDefault();
    } else if (e.key === "Enter") {
      if (searchResults.length) {
        this.selectResultItem(searchResults[this.state.selectedResultIndex]);
      }
      this.closeSearch(e);
      e.preventDefault();
    } else if (e.key === "Tab") {
      this.closeSearch(e);
      e.preventDefault();
    }
  },

  // Renderers
  buildSummaryMsg() {
    if (this.state.symbolSearchEnabled) {
      return L10N.getFormatStr("sourceSearch.resultsSummary1",
        this.state.symbolSearchResults.length);
    }
    const { searchResults: { count, index }, query } = this.props;

    if (query.trim() == "") {
      return "";
    }

    if (count == 0) {
      return L10N.getStr("editor.noResults");
    }

    if (index == -1) {
      return L10N.getFormatStr("sourceSearch.resultsSummary1", count);
    }

    return L10N.getFormatStr("editor.searchResults", index + 1, count);
  },

  buildPlaceHolder() {
    const { symbolSearchEnabled, selectedSymbolType } = this.state;
    if (symbolSearchEnabled) {
      return L10N
        .getFormatStr(`symbolSearch.search.${selectedSymbolType}Placeholder`);
    }

    return L10N.getStr("sourceSearch.search.placeholder");
  },

  renderSearchModifiers() {
    if (!isEnabled("searchModifiers")) {
      return;
    }

    const {
      modifiers: { caseSensitive, wholeWord, regexMatch },
      toggleModifier } = this.props;
    const { symbolSearchEnabled } = this.state;

    function searchModBtn(modVal, className, svgName) {
      const defaultMods = { caseSensitive, wholeWord, regexMatch };
      return dom.button({
        className: classnames(className, {
          active: !symbolSearchEnabled && !Object.values(modVal)[0],
          disabled: symbolSearchEnabled
        }),
        onClick: () => !symbolSearchEnabled ?
        toggleModifier(Object.assign(defaultMods, modVal)) : null
      }, Svg(svgName));
    }

    return dom.div(
      { className: "search-modifiers" },
      searchModBtn({
        regexMatch: !regexMatch }, "regex-match-btn", "regex-match"),
      searchModBtn({
        caseSensitive: !caseSensitive }, "case-sensitive-btn", "case-match"),
      searchModBtn({
        wholeWord: !wholeWord }, "whole-word-btn", "whole-word-match")
    );
  },

  renderSearchTypeToggle() {
    if (!isEnabled("symbolSearch")) {
      return;
    }
    const { toggleSymbolSearch } = this;
    const { symbolSearchEnabled, selectedSymbolType } = this.state;
    const { sourceText } = this.props;

    function searchTypeBtn(searchType) {
      return dom.button({
        className: classnames("search-type-btn", {
          active: symbolSearchEnabled && selectedSymbolType == searchType
        }),
        onClick: e => {
          if (selectedSymbolType == searchType) {
            toggleSymbolSearch(e, { toggle: true, searchType });
            return;
          }
          toggleSymbolSearch(e, { toggle: false, searchType });
        }
      }, searchType);
    }

    let classSearchBtn;
    if (sourceText) {
      const symbolDeclarations = getSymbols(sourceText.toJS());
      if (symbolDeclarations.classes.length) {
        classSearchBtn = searchTypeBtn("classes");
      }
    }

    return dom.section(
      { className: "search-type-toggles" },
      dom.h1(
        { className: "search-toggle-title" },
        "Search for:"
      ),
      searchTypeBtn("functions"),
      searchTypeBtn("variables"),
      classSearchBtn
    );
  },

  renderBottomBar() {
    if (!isEnabled("searchModifiers") || !isEnabled("symbolSearch")) {
      return;
    }

    return dom.div(
      { className: "search-bottom-bar" },
      this.renderSearchTypeToggle(),
      this.renderSearchModifiers()
    );
  },

  renderResults() {
    const {
      symbolSearchEnabled, symbolSearchResults, selectedResultIndex
    } = this.state;
    const { query } = this.props;
    if (query == "" ||
      !symbolSearchEnabled || !symbolSearchResults.length) {
      return;
    }

    return ResultList({
      items: symbolSearchResults,
      selected: selectedResultIndex,
      selectItem: this.selectResultItem,
      ref: "resultList"
    });
  },

  render() {
    const {
      searchResults: { count },
      query,
    } = this.props;

    if (!this.state.enabled) {
      return dom.div();
    }

    return dom.div(
      { className: "search-bar" },
      SearchInput({
        query,
        count,
        placeholder: this.buildPlaceHolder(),
        summaryMsg: this.buildSummaryMsg(),
        onChange: this.onChange,
        onKeyUp: this.onKeyUp,
        onKeyDown: this.onKeyDown,
        handleClose: this.closeSearch
      }),
      this.renderResults(),
      this.renderBottomBar()
    );
  }
});

module.exports = SearchBar;
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Backbone, EJS, $, window*/

var navigationView = Backbone.View.extend({
  el: '.header',
  initialize: function () {
    var self = this;
    $(window).resize(function() {
      self.handleResize();
    });
    this.handleResize();
  },

  template: new EJS({url: 'js/templates/navigationView.ejs'}),

  render: function() {
    $(this.el).html(this.template.text);
    this.handleResize();
    return this;
  },

  handleResize: function () {
    var oldWidth = $('#content').width();
    var containerWidth = $(window).width() - 70;
    /*var spanWidth = 242;*/
    var spanWidth = 243;
    var divider = containerWidth / spanWidth;
    var roundDiv = parseInt(divider, 10);
    var newWidth = roundDiv*spanWidth;
    var marginWidth = ((containerWidth+30) - newWidth)/2;
    $('#content').width(newWidth)
      .css('margin-left', marginWidth)
      .css('margin-right', marginWidth);
    $('.arango-logo').css('margin-left', marginWidth - 17);
    $('.footer-right p').css('margin-right', marginWidth + 25);
    $('.nav-collapse').css('margin-right', marginWidth - 10);
    if (newWidth !== oldWidth && window.App) {
      window.App.graphView.handleResize(newWidth);
    }
  },

  selectMenuItem: function (menuItem) {
    $('.nav li').removeClass('active');
    if (menuItem) {
      $('.' + menuItem).addClass('active');
    }
  }

});
<commit_msg>small css change<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Backbone, EJS, $, window*/

var navigationView = Backbone.View.extend({
  el: '.header',
  initialize: function () {
    var self = this;
    $(window).resize(function() {
      self.handleResize();
    });
    this.handleResize();
  },

  template: new EJS({url: 'js/templates/navigationView.ejs'}),

  render: function() {
    $(this.el).html(this.template.text);
    this.handleResize();
    return this;
  },

  handleResize: function () {
    var oldWidth = $('#content').width();
    var containerWidth = $(window).width() - 70;
    /*var spanWidth = 242;*/
    var spanWidth = 243;
    var divider = containerWidth / spanWidth;
    var roundDiv = parseInt(divider, 10);
    var newWidth = roundDiv*spanWidth -1;
    var marginWidth = ((containerWidth+30) - newWidth)/2;
    $('#content').width(newWidth)
      .css('margin-left', marginWidth)
      .css('margin-right', marginWidth);
    $('.arango-logo').css('margin-left', marginWidth - 17);
    $('.footer-right p').css('margin-right', marginWidth + 25);
    $('.nav-collapse').css('margin-right', marginWidth - 10);
    if (newWidth !== oldWidth && window.App) {
      window.App.graphView.handleResize(newWidth);
    }
  },

  selectMenuItem: function (menuItem) {
    $('.nav li').removeClass('active');
    if (menuItem) {
      $('.' + menuItem).addClass('active');
    }
  }

});
<|endoftext|>