<commit_before>/*! please.js - v0.1.0 - 2013-06-20
* Copyright (c) 2013 Wingify; Licensed MIT */
!function($){function Request(){this.init.apply(this,[].slice.call(arguments))}function Response(a){this.init(a)}function UnserializableResponseData(a){this.id=a,this.type="unserializable"}var defaults={targetWindow:window,targetOrigin:"*"},please=function(a,b){return $.extend(please.bind(),{targetWindow:a,targetOrigin:b,call:please.call,set:please.set,get:please.get,eval:please.eval,$:please.$})},requests={},responses={};window.please=please,please.requests=requests,please.responses=responses,please.defaults=function(a){$.extend(!0,defaults,a)},please.init=function(a){a.addEventListener("message",please_messageHandler)};var please_request=function(a){return function(){var b=new Request(a);return b.targetWindow=this.targetWindow||defaults.targetWindow,b.targetOrigin=this.targetOrigin||defaults.targetOrigin,b.data=[].slice.call(arguments),b.send(),b}},please_messageHandler=function(a){try{var b=JSON.parse(a.data)}catch(c){return console.log("error parsing json data"),void 0}if("request"===b.type){var d=new Response(b);responses[d.id]=d.data,d.targetWindow=a.source,d.targetOrigin=a.origin,d.send()}else"response"===b.type&&(console.log("response received:",b),b.data&&"unserializable"===b.data.type&&(b.data=UnserializableResponseData.create(b.data)),requests[b.id].resolve(b.data),delete requests[b.id])};please.call=please_request("call"),please.set=please_request("set"),please.get=please_request("get"),please.eval=please_request("eval"),please.$=please_request("$"),please.$=function(){for(var a=please_request("$").apply(this,[].slice.call(arguments)),b=Object.keys($.fn),c=function(a){for(var b in a)"function"==typeof a[b]&&(a[b]=a[b].toString())},d=function(a){return a.map(function(a){return"function"==typeof a?a.toString():("object"==typeof a&&($.extend(!0,{},a),c(a)),a)})},e=function(a){return function(){var b=[].slice.call(arguments);b=d(b);var c=new Request("$_fn");return c.targetWindow=this.targetWindow||defaults.targetWindow,c.targetOrigin=this.targetOrigin||defaults.targetOrigin,c.data=[this,a].concat(b),c.send(),c}},f=0,g=b.length;g>f;f++){var h=b[f];"constructor"!==h&&"init"!==h&&"promise"!==h&&"function"==typeof $.fn[h]&&(a[h]=e(h))}var i=["draggable","sortable"];for(f=0,g=i.length;g>f;f++){var h=i[f];a[h]=e(h)}return a};var please_call=function(a){var b,c=a.split("."),d=b=window,e=[].slice.call(arguments,1);return c.forEach(function(a,e){e===c.length-1&&(b=d),d=d[a]}),d.apply(b,e)},please_set=function(a,b){var c=a.split("."),d=window;c.forEach(function(a,e){e===c.length-1?d[a]=b:d=d[a]})},please_get=function(a){var b=a.split("."),c=window;return b.forEach(function(a){c=c[a]}),c},please_eval=function(a){$.globalEval(a)},please_$=function(){return $.apply($,[].slice.call(arguments))},please_$_fn=function(parentReq,funcName){var $jq=responses[parentReq.id];if(!($jq instanceof $))return null;for(var args=[].slice.call(arguments,2),i=0;i<args.length;i++)args[i]=function(arg){if("string"==typeof arg)try{var fn;return eval("fn = "+arg),"function"==typeof fn?fn:arg}catch(e){return arg}return"object"==typeof arg&&mapObjectStringsToFunctions(arg),arg}(args[i]);var retval;return retval="length"===funcName?$jq.length:$jq[funcName].apply($jq,args)};Request.prototype={init:function(a){$.extend(this,$.Deferred());for(var b=+new Date;b===+new Date;);b=+new Date,this.id=b,this.name=a,this.data=[].slice.call(arguments),requests[b]=this},send:function(){this.targetWindow=this.targetWindow||defaults.targetWindow,this.targetOrigin=this.targetOrigin||defaults.targetOrigin;try{var a=this.data,b=a instanceof $?a.toArray():a;if(b&&b.length&&b[0]instanceof Node)throw"";this.targetWindow.postMessage(JSON.stringify(this),this.targetOrigin),console.log(window.location.href,"sent message:",JSON.stringify(this))}catch(c){console.log(window.location.href,"sent message: Unserializable#",this.id),this.targetWindow.postMessage(new UnserializableResponseData(this.id),this.targetOrigin)}},perform:function(){var please_fn;return eval("please_fn = please_"+this.name),please_fn.apply(this,this.data)},toJSON:function(){return{id:this.id,name:this.name,type:"request",data:this.data}}},Request.create=function(a){return $.extend(new Request,a)},Response.prototype={init:function(a){this.id=a.id,this.name=a.name,this.data=Request.create(a).perform()},send:function(){try{var a=this.data,b=a instanceof $?a.toArray():a;if(b&&b.length&&b[0]instanceof Node)throw"";JSON.stringify(this),this.targetWindow.postMessage(JSON.stringify(this),this.targetOrigin)}catch(c){this.data=new UnserializableResponseData(this.id),this.targetWindow.postMessage(JSON.stringify(this),this.targetOrigin)}console.log(window.location.href,"sent message:",JSON.stringify(this))},toJSON:function(){return{id:this.id,name:this.name,type:"response",data:this.data}}},UnserializableResponseData.create=function(a){var b=$.extend(new UnserializableResponseData,a);return b},please.Request=Request,please.Response=Response,please.UnserializableResponseData=UnserializableResponseData}(jQuery);<commit_msg>[v0.1.0] update build<commit_after>/*! please.js - v0.1.0 - 2013-07-15
* Copyright (c) 2013 Wingify; Licensed MIT */
!function($){function Request(){this.init.apply(this,[].slice.call(arguments))}function Response(a){this.init(a)}function UnserializableResponseData(a){this.id=a,this.type="unserializable"}var defaults={targetWindow:window,targetOrigin:"*"},please=function(a,b){return $.extend(please.bind(),{targetWindow:a,targetOrigin:b,call:please.call,set:please.set,get:please.get,eval:please.eval,$:please.$})},requests={},responses={};window.please=please,please.requests=requests,please.responses=responses,please.defaults=function(a){return $.extend(!0,defaults,a),please},please.init=function(a){return a.addEventListener("message",please_messageHandler),please};var please_request=function(a){return function(){var b=new Request(a);return b.targetWindow=this.targetWindow||defaults.targetWindow,b.targetOrigin=this.targetOrigin||defaults.targetOrigin,b.data=[].slice.call(arguments),b.send(),b}},please_messageHandler=function(a){try{var b=JSON.parse(a.data)}catch(c){return console.log("error parsing json data"),void 0}if("request"===b.type){var d=new Response(b);responses[d.id]=d.data,d.targetWindow=a.source,d.targetOrigin="null"===a.origin?defaults.targetOrigin:a.origin,d.send()}else"response"===b.type&&(b.data&&"unserializable"===b.data.type&&(b.data=UnserializableResponseData.create(b.data)),b.success?requests[b.id].resolve(b.data):requests[b.id].reject(new please.Error(b.data)),delete requests[b.id])};please.call=please_request("call"),please.set=please_request("set"),please.get=please_request("get"),please.eval=please_request("eval"),please.$=please_request("$"),please.$=function(){for(var a=please_request("$").apply(this,[].slice.call(arguments)),b=Object.keys($.fn),c=function(a){for(var b in a)"function"==typeof a[b]&&(a[b]=a[b].toString())},d=function(a){return a.map(function(a){return"function"==typeof a?a.toString():("object"==typeof a&&($.extend(!0,{},a),c(a)),a)})},e=function(a){return function(){var b=[].slice.call(arguments);b=d(b);var c=new Request("$_fn");return c.targetWindow=this.targetWindow||defaults.targetWindow,c.targetOrigin=this.targetOrigin||defaults.targetOrigin,c.data=[this,a].concat(b),c.send(),c}},f=0,g=b.length;g>f;f++){var h=b[f];"constructor"!==h&&"init"!==h&&"promise"!==h&&"function"==typeof $.fn[h]&&(a[h]=e(h))}var i=["draggable","sortable"];for(f=0,g=i.length;g>f;f++){var h=i[f];a[h]=e(h)}return a};var please_call=function(a){var b,c=a.split("."),d=b=window,e=[].slice.call(arguments,1);return c.forEach(function(a,e){e===c.length-1&&(b=d),d=d[a]}),d.apply(b,e)},please_set=function(a,b){var c=a.split("."),d=window;c.forEach(function(a,e){e===c.length-1?d[a]=b:d=d[a]})},please_get=function(a){var b=a.split("."),c=window;return b.forEach(function(a){c=c[a]}),c},please_eval=function(a){return $.globalEval(a)},please_$=function(){return $.apply($,[].slice.call(arguments))},please_$_fn=function(parentReq,funcName){var $jq=responses[parentReq.id];if(!($jq instanceof $))return null;for(var args=[].slice.call(arguments,2),i=0;i<args.length;i++)args[i]=function(arg){if("string"==typeof arg)try{var fn;return eval("fn = "+arg),"function"==typeof fn?fn:arg}catch(e){return arg}return"object"==typeof arg&&mapObjectStringsToFunctions(arg),arg}(args[i]);var retval;return retval="length"===funcName?$jq.length:$jq[funcName].apply($jq,args)};Request.prototype={init:function(a){$.extend(this,$.Deferred());for(var b=+new Date;b===+new Date;);b=+new Date,this.id=b,this.name=a,this.data=[].slice.call(arguments),this.type="request",requests[b]=this},send:function(){this.targetWindow=this.targetWindow||defaults.targetWindow,this.targetOrigin=this.targetOrigin||defaults.targetOrigin;try{var a=this.data,b=a instanceof $?a.toArray():a;if(b&&b.length&&b[0]instanceof Node)throw"";this.targetWindow.postMessage(JSON.stringify(this),this.targetOrigin)}catch(c){this.targetWindow.postMessage(new UnserializableResponseData(this.id),this.targetOrigin)}},perform:function(){return eval("please_"+this.name).apply(this,this.data)},toJSON:function(){return{id:this.id,name:this.name,type:this.type,data:this.data}}},Request.create=function(a){return $.extend(new Request,a)},Response.prototype={init:function(a){this.id=a.id,this.name=a.name,this.type="response";try{this.data=Request.create(a).perform(),this.success=!0}catch(b){this.data=new please.Error(b),this.success=!1}},send:function(){try{this.targetWindow=this.targetWindow||defaults.targetWindow,this.targetOrigin=this.targetOrigin||defaults.targetOrigin;var a=this.data,b=a instanceof $?a.toArray():a;if(b&&b.length&&b[0]instanceof Node)throw"";JSON.stringify(this),this.targetWindow.postMessage(JSON.stringify(this),this.targetOrigin)}catch(c){this.data=new UnserializableResponseData(this.id),this.targetWindow.postMessage(JSON.stringify(this),this.targetOrigin)}finally{if(!this.success)throw this.data.error}},toJSON:function(){return{id:this.id,name:this.name,type:this.type,data:this.data,success:this.success}}},UnserializableResponseData.create=function(a){var b=$.extend(new UnserializableResponseData,a);return b},please.Error=function(a){this.error=a,$.extend(this,a),this.name=a.name,this.message=a.message,this.number=a.number,this.description=a.description,this.fileName=a.fileName,this.lineNumber=a.lineNumber,this.stack=a.stack},please.Request=Request,please.Response=Response,please.UnserializableResponseData=UnserializableResponseData}(jQuery);<|endoftext|>


<commit_before>'use strict';
export default class ArrayCursor {
  constructor(connection, body) {
    this.extra = body.extra;
    this._connection = connection;
    this._api = this._connection.route('_api');
    this._result = body.result;
    this._hasMore = Boolean(body.hasMore);
    this._id = body.id;
    this._index = 0;
    this.count = body.count;
  }

  _drain(cb) {
    const {promise, callback} = this._connection.promisify(cb);
    this._more(err => (
      err ? callback(err) : (
        !this._hasMore
        ? callback(null, this)
        : this._drain(cb)
      )
    ));
    return promise;
  }

  _more(callback) {
    if (!this._hasMore) callback(null, this);
    else {
      this._api.put(`cursor/${this._id}`, (err, res) => {
        if (err) callback(err);
        else {
          this._result = res.body.result;
          this._hasMore = res.body.hasMore;
          this._index = 0;
          callback(null, this);
        }
      });
    }
  }

  all(cb) {
    const {promise, callback} = this._connection.promisify(cb);
    this._drain(err => {
      this._index = this._result.length;
      if (err) callback(err);
      else callback(null, this._result);
    });
    return promise;
  }

  next(cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const next = () => {
      const value = this._result[this._index];
      this._index += 1;
      callback(null, value);
    };
    if (this._index < this._result.length) next();
    else {
      if (!this._hasMore) callback(null);
      else {
        this._more(err => err ? callback(err) : this.rewind().next());
      }
    }
    return promise;
  }

  hasNext() {
    return (this._hasMore || this._index < this._result.length);
  }

  each(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        let result;
        while (this._index < this._result.length) {
          result = fn(this._result[this._index], this._index, this);
          this._index++;
          if (result === false) break;
        }
        if (!this._hasMore || result === false) callback(null, result);
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  every(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        let result = true;
        while (this._index < this._result.length) {
          result = fn(this._result[this._index], this._index, this);
          this._index++;
          if (!result) break;
        }
        if (!this._hasMore || !result) callback(null, Boolean(result));
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  some(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        let result = false;
        while (this._index < this._result.length) {
          result = fn(this._result[this._index], this._index, this);
          this._index++;
          if (result) break;
        }
        if (!this._hasMore || result) callback(null, Boolean(result));
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  map(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const result = [];
    const loop = () => {
      try {
        while (this._index < this._result.length) {
          result.push(fn(this._result[this._index], this._index, this));
          this._index++;
        }
        if (!this._hasMore) callback(null, result);
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  reduce(fn, accu, cb) {
    if (typeof accu === 'function') {
      cb = accu;
      accu = undefined;
    }
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        while (this._index < this._result.length) {
          accu = fn(accu, this._result[this._index], this._index, this);
          this._index++;
        }
        if (!this._hasMore) callback(null, accu);
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    if (accu !== undefined) {
      this._index = 0;
      loop();
    } else if (this._result.length > 1) {
      accu = this._result[0];
      this._index = 1;
      loop();
    } else {
      this._more(err => {
        if (err) callback(err);
        else {
          accu = this._result[0];
          this._index = 1;
          loop();
        }
      });
    }
    return promise;
  }

  rewind() {
    this._index = 0;
    return this;
  }
}
<commit_msg>Removed the index in favor of shifting the result of the results array<commit_after>'use strict';
export default class ArrayCursor {
  constructor(connection, body) {
    this.extra = body.extra;
    this._connection = connection;
    this._api = this._connection.route('_api');
    this._result = body.result;
    this._hasMore = Boolean(body.hasMore);
    this._id = body.id;
    this.count = body.count;
  }

  _drain(cb) {
    const {promise, callback} = this._connection.promisify(cb);
    this._more(err => (
      err ? callback(err) : (
        !this._hasMore
        ? callback(null, this)
        : this._drain(cb)
      )
    ));
    return promise;
  }

  _more(callback) {
    if (!this._hasMore) callback(null, this);
    else {
      this._api.put(`cursor/${this._id}`, (err, res) => {
        if (err) callback(err);
        else {
          this._result.push.apply(this._result, res.body.result);
          this._hasMore = res.body.hasMore;
          callback(null, this);
        }
      });
    }
  }

  all(cb) {
    const {promise, callback} = this._connection.promisify(cb);
    this._drain(err => {
      if (err) callback(err);
      else callback(null, this._result);
    });
    return promise;
  }

  next(cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const next = () => {
      const value = this._result.shift();
      callback(null, value);
    };
    if (this._result[0]) next();
    else {
      if (!this._hasMore) callback(null);
      else {
        this._more(err => err ? callback(err) : next());
      }
    }
    return promise;
  }

  hasNext() {
    return (this._hasMore || this._result.length[0]);
  }

  each(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        let result;
        while (this._result[0]) {
          result = fn(this._result.shift(), this);
          if (result === false) break;
        }
        if (!this._hasMore || result === false) callback(null, result);
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  every(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        let result = true;
        while (this._result[0]) {
          result = fn(this._result.shift(), this);
          if (!result) break;
        }
        if (!this._hasMore || !result) callback(null, Boolean(result));
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  some(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        let result = false;
        while (this._result[0]) {
          result = fn(this._result.shift(), this);
          if (result) break;
        }
        if (!this._hasMore || result) callback(null, Boolean(result));
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  map(fn, cb) {
    const {promise, callback} = this._connection.promisify(cb);
    const result = [];
    const loop = () => {
      try {
        while (this._result[0]) {
          result.push(fn(this._result.shift(), this));
        }
        if (!this._hasMore) callback(null, result);
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    loop();
    return promise;
  }

  reduce(fn, accu, cb) {
    if (typeof accu === 'function') {
      cb = accu;
      accu = undefined;
    }
    const {promise, callback} = this._connection.promisify(cb);
    const loop = () => {
      try {
        while (this._result[0]) {
          accu = fn(accu, this._result.shift(), this);
        }
        if (!this._hasMore) callback(null, accu);
        else {
          this._more(err => err ? callback(err) : loop());
        }
      } catch (e) {
        callback(e);
      }
    };
    if (accu !== undefined) {
      loop();
    } else if (this._result.length > 1) {
      accu = this._result.shift();
      loop();
    } else {
      this._more(err => {
        if (err) callback(err);
        else {
          accu = this._result.shift();
          loop();
        }
      });
    }
    return promise;
  }

  rewind() {
    //this._index = 0;
    return this;
  }
}
<|endoftext|>


<commit_before>/*
 * Simple jQuery Dialog
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Contributors: @johnbender
 * Licensed under the MIT, GPL licenses.
 */

(function( w, $ ){
	w.componentNamespace = w.componentNamespace || w;

	var pluginName = "dialog", cl, ev,
		nullHash = "dialog",
		doc = w.document,
		docElem = doc.documentElement,
		body = doc.body,
		$html = $( docElem );

	var Dialog = w.componentNamespace.Dialog = function( element ){
		this.$el = $( element );
		this.$background =
			$( doc.createElement('div') ).addClass( cl.bkgd ).appendTo( "body");
		this.hash = this.$el.attr( "id" ) + "-dialog";

		this.isOpen = false;
		this.positionMedia = this.$el.attr( 'data-set-position-media' );
		this.isTransparentBackground = this.$el.is( '[data-transbg]' );
	};

	Dialog.events = ev = {
		open: pluginName + "-open",
		close: pluginName + "-close"
	};

	Dialog.classes = cl = {
		open: pluginName + "-open",
		opened: pluginName + "-opened",
		content: pluginName + "-content",
		close: pluginName + "-close",
		closed: pluginName + "-closed",
		bkgd: pluginName + "-background",
		bkgdOpen: pluginName + "-background-open",
		bkgdTrans: pluginName + "-background-trans"
	};

	Dialog.prototype.isSetScrollPosition = function() {
		return !this.positionMedia ||
			( w.matchMedia && w.matchMedia( this.positionMedia ).matches );
	};

	Dialog.prototype.destroy = function() {
		this.$background.remove();
	};

	Dialog.prototype.open = function( e ) {
		this.$background[ 0 ].style.height = Math.max( docElem.scrollHeight, docElem.clientHeight ) + "px";
		this.$el.addClass( cl.open );
		this.$background.addClass( cl.bkgdOpen );
		this._setBackgroundTransparency();

		if( this.isSetScrollPosition() ) {
			this.scroll = "pageYOffset" in w ? w.pageYOffset : ( docElem.scrollY || docElem.scrollTop || ( body && body.scrollY ) || 0 );
			this.$el[ 0 ].style.top = this.scroll + "px";
		} else {
			this.$el[ 0 ].style.top = '';
		}

		$html.addClass( cl.open );
		this.isOpen = true;

		location.hash = this.hash;

		if( doc.activeElement ){
			this.focused = doc.activeElement;
		}
		this.$el[ 0 ].focus();

		this.$el.trigger( cl.opened );
	};

	Dialog.prototype._setBackgroundTransparency = function() {
		if( this.isTransparentBackground ){
			this.$background.addClass( cl.bkgdTrans );
		}
	};

	Dialog.prototype.close = function(){
		if( !this.isOpen ){
			return;
		}

		this.$el.removeClass( cl.open );

		this.$background.removeClass( cl.bkgdOpen );
		$html.removeClass( cl.open );

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

		if( this.isSetScrollPosition() ) {
			w.scrollTo( 0, this.scroll );
		}

		this.isOpen = false;

		this.$el.trigger( cl.closed );
	};
}( this, jQuery ));
<commit_msg>Adds [data-nobg] option to opt-out of the background/curtain when a dialog is open.<commit_after>/*
 * Simple jQuery Dialog
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Contributors: @johnbender
 * Licensed under the MIT, GPL licenses.
 */

(function( w, $ ){
	w.componentNamespace = w.componentNamespace || w;

	var pluginName = "dialog", cl, ev,
		nullHash = "dialog",
		doc = w.document,
		docElem = doc.documentElement,
		body = doc.body,
		$html = $( docElem );

	var Dialog = w.componentNamespace.Dialog = function( element ){
		this.$el = $( element );
		this.$background = !this.$el.is( '[data-nobg]' ) ?
			$( doc.createElement('div') ).addClass( cl.bkgd ).appendTo( "body") :
			$( [] );
		this.hash = this.$el.attr( "id" ) + "-dialog";

		this.isOpen = false;
		this.positionMedia = this.$el.attr( 'data-set-position-media' );
		this.isTransparentBackground = this.$el.is( '[data-transbg]' );
	};

	Dialog.events = ev = {
		open: pluginName + "-open",
		close: pluginName + "-close"
	};

	Dialog.classes = cl = {
		open: pluginName + "-open",
		opened: pluginName + "-opened",
		content: pluginName + "-content",
		close: pluginName + "-close",
		closed: pluginName + "-closed",
		bkgd: pluginName + "-background",
		bkgdOpen: pluginName + "-background-open",
		bkgdTrans: pluginName + "-background-trans"
	};

	Dialog.prototype.isSetScrollPosition = function() {
		return !this.positionMedia ||
			( w.matchMedia && w.matchMedia( this.positionMedia ).matches );
	};

	Dialog.prototype.destroy = function() {
		this.$background.remove();
	};

	Dialog.prototype.open = function( e ) {
		if( this.$background.length ) {
			this.$background[ 0 ].style.height = Math.max( docElem.scrollHeight, docElem.clientHeight ) + "px";
		}
		this.$el.addClass( cl.open );
		this.$background.addClass( cl.bkgdOpen );
		this._setBackgroundTransparency();

		if( this.isSetScrollPosition() ) {
			this.scroll = "pageYOffset" in w ? w.pageYOffset : ( docElem.scrollY || docElem.scrollTop || ( body && body.scrollY ) || 0 );
			this.$el[ 0 ].style.top = this.scroll + "px";
		} else {
			this.$el[ 0 ].style.top = '';
		}

		$html.addClass( cl.open );
		this.isOpen = true;

		location.hash = this.hash;

		if( doc.activeElement ){
			this.focused = doc.activeElement;
		}
		this.$el[ 0 ].focus();

		this.$el.trigger( cl.opened );
	};

	Dialog.prototype._setBackgroundTransparency = function() {
		if( this.isTransparentBackground ){
			this.$background.addClass( cl.bkgdTrans );
		}
	};

	Dialog.prototype.close = function(){
		if( !this.isOpen ){
			return;
		}

		this.$el.removeClass( cl.open );

		this.$background.removeClass( cl.bkgdOpen );
		$html.removeClass( cl.open );

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

		if( this.isSetScrollPosition() ) {
			w.scrollTo( 0, this.scroll );
		}

		this.isOpen = false;

		this.$el.trigger( cl.closed );
	};
}( this, jQuery ));
<|endoftext|>


<commit_before>'use strict'
/**
 * Created by acastillo on 7/1/16.
 */
define(['src/util/api', 'src/util/ui', 'OCLE', './ExpandableMolecule','elnPlugin'], function (API, UI, OCLE, ExpandableMolecule, elnPlugin) {

    function loadSampleOnVisualizer(){
        var roc = API.cache('roc');
        var couchDB = API.cache('couchDB');
        var uuid = couchDB.uuid;

        if (!roc && uuid) {
            var couchUrl = couchDB.couchUrl;
            var database = couchDB.database;
            roc = new Roc({
                url: couchUrl,
                database: database,
                processor: elnPlugin,
                kind: couchDB.kind
            });

            roc.document(uuid, {
                varName: 'sample'
            }).then(function (sample) {
                var sampleVar = API.getVar('sample');

                API.createData('annot1d', null);
                API.createData('annot2d', null);
                API.setVariable('sampleCode', sampleVar, ['$id', 0]);
                API.setVariable('creationDate', sampleVar, ['$creationDate']);
                API.setVariable('modificationDate', sampleVar, ['$modificationDate']);
                API.setVariable('content', sampleVar, ['$content']);
                API.setVariable('molfile', sampleVar, ['$content', 'general', 'molfile']);
                API.setVariable('mf', sampleVar, ['$content', 'general', 'mf']);
                API.setVariable('mw', sampleVar, ['$content', 'general', 'mw']);
                API.setVariable('description', sampleVar, ['$content', 'general', 'description']);
                API.setVariable('iupac', sampleVar, ['$content', 'general', 'iupac']);
                API.setVariable('bp', sampleVar, ['$content', 'physical', 'bp']);
                API.setVariable('nd', sampleVar, ['$content', 'physical', 'nd']);
                /PI.setVariable('mp', sampleVar, ['$content', 'physical', 'mp']);
                API.setVariable('density', sampleVar, ['$content', 'physical', 'density']);
                API.setVariable('nmr', sampleVar, ['$content', 'spectra', 'nmr']);
                API.setVariable('ir', sampleVar, ['$content', 'spectra', 'ir']);
                API.setVariable('mass', sampleVar, ['$content', 'spectra', 'mass']);
                updateAttachments(sample);

                var expandableMolecule = new ExpandableMolecule(sample);
                API.cache('expandableMolecule', expandableMolecule);
                if(typeof IframeBridge !='undefined'){
                    sample.onChange(function (event) {
                        IframeBridge.postMessage('tab.status', {
                            saved: false
                        });
                    });
                }

            });

            API.cache('roc', roc);

            if (!roc) return;

            var sample = API.getData('sample');

            if (this.action) {
                switch (this.action.name) {
                    case 'refresh':
                        roc.get(uuid);
                        break;
                    case 'save':
                        roc.update(sample).then(function () {
                            sample.onChange(function (event) {
                                IframeBridge.postMessage('tab.status', {
                                    saved: true
                                });
                            });
                        });
                        break;
                    default:
                        break
                }
            }
        }
    }

    function updateAttachments(entry) {
        return roc.getAttachmentList(API.cache('couchDB').uuid).then(function (list) {
            API.createData('sampleAttachments', list);
        })
    }

    return loadSampleOnVisualizer;
}
<commit_msg>typo on API<commit_after>'use strict'
/**
 * Created by acastillo on 7/1/16.
 */
define(['src/util/api', 'src/util/ui', 'OCLE', './ExpandableMolecule','elnPlugin'], function (API, UI, OCLE, ExpandableMolecule, elnPlugin) {

    function loadSampleOnVisualizer(){
        var roc = API.cache('roc');
        var couchDB = API.cache('couchDB');
        var uuid = couchDB.uuid;

        if (!roc && uuid) {
            var couchUrl = couchDB.couchUrl;
            var database = couchDB.database;
            roc = new Roc({
                url: couchUrl,
                database: database,
                processor: elnPlugin,
                kind: couchDB.kind
            });

            roc.document(uuid, {
                varName: 'sample'
            }).then(function (sample) {
                var sampleVar = API.getVar('sample');

                API.createData('annot1d', null);
                API.createData('annot2d', null);
                API.setVariable('sampleCode', sampleVar, ['$id', 0]);
                API.setVariable('creationDate', sampleVar, ['$creationDate']);
                API.setVariable('modificationDate', sampleVar, ['$modificationDate']);
                API.setVariable('content', sampleVar, ['$content']);
                API.setVariable('molfile', sampleVar, ['$content', 'general', 'molfile']);
                API.setVariable('mf', sampleVar, ['$content', 'general', 'mf']);
                API.setVariable('mw', sampleVar, ['$content', 'general', 'mw']);
                API.setVariable('description', sampleVar, ['$content', 'general', 'description']);
                API.setVariable('iupac', sampleVar, ['$content', 'general', 'iupac']);
                API.setVariable('bp', sampleVar, ['$content', 'physical', 'bp']);
                API.setVariable('nd', sampleVar, ['$content', 'physical', 'nd']);
                API.setVariable('mp', sampleVar, ['$content', 'physical', 'mp']);
                API.setVariable('density', sampleVar, ['$content', 'physical', 'density']);
                API.setVariable('nmr', sampleVar, ['$content', 'spectra', 'nmr']);
                API.setVariable('ir', sampleVar, ['$content', 'spectra', 'ir']);
                API.setVariable('mass', sampleVar, ['$content', 'spectra', 'mass']);
                updateAttachments(sample);

                var expandableMolecule = new ExpandableMolecule(sample);
                API.cache('expandableMolecule', expandableMolecule);
                if(typeof IframeBridge !='undefined'){
                    sample.onChange(function (event) {
                        IframeBridge.postMessage('tab.status', {
                            saved: false
                        });
                    });
                }

            });

            API.cache('roc', roc);

            if (!roc) return;

            var sample = API.getData('sample');

            if (this.action) {
                switch (this.action.name) {
                    case 'refresh':
                        roc.get(uuid);
                        break;
                    case 'save':
                        roc.update(sample).then(function () {
                            sample.onChange(function (event) {
                                IframeBridge.postMessage('tab.status', {
                                    saved: true
                                });
                            });
                        });
                        break;
                    default:
                        break
                }
            }
        }
    }

    function updateAttachments(entry) {
        return roc.getAttachmentList(API.cache('couchDB').uuid).then(function (list) {
            API.createData('sampleAttachments', list);
        })
    }

    return loadSampleOnVisualizer;
}
<|endoftext|>


<commit_before>function tree() {
    var _chart = {};

    var _width = 1600, _height = 800,
            _margins = {top: 30, left: 120, right: 30, bottom: 30},
            _svg,
            _nodes,
            _i = 0,
            _tree,
            _diagonal,
            _bodyG;

   function zoom() {
	 _svg.attr("transform", "translate("
     + d3.event.translate
     + ")scale(" + d3.event.scale + ")");
   }

    _chart.render = function () {
    	tree.iterator += 1;
        if (!_svg) {
            _svg = d3.select("body").append("svg")
                    .attr("height", _height)
                    .attr("width", _width)
                    .attr("id", "graph");

        }

        renderBody(_svg);
    };

    function renderBody(svg) {
        if (!_bodyG) {
            _bodyG = svg.append("g")
				.attr("class", "body")
				.attr("transform", function (d) {
					return "translate(" + _margins.left
						+ "," + _margins.top + ")";
				}).call( // <-A
                        d3.behavior.zoom() // <-B
                        .scaleExtent([1, 8]) // <-C
                        .on("zoom", zoom) // <-D
                );
        }

        _tree = d3.layout.tree()
                .size([
					(_height - _margins.top - _margins.bottom),
					(_width - _margins.left - _margins.right)
				]);

        _diagonal = d3.svg.diagonal()
                .projection(function (d) {
                    return [d.y, d.x];
                });

        _nodes.x0 = (_height - _margins.top - _margins.bottom) / 2;
        _nodes.y0 = 0;

        render(_nodes);
    }

    function render(source) {
        var nodes = _tree.nodes(_nodes).reverse();

        renderNodes(nodes, source);

        renderLinks(nodes, source);
    }

    function renderNodes(nodes, source) {
        nodes.forEach(function (d) {
            d.y = d.depth * 90;
        });

        var node = _bodyG.selectAll("g.node")
                .data(nodes, function (d) {
                    return d.id || (d.id = ++_i);
                });

        var nodeEnter = node.enter().append("svg:g")
                .attr("class", "node")
                .attr("transform", function (d) {
                    return "translate(" + source.y0
						+ "," + source.x0 + ")";
                })
                .on("click", function (d) {
                    toggle(d);
                    render(d);
                });

    var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

        nodeEnter.append("svg:circle")
                .attr("r", 1e-6)
                .attr("class","synsetNode")
                .style("fill", "steelblue")
                .attr("title",function(d){
                	var str = "Definition: " + d.data.definition + "
";
                	str += "POS: " + d.data.pos;
                	str += "
";
                	str += "Lexical Domain: " + d.data.lexdomain;
                  str += "
";
                  str += "Counter: " + d.count;
                  str += "Corpus words: " + d.words;
                	return str; })
                .on("mouseover", function(d) {
                  var str = "";
                  if (d.words){
                    str += "Words: " + d.words.join(", ");
                    str += "
"
                    str += "Definition: " + d.data.definition + "
";
                    str += "POS: " + d.data.pos;
                    str += "
";
                    str += "Lexical Domain: " + d.data.lexdomain;
                    str += "
";
                    str += "Count: " + d.count;
                  }
                  else {
                    str += "Definition: " + d.data.definition + "
";
                    str += "POS: " + d.data.pos;
                    str += "
";
                    str += "Lexical Domain: " + d.data.lexdomain;
                    str += "
";
                    str += "Count: " + d.count;
                  }
                    div.transition()
                       .duration(200)
                       .style("opacity", .9);
                    div.html(str)
                       .style("left", (d3.event.pageX) + "px")
                       .style("top", (d3.event.pageY - 100) + "px");
                  })
                .on("mouseout", function(d) {
                    div.transition()
                        .duration(500)
                        .style("opacity", 0);
                });

        var nodeUpdate = node.transition()
                .attr("transform", function (d) {
                    return "translate(" + d.y + "," + d.x + ")";
                });

        nodeUpdate.select("circle")
                .attr("r", 4.5)
                .style("fill", "steelblue");

        var nodeExit = node.exit().transition()
                .attr("transform", function (d) {
                    return "translate(" + source.y
						+ "," + source.x + ")";
                })
                .remove();

        nodeExit.select("circle")
                .attr("r", 1e-6);

        renderLabels(nodeEnter, nodeUpdate, nodeExit);

        nodes.forEach(function (d) {
            d.x0 = d.x;
            d.y0 = d.y;
        });
    }

    function renderLabels(nodeEnter, nodeUpdate, nodeExit) {
        nodeEnter.append("svg:text")
                .attr("x", function (d) {
                    return d.children || d._children ? -10 : 10;
                })
                .attr("class","synsetLabels")
                .attr("dy", ".35em")
                .attr("text-anchor", function (d) {
                    return d.children || d._children ? "end" : "start";
                })
                .text(function (d) {
                	console.log(d.words)
                    var words =  d.data.words.slice(0, 3).map(function(e){ return e.lemma; });
                    return words.join(", ");
                })
                .style("fill-opacity", 1e-6);

        nodeUpdate.select("text")
                .style("fill-opacity", 1);

        nodeExit.select("text")
                .style("fill-opacity", 1e-6);

        nodeEnter.append("svg:text")
                 .attr("class","words")
                 .attr("x", function (d) {
                    return d.children || d._children ? -10 : 10;
                })
                .attr("dy", ".35em")
                .attr("text-anchor", function (d) {
                    return d.children || d._children ? "end" : "start";
                })
                .text(function (d) {
                    var words =  d.words || [];
                    return words.slice(0,3).join(", ");
                })
    }

    function renderLinks(nodes, source) {
        var link = _bodyG.selectAll("path.link")
                .data(_tree.links(nodes), function (d) {
                  console.log(d.target.id)
                    return d.target.id;
                });

        link.enter().insert("svg:path", "g")
                .attr("class", "link")
                .attr("d", function (d) {
                    var o = {x: source.x0, y: source.y0};
                    return _diagonal({source: o, target: o});
                });

        link.transition()
                .attr("d", _diagonal);

        link.exit().transition()
                .attr("d", function (d) {
                    var o = {x: source.x, y: source.y};
                    return _diagonal({source: o, target: o});
                })
                .remove();

        $("#spinnerContainer").hide();
    }

    function toggle(d) {
        if (d.children) {
            d._children = d.children;
            d.children = null;
        } else {
            d.children = d._children;
            d._children = null;
        }
    }

    function toggleAll(d) {
        if (d.children) {
            d.children.forEach(toggleAll);
            toggle(d);
        }
    }

    _chart.width = function (w) {
        if (!arguments.length) return _width;
        _width = w;
        return _chart;
    };

    _chart.height = function (h) {
        if (!arguments.length) return _height;
        _height = h;
        return _chart;
    };

    _chart.margins = function (m) {
        if (!arguments.length) return _margins;
        _margins = m;
        return _chart;
    };

    _chart.nodes = function (n) {
        if (!arguments.length) return _nodes;
        _nodes = n;
        return _chart;
    };

    return _chart;
}

var chart = tree();

paintSentenceGraph.last_query = "";

function paintSentenceGraph(type) {
  var $docs = $("#document_holder textarea");
  var corpus = [];
  $docs.each(function(index, elem){
    corpus.push(elem.value);
  });

  var treshold = $("#pruning_treshold").val();
  var postData = {"corpus": corpus,
                  "treshold": treshold};
  var postDataJSON = JSON.stringify(postData);
	query = encodeURIComponent($("#input_text").val());

    if(query !== ""){
      if(postDataJSON !== paintSentenceGraph.last_query){
      url = "http://philipp-burckhardt.com:12000/analyze_corpus";

        $.ajax({
            type : "POST",
            url : url,
            data: postDataJSON
        }).done(function(msg) {
            var root = msg;
            root.data = {};
            root.count = "NA";
            root.parentId = "NA";
            root.words = null;
            root.data.words = [{lemma: "root"}];
            root.data.lexdomain = "NA";
            root.data.definition = "NA";
            root.data.pos = "NA";
            root.data.children = msg;
            console.log(root)
            paintSentenceGraph.data = root;

            switch(type){
              case "text":
                renderText(paintSentenceGraph.data);
              break;
              case "graph":
                chart.nodes(root).render();
              break;
            }

            paintSentenceGraph.last_query  = corpusJSON;
        });
      } else {
           switch(type){
              case "text":
              console.log(paintSentenceGraph.data)
                renderText(paintSentenceGraph.data);
              break;
              case "graph":
                chart.nodes(paintSentenceGraph.data).render();
              break;
            }

      }
    }

}

function clearSentence(){
	d3.select("#graph").remove();
  d3.select("#dendogram").remove();
	chart = tree();
}

function renderText(input){

var countLeafElements = (function (){
  var counter = 0;
  return function(obj){
    if (obj.children && obj.children.length > 0){
      obj.children.forEach(countLeafElements);
    } else {
      counter += 1;
    }
    return counter;
  }
}());

var numberOfLeafs = countLeafElements(input);

var width = window.innerWidth,
    height = numberOfLeafs *  15;

var cluster = d3.layout.cluster()
    .size([height, width - 160]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("id","dendogram")
    .append("g")
    .attr("transform", "translate(40,0)");

  var nodes = cluster.nodes(input),
      links = cluster.links(nodes);

  console.log(_nodes)

  var link = svg.selectAll(".link")
      .data(links)
      .enter().append("path")
      .attr("id",function(d){ return d.synsetid })
      .attr("class", "link")
      .attr("d", diagonal);

  var node = svg.selectAll(".node")
      .data(nodes)
      .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("text")
      .attr("dx", function(d) { return d.children ? -8 : 8; })
      .attr("dy", 3)
      .style("text-anchor", function(d) { return d.children ? "end" : "start"; })
      .style("-webkit-transform","rotate(0deg)")
      .text(function(d) { return d.words[0].lemma; });

  return svg;
}

var docCount = 1;
$(function() {
  $body = $("body");
  $body.append("

");
  $spinnerContainer = $("#spinnerContainer");
  $spinnerContainer.append("

")
  $("#spinner").append("

");

  $document_holder = $("#document_holder");
  $document_holder.append("
Document " + docCount + "
")
  $document_holder.append("<textarea rows=4> </textarea>");

  $addDocumentBtn = $("#add_document_button");
  $addDocumentBtn.on("click", function(){
  	docCount += 1;
  	$document_holder.append("
Document " + docCount + "
")
  	$document_holder.append("<textarea rows=4> </textarea>");
  })

  $("#analyze_button").on("click", function(){
    $spinnerContainer.fadeIn();
    $("body").css({"overflow-y":"scroll"});
    $(".row").hide();
    $("#back_button").show();

    d3.select("#graph").remove();
    chart = tree();
    paintSentenceGraph("graph");
  });

  $("#back_button").on("click",function(){
    clearSentence();
    $(this).hide();
    $(".row").fadeIn("normal");
  })

});<commit_msg>site js changes<commit_after>function tree() {
    var _chart = {};

    var _width = 1600, _height = 800,
            _margins = {top: 30, left: 120, right: 30, bottom: 30},
            _svg,
            _nodes,
            _i = 0,
            _tree,
            _diagonal,
            _bodyG;

   function zoom() {
	 _svg.attr("transform", "translate("
     + d3.event.translate
     + ")scale(" + d3.event.scale + ")");
   }

    _chart.render = function () {
    	tree.iterator += 1;
        if (!_svg) {
            _svg = d3.select("body").append("svg")
                    .attr("height", _height)
                    .attr("width", _width)
                    .attr("id", "graph");
        }

        renderBody(_svg);
    };

    function renderBody(svg) {
        if (!_bodyG) {
            _bodyG = svg.append("g")
				.attr("class", "body")
				.attr("transform", function (d) {
					return "translate(" + _margins.left
						+ "," + _margins.top + ")";
				}).call( // <-A
                        d3.behavior.zoom() // <-B
                        .scaleExtent([1, 8]) // <-C
                        .on("zoom", zoom) // <-D
                );
        }

        _tree = d3.layout.tree()
                .size([
					(_height - _margins.top - _margins.bottom),
					(_width - _margins.left - _margins.right)
				]);

        _diagonal = d3.svg.diagonal()
                .projection(function (d) {
                    return [d.y, d.x];
                });

        _nodes.x0 = (_height - _margins.top - _margins.bottom) / 2;
        _nodes.y0 = 0;

        render(_nodes);
    }

    function render(source) {
        var nodes = _tree.nodes(_nodes).reverse();

        renderNodes(nodes, source);

        renderLinks(nodes, source);
    }

    function renderNodes(nodes, source) {
        nodes.forEach(function (d) {
            d.y = d.depth * 90;
        });

        var node = _bodyG.selectAll("g.node")
                .data(nodes, function (d) {
                    return d.id || (d.id = ++_i);
                });

        var nodeEnter = node.enter().append("svg:g")
                .attr("class", "node")
                .attr("transform", function (d) {
                    return "translate(" + source.y0
						+ "," + source.x0 + ")";
                })
                .on("click", function (d) {
                    toggle(d);
                    render(d);
                });

    var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

        nodeEnter.append("svg:circle")
                .attr("r", 1e-6)
                .attr("class","synsetNode")
                .style("fill", "steelblue")
                .attr("title",function(d){
                	var str = "Definition: " + d.data.definition + "
";
                	str += "POS: " + d.data.pos;
                	str += "
";
                	str += "Lexical Domain: " + d.data.lexdomain;
                  str += "
";
                  str += "Counter: " + d.count;
                  str += "Corpus words: " + d.words;
                	return str; })
                .on("mouseover", function(d) {
                  var str = "";
                  if (d.words){
                    str += "Words: " + d.words.map(function(x){
                      return x.string + "(" + x.count + ")"}).join(" , ");
                    str += "
"
                    str += "Definition: " + d.data.definition + "
";
                    str += "POS: " + d.data.pos;
                    str += "
";
                    str += "Lexical Domain: " + d.data.lexdomain;
                    str += "
";
                    str += "Count: " + d.count;
                  }
                  else {
                    str += "Definition: " + d.data.definition + "
";
                    str += "POS: " + d.data.pos;
                    str += "
";
                    str += "Lexical Domain: " + d.data.lexdomain;
                    str += "
";
                    str += "Count: " + d.count;
                  }
                    div.transition()
                       .duration(200)
                       .style("opacity", .9);
                    div.html(str)
                       .style("left", (d3.event.pageX) + "px")
                       .style("top", (d3.event.pageY - 100) + "px");
                  })
                .on("mouseout", function(d) {
                    div.transition()
                        .duration(500)
                        .style("opacity", 0);
                });

        var nodeUpdate = node.transition()
                .attr("transform", function (d) {
                    return "translate(" + d.y + "," + d.x + ")";
                });

        nodeUpdate.select("circle")
                .attr("r", 4.5)
                .style("fill", "steelblue");

        var nodeExit = node.exit().transition()
                .attr("transform", function (d) {
                    return "translate(" + source.y
						+ "," + source.x + ")";
                })
                .remove();

        nodeExit.select("circle")
                .attr("r", 1e-6);

        renderLabels(nodeEnter, nodeUpdate, nodeExit);

        nodes.forEach(function (d) {
            d.x0 = d.x;
            d.y0 = d.y;
        });
    }

    function renderLabels(nodeEnter, nodeUpdate, nodeExit) {
        nodeEnter.append("svg:text")
                .attr("x", function (d) {
                    return d.children || d._children ? -10 : 10;
                })
                .attr("class","synsetLabels")
                .attr("dy", ".35em")
                .attr("text-anchor", function (d) {
                    return d.children || d._children ? "end" : "start";
                })
                .text(function (d) {
                	console.log(d.words)
                    var words =  d.data.words.slice(0, 3).map(function(e){ return e.lemma; });
                    return words.join(", ");
                })
                .style("fill-opacity", 1e-6);

        nodeUpdate.select("text")
                .style("fill-opacity", 1);

        nodeExit.select("text")
                .style("fill-opacity", 1e-6);

    }

    function renderLinks(nodes, source) {
        var link = _bodyG.selectAll("path.link")
                .data(_tree.links(nodes), function (d) {
                    return d.target.id;
                });

        link.enter().insert("svg:path", "g")
                .attr("class", "link")
                .attr("d", function (d) {
                    var o = {x: source.x0, y: source.y0};
                    return _diagonal({source: o, target: o});
                });

        link.transition()
                .attr("d", _diagonal);

        link.exit().transition()
                .attr("d", function (d) {
                    var o = {x: source.x, y: source.y};
                    return _diagonal({source: o, target: o});
                })
                .remove();

        $("#spinnerContainer").hide();
    }

    function toggle(d) {
        if (d.children) {
            d._children = d.children;
            d.children = null;
        } else {
            d.children = d._children;
            d._children = null;
        }
    }

    function toggleAll(d) {
        if (d.children) {
            d.children.forEach(toggleAll);
            toggle(d);
        }
    }

    _chart.width = function (w) {
        if (!arguments.length) return _width;
        _width = w;
        return _chart;
    };

    _chart.height = function (h) {
        if (!arguments.length) return _height;
        _height = h;
        return _chart;
    };

    _chart.margins = function (m) {
        if (!arguments.length) return _margins;
        _margins = m;
        return _chart;
    };

    _chart.nodes = function (n) {
        if (!arguments.length) return _nodes;
        _nodes = n;
        return _chart;
    };

    return _chart;
}

var chart = tree();

paintSentenceGraph.last_query = "";

function paintSentenceGraph(type) {
  var $docs = $("#document_holder textarea");
  var corpus = [];
  $docs.each(function(index, elem){
    corpus.push(elem.value);
  });

  var treshold = $("#pruning_treshold").val();
  if(treshold ==="sqrt(n)"){
    treshold = Math.sqrt(corpus.length);
  }

  var postData = {"corpus": corpus,
                  "treshold": treshold};
  var postDataJSON = JSON.stringify(postData);
	query = encodeURIComponent($("#input_text").val());

    if(query !== ""){
      if(postDataJSON !== paintSentenceGraph.last_query){
      url = "http://localhost:12000/analyze_corpus";

        $.ajax({
            type : "POST",
            url : url,
            data: postDataJSON
        }).done(function(msg) {
            var root = msg;
            root.data = {};
            root.count = "NA";
            root.parentId = "NA";
            root.words = null;
            root.data.words = [{lemma: "root"}];
            root.data.lexdomain = "NA";
            root.data.definition = "NA";
            root.data.pos = "NA";
            root.data.children = msg;
            console.log(root)
            paintSentenceGraph.data = root;

            switch(type){
              case "text":
                renderText(paintSentenceGraph.data);
              break;
              case "graph":
                chart.nodes(root).render();
                //get svg element.
                var svg = document.getElementById("graph");

                //get svg source.
                var serializer = new XMLSerializer();
                var source = serializer.serializeToString(svg);

                //add name spaces.
                if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
                    source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
                }
                if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
                    source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
                }
                //add xml declaration
                source = '<?xml version="1.0" standalone="no"?><?xml-stylesheet href="styles.css" type="text/css"?> \r\n' + source;
                //convert svg source to URI data scheme.
                var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);
                document.getElementById("save_svg_button").href = url;

              break;
            }

            paintSentenceGraph.last_query  = postDataJSON;
        });
      } else {
           switch(type){
              case "text":
              console.log(paintSentenceGraph.data)
                renderText(paintSentenceGraph.data);
              break;
              case "graph":
                chart.nodes(paintSentenceGraph.data).render();
              break;
            }

      }
    }

}

function clearSentence(){
	d3.select("#graph").remove();
  d3.select("#dendogram").remove();
	chart = tree();
}

function renderText(input){

var countLeafElements = (function (){
  var counter = 0;
  return function(obj){
    if (obj.children && obj.children.length > 0){
      obj.children.forEach(countLeafElements);
    } else {
      counter += 1;
    }
    return counter;
  }
}());

var numberOfLeafs = countLeafElements(input);

var width = window.innerWidth,
    height = numberOfLeafs *  15;

var cluster = d3.layout.cluster()
    .size([height, width - 160]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("id","dendogram")
    .append("g")
    .attr("transform", "translate(40,0)");

  var nodes = cluster.nodes(input),
      links = cluster.links(nodes);

  console.log(_nodes)

  var link = svg.selectAll(".link")
      .data(links)
      .enter().append("path")
      .attr("id",function(d){ return d.synsetid })
      .attr("class", "link")
      .attr("d", diagonal);

  var node = svg.selectAll(".node")
      .data(nodes)
      .enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("text")
      .attr("dx", function(d) { return d.children ? -8 : 8; })
      .attr("dy", 3)
      .style("text-anchor", function(d) { return d.children ? "end" : "start"; })
      .style("-webkit-transform","rotate(0deg)")
      .text(function(d) {
        console.log(d.words[0])
        return d.words[0].lemma;
      });

  return svg;
}

var docCount = 1;
$(function() {
  $body = $("body");
  $body.append("

");
  $spinnerContainer = $("#spinnerContainer");
  $spinnerContainer.append("

")
  $("#spinner").append("

");

  $document_holder = $("#document_holder");
  $document_holder.append("
Document " + docCount + "
")
  $document_holder.append("<textarea rows=4> </textarea>");

  $addDocumentBtn = $("#add_document_button");
  $addDocumentBtn.on("click", function(){
  	docCount += 1;
  	$document_holder.append("
Document " + docCount + "
")
  	$document_holder.append("<textarea rows=4> </textarea>");
  })

  $("#analyze_button").on("click", function(){
    $spinnerContainer.fadeIn();
    $("body").css({"overflow-y":"scroll"});
    $(".row").hide();
    $("#plot_menu").show();

    d3.select("#graph").remove();
    chart = tree();
    paintSentenceGraph("graph");

  });

  $("#back_button").on("click",function(){
    clearSentence();
    $("#plot_menu").hide();
    $(".row").fadeIn("normal");
  })

});<|endoftext|>


<commit_before>export class Error extends this.Error {
  constructor(message) {
    super(message);
    this.message = message;
  }
}

export class Warning extends Error {
  constructor(message) {
    super(message);
    this.message = message;
  }
}
<commit_msg>Change `Warning` name<commit_after>export class Error extends this.Error {
  constructor(message) {
    super(message);
    this.message = message;
  }
}

export class Warning extends Error {
  constructor(message) {
    super(message);
    this.message = message;
  }

  get name() {
    return 'Warning';
  }
}
<|endoftext|>


<commit_before>(function(window, undefined) {

	var socket = io.connect('http://localhost');

	socket.on('player connect', function (data) {
		console.log('connection');
		console.log(data);
	});

	socket.on('player disconnect', function (data) {
		console.log('disconnection');
		console.log(data);
	});

})(window);

// CONSTANTS

// Size of the playing field
var WINDOW_WIDTH = 1280;
var WINDOW_HEIGHT = 800;

var SHIP_RADIUS = 50;

Crafty.c('ship', {
	init: function() {
		if (!this.has('2D')) this.addComponent('2D');
		if (!this.has('DOM')) this.addComponent('DOM');
		if (!this.has('Color')) this.addComponent('Color');

		this.attr({
			h: SHIP_RADIUS,
			w: SHIP_RADIUS
		});

		this.origin('center');

		this.color('#fff');
	},
	vel_x: 0,
	vel_y: 0
});

Crafty.c('player', {
	init: function () {
		if (!this.has('ship')) this.addComponent('ship');

		this.move = {
			down: false,
			left: false,
			right: false,
			up: false
		};
	}
});

Crafty.scene('ship_test', function() {
	// test a ship
	Crafty.e('ship, player').attr({
		x: WINDOW_WIDTH / 2,
		y: WINDOW_HEIGHT / 2
	});
});

window.onload = function() {
	//start crafty, full screen
	Crafty.init(WINDOW_WIDTH, WINDOW_HEIGHT);
	Crafty.scene('ship_test');
};

//Blarg<commit_msg>Initial implementation of physics and a test ship field.<commit_after>(function(window, undefined) {

	var socket = io.connect('http://localhost');

	socket.on('player connect', function (data) {
		console.log('connection');
		console.log(data);
	});

	socket.on('player disconnect', function (data) {
		console.log('disconnection');
		console.log(data);
	});

})(window);

// CONSTANTS

// Size of the playing field
var WINDOW_WIDTH = 1280;
var WINDOW_HEIGHT = 800;
var FIELD_WIDTH = 800;
var FIELD_HEIGHT = 800;

// Ship constants
var SHIP_RADIUS = 50;
var SHIP_MAX_ACCEL = 0.1;

// Physics constants
var TIME_CONST = 1;
var TIME_CONST_SQU_HALF = TIME_CONST * TIME_CONST / 2;
var DEG_TO_RAD = Math.PI / 180;

// Controls
var CTRL_ACCEL = Crafty.keys.W;
var CTRL_DECEL = Crafty.keys.S;
var CTRL_TURN_CW = Crafty.keys.A;
var CTRL_TURN_CCW = Crafty.keys.D;

Crafty.c('ship', {
	init: function() {
		if (!this.has('2D')) this.addComponent('2D');
		if (!this.has('DOM')) this.addComponent('DOM');
		if (!this.has('Color')) this.addComponent('Color');

		this.attr({
			h: SHIP_RADIUS,
			w: SHIP_RADIUS,
			vx: 0,
			vy: 0,
			ax: 0,
			ay: 0,
			health: 100,
			weapon: 100,
			engine: 100,
			rotation: -90
		});

		this.origin('center');

		this.color('#fff');

		this.bind("EnterFrame", function(e) {
			this.vx = this.vx + this.ax * TIME_CONST;
			this.vy = this.vy + this.ay * TIME_CONST;
			this.x = this.x + this.vx * TIME_CONST + TIME_CONST_SQU_HALF * this.ax;
			while (this.x > FIELD_WIDTH) {
				this.x -= FIELD_WIDTH;
			}
			while (this.x < 0) {
				this.x += FIELD_WIDTH;
			}
			while (this.y > FIELD_HEIGHT) {
				this.y -= FIELD_HEIGHT;
			}
			while (this.y < 0) {
				this.y += FIELD_HEIGHT;
			}
			this.y = this.y + this.vy * TIME_CONST + TIME_CONST_SQU_HALF * this.ay;
		});
	}
});

Crafty.c('player', {
	init: function () {
		if (!this.has('ship')) this.addComponent('ship');
		if(!this.has('Keyboard')) this.addComponent('Keyboard');

		this.shoot = true;

		this.bind("EnterFrame", function(e) {
			// TODO: drain fuel here and variable turn rate
			if (this.isDown(CTRL_TURN_CW)) {
				if (this.isDown(CTRL_TURN_CCW)) {

				} else {
					this.rotation = (this.rotation - 5) % 360;
					console.log("rotation - 5");
				}
			} else {
				if (this.isDown(CTRL_TURN_CCW)) {
					this.rotation = (this.rotation + 5) % 360;
				}
			}

			var acc = 0;
			if (this.isDown(CTRL_ACCEL)) {
				acc = SHIP_MAX_ACCEL;
				// TODO: drain fuel here and vary accel
			}
			if (this.isDown(CTRL_DECEL)) {
				acc -= SHIP_MAX_ACCEL / 2;
				// TODO: drain fuel here and vary accel
			}

			this.ax = acc * Math.cos(this.rotation * DEG_TO_RAD);
			this.ay = acc * Math.sin(this.rotation * DEG_TO_RAD);
		});
	}
});

Crafty.scene('ship_test', function() {
	// test a ship
	Crafty.e('ship, player').attr({
		x: FIELD_WIDTH / 2,
		y: FIELD_HEIGHT / 2
	});
});

window.onload = function() {
	//start crafty, full screen
	Crafty.init(WINDOW_WIDTH, WINDOW_HEIGHT);
	Crafty.scene('ship_test');
};

//Blarg<|endoftext|>


<commit_before>angular.module('socially', [
  'angular-meteor',
  'ui.router',
  'accounts.ui',
  'angularUtils.directives.dirPagination'
]);

function onReady() {
  angular.bootstrap(document, ['socially'], {
    strictDi: true
  });
}

if (Meteor.isCordova)
  angular.element(document).on("deviceready", onReady);
else
  angular.element(document).ready(onReady);<commit_msg>Step 16.2: Add google maps module dependency<commit_after>angular.module('socially', [
  'angular-meteor',
  'ui.router',
  'accounts.ui',
  'angularUtils.directives.dirPagination',
  'uiGmapgoogle-maps'
]);

function onReady() {
  angular.bootstrap(document, ['socially'], {
    strictDi: true
  });
}

if (Meteor.isCordova)
  angular.element(document).on("deviceready", onReady);
else
  angular.element(document).ready(onReady);<|endoftext|>


<commit_before>var $ = require('jquery')
  , moment = require('moment')
  , Waypoint = require('jquery-waypoints')
  , vid2gif = require('vid2gif')
  , createIdenticon = require('./identicon')

module.exports = function(listElem, muteSet) {
  return new MessageList(listElem, muteSet)
}

var MESSAGE_LIMIT = 30
  , MAX_RECYCLED = 6
  , NUM_VIDEO_FRAMES = 10

class MessageList {
  constructor(listElem, muteSet) {
    this.elem = listElem
    this.messages = []
    this._recycled = []

    this._mutes = muteSet
  }

  addMessage(chat, removeOverLimit = true) {
    if (this._mutes.has(chat.userId)) {
      return
    }

    var newCount = this.messages.length + 1
    if (removeOverLimit && newCount > MESSAGE_LIMIT) {
      let removed = this.messages.splice(0, newCount - MESSAGE_LIMIT)
      this._recycle(removed)
    }

    var message = this._recycled.length ? this._recycled.pop() : new Message(this)
    message.bind(chat)
    this.messages.push(message)
    this.elem.append(message.elem)
    this._refreshWaypoints()
    return message
  }

  muteUser(userId) {
    this._mutes.add(userId)

    var userMessages = []
      , nonUserMessages = []
    for (let message of this.messages) {
      if (message.userId == userId) {
        userMessages.push(message)
      } else {
        nonUserMessages.push(message)
      }
    }

    this._recycle(userMessages)
    this.messages = nonUserMessages
    this._refreshWaypoints()
  }

  _recycle(messages) {
    for (let message of messages) {
      message.elem.detach()
      message.unbind()
    }

    var toRecycle = Math.max(MAX_RECYCLED - this._recycled.length, 0)
    toRecycle = Math.min(toRecycle, messages.length)
    this._recycled = this._recycled.concat(messages.slice(0, toRecycle))
    for (let message of messages.slice(toRecycle, messages.length)) {
      message.elem.remove()
      message.dispose()
    }
  }

  _refreshWaypoints() {
    if (!this._waypointTimeout) {
      this._waypointTimeout = setTimeout(() => {
        Waypoint.refreshAll()
        this._waypointTimeout = null
      }, 0)
    }
  }
}

var MESSAGE_HTML = [
  '
',
    '
',
      '<video autoplay loop webkit-playsinline />',
      '<button class="save shadow-1" title="Save as GIF">',
        '
',
      '</button>',
    '
',
    '
',
    '
',
      '<time/>',
      '
',
      '
',
        '<button class="mute shadow-1" title="Mute user">',
          '
',
        '</button>',
      '
',
    '
',
  '
',
].join('')

class Message {
  constructor(owner) {
    this._disposed = false
    this._userId = null
    this.owner = owner

    this.root = $(MESSAGE_HTML)
    this.video = this.root.find('video')
    this.saveButton = this.root.find('.save')
    this.chatText = this.root.find('>p')
    this.timestamp = this.root.find('time')
    // placeholder div so it can be replaced with the real thing when bound
    this.identicon = this.root.find('.identicon')
    this.muteButton = this.root.find('.mute')

    this.waypoints = [
      new Waypoint({
        element: this.root[0],
        offset: () => -this.root.outerHeight(),
        handler: direction => this.handleWaypoint('bottom', direction),
      }),
      new Waypoint({
        element: this.root[0],
        offset: '100%',
        handler: direction => this.handleWaypoint('top', direction),
      }),
    ]
    for (let waypoint of this.waypoints) {
      waypoint.disable()
    }

    this.saveButton.on('click', () => this.saveGif())
    this.muteButton.on('click', () => this.mute())
  }

  bind({ key, text, sent, userId, from, video, videoMime, videoType }) {
    this._throwIfDisposed()
    this.unbind()

    var blob = new Blob([ video ], { type: videoMime })
      , url = window.URL.createObjectURL(blob)
    this.video.attr('src', url)

    this.chatText.html(text)

    var sentDate = moment(new Date(sent))
    this.timestamp.attr('datetime', sentDate.toISOString()).text(sentDate.format('LT'))

    var newIdenticon = createIdenticon(userId)
    this.identicon.replaceWith(newIdenticon)
    this.identicon = newIdenticon

    this._userId = userId
    for (let waypoint of this.waypoints) {
      waypoint.enable()
    }
  }

  unbind() {
    this._throwIfDisposed()
    this._userId = null

    if(this.video.attr('src')) {
      let src = this.video.attr('src')
      this.video.attr('src', '')
      window.URL.revokeObjectURL(src)
    }
    for (let waypoint of this.waypoints) {
      waypoint.disable()
    }
  }

  dispose() {
    this._throwIfDisposed()
    this._disposed = true

    for (let waypoint of this.waypoints) {
      waypoint.destroy()
    }
    this.waypoints.length = 0
  }

  saveGif() {
    this._throwIfDisposed()
    this.saveButton.prop('disabled', true)
    vid2gif(this.video[0], NUM_VIDEO_FRAMES, (err, gifBlob) => {
      this.saveButton.prop('disabled', false)
      if (err) {
        // TODO(tec27): need a good way to display this error to users
        console.error('Error creating GIF:')
        return console.dir(err)
      }

      var url = window.URL.createObjectURL(gifBlob)
        , link = $('')
        , click = document.createEvent('MouseEvents')

      link
        .attr('href', url)
        .attr('download', Date.now() + '.gif')
      click.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0,
          false, false, false, false, 0, null)
      link[0].dispatchEvent(click)
      window.URL.revokeObjectURL(url)
    })
  }

  mute() {
    this._throwIfDisposed()
    this.owner.muteUser(this._userId)
  }

  handleWaypoint(side, direction) {
    if ((side == 'top' && direction == 'down') || (side == 'bottom' && direction == 'up')) {
      this.root.addClass('displayed')
      // Workaround for a bug in Chrome where calling play() on a looping video that is on or
      // around its last frame results in it thinking its playing, but actually being paused
      if (this.video[0].duration &&
          Math.abs(this.video[0].currentTime - this.video[0].duration) < 0.2) {
        this.video[0].currentTime = 0
      }
      this.video[0].play()
    } else {
      this.root.removeClass('displayed')
      this.video[0].pause()
    }
    // TODO(tec27): tell owner about this so it can recycle on scrolling?
  }

  get elem() {
    return this.root
  }

  get userId() {
    return this._userId
  }

  _throwIfDisposed() {
    if (this._disposed) throw new Error('Message already disposed!')
  }
}
<commit_msg>Handle mobile safari a bit better: don't auto-open full screen videos when waypoints update.<commit_after>var $ = require('jquery')
  , moment = require('moment')
  , Waypoint = require('jquery-waypoints')
  , vid2gif = require('vid2gif')
  , createIdenticon = require('./identicon')

module.exports = function(listElem, muteSet) {
  return new MessageList(listElem, muteSet)
}

var MESSAGE_LIMIT = 30
  , MAX_RECYCLED = 6
  , NUM_VIDEO_FRAMES = 10

class MessageList {
  constructor(listElem, muteSet) {
    this.elem = listElem
    this.messages = []
    this._recycled = []

    this._mutes = muteSet
  }

  addMessage(chat, removeOverLimit = true) {
    if (this._mutes.has(chat.userId)) {
      return
    }

    var newCount = this.messages.length + 1
    if (removeOverLimit && newCount > MESSAGE_LIMIT) {
      let removed = this.messages.splice(0, newCount - MESSAGE_LIMIT)
      this._recycle(removed)
    }

    var message = this._recycled.length ? this._recycled.pop() : new Message(this)
    message.bind(chat)
    this.messages.push(message)
    this.elem.append(message.elem)
    this._refreshWaypoints()
    return message
  }

  muteUser(userId) {
    this._mutes.add(userId)

    var userMessages = []
      , nonUserMessages = []
    for (let message of this.messages) {
      if (message.userId == userId) {
        userMessages.push(message)
      } else {
        nonUserMessages.push(message)
      }
    }

    this._recycle(userMessages)
    this.messages = nonUserMessages
    this._refreshWaypoints()
  }

  _recycle(messages) {
    for (let message of messages) {
      message.elem.detach()
      message.unbind()
    }

    var toRecycle = Math.max(MAX_RECYCLED - this._recycled.length, 0)
    toRecycle = Math.min(toRecycle, messages.length)
    this._recycled = this._recycled.concat(messages.slice(0, toRecycle))
    for (let message of messages.slice(toRecycle, messages.length)) {
      message.elem.remove()
      message.dispose()
    }
  }

  _refreshWaypoints() {
    if (!this._waypointTimeout) {
      this._waypointTimeout = setTimeout(() => {
        Waypoint.refreshAll()
        this._waypointTimeout = null
      }, 0)
    }
  }
}

var MESSAGE_HTML = [
  '
',
    '
',
      '<video loop webkit-playsinline />',
      '<button class="save shadow-1" title="Save as GIF">',
        '
',
      '</button>',
    '
',
    '
',
    '
',
      '<time/>',
      '
',
      '
',
        '<button class="mute shadow-1" title="Mute user">',
          '
',
        '</button>',
      '
',
    '
',
  '
',
].join('')

class Message {
  constructor(owner) {
    this._disposed = false
    this._userId = null
    this.owner = owner

    this.root = $(MESSAGE_HTML)
    this.video = this.root.find('video')
    this.saveButton = this.root.find('.save')
    this.chatText = this.root.find('>p')
    this.timestamp = this.root.find('time')
    // placeholder div so it can be replaced with the real thing when bound
    this.identicon = this.root.find('.identicon')
    this.muteButton = this.root.find('.mute')

    this.waypoints = [
      new Waypoint({
        element: this.root[0],
        offset: () => -this.root.outerHeight(),
        handler: direction => this.handleWaypoint('bottom', direction),
      }),
      new Waypoint({
        element: this.root[0],
        offset: '100%',
        handler: direction => this.handleWaypoint('top', direction),
      }),
    ]
    for (let waypoint of this.waypoints) {
      waypoint.disable()
    }

    this.saveButton.on('click', () => this.saveGif())
    this.muteButton.on('click', () => this.mute())
  }

  bind({ key, text, sent, userId, from, video, videoMime, videoType }) {
    this._throwIfDisposed()
    this.unbind()

    var blob = new Blob([ video ], { type: videoMime })
      , url = window.URL.createObjectURL(blob)
    this.video.attr('src', url)

    this.chatText.html(text)

    var sentDate = moment(new Date(sent))
    this.timestamp.attr('datetime', sentDate.toISOString()).text(sentDate.format('LT'))

    var newIdenticon = createIdenticon(userId)
    this.identicon.replaceWith(newIdenticon)
    this.identicon = newIdenticon

    this._userId = userId
    for (let waypoint of this.waypoints) {
      waypoint.enable()
    }
  }

  unbind() {
    this._throwIfDisposed()
    this._userId = null

    if(this.video.attr('src')) {
      let src = this.video.attr('src')
      this.video.attr('src', '')
      window.URL.revokeObjectURL(src)
    }
    for (let waypoint of this.waypoints) {
      waypoint.disable()
    }
  }

  dispose() {
    this._throwIfDisposed()
    this._disposed = true

    for (let waypoint of this.waypoints) {
      waypoint.destroy()
    }
    this.waypoints.length = 0
  }

  saveGif() {
    this._throwIfDisposed()
    this.saveButton.prop('disabled', true)
    vid2gif(this.video[0], NUM_VIDEO_FRAMES, (err, gifBlob) => {
      this.saveButton.prop('disabled', false)
      if (err) {
        // TODO(tec27): need a good way to display this error to users
        console.error('Error creating GIF:')
        return console.dir(err)
      }

      var url = window.URL.createObjectURL(gifBlob)
        , link = $('')
        , click = document.createEvent('MouseEvents')

      link
        .attr('href', url)
        .attr('download', Date.now() + '.gif')
      click.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0,
          false, false, false, false, 0, null)
      link[0].dispatchEvent(click)
      window.URL.revokeObjectURL(url)
    })
  }

  mute() {
    this._throwIfDisposed()
    this.owner.muteUser(this._userId)
  }

  handleWaypoint(side, direction) {
    if ((side == 'top' && direction == 'down') || (side == 'bottom' && direction == 'up')) {
      this.root.addClass('displayed')
      // Workaround for a bug in Chrome where calling play() on a looping video that is on or
      // around its last frame results in it thinking its playing, but actually being paused
      if (this.video[0].duration &&
          Math.abs(this.video[0].currentTime - this.video[0].duration) < 0.2) {
        this.video[0].currentTime = 0
      }
      playVideo(this.video[0])
    } else {
      this.root.removeClass('displayed')
      this.video[0].pause()
    }
    // TODO(tec27): tell owner about this so it can recycle on scrolling?
  }

  get elem() {
    return this.root
  }

  get userId() {
    return this._userId
  }

  _throwIfDisposed() {
    if (this._disposed) throw new Error('Message already disposed!')
  }
}

// wish there was a better way to detect the "must watch videos in fullscreen only" restriction, but
// as of yet this is all I know
var isSmallIos = /iPhone|iPod/.test(navigator.userAgent)
function playVideo(video) {
  // don't actually call play on small iOS devices since this will cause an annoying video popup
  // for them
  if (!isSmallIos) {
    setTimeout(() => video.play(), 0)
  }
}
<|endoftext|>


<commit_before>var EventManager = require('dom-event-manager');

var eventManager;

function eventHandler(name, e) {
  var element = e.delegateTarget;

  if (!element.domLayerNode || !element.domLayerNode.events) {
    return;
  }

  var events = []
  var mouseClickEventName;
  var bail = false;

  if (name.substr(name.length - 5) === 'click') {
    mouseClickEventName = 'onmouse' + name;
    if (element.domLayerNode.events[mouseClickEventName]) {
      events.push(mouseClickEventName);
    }
    // Do not call the `click` handler if it's not a left click.
    if (e.button !== 0) {
      bail = true;
    }
  }

  var eventName;
  if (!bail) {
    eventName = 'on' + name;
    if (element.domLayerNode.events[eventName]) {
      events.push(eventName);
    }
  }

  if (!events.length) {
    return;
  }

  for (var i = 0, len = events.length; i < len ; i++) {
    element.domLayerNode.events[events[i]](e, element.domLayerNode);
  }
}

function getManager() {
  if (eventManager) {
    return eventManager;
  }
  return eventManager = new EventManager(eventHandler);
}

function init() {
  var em = getManager();
  em.bindDefaultEvents();
  return em;
}

module.exports = {
  EventManager: EventManager,
  getManager: getManager,
  init: init
};
<commit_msg>Support 'auxclick' event.<commit_after>var EventManager = require('dom-event-manager');

var eventManager;

function eventHandler(name, e) {
  var element = e.delegateTarget;

  if (!element.domLayerNode || !element.domLayerNode.events) {
    return;
  }

  var events = []
  var mouseClickEventName;
  var bail = false;

  if (name.substr(name.length - 5) === 'click') {
    mouseClickEventName = 'onmouse' + name;
    if (element.domLayerNode.events[mouseClickEventName]) {
      events.push(mouseClickEventName);
    }
    // Do not call the `click` handler if it's not a left click.
    if (e.button !== 0 && name.substr(0, 3) !== 'aux') {
      bail = true;
    }
  }

  var eventName;
  if (!bail) {
    eventName = 'on' + name;
    if (element.domLayerNode.events[eventName]) {
      events.push(eventName);
    }
  }

  if (!events.length) {
    return;
  }

  for (var i = 0, len = events.length; i < len ; i++) {
    element.domLayerNode.events[events[i]](e, element.domLayerNode);
  }
}

function getManager() {
  if (eventManager) {
    return eventManager;
  }
  return eventManager = new EventManager(eventHandler);
}

function init() {
  var em = getManager();
  em.bindDefaultEvents();
  return em;
}

module.exports = {
  EventManager: EventManager,
  getManager: getManager,
  init: init
};
<|endoftext|>