<commit_before>/*
 * PsychoMonkey
 * Copyright (C) 2012 Simon Kornblith
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var PTB = function(context) {
	this.ctx = context;
}
PTB.prototype = {
	"FillOval":function(color, rect) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "fillStyle", "white");
			var rects = this._getRectArray();
			for(var i=0; i<rects.length; i++) {
				if(colorArray) this.ctx.fillStyle = this._colorToStyle(colorArray[i]);
				this._makeOvalPath(rects[i]);
				this.ctx.fill();
			}
		} finally {
			this.ctx.restore();
		}
	},
	"FrameOval":function(color, rect, penWidth) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "strokeStyle", "white");
			if(typeof penWidth !== "object") penWidth = [penWidth];
			if(penWidth.length === 1) this.ctx.lineWidth = penWidth ? penWidth : 1;
			var rects = this._getRectArray();
			for(var i=0; i<rects.length; i++) {
				if(colorArray) this.ctx.strokeStyle = this._colorToStyle(colorArray[i]);
				if(penWith.length !== 1) this.ctx.lineWidth = penWidth[i];
				this._makeOvalPath(rects[i]);
				this.ctx.stroke();
			}
		} finally {
			this.ctx.restore();
		}
	},
	"FillRect":function(color, rect) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "fillStyle", "white");
			var rects = this._getRectArray();
			for(var i=0; i<rects.length; i++) {
				var rect = rects[i];
				if(colorArray) this.ctx.fillStyle = this._colorToStyle(colorArray[i]);
				this.ctx.fillRect(rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]);
			}
		} finally {
			this.ctx.restore();
		}
	},
	"FrameRect":function(color, rect, penWidth) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "strokeStyle", "white");
			if(typeof penWidth !== "object") penWidth = [penWidth];
			if(penWidth.length === 1) this.ctx.lineWidth = penWidth ? penWidth : 1;
			var rects = this._getRectArray();
			for(var i=0; i<rects.length; i++) {
				var rect = rects[i];
				if(colorArray) this.ctx.strokeStyle = this._colorToStyle(colorArray[i]);
				if(penWidth.length !== 1) this.ctx.lineWidth = penWidth[i];
				this.ctx.strokeRect(rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]);
			}
		} finally {
			this.ctx.restore();
		}
	},
	"DrawDots":function(xy, size, color, center, dot_type) {
		this.ctx.save();
		try {
			if(!size) size = 1;
			if(!dot_type) dot_type = 0;

			var colorArray = this._getColorArrayOrSetColor(color, "fillStyle", "black");
			if(center) this.ctx.translate(center[0], center[1]);

			var x = typeof xy[0] === "object" ? xy[0] : [xy[0]],
				y = typeof xy[1] === "object" ? xy[1] : [xy[1]];
			for(var i=0; i<x.length; i++) {
				if(colorArray) this.ctx.fillStyle = this._colorToStyle(colorArray[i]);
				var dotSize = typeof size === "object" ? size[i] : size;
				if(dot_type === 0) {
					this.ctx.fillRect(x[i]-dotSize/2, y[i]-dotSize/2,
						x[i]+dotSize/2, y[i]+dotSize/2);
				} else {
					this.ctx.beginPath();
					this.ctx.arc(x[i], y[i], dotSize/2, 0, Math.PI*2, false);
					this.ctx.closePath();
					this.ctx.fill();
				}
			}
		} finally {
			this.ctx.restore();
		}
	},
	"_transpose":function(array) {
		var newArray = [];
		for(var i=0; i<array[0].length; i++) {
			var newArrayX = [];
			for(var j=0; j<array.length; j++) {
				newArrayX.push(array[j][i]);
			}
			newArray.push(newArrayX);
		}
		return newArray;
	},
	"_makeOvalPath":function(rect) {
		var width = rect[3]-rect[1],
			height = rect[4]-rect[2];
		this.ctx.beginPath();
		this.ctx.translate(rect[1]+width/2, rect[2]+height/2);
		this.ctx.scale(width/2, height/2);
		this.ctx.arc(0, 0, 1, 0, Math.PI*2, false);
		this.ctx.closePath();
	},
	"_getColorArrayOrSetColor":function(color, style, defaultColor) {
		if(color === null || color === undefined) {
			this.ctx[style] = defaultColor;
			return undefined;
		}
		if(typeof color === "object" && typeof color[0] === "object") {
			return this._transpose(color);
		}
		this.ctx[style] = this._colorToStyle(color);
		return undefined;
	},
	"_getRectArray":function(rect) {
		if(!rect) {
			return [0, 0, CONFIG.displaySize[0], CONFIG.displaySize[1]];
		}
		if(typeof rect[0] === "object") {
			return this._transpose(rect);
		}
		return [rect];
	},
	"_colorToStyle":function(color) {
		if(color === null || color === undefined) {
			return "white";
		} else if(typeof color !== "object") {
			return "rgb("+color+", "+color+", "+color+")";
		} else if(color.length === 1) {
			return "rgb("+color[0]+", "+color[0]+", "+color[0]+")";
		} else if(color.length === 3) {
			return "rgb("+color[0]+", "+color[1]+", "+color[2]+")";
		} else if(color.length === 4) {
			return "rgba("+color[0]+", "+color[1]+", "+color[2]+", "+color[3]+")";
		} else {
			throw new Error("Invalid color");
		}
	}
};

var OSD = function(div) {
};
OSD.prototype.update = function(info) {
};

var Client = function(canvas) {
	this.canvas = canvas;
	this.ctx = canvas.getContext("2d");
	this.ptb = new PTB(this.ctx);
	this._lastEyePosition = null;
	this._textures = {};
}
Client.prototype = {
	/**
	 * Updates the on-screen display
	 */
	"OSD":function(info) {
		document.getElementById("osd-state").textContent = info.state;

		var longestKey = 0,
			keyInfoStrings = [];
		for(var i in info.keyInfo) {
			if(i.length > longestKey) longestKey = i.length;
		}
		for(var i in info.keyInfo) {
			var str = i;
			while(str.length < longestKey) str += " ";
			str += " - "+info.keyInfo[i];
			keyInfoStrings.push(str);
		}
		document.getElementById("osd-keyInfo").textContent = keyInfoStrings.join("\n");

		var performanceStrings = [];
		for(var i in info.performance) {
			var success = info.performance[i][0];
			var total = info.performance[i][1];
			if(total == 0) {
				var pct = 0;
			} else {
				var pct = Math.round(success/total*100);
			}
			performanceStrings.push(i+" "+success+"/"+total+" ("+pct+"%)");
		}
		document.getElementById("osd-performance").textContent = performanceStrings.join("\n");
	},

	/**
	 * Updates targets plotted over the canvas
	 */
	"TRG":function(payload) {
		for(var i=0; i<payload.targetRects.length; i++) {
			this.ptb[payload.targetIsOval[i] ? "FrameOval" : "FrameRect"]([255, 255, 0, 1],
				payload.targetRects[i]);
		}
	},

	/**
	 * Redraws the underlying image
	 */
	"DRW":function(directives) {
		this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
		if(!(directives instanceof Array)) directives = [directives];
		for(var i=0; i<directives.length; i++) {
			var directive = directives[i];
			if(directive.command === "DrawTexture") {
				this.ctx.save();
				var texture = this._textures[directive.arguments[0]],
					sourceRect = directive.arguments[1],
					destinationRect = directive.arguments[2],
					rotationAngle = directive.arguments[3],
					globalAlpha = directive.arguments[5];

				try {
					if(rotationAngle) this.ctx.rotate(rotationAngle*Math.PI/180);
					if(globalAlpha) this.ctx.globalAlpha = globalAlpha;

					if(sourceRect) {
						this.ctx.drawImage(texture, sourceRect[0], sourceRect[1],
							sourceRect[2]-sourceRect[0], sourceRect[3]-sourceRect[1],
							destinationRect[0], destinationRect[1],
							destinationRect[2]-destinationRect[0],
							destinationRect[3]-destinationRect[1]);
					} else {
						this.ctx.drawImage(texture, destinationRect[0], destinationRect[1],
							destinationRect[2]-destinationRect[0],
							destinationRect[3]-destinationRect[1]);
					}
				} finally {
					this.ctx.restore();
				}
			} else {
				this.ptb[directive.command].apply(this.ptb, directive.arguments);
			}
		}
	},

	/**
	 * Draws eye data
	 */
	"EYE":function(pos) {
		this.ctx.save();
		if(this._lastEyePosition) {
			this.ctx.fillColor = "rgb(0, 0, 255)";
			this.ctx.fillRect(this._lastEyePosition[0]-2, this._lastEyePosition[1]-2,
				this._lastEyePosition[0]+2, this._lastEyePosition[1]+2);
		}
		if(pos[0]-2 >= 0 && pos[1]-2 >= 0 && pos[0]+2 < CONFIG.displaySize[0] &&
				pos[1]+2 < CONFIG.displaySize[1]) {
			this.ctx.fillColor = "rgb(255, 0, 0)";
			this.ctx.fillRect(pos[0]-2, pos[1]-2, pos[0]+2, pos[1]+2);
		}
		this.ctx.restore();
	},

	/**
	 * Preloads textures
	 */
	"TXT":function(textureIndices) {
		for(var i=0; i<textureIndices.length; i++) {
			var textureIndex = textureIndices[i];
			if(!this._textures[textureIndex]) {
				var img = document.createElement("img");
				img.src = "/texture/"+textureIndex+".png";
				document.getElementById("textures").appendChild(img);
				this._textures[textureIndex] = img;
			}
		}
	}
};

window.addEventListener("DOMContentLoaded", function(event) {
	var canvas = document.createElement("canvas");
	canvas.width = CONFIG.displaySize[0];
	canvas.height = CONFIG.displaySize[1];
	canvas.id = "pmcanvas";
	document.body.appendChild(canvas);
	document.getElementById("osd").style.height = CONFIG.OSDHeight/CONFIG.displaySize[1]*100+"%";

	var client = new Client(canvas);

	var ws = new WebSocket("ws://"+window.location.hostname+":20557/");
	ws.onmessage = function(event) {
		var data = event.data,
			code = data.substr(0, 3),
			payload = JSON.parse(data.substr(5));
		console.log(data);
		if(code in client) {
			client[code](payload);
		} else {
			console.error("Could not parse message: "+data);
		}
	};
}, false);<commit_msg>More bug fixes<commit_after>/*
 * PsychoMonkey
 * Copyright (C) 2012 Simon Kornblith
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var PTB = function(context) {
	this.ctx = context;
}
PTB.prototype = {
	"FillOval":function(color, rect) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "fillStyle", "white");
			var rects = this._getRectArray(rect);
			for(var i=0; i<rects.length; i++) {
				if(colorArray) this.ctx.fillStyle = this._colorToStyle(colorArray[i]);
				this._makeOvalPath(rects[i]);
				this.ctx.fill();
			}
		} finally {
			this.ctx.restore();
		}
	},
	"FrameOval":function(color, rect, penWidth) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "strokeStyle", "white");
			if(typeof penWidth !== "object") penWidth = [penWidth];
			if(penWidth.length === 1) this.ctx.lineWidth = penWidth ? penWidth : 1;
			var rects = this._getRectArray(rect);
			for(var i=0; i<rects.length; i++) {
				if(colorArray) this.ctx.strokeStyle = this._colorToStyle(colorArray[i]);
				if(penWith.length !== 1) this.ctx.lineWidth = penWidth[i];
				this._makeOvalPath(rects[i]);
				this.ctx.stroke();
			}
		} finally {
			this.ctx.restore();
		}
	},
	"FillRect":function(color, rect) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "fillStyle", "white");
			var rects = this._getRectArray(rect);
			for(var i=0; i<rects.length; i++) {
				var rect = rects[i];
				if(colorArray) this.ctx.fillStyle = this._colorToStyle(colorArray[i]);
				this.ctx.fillRect(rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]);
			}
		} finally {
			this.ctx.restore();
		}
	},
	"FrameRect":function(color, rect, penWidth) {
		this.ctx.save();
		try {
			var colorArray = this._getColorArrayOrSetColor(color, "strokeStyle", "white");
			if(typeof penWidth !== "object") penWidth = [penWidth];
			if(penWidth.length === 1) this.ctx.lineWidth = penWidth ? penWidth : 1;
			var rects = this._getRectArray(rect);
			for(var i=0; i<rects.length; i++) {
				var rect = rects[i];
				if(colorArray) this.ctx.strokeStyle = this._colorToStyle(colorArray[i]);
				if(penWidth.length !== 1) this.ctx.lineWidth = penWidth[i];
				this.ctx.strokeRect(rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]);
			}
		} finally {
			this.ctx.restore();
		}
	},
	"DrawDots":function(xy, size, color, center, dot_type) {
		this.ctx.save();
		try {
			if(!size) size = 1;
			if(!dot_type) dot_type = 0;

			var colorArray = this._getColorArrayOrSetColor(color, "fillStyle", "black");
			if(center) this.ctx.translate(center[0], center[1]);

			var x = typeof xy[0] === "object" ? xy[0] : [xy[0]],
				y = typeof xy[1] === "object" ? xy[1] : [xy[1]];
			for(var i=0; i<x.length; i++) {
				if(colorArray) this.ctx.fillStyle = this._colorToStyle(colorArray[i]);
				var dotSize = typeof size === "object" ? size[i] : size;
				if(dot_type === 0) {
					this.ctx.fillRect(x[i]-dotSize/2, y[i]-dotSize/2,
						x[i]+dotSize/2, y[i]+dotSize/2);
				} else {
					this.ctx.beginPath();
					this.ctx.arc(x[i], y[i], dotSize/2, 0, Math.PI*2, false);
					this.ctx.closePath();
					this.ctx.fill();
				}
			}
		} finally {
			this.ctx.restore();
		}
	},
	"_transpose":function(array) {
		var newArray = [];
		for(var i=0; i<array[0].length; i++) {
			var newArrayX = [];
			for(var j=0; j<array.length; j++) {
				newArrayX.push(array[j][i]);
			}
			newArray.push(newArrayX);
		}
		return newArray;
	},
	"_makeOvalPath":function(rect) {
		var width = rect[3]-rect[1],
			height = rect[4]-rect[2];
		this.ctx.beginPath();
		this.ctx.translate(rect[1]+width/2, rect[2]+height/2);
		this.ctx.scale(width/2, height/2);
		this.ctx.arc(0, 0, 1, 0, Math.PI*2, false);
		this.ctx.closePath();
	},
	"_getColorArrayOrSetColor":function(color, style, defaultColor) {
		if(color === null || color === undefined) {
			this.ctx[style] = defaultColor;
			return undefined;
		}
		if(typeof color === "object" && typeof color[0] === "object") {
			return this._transpose(color);
		}
		this.ctx[style] = this._colorToStyle(color);
		return undefined;
	},
	"_getRectArray":function(rect) {
		if(!rect) {
			return [[0, 0, CONFIG.displaySize[0], CONFIG.displaySize[1]]];
		}
		if(typeof rect[0] === "object") {
			return this._transpose(rect);
		}
		return [rect];
	},
	"_colorToStyle":function(color) {
		if(color === null || color === undefined) {
			return "white";
		} else if(typeof color !== "object") {
			return "rgb("+color+", "+color+", "+color+")";
		} else if(color.length === 1) {
			return "rgb("+color[0]+", "+color[0]+", "+color[0]+")";
		} else if(color.length === 3) {
			return "rgb("+color[0]+", "+color[1]+", "+color[2]+")";
		} else if(color.length === 4) {
			return "rgba("+color[0]+", "+color[1]+", "+color[2]+", "+color[3]+")";
		} else {
			throw new Error("Invalid color");
		}
	}
};

var OSD = function(div) {
};
OSD.prototype.update = function(info) {
};

var Client = function(canvas) {
	this.canvas = canvas;
	this.ctx = canvas.getContext("2d");
	this.ptb = new PTB(this.ctx);
	this._lastEyePosition = null;
	this._textures = {};
}
Client.prototype = {
	/**
	 * Updates the on-screen display
	 */
	"OSD":function(info) {
		document.getElementById("osd-state").textContent = info.state;

		var longestKey = 0,
			keyInfoStrings = [];
		for(var i in info.keyInfo) {
			if(i.length > longestKey) longestKey = i.length;
		}
		for(var i in info.keyInfo) {
			var str = i;
			while(str.length < longestKey) str += " ";
			str += " - "+info.keyInfo[i];
			keyInfoStrings.push(str);
		}
		document.getElementById("osd-keyInfo").textContent = keyInfoStrings.join("\n");

		var performanceStrings = [];
		for(var i in info.performance) {
			var success = info.performance[i][0];
			var total = info.performance[i][1];
			if(total == 0) {
				var pct = 0;
			} else {
				var pct = Math.round(success/total*100);
			}
			performanceStrings.push(i+" "+success+"/"+total+" ("+pct+"%)");
		}
		document.getElementById("osd-performance").textContent = performanceStrings.join("\n");
	},

	/**
	 * Updates targets plotted over the canvas
	 */
	"TRG":function(payload) {
		for(var i=0; i<payload.targetRects.length; i++) {
			this.ptb[payload.targetIsOval[i] ? "FrameOval" : "FrameRect"]([255, 255, 0, 1],
				payload.targetRects[i]);
		}
	},

	/**
	 * Redraws the underlying image
	 */
	"DRW":function(directives) {
		this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
		if(!(directives instanceof Array)) directives = [directives];
		for(var i=0; i<directives.length; i++) {
			var directive = directives[i];
			if(directive.command === "DrawTexture") {
				this.ctx.save();
				var texture = this._textures[directive.arguments[0]],
					sourceRect = directive.arguments[1],
					destinationRect = directive.arguments[2],
					rotationAngle = directive.arguments[3],
					globalAlpha = directive.arguments[5];

				try {
					if(rotationAngle) this.ctx.rotate(rotationAngle*Math.PI/180);
					if(globalAlpha) this.ctx.globalAlpha = globalAlpha;

					if(sourceRect) {
						this.ctx.drawImage(texture, sourceRect[0], sourceRect[1],
							sourceRect[2]-sourceRect[0], sourceRect[3]-sourceRect[1],
							destinationRect[0], destinationRect[1],
							destinationRect[2]-destinationRect[0],
							destinationRect[3]-destinationRect[1]);
					} else {
						this.ctx.drawImage(texture, destinationRect[0], destinationRect[1],
							destinationRect[2]-destinationRect[0],
							destinationRect[3]-destinationRect[1]);
					}
				} finally {
					this.ctx.restore();
				}
			} else {
				this.ptb[directive.command].apply(this.ptb, directive.arguments);
			}
		}
	},

	/**
	 * Draws eye data
	 */
	"EYE":function(pos) {
		this.ctx.save();
		if(this._lastEyePosition) {
			this.ctx.fillColor = "rgb(0, 0, 255)";
			this.ctx.fillRect(this._lastEyePosition[0]-2, this._lastEyePosition[1]-2,
				this._lastEyePosition[0]+2, this._lastEyePosition[1]+2);
		}
		if(pos[0]-2 >= 0 && pos[1]-2 >= 0 && pos[0]+2 < CONFIG.displaySize[0] &&
				pos[1]+2 < CONFIG.displaySize[1]) {
			this.ctx.fillColor = "rgb(255, 0, 0)";
			this.ctx.fillRect(pos[0]-2, pos[1]-2, pos[0]+2, pos[1]+2);
		}
		this.ctx.restore();
	},

	/**
	 * Preloads textures
	 */
	"TXT":function(textureIndices) {
		for(var i=0; i<textureIndices.length; i++) {
			var textureIndex = textureIndices[i];
			if(!this._textures[textureIndex]) {
				var img = document.createElement("img");
				img.src = "/texture/"+textureIndex+".png";
				document.getElementById("textures").appendChild(img);
				this._textures[textureIndex] = img;
			}
		}
	}
};

window.addEventListener("DOMContentLoaded", function(event) {
	var canvas = document.createElement("canvas");
	canvas.width = CONFIG.displaySize[0];
	canvas.height = CONFIG.displaySize[1];
	canvas.id = "pmcanvas";
	document.body.appendChild(canvas);
	document.getElementById("osd").style.height = CONFIG.OSDHeight/CONFIG.displaySize[1]*100+"%";

	var client = new Client(canvas);

	var ws = new WebSocket("ws://"+window.location.hostname+":20557/");
	ws.onmessage = function(event) {
		var data = event.data,
			code = data.substr(0, 3),
			payload = JSON.parse(data.substr(5));
		console.log(data);
		if(code in client) {
			client[code](payload);
		} else {
			console.error("Could not parse message: "+data);
		}
	};
}, false);<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview New (evolving) renderer.
 * Thrasos: spirit of boldness.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.module('Blockly.thrasos.RenderInfo');
goog.module.declareLegacyNamespace();

const BaseRenderInfo = goog.require('Blockly.blockRendering.RenderInfo');
/* eslint-disable-next-line no-unused-vars */
const BlockSvg = goog.requireType('Blockly.BlockSvg');
/* eslint-disable-next-line no-unused-vars */
const Field = goog.requireType('Blockly.blockRendering.Field');
const InRowSpacer = goog.require('Blockly.blockRendering.InRowSpacer');
/* eslint-disable-next-line no-unused-vars */
const Renderer = goog.requireType('Blockly.thrasos.Renderer');
const Types = goog.require('Blockly.blockRendering.Types');
const object = goog.require('Blockly.utils.object');

/**
 * An object containing all sizing information needed to draw this block.
 *
 * This measure pass does not propagate changes to the block (although fields
 * may choose to rerender when getSize() is called).  However, calling it
 * repeatedly may be expensive.
 *
 * @param {!Renderer} renderer The renderer in use.
 * @param {!BlockSvg} block The block to measure.
 * @constructor
 * @package
 * @extends {BaseRenderInfo}
 */
const RenderInfo = function(renderer, block) {
  RenderInfo.superClass_.constructor.call(this, renderer, block);
};
object.inherits(RenderInfo,
    BaseRenderInfo);

/**
 * Get the block renderer in use.
 * @return {!Renderer} The block renderer in use.
 * @package
 */
RenderInfo.prototype.getRenderer = function() {
  return /** @type {!Renderer} */ (this.renderer_);
};

/**
 * @override
 */
RenderInfo.prototype.addElemSpacing_ = function() {
  let hasExternalInputs = false;
  for (let i = 0; i < this.rows.length; i++) {
    const row = this.rows[i];
    if (row.hasExternalInput) {
      hasExternalInputs = true;
      break;
    }
  }
  for (let i = 0; i < this.rows.length; i++) {
    const row = this.rows[i];
    const oldElems = row.elements;
    row.elements = [];
    // No spacing needed before the corner on the top row or the bottom row.
    if (row.startsWithElemSpacer()) {
      // There's a spacer before the first element in the row.
      row.elements.push(new InRowSpacer(
          this.constants_, this.getInRowSpacing_(null, oldElems[0])));
    }
    for (let e = 0; e < oldElems.length - 1; e++) {
      row.elements.push(oldElems[e]);
      const spacing = this.getInRowSpacing_(oldElems[e], oldElems[e + 1]);
      row.elements.push(
          new InRowSpacer(this.constants_, spacing));
    }
    row.elements.push(oldElems[oldElems.length - 1]);
    if (row.endsWithElemSpacer()) {
      let spacing = this.getInRowSpacing_(oldElems[oldElems.length - 1], null);
      if (hasExternalInputs && row.hasDummyInput) {
        spacing += this.constants_.TAB_WIDTH;
      }
      // There's a spacer after the last element in the row.
      row.elements.push(new InRowSpacer(
          this.constants_, spacing));
    }
  }
};

/**
 * @override
 */
RenderInfo.prototype.getInRowSpacing_ = function(prev, next) {
  if (!prev) {
    // Between an editable field and the beginning of the row.
    if (next && Types.isField(next) &&
        (/** @type {Field} */ (next)).isEditable) {
      return this.constants_.MEDIUM_PADDING;
    }
    // Inline input at the beginning of the row.
    if (next && Types.isInlineInput(next)) {
      return this.constants_.MEDIUM_LARGE_PADDING;
    }
    if (next && Types.isStatementInput(next)) {
      return this.constants_.STATEMENT_INPUT_PADDING_LEFT;
    }
    // Anything else at the beginning of the row.
    return this.constants_.LARGE_PADDING;
  }

  // Spacing between a non-input and the end of the row.
  if (!Types.isInput(prev) && !next) {
    // Between an editable field and the end of the row.
    if (Types.isField(prev) &&
        (/** @type {Field} */ (prev)).isEditable) {
      return this.constants_.MEDIUM_PADDING;
    }
    // Padding at the end of an icon-only row to make the block shape clearer.
    if (Types.isIcon(prev)) {
      return (this.constants_.LARGE_PADDING * 2) + 1;
    }
    if (Types.isHat(prev)) {
      return this.constants_.NO_PADDING;
    }
    // Establish a minimum width for a block with a previous or next connection.
    if (Types.isPreviousOrNextConnection(prev)) {
      return this.constants_.LARGE_PADDING;
    }
    // Between rounded corner and the end of the row.
    if (Types.isLeftRoundedCorner(prev)) {
      return this.constants_.MIN_BLOCK_WIDTH;
    }
    // Between a jagged edge and the end of the row.
    if (Types.isJaggedEdge(prev)) {
      return this.constants_.NO_PADDING;
    }
    // Between noneditable fields and icons and the end of the row.
    return this.constants_.LARGE_PADDING;
  }

  // Between inputs and the end of the row.
  if (Types.isInput(prev) && !next) {
    if (Types.isExternalInput(prev)) {
      return this.constants_.NO_PADDING;
    } else if (Types.isInlineInput(prev)) {
      return this.constants_.LARGE_PADDING;
    } else if (Types.isStatementInput(prev)) {
      return this.constants_.NO_PADDING;
    }
  }

  // Spacing between a non-input and an input.
  if (!Types.isInput(prev) &&
      next && Types.isInput(next)) {
    // Between an editable field and an input.
    if (Types.isField(prev) &&
        (/** @type {Field} */ (prev)).isEditable) {
      if (Types.isInlineInput(next)) {
        return this.constants_.SMALL_PADDING;
      } else if (Types.isExternalInput(next)) {
        return this.constants_.SMALL_PADDING;
      }
    } else {
      if (Types.isInlineInput(next)) {
        return this.constants_.MEDIUM_LARGE_PADDING;
      } else if (Types.isExternalInput(next)) {
        return this.constants_.MEDIUM_LARGE_PADDING;
      } else if (Types.isStatementInput(next)) {
        return this.constants_.LARGE_PADDING;
      }
    }
    return this.constants_.LARGE_PADDING - 1;
  }

  // Spacing between an icon and an icon or field.
  if (Types.isIcon(prev) &&
      next && !Types.isInput(next)) {
    return this.constants_.LARGE_PADDING;
  }

  // Spacing between an inline input and a field.
  if (Types.isInlineInput(prev) &&
      next && Types.isField(next)) {
    // Editable field after inline input.
    if ((/** @type {Field} */ (next)).isEditable) {
      return this.constants_.MEDIUM_PADDING;
    } else {
      // Noneditable field after inline input.
      return this.constants_.LARGE_PADDING;
    }
  }

  if (Types.isLeftSquareCorner(prev) && next) {
    // Spacing between a hat and a corner
    if (Types.isHat(next)) {
      return this.constants_.NO_PADDING;
    }
    // Spacing between a square corner and a previous or next connection
    if (Types.isPreviousConnection(next) ||
        Types.isNextConnection(next)) {
      return next.notchOffset;
    }
  }

  // Spacing between a rounded corner and a previous or next connection.
  if (Types.isLeftRoundedCorner(prev) && next) {
    return next.notchOffset - this.constants_.CORNER_RADIUS;
  }

  // Spacing between two fields of the same editability.
  if (Types.isField(prev) &&
      next && Types.isField(next) &&
      ((/** @type {Field} */ (prev)).isEditable ==
          (/** @type {Field} */ (next)).isEditable)) {
    return this.constants_.LARGE_PADDING;
  }

  // Spacing between anything and a jagged edge.
  if (next && Types.isJaggedEdge(next)) {
    return this.constants_.LARGE_PADDING;
  }

  return this.constants_.MEDIUM_PADDING;
};

/**
 * @override
 */
RenderInfo.prototype.getSpacerRowHeight_ = function(
    prev, next) {
  // If we have an empty block add a spacer to increase the height.
  if (Types.isTopRow(prev) &&
      Types.isBottomRow(next)) {
    return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;
  }
  // Top and bottom rows act as a spacer so we don't need any extra padding.
  if (Types.isTopRow(prev) ||
      Types.isBottomRow(next)) {
    return this.constants_.NO_PADDING;
  }
  if (prev.hasExternalInput && next.hasExternalInput) {
    return this.constants_.LARGE_PADDING;
  }
  if (!prev.hasStatement && next.hasStatement) {
    return this.constants_.BETWEEN_STATEMENT_PADDING_Y;
  }
  if (prev.hasStatement && next.hasStatement) {
    return this.constants_.LARGE_PADDING;
  }
  if (prev.hasDummyInput || next.hasDummyInput) {
    return this.constants_.LARGE_PADDING;
  }
  return this.constants_.MEDIUM_PADDING;
};

/**
 * @override
 */
RenderInfo.prototype.getElemCenterline_ = function(row, elem) {
  if (Types.isSpacer(elem)) {
    return row.yPos + elem.height / 2;
  }
  if (Types.isBottomRow(row)) {
    const baseline = row.yPos + row.height - row.descenderHeight;
    if (Types.isNextConnection(elem)) {
      return baseline + elem.height / 2;
    }
    return baseline - elem.height / 2;
  }
  if (Types.isTopRow(row)) {
    if (Types.isHat(elem)) {
      return row.capline - elem.height / 2;
    }
    return row.capline + elem.height / 2;
  }

  let result = row.yPos;
  if (Types.isField(elem) && row.hasStatement) {
    const offset = this.constants_.TALL_INPUT_FIELD_OFFSET_Y +
        elem.height / 2;
    result += offset;
  } else {
    result += (row.height / 2);
  }
  return result;
};

/**
 * @override
 */
RenderInfo.prototype.finalize_ = function() {
  // Performance note: this could be combined with the draw pass, if the time
  // that this takes is excessive.  But it shouldn't be, because it only
  // accesses and sets properties that already exist on the objects.
  let widestRowWithConnectedBlocks = 0;
  let yCursor = 0;
  for (let i = 0; i < this.rows.length; i++) {
    const row = this.rows[i];
    row.yPos = yCursor;
    row.xPos = this.startX;
    yCursor += row.height;

    widestRowWithConnectedBlocks =
        Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks);
    // Add padding to the bottom row if block height is less than minimum
    const heightWithoutHat = yCursor - this.topRow.ascenderHeight;
    if (row == this.bottomRow &&
        heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) {
      // But the hat height shouldn't be part of this.
      const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat;
      this.bottomRow.height += diff;
      yCursor += diff;
    }
    this.recordElemPositions_(row);
  }
  if (this.outputConnection && this.block_.nextConnection &&
      this.block_.nextConnection.isConnected()) {
    // Include width of connected block in value to stack width measurement.
    widestRowWithConnectedBlocks =
        Math.max(widestRowWithConnectedBlocks,
            this.block_.nextConnection.targetBlock().getHeightWidth().width);
  }

  this.bottomRow.baseline = yCursor - this.bottomRow.descenderHeight;
  this.widthWithChildren = widestRowWithConnectedBlocks + this.startX;

  this.height = yCursor;
  this.startY = this.topRow.capline;
};

exports = RenderInfo;
<commit_msg>clang-format core/renderers/thrasos/info.js<commit_after>/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview New (evolving) renderer.
 * Thrasos: spirit of boldness.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.module('Blockly.thrasos.RenderInfo');
goog.module.declareLegacyNamespace();

const BaseRenderInfo = goog.require('Blockly.blockRendering.RenderInfo');
/* eslint-disable-next-line no-unused-vars */
const BlockSvg = goog.requireType('Blockly.BlockSvg');
/* eslint-disable-next-line no-unused-vars */
const Field = goog.requireType('Blockly.blockRendering.Field');
const InRowSpacer = goog.require('Blockly.blockRendering.InRowSpacer');
/* eslint-disable-next-line no-unused-vars */
const Renderer = goog.requireType('Blockly.thrasos.Renderer');
const Types = goog.require('Blockly.blockRendering.Types');
const object = goog.require('Blockly.utils.object');

/**
 * An object containing all sizing information needed to draw this block.
 *
 * This measure pass does not propagate changes to the block (although fields
 * may choose to rerender when getSize() is called).  However, calling it
 * repeatedly may be expensive.
 *
 * @param {!Renderer} renderer The renderer in use.
 * @param {!BlockSvg} block The block to measure.
 * @constructor
 * @package
 * @extends {BaseRenderInfo}
 */
const RenderInfo = function(renderer, block) {
  RenderInfo.superClass_.constructor.call(this, renderer, block);
};
object.inherits(RenderInfo, BaseRenderInfo);

/**
 * Get the block renderer in use.
 * @return {!Renderer} The block renderer in use.
 * @package
 */
RenderInfo.prototype.getRenderer = function() {
  return /** @type {!Renderer} */ (this.renderer_);
};

/**
 * @override
 */
RenderInfo.prototype.addElemSpacing_ = function() {
  let hasExternalInputs = false;
  for (let i = 0; i < this.rows.length; i++) {
    const row = this.rows[i];
    if (row.hasExternalInput) {
      hasExternalInputs = true;
      break;
    }
  }
  for (let i = 0; i < this.rows.length; i++) {
    const row = this.rows[i];
    const oldElems = row.elements;
    row.elements = [];
    // No spacing needed before the corner on the top row or the bottom row.
    if (row.startsWithElemSpacer()) {
      // There's a spacer before the first element in the row.
      row.elements.push(new InRowSpacer(
          this.constants_, this.getInRowSpacing_(null, oldElems[0])));
    }
    for (let e = 0; e < oldElems.length - 1; e++) {
      row.elements.push(oldElems[e]);
      const spacing = this.getInRowSpacing_(oldElems[e], oldElems[e + 1]);
      row.elements.push(new InRowSpacer(this.constants_, spacing));
    }
    row.elements.push(oldElems[oldElems.length - 1]);
    if (row.endsWithElemSpacer()) {
      let spacing = this.getInRowSpacing_(oldElems[oldElems.length - 1], null);
      if (hasExternalInputs && row.hasDummyInput) {
        spacing += this.constants_.TAB_WIDTH;
      }
      // There's a spacer after the last element in the row.
      row.elements.push(new InRowSpacer(this.constants_, spacing));
    }
  }
};

/**
 * @override
 */
RenderInfo.prototype.getInRowSpacing_ = function(prev, next) {
  if (!prev) {
    // Between an editable field and the beginning of the row.
    if (next && Types.isField(next) &&
        (/** @type {Field} */ (next)).isEditable) {
      return this.constants_.MEDIUM_PADDING;
    }
    // Inline input at the beginning of the row.
    if (next && Types.isInlineInput(next)) {
      return this.constants_.MEDIUM_LARGE_PADDING;
    }
    if (next && Types.isStatementInput(next)) {
      return this.constants_.STATEMENT_INPUT_PADDING_LEFT;
    }
    // Anything else at the beginning of the row.
    return this.constants_.LARGE_PADDING;
  }

  // Spacing between a non-input and the end of the row.
  if (!Types.isInput(prev) && !next) {
    // Between an editable field and the end of the row.
    if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) {
      return this.constants_.MEDIUM_PADDING;
    }
    // Padding at the end of an icon-only row to make the block shape clearer.
    if (Types.isIcon(prev)) {
      return (this.constants_.LARGE_PADDING * 2) + 1;
    }
    if (Types.isHat(prev)) {
      return this.constants_.NO_PADDING;
    }
    // Establish a minimum width for a block with a previous or next connection.
    if (Types.isPreviousOrNextConnection(prev)) {
      return this.constants_.LARGE_PADDING;
    }
    // Between rounded corner and the end of the row.
    if (Types.isLeftRoundedCorner(prev)) {
      return this.constants_.MIN_BLOCK_WIDTH;
    }
    // Between a jagged edge and the end of the row.
    if (Types.isJaggedEdge(prev)) {
      return this.constants_.NO_PADDING;
    }
    // Between noneditable fields and icons and the end of the row.
    return this.constants_.LARGE_PADDING;
  }

  // Between inputs and the end of the row.
  if (Types.isInput(prev) && !next) {
    if (Types.isExternalInput(prev)) {
      return this.constants_.NO_PADDING;
    } else if (Types.isInlineInput(prev)) {
      return this.constants_.LARGE_PADDING;
    } else if (Types.isStatementInput(prev)) {
      return this.constants_.NO_PADDING;
    }
  }

  // Spacing between a non-input and an input.
  if (!Types.isInput(prev) && next && Types.isInput(next)) {
    // Between an editable field and an input.
    if (Types.isField(prev) && (/** @type {Field} */ (prev)).isEditable) {
      if (Types.isInlineInput(next)) {
        return this.constants_.SMALL_PADDING;
      } else if (Types.isExternalInput(next)) {
        return this.constants_.SMALL_PADDING;
      }
    } else {
      if (Types.isInlineInput(next)) {
        return this.constants_.MEDIUM_LARGE_PADDING;
      } else if (Types.isExternalInput(next)) {
        return this.constants_.MEDIUM_LARGE_PADDING;
      } else if (Types.isStatementInput(next)) {
        return this.constants_.LARGE_PADDING;
      }
    }
    return this.constants_.LARGE_PADDING - 1;
  }

  // Spacing between an icon and an icon or field.
  if (Types.isIcon(prev) && next && !Types.isInput(next)) {
    return this.constants_.LARGE_PADDING;
  }

  // Spacing between an inline input and a field.
  if (Types.isInlineInput(prev) && next && Types.isField(next)) {
    // Editable field after inline input.
    if ((/** @type {Field} */ (next)).isEditable) {
      return this.constants_.MEDIUM_PADDING;
    } else {
      // Noneditable field after inline input.
      return this.constants_.LARGE_PADDING;
    }
  }

  if (Types.isLeftSquareCorner(prev) && next) {
    // Spacing between a hat and a corner
    if (Types.isHat(next)) {
      return this.constants_.NO_PADDING;
    }
    // Spacing between a square corner and a previous or next connection
    if (Types.isPreviousConnection(next) || Types.isNextConnection(next)) {
      return next.notchOffset;
    }
  }

  // Spacing between a rounded corner and a previous or next connection.
  if (Types.isLeftRoundedCorner(prev) && next) {
    return next.notchOffset - this.constants_.CORNER_RADIUS;
  }

  // Spacing between two fields of the same editability.
  if (Types.isField(prev) && next && Types.isField(next) &&
      ((/** @type {Field} */ (prev)).isEditable ==
       (/** @type {Field} */ (next)).isEditable)) {
    return this.constants_.LARGE_PADDING;
  }

  // Spacing between anything and a jagged edge.
  if (next && Types.isJaggedEdge(next)) {
    return this.constants_.LARGE_PADDING;
  }

  return this.constants_.MEDIUM_PADDING;
};

/**
 * @override
 */
RenderInfo.prototype.getSpacerRowHeight_ = function(prev, next) {
  // If we have an empty block add a spacer to increase the height.
  if (Types.isTopRow(prev) && Types.isBottomRow(next)) {
    return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;
  }
  // Top and bottom rows act as a spacer so we don't need any extra padding.
  if (Types.isTopRow(prev) || Types.isBottomRow(next)) {
    return this.constants_.NO_PADDING;
  }
  if (prev.hasExternalInput && next.hasExternalInput) {
    return this.constants_.LARGE_PADDING;
  }
  if (!prev.hasStatement && next.hasStatement) {
    return this.constants_.BETWEEN_STATEMENT_PADDING_Y;
  }
  if (prev.hasStatement && next.hasStatement) {
    return this.constants_.LARGE_PADDING;
  }
  if (prev.hasDummyInput || next.hasDummyInput) {
    return this.constants_.LARGE_PADDING;
  }
  return this.constants_.MEDIUM_PADDING;
};

/**
 * @override
 */
RenderInfo.prototype.getElemCenterline_ = function(row, elem) {
  if (Types.isSpacer(elem)) {
    return row.yPos + elem.height / 2;
  }
  if (Types.isBottomRow(row)) {
    const baseline = row.yPos + row.height - row.descenderHeight;
    if (Types.isNextConnection(elem)) {
      return baseline + elem.height / 2;
    }
    return baseline - elem.height / 2;
  }
  if (Types.isTopRow(row)) {
    if (Types.isHat(elem)) {
      return row.capline - elem.height / 2;
    }
    return row.capline + elem.height / 2;
  }

  let result = row.yPos;
  if (Types.isField(elem) && row.hasStatement) {
    const offset = this.constants_.TALL_INPUT_FIELD_OFFSET_Y + elem.height / 2;
    result += offset;
  } else {
    result += (row.height / 2);
  }
  return result;
};

/**
 * @override
 */
RenderInfo.prototype.finalize_ = function() {
  // Performance note: this could be combined with the draw pass, if the time
  // that this takes is excessive.  But it shouldn't be, because it only
  // accesses and sets properties that already exist on the objects.
  let widestRowWithConnectedBlocks = 0;
  let yCursor = 0;
  for (let i = 0; i < this.rows.length; i++) {
    const row = this.rows[i];
    row.yPos = yCursor;
    row.xPos = this.startX;
    yCursor += row.height;

    widestRowWithConnectedBlocks =
        Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks);
    // Add padding to the bottom row if block height is less than minimum
    const heightWithoutHat = yCursor - this.topRow.ascenderHeight;
    if (row == this.bottomRow &&
        heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) {
      // But the hat height shouldn't be part of this.
      const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat;
      this.bottomRow.height += diff;
      yCursor += diff;
    }
    this.recordElemPositions_(row);
  }
  if (this.outputConnection && this.block_.nextConnection &&
      this.block_.nextConnection.isConnected()) {
    // Include width of connected block in value to stack width measurement.
    widestRowWithConnectedBlocks = Math.max(
        widestRowWithConnectedBlocks,
        this.block_.nextConnection.targetBlock().getHeightWidth().width);
  }

  this.bottomRow.baseline = yCursor - this.bottomRow.descenderHeight;
  this.widthWithChildren = widestRowWithConnectedBlocks + this.startX;

  this.height = yCursor;
  this.startY = this.topRow.capline;
};

exports = RenderInfo;
<|endoftext|>


<commit_before>import 'systemjs-hmr/dist/next.js'
import io from 'socket.io-client'

const storage = {
    _socket: null
}

const run = (name, fn, ...args) => (
    storage[name] ?
        storage[name] :
        Promise.resolve(fn.apply(args)).then(result => {
            storage[name] = result || true
        })
)

const defaultOptions = {
    port: 1337
}

let config = {}

const connect = (opts = {}) => {
    const options = Object.assign({}, defaultOptions, opts)

    if (storage._socket == null) {

        let socket = storage._socket = io("https://" + window.location.hostname + ":" + options.port)

        socket.on('connect', () => {
            socket.emit('identification', navigator.userAgent)
        })

        socket.on('config', c => {
            config = c
        })

        socket.on('reload', () => {
            document.location.reload(true)
        })

        socket.on('change', (event) => {
            System.reload(event.path, {
                roots: config.entries
            })
        })
    }
}

export {storage, run, connect}
<commit_msg>Normalize roots<commit_after>import 'systemjs-hmr/dist/next.js'
import io from 'socket.io-client'

const storage = {
    _socket: null
}

const run = (name, fn, ...args) => (
    storage[name] ?
        storage[name] :
        Promise.resolve(fn.apply(args)).then(result => {
            storage[name] = result || true
        })
)

const defaultOptions = {
    port: 1337
}

let config = {}

const connect = (opts = {}) => {
    const options = Object.assign({}, defaultOptions, opts)

    if (storage._socket == null) {

        let socket = storage._socket = io("https://" + window.location.hostname + ":" + options.port)

        socket.on('connect', () => {
            socket.emit('identification', navigator.userAgent)
        })

        socket.on('config', c => {
            config = c
        })

        socket.on('reload', () => {
            document.location.reload(true)
        })

        socket.on('change', (event) => {
            System.reload(event.path, {
                // Untill systemjs-hmr normalizes roots
                roots: config.entries.map(System.normalizeSync)
            })
        })
    }
}

export {storage, run, connect}
<|endoftext|>


<commit_before>var Dispatcher = require('./dispatcher');
var resources = require('./resources');

/**
 * Creates an Asana API Client
 * @constructor
 * @param {Dispatcher} dispatcher The request dispatcher to use
 */
function Client(dispatcher) {
  var me = this;
  me.dispatcher = dispatcher;
  Object.keys(resources).forEach(function(key) {
    me[key.toLowerCase()] = new resources[key](me.dispatcher);
  });
}

/**
 * Create a client for basic auth
 * @param  {String} apiKey The Asana Api Key for the user
 * @return {Client}        The instantiated client
 */
Client.basicAuth = function(apiKey) {
  return new Client(new Dispatcher('auth', {
    user: apiKey,
    pass: ''
  }));
};

/**
 * Create a client for OAuth access
 * @param  {String} token The Asana OAuth token for the user
 * @return {Client}       The instantiated client
 */
Client.oauth = function(token) {
  return new Client(new Dispatcher('bearer', token));
};

module.exports = Client;<commit_msg>Setting the resources manually<commit_after>var Dispatcher = require('./dispatcher');
var resources = require('./resources');

/**
 * Creates an Asana API Client
 * @constructor
 * @param {Dispatcher} dispatcher The request dispatcher to use
 */
function Client(dispatcher) {
  /** @member {Dispatcher} **/
  this.dispatcher = dispatcher;
  /** @member {Teams} **/
  this.teams = new resources.Teams(this.dispatcher);
  /** @member {Users} **/
  this.users = new resources.Users(this.dispatcher);
  /** @member {Workspaces} **/
  this.workspaces = new resources.Workspaces(this.dispatcher);
}

/**
 * Create a client for basic auth
 * @param  {String} apiKey The Asana Api Key for the user
 * @return {Client}        The instantiated client
 */
Client.basicAuth = function(apiKey) {
  return new Client(new Dispatcher('auth', {
    user: apiKey,
    pass: ''
  }));
};

/**
 * Create a client for OAuth access
 * @param  {String} token The Asana OAuth token for the user
 * @return {Client}       The instantiated client
 */
Client.oauth = function(token) {
  return new Client(new Dispatcher('bearer', token));
};

module.exports = Client;<|endoftext|>


<commit_before>var request = require('request');
var fs = require('fs');
var tar = require('tar');
var childProcess = require('child_process');
var client = {};
var baseUrl = '';

/**
 * Create a new project.
 * @param  {String} name
 * @param  {Function} callback
 * @return {null}
 */
client.create = function(name, callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    loadSettings();
    var dependencies = process.cwd() + '/package.json';
    if (!fs.existsSync(dependencies)) {
        return callback('package.json doesn\'t exists. Can\'t create project "' + name + '"');
    }

    var data = {
        name: name,
        dependencies: JSON.parse(fs.readFileSync(dependencies))
    };
    request.post(baseUrl + '/create', { form: data }, function(err, res, body) {
        var body = JSON.parse(body);
        if (!err && res.statusCode === 200) {
            return callback(null, body.msg);
        }
        callback(body.msg);
    });
}

/**
 * Download the latest build from the project.
 * @param  {String}   name
 * @param  {Function} callback
 * @return {null}
 */
client.download = function(name, callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    loadSettings();
    var dependencies = process.cwd() + '/package.json';
    var firstTime = fs.existsSync(process.cwd() + '/node_modules');
    var data = {
        name: name,
        first: !firstTime,
        dependencies: JSON.parse(fs.readFileSync(dependencies))
    };
    var tarFile = 'compressed.tar.gz';
    var tarFileDownloaded = false;
    var compressedDependencies = fs.createWriteStream(tarFile);
    compressedDependencies.on('error', function(err) {
        return callback('An error ocurred while writing the dependencies .tar file. Please try again :S');
    });
    compressedDependencies.on('finish', function() {
        if (tarFileDownloaded) {
            console.log('Downloaded compressed.tar.gz. Extracting...');
            extractDependencies('node_modules', function(err) {
                if (err) {
                    return callback(err);
                }
                console.log('Extract completed.');
                var child = childProcess.spawn('npm', ['rebuild'], { silent: true });
                child.on('close', function() {
                    if (fs.existsSync(tarFile)) {
                        fs.unlinkSync(tarFile);
                    }
                    return callback(null, 'Downloaded and rebuilt dependencies for "' + name + '"');
                });
            });
        }
    });

    var response = request.post(baseUrl + '/download', { form: data });
    response.on('data', function(data) {
        // show a pretty download progress bar?
    });
    response.on('response', function(res) {
        if (res.statusCode !== 200) {
            if (fs.existsSync(tarFile)) {
                fs.unlinkSync(tarFile);
            }
            return callback(res.headers['error-message']);
        }

        // if we get a 200 response from the server, this value will be set.
        // Now, no matter what response we get, the "compressedDependencies" stream
        // will still be piped (with nothing) and that "finish" event will still occur.
        // I can't figure out a way to maybe stop piping or to not pipe at all,
        // if the response is not a 200
        // I think this is not a good approach and can be handled better.
        tarFileDownloaded = true;
    });
    response.on('error', function(err) {
        return callback(err);
    });
    response.pipe(compressedDependencies);
}

/**
 * Build a new version of the project dependencies.
 * @param  {String}   name
 * @param  {Function} callback
 * @return {null}
 */
client.build = function(name, callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    loadSettings();
    var dependencies = process.cwd() + '/package.json';
    if (!fs.existsSync(dependencies)) {
        return callback('package.json doesn\'t exists. Can\'t create new build for project "' + name + '"');
    }

    var data = {
        name: name,
        dependencies: JSON.parse(fs.readFileSync(dependencies))
    };
    request.post(baseUrl + '/build', { form: data }, function(err, res, body) {
        var body = JSON.parse(body);
        if (!err && res.statusCode === 200) {
            return callback(null, body.msg);
        }
        callback(body.msg);
    });
}

/**
 * Generate a basic finalizer.json file.
 * @param  {Function} callback
 * @return {null}
 */
client.init = function(callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    var data = {
        baseUrl: 'http://localhost:8000'
    };

    if (fs.existsSync(finalizerFile)) {
        return callback('finalizer.json file already exists.');
    }
    fs.writeFile(process.cwd() + '/finalizer.json', JSON.stringify(data), function(err) {
        if (err) {
            console.log(err);
            return callback('There was an error creating the finalizer.json file.');
        }
        return callback(null, 'finalizer.json file created.');
    });
}

/**
 * Check connection to the build server.
 * @param  {Function} callback
 * @return {null}
 */
client.check = function(callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    loadSettings();
    var data = {
        status: 'PING'
    };
    request.post(baseUrl + '/check', { form: data }, function(err, res, body) {
        if (!err && res.statusCode === 200) {
            var body = JSON.parse(body);
            return callback(null, body.msg + '! Connection established.');
        }
        return callback('Connection to build server not established. Check your finalizer.json file.');
    });
}

function extractDependencies(path, callback) {
    var extractor = tar.Extract({ path: path, strip: 1 })
        .on('error', function(err) {
            return callback(err);
        })
        .on('end', function() {
            return callback(null);
        });

    fs.createReadStream(process.cwd() + '/compressed.tar.gz')
        .on('error', function(err) {
            return callback(err);
        })
        .pipe(extractor);
}

/**
 * Load basic settings from finalizer.json file.
 * @return {null}
 */
function loadSettings() {
    var settings = require('./settings');
    baseUrl = settings.baseUrl + '/api';
}

module.exports = client;
<commit_msg>Keep connection open<commit_after>var request = require('request');
var fs = require('fs');
var tar = require('tar');
var childProcess = require('child_process');
var client = {};
var baseUrl = '';

/**
 * Create a new project.
 * @param  {String} name
 * @param  {Function} callback
 * @return {null}
 */
client.create = function(name, callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    let settings = loadSettings();
    var dependencies = process.cwd() + '/package.json';
    if (!fs.existsSync(dependencies)) {
        return callback('package.json doesn\'t exists. Can\'t create project "' + name + '"');
    }

    var data = {
        name: name,
        dependencies: JSON.parse(fs.readFileSync(dependencies))
    };
    request.post(baseUrl + '/create', { form: data }, function(err, res, body) {
        var body = JSON.parse(body);
        if (!err && res.statusCode === 200) {
            return callback(null, body.msg);
        }
        callback(body.msg);
    });
}

/**
 * Download the latest build from the project.
 * @param  {String}   name
 * @param  {Function} callback
 * @return {null}
 */
client.download = function(name, callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    let settings = loadSettings();
    var dependencies = process.cwd() + '/package.json';
    var firstTime = fs.existsSync(process.cwd() + '/node_modules');
    var data = {
        name: name,
        first: !firstTime,
        buildId: settings.buildId
        // dependencies: JSON.parse(fs.readFileSync(dependencies))
    };

    var tarFile = 'compressed.tar.gz';
    var tarFileDownloaded = false;
    var buildId = null;
    var compressedDependencies = fs.createWriteStream(tarFile);

    compressedDependencies.on('error', function(err) {
        return callback('An error ocurred while writing the dependencies .tar file. Please try again :S');
    });

    compressedDependencies.on('finish', function() {
        if (tarFileDownloaded) {
            console.log('Downloaded compressed.tar.gz. Extracting...');
            extractDependencies('node_modules', function(err) {
                if (err) {
                    return callback(err);
                }
                console.log('Extract completed.');
                var child = childProcess.spawn('npm', ['rebuild'], { silent: true });
                child.on('close', function() {
                    if (fs.existsSync(tarFile)) {
                        fs.unlinkSync(tarFile);
                    }

                    if (buildId) {
                        settings.buildId = buildId;
                        fs.writeFile(process.cwd() + '/finalizer.json', JSON.stringify(settings), function(err) {
                            if (err) {
                                console.log(err);
                                return callback('There was an error adding build ID to the finalizer.json file.');
                            }
                            console.log('build id saved');
                            return callback(null, 'Downloaded and rebuilt dependencies for "' + name + '"');
                        });
                    } else {
                        return callback(null, 'Downloaded and rebuilt dependencies for "' + name + '"');
                    }
                });
            });
        }
    });

    var response = request.post(baseUrl + '/download', { form: data });
    response.on('data', function(data) {
        // show a pretty download progress bar?
    });
    response.on('response', function(res) {
        const headers = res.headers;
        buildId = headers['build-id-header'];
        if (res.statusCode !== 200) {
            if (fs.existsSync(tarFile)) {
                fs.unlinkSync(tarFile);
            }
            return callback(res.headers['error-message']);
        }

        // if we get a 200 response from the server, this value will be set.
        // Now, no matter what response we get, the "compressedDependencies" stream
        // will still be piped (with nothing) and that "finish" event will still occur.
        // I can't figure out a way to maybe stop piping or to not pipe at all,
        // if the response is not a 200
        // I think this is not a good approach and can be handled better.
        tarFileDownloaded = true;
    });
    response.on('error', function(err) {
        return callback(err);
    });
    response.pipe(compressedDependencies);
}

/**
 * Build a new version of the project dependencies.
 * @param  {String}   name
 * @param  {Function} callback
 * @return {null}
 */
client.build = function(name, callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    loadSettings();
    var dependencies = process.cwd() + '/package.json';
    if (!fs.existsSync(dependencies)) {
        return callback('package.json doesn\'t exists. Can\'t create new build for project "' + name + '"');
    }

    var data = {
        name: name,
        dependencies: JSON.parse(fs.readFileSync(dependencies))
    };
    request.post(baseUrl + '/build', { form: data }, function(err, res, body) {
        var body = JSON.parse(body);
        if (!err && res.statusCode === 200) {
            return callback(null, body.msg);
        }
        callback(body.msg);
    });
}

/**
 * Generate a basic finalizer.json file.
 * @param  {Function} callback
 * @return {null}
 */
client.init = function(callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    var data = {
        baseUrl: 'http://localhost:8000'
    };

    if (fs.existsSync(finalizerFile)) {
        return callback('finalizer.json file already exists.');
    }
    fs.writeFile(process.cwd() + '/finalizer.json', JSON.stringify(data), function(err) {
        if (err) {
            console.log(err);
            return callback('There was an error creating the finalizer.json file.');
        }
        return callback(null, 'finalizer.json file created.');
    });
}

/**
 * Check connection to the build server.
 * @param  {Function} callback
 * @return {null}
 */
client.check = function(callback) {
    var finalizerFile = process.cwd() + '/finalizer.json';
    if (!fs.existsSync(finalizerFile)) {
        return callback('finalizer.json doesn\'t exists. Please, run "finalizer init"');
    }
    loadSettings();
    var data = {
        status: 'PING'
    };
    request.post(baseUrl + '/check', { form: data }, function(err, res, body) {
        console.log(baseUrl + '/check');
        if (!err && res.statusCode === 200) {
            var body = JSON.parse(body);
            return callback(null, body.msg + '! Connection established.');
        }
        return callback('Connection to build server not established. Check your finalizer.json file.');
    });
}

function extractDependencies(path, callback) {
    var extractor = tar.Extract({ path: path, strip: 1 })
        .on('error', function(err) {
            return callback(err);
        })
        .on('end', function() {
            return callback(null);
        });

    fs.createReadStream(process.cwd() + '/compressed.tar.gz')
        .on('error', function(err) {
            return callback(err);
        })
        .pipe(extractor);
}

/**
 * Load basic settings from finalizer.json file.
 * @return {null}
 */
function loadSettings() {
    var settings = require('./settings');
    baseUrl = settings.baseUrl + '/api';

    return settings;
}

module.exports = client;
<|endoftext|>


<commit_before>/*
 * ------------------------------------------
 * 重写History API封装实现文件
 * @version  1.0
 * @author   genify(caijf@corp.netease.com)
 * ------------------------------------------
 */
var f = function(){
    var _v = NEJ.P('nej.v'),
        _hflag = !1, // is history
        _hpool = []; // history url list
    /**
     * 当前历史索引
     * @type Number
     */
    history.index = 0;
    /**
     * 历史队列长度
     * @type Number
     */
    history.size = _hpool.length;
    /**
     * 跳转到历史
     * @api    {history.go}
     * @param  {Number} 步长
     * @return {history}
     */
    history.go = function(_step){
        if (history.length<2) return this;
        var _index = history.index+_step;
        history.index = Math.max(0,
                        Math.min(_index,
                        history.size-1));
        _hflag = !0;
        location.redirect(_hpool[history.index],!0);
        return this;
    };
    /**
     * 从历史记录移出一个历史
     * @return {Void}
     */
    history.pop = function(){
        _hpool.pop();
        history.size = _hpool.length;
        history.index = Math.min(
            history.index,
            history.size-1
        );
    };
    /**
     * 后退
     * @api    {history.back}
     * @return {history}
     */
    history.back = function(){
        history.go(-1);
        return this;
    };
    /**
     * 前进
     * @api    {history.forward}
     * @return {history}
     */
    history.forward = function(){
        history.go(1);
        return this;
    };
    // listener history change
    _v._$addEvent(location,'urlchange',
        function(_event){
            // from history
            if (_hflag){
                _hflag = !1;
                return;
            }
            // save history
            var _url = _event.href,
                _cur = _hpool[history.index];
            if (_url!=_cur){
                if (_cur!=null)
                    history.index++;
                _hpool[history.index] = _url;
                history.size  = history.index+1;
                // remove size -> length
                var _count = _hpool.length-history.size;
                if (_count>0) _hpool.splice(history.size,_count);
            }
        });
};
NEJ.define('{lib}util/history/history.override.js',
          ['{lib}util/history/history.js'],f);
<commit_msg>bugfix history override for ios7<commit_after>/*
 * ------------------------------------------
 * 重写History API封装实现文件
 * @version  1.0
 * @author   genify(caijf@corp.netease.com)
 * ------------------------------------------
 */
var f = function(){
    var _v = NEJ.P('nej.v'),
        _hflag = !1, // is history
        _hpool = []; // history url list
    /**
     * 当前历史索引
     * @type Number
     */
    history.index = 0;
    /**
     * 历史队列长度
     * @type Number
     */
    history.size = _hpool.length;
    /**
     * 跳转到历史
     * @api    {history.go}
     * @param  {Number} 步长
     * @return {history}
     */
    history.go = function(_step){
        if (history.size<2) return this;
        var _index = history.index+_step;
        history.index = Math.max(0,
                        Math.min(_index,
                        history.size-1));
        _hflag = !0;
        location.redirect(_hpool[history.index],!0);
        return this;
    };
    /**
     * 从历史记录移出一个历史
     * @return {Void}
     */
    history.pop = function(){
        _hpool.pop();
        history.size = _hpool.length;
        history.index = Math.min(
            history.index,
            history.size-1
        );
    };
    /**
     * 后退
     * @api    {history.back}
     * @return {history}
     */
    history.back = function(){
        history.go(-1);
        return this;
    };
    /**
     * 前进
     * @api    {history.forward}
     * @return {history}
     */
    history.forward = function(){
        history.go(1);
        return this;
    };
    // listener history change
    _v._$addEvent(location,'urlchange',
        function(_event){
            // from history
            if (_hflag){
                _hflag = !1;
                return;
            }
            // save history
            var _url = _event.href,
                _cur = _hpool[history.index];
            if (_url!=_cur){
                if (_cur!=null)
                    history.index++;
                _hpool[history.index] = _url;
                history.size  = history.index+1;
                // remove size -> length
                var _count = _hpool.length-history.size;
                if (_count>0) _hpool.splice(history.size,_count);
            }
        });
};
NEJ.define(
    '{lib}util/history/history.override.js',[
    '{lib}util/history/history.js'
],f);
<|endoftext|>


<commit_before>angular.module('mgo.ui.router.directives', []);

angular.module('mgo.ui.router.directives').directive('uiGoto', function() {
    return {
        restrict : 'A',
        controller: ['$scope', '$element', '$attrs', '$state',
             function ($scope, $element, $attrs, $state) {

            $element.click(function(e) {
                e.preventDefault();
                var state = $attrs.uiGoto;

                var params = {};
                if ($attrs.uiGotoParams) {
                    var params = $scope.$eval($attrs.uiGotoParams);
                    if (!angular.isObject(params)) {
                        throw new Error("Parameters for uiGotoParams must be an object");
                    }
                }

               $scope.$apply(function() {
                   $state.transitionTo(state, angular.extend({}, $state.params, params));
               })
            });

        }]
    }
});
<commit_msg>Added dependency for ui.router<commit_after>angular.module('mgo.ui.router.directives', ['ui.router']);

angular.module('mgo.ui.router.directives').directive('uiGoto', function() {
    return {
        restrict : 'A',
        controller: ['$scope', '$element', '$attrs', '$state',
             function ($scope, $element, $attrs, $state) {

            $element.click(function(e) {
                e.preventDefault();
                var state = $attrs.uiGoto;

                var params = {};
                if ($attrs.uiGotoParams) {
                    var params = $scope.$eval($attrs.uiGotoParams);
                    if (!angular.isObject(params)) {
                        throw new Error("Parameters for uiGotoParams must be an object");
                    }
                }

               $scope.$apply(function() {
                   $state.transitionTo(state, angular.extend({}, $state.params, params));
               })
            });

        }]
    }
});
<|endoftext|>


<commit_before>/**
 * Cross-browser reference to the root document node.
 * @type {Element|Node|HTMLElement}
 */
export const document_root = (
  document.documentElement ||
  document.body.parentNode ||
  document.body
);

/**
 * Cross-browser function to get left and top position of viewport relative to
 * the document.
 * @returns {*}
 */
export default function () {
  // modern browsers
  if (typeof window.pageXOffset !== 'undefined') {
    return {
      left: window.pageXOffset,
      top: window.pageYOffset
    }
  }

  // obsolete browsers
  return {
    left: document_root.scrollLeft,
    top: document_root.scrollTop
  }
}
<commit_msg>fix: prevent invalid results when `window.pageYOffset` is set to invalid value<commit_after>/**
 * Cross-browser reference to the root document node.
 * @type {Element|Node|HTMLElement}
 */
export const document_root = (
  document.documentElement ||
  document.body.parentNode ||
  document.body
);

/**
 * Cross-browser function to get left and top position of viewport relative to
 * the document.
 * @returns {*}
 */
export default function () {
  // modern browsers
  if (
    typeof window.pageXOffset !== 'undefined' &&
    typeof window.pageYOffset !== 'undefined'
  ) {
    return {
      left: window.pageXOffset,
      top: window.pageYOffset
    }
  }

  // obsolete browsers
  if (
    typeof document_root.scrollLeft !== 'undefined' &&
    typeof document_root.scrollTop !== 'undefined'
  ) {
    return {
      left: document_root.scrollLeft,
      top: document_root.scrollTop
    }
  }

  return {left: 0, top: 0}
}
<|endoftext|>


<commit_before>/* global expect jest test */
const { Lyric } = require('./lyrical-nonsense');

jest.setTimeout(20_000); // 20 second timeout

async function testLyric(object) {
  const { url, title, artist, lyricist, composer, arranger, length } = object;
  const inst = new Lyric(url);
  await inst.get();

  expect(inst.title).toBe(title);
  expect(inst.artist).toBe(artist);
  if (lyricist) expect(inst.lyricist).toBe(lyricist);
  if (composer) expect(inst.composer).toBe(composer);
  if (arranger) expect(inst.arranger).toBe(arranger);
  if (length > 0) expect(inst.lyric.length).toBe(length);
}

test('', async () => {
  await testLyric({
    url: 'https://www.lyrical-nonsense.com/global/lyrics/lisa/homura/#Romaji',
    title: 'Homura',
    artist: 'LiSA',
    lyricist: '梶浦由記・LiSA',
    composer: '梶浦由記',
    length: 1019,
  });
});

test('', async () => {
  await testLyric({
    url: 'https://www.lyrical-nonsense.com/lyrics/minami-373/kawaki-wo-ameku/',
    title: 'カワキヲアメク',
    artist: '美波',
    lyricist: '美波',
    composer: '美波',
    length: 748,
  });
});

test('', async () => {
  await testLyric({
    url: 'https://www.lyrical-nonsense.com/global/lyrics/kenshi-yonezu/lemon/#Espanol',
    title: 'Lemon',
    artist: 'Kenshi Yonezu',
    length: 1665,
  });
});

// https://www.lyrical-nonsense.com/lyrics/asca/resister/#LyricsPlus
// https://www.lyrical-nonsense.com/lyrics/kenshi-yonezu/lemon/#Espanol
<commit_msg>fix lyrical-nonse test case<commit_after>/* global expect jest test */
const { Lyric } = require('./lyrical-nonsense');

jest.setTimeout(20_000); // 20 second timeout

async function testLyric(object) {
  const { url, title, artist, lyricist, composer, arranger, length } = object;
  const inst = new Lyric(url);
  await inst.get();

  expect(inst.title).toBe(title);
  expect(inst.artist).toBe(artist);
  if (lyricist) expect(inst.lyricist).toBe(lyricist);
  if (composer) expect(inst.composer).toBe(composer);
  if (arranger) expect(inst.arranger).toBe(arranger);
  if (length > 0) expect(inst.lyric.length).toBe(length);
}

test('', async () => {
  await testLyric({
    url: 'https://www.lyrical-nonsense.com/global/lyrics/lisa/homura/#Romaji',
    title: 'Homura',
    artist: 'LiSA',
    lyricist: 'Yuki Kajiura・LiSA',
    composer: 'Yuki Kajiura',
    length: 1019,
  });
});

test('', async () => {
  await testLyric({
    url: 'https://www.lyrical-nonsense.com/lyrics/minami-373/kawaki-wo-ameku/',
    title: 'カワキヲアメク',
    artist: '美波',
    lyricist: '美波',
    composer: '美波',
    length: 748,
  });
});

test('', async () => {
  await testLyric({
    url: 'https://www.lyrical-nonsense.com/global/lyrics/kenshi-yonezu/lemon/#Espanol',
    title: 'Lemon',
    artist: 'Kenshi Yonezu',
    length: 1665,
  });
});

// https://www.lyrical-nonsense.com/lyrics/asca/resister/#LyricsPlus
// https://www.lyrical-nonsense.com/lyrics/kenshi-yonezu/lemon/#Espanol
<|endoftext|>


<commit_before>var ms = require('ms');

module.exports = settings;
module.exports.mode = process.env.NODE_ENV || 'development';

var cache = {};
function settings(transformer) {
  if (cache['key:' + transformer]) return cache['key:' + transformer];
  var exports = setter();

  exports.production = setter();
  exports.production.cache = true;
  exports.production.minify = true;
  exports.production.gzip = true;

  exports.development = setter();
  exports.development.cache = false;
  exports.development.minify = false;
  exports.development.gzip = false;

  exports.normalize = normalize;
  function normalize(options) {
    var defaults = exports[module.exports.mode];
    options = options || {};

    Object.keys(defaults)
      .forEach(function (key) {
        if (options[key] === null || options[key] === undefined) {
          options[key] = defaults[key];
        }
      });
    Object.keys(exports)
      .forEach(function (key) {
        if (key !== 'production' && key !== 'development' && key !== 'normalize' && (options[key] === null || options[key] === undefined)) {
          options[key] = exports[key];
        }
      });

    if (typeof options.cache === 'string' && ms(options.cache)) {
      options.cache = 'public, max-age=' + Math.floor(ms(options.cache)/1000);
    } else if (options.cache === true) {
      options.cache = 'public, max-age=60';
    } else if (typeof options.cache === 'number') {
      options.cache = 'public, max-age=' + Math.floor(options.cache/1000);
    } else if (typeof options.cache === 'object') {
      options.cache = (options.cache.private ? 'private' : 'public') + ', max-age='
                    + Math.floor(ms(options.cache.maxAge.toString())/1000);
    }

    return options;
  }

  return cache['key:' + transformer] = exports;
}

function setter(obj) {
  obj = obj || set;
  function set(key) {
    if (arguments.length === 2) {
      obj[key] = arguments[1];
      return this;
    } else if (typeof key === 'string') {
      Object.keys(key)
        .forEach(function (k) {
          obj[k] = key[k];
        });
      return this;
    } else {
      return obj[key];
    }
  }
  return set;
}
<commit_msg>Fix a bug in what was admissable to the settings function<commit_after>var ms = require('ms');

module.exports = settings;
module.exports.mode = process.env.NODE_ENV || 'development';

var cache = {};
function settings(transformer) {
  if (cache['key:' + transformer]) return cache['key:' + transformer];
  var exports = setter();

  exports.production = setter();
  exports.production.cache = true;
  exports.production.minify = true;
  exports.production.gzip = true;

  exports.development = setter();
  exports.development.cache = false;
  exports.development.minify = false;
  exports.development.gzip = false;

  exports.normalize = normalize;
  function normalize(options) {
    var defaults = exports[module.exports.mode];
    options = options || {};

    Object.keys(defaults)
      .forEach(function (key) {
        if (options[key] === null || options[key] === undefined) {
          options[key] = defaults[key];
        }
      });
    Object.keys(exports)
      .forEach(function (key) {
        if (key !== 'production' && key !== 'development' && key !== 'normalize' && (options[key] === null || options[key] === undefined)) {
          options[key] = exports[key];
        }
      });

    if (typeof options.cache === 'string' && ms(options.cache)) {
      options.cache = 'public, max-age=' + Math.floor(ms(options.cache)/1000);
    } else if (options.cache === true) {
      options.cache = 'public, max-age=60';
    } else if (typeof options.cache === 'number') {
      options.cache = 'public, max-age=' + Math.floor(options.cache/1000);
    } else if (typeof options.cache === 'object') {
      options.cache = (options.cache.private ? 'private' : 'public') + ', max-age='
                    + Math.floor(ms(options.cache.maxAge.toString())/1000);
    }

    return options;
  }

  return cache['key:' + transformer] = exports;
}

function setter(obj) {
  obj = obj || set;
  function set(key) {
    if (arguments.length === 2) {
      obj[key] = arguments[1];
      return this;
    } else if (typeof key === 'object') {
      Object.keys(key)
        .forEach(function (k) {
          obj[k] = key[k];
        });
      return this;
    } else {
      return obj[key];
    }
  }
  return set;
}
<|endoftext|>


<commit_before>import $ from 'jquery';
import _ from 'underscore';
import Mediaplayer from 'picnic/mediaplayer/views/Mediaplayer';
import ApiLoader from 'picnic/vimeoplayer/services/ApiLoader';
import Logger from 'picnic/core/utils/Logger';

var
	MODULE_NAME = 'vimeoplayer',
	DATA_VIDEOID = 'vimeoid',
	EVENT_PLAY = 'play',
	EVENT_STOP = 'stop',
	EVENT_PAUSE = 'pause',
	EVENT_COMPLETE = 'complete',
	EVENT_UPDATEPROGRESS = 'updateprogress',
	DEFAULTS = {
		debug: false,
		loader: new ApiLoader(),
		eventNamespace: 'vimeoplayer',
		trigger: 'a',
		classLoading: 'loading',
		classPlaying: 'playing',
		playerHideSpeed: 300,
		playerProgressSteps: 5,
		playerProgressInterval: 1000,
		playerOptions: {
			autoplay: true
		}
	}
;

/**
 * A module including a view to generate a Vimeo player.
 *
 * The view requires for each element a video id passed by the data attribute
 * `data-vimeoid` and an element that triggers the play event on click, as you can see
 * in the example below.
 *
 * @class Vimeoplayer
 * @see {@link https://github.com/vimeo/player.js|Vimeo Player API}
 * @example
 *

 *
 * 				Play video
 *
 *

 */
class View extends Mediaplayer {

	/**
	 * Creates an instance of the view.
	 *
	 * @constructor
	 * @param {object} options The settings for the view
	 * @param {object} options.context The reference to the backbone.geppetto context
	 * @param {object} options.el The element reference for a backbone.view
	 * @param {boolean} options.debug Enable debug mode. The default value is false
	 * @param {object} options.loader ApiLoader reference
	 * @param {string} options.eventNamespace Set the namespace for events to dispatch
	 *		onto the Context's Event Bus
	 * @param {string} options.trigger Name of the element that triggers the
	 *		inizialize or play event. The default value is "a"
	 * @param {string} options.classLoading Set a CSS class on loading the video.
	 *		The default value is "loading"
	 * @param {string} options.classPlaying Set a CSS class on playing the video.
	 *		The default value is "playing"
	 * @param {number} options.playerHideSpeed Set the speed of the hide animation,
	 *		in miliseconds. The default value is 300
	 * @param {number} options.playerProgressSteps Update progress every x steps,
	 *		in percent. The default value is 5
	 * @param {number} options.playerProgressInterval Set the progress interval,
	 *		in milliseconds. The default value is 1000
	 * @param {object} options.playerOptions Vimeo Player options,
	 *		see https://github.com/vimeo/player.js#embed-options.
	 *		By default the autoplay option is set to true
	 */
	constructor(options) {
		super($.extend(true, {}, DEFAULTS, options));

		if (this.options.debug) {
			this._logger = new Logger({
				modulename: MODULE_NAME + ' (' + this.getVideoId() + ')'
			});
		} else {
			this._logger = {log: function() {}};
		}

		this._resetProgress();
	}

	//================================================================================
	// Public Methods
	//================================================================================

	/**
	 * This renders the content of this view
	 *
	 * @return {object} The instance of this view
	 */
	render() {
		super.render();
		this._bindEvents();
		return this;
	}

	/**
	 * Remove event listeners
	 */
	destroy() {
		// Remove click event
		this.$el.off('click.' + this.options.eventNamespace);

		// Remove Vimeo API Event listeners
		if (this._player) {
			this._player.off('play');
			this._player.off('pause');
			this._player.off('ended');
			this._player.off('loaded');
			this._player.off('error');
		}

		super.destroy();
	}

	/**
	 * Play the video if is initialized otherwise render it
	 */
	play() {
		if (this._hasPlayer()) {
			this._player.play();
			this._onPlayHandler();
		} else {
			this._renderPlayer();
		}
	}

	/**
	 * Pause the video
	 */
	pause() {
		if (this._hasPlayer()) {
			this._player.pause();
			this._onPauseHandler();
		}
	}

	/**
	 * Stop the video
	 */
	stop() {
		this.stopMedia();
	}

	/**
	 * Overwrite default stopMedia method
	 */
	stopMedia() {
		if (this._hasPlayer()) {
			this._player.unload();
			this._onStopHandler();
		}
	}

	/**
	 * Get the id of the video
	 *
	 * @return {number} The id of the video
	 */
	getVideoId() {
		return this.$el.data(DATA_VIDEOID);
	}

	/**
	 * Get the progress of the video
	 *
	 * @return {number} The progress of the video
	 */
	getProgress() {
		return this._progress;
	}

	//================================================================================
	// Private Methods
	//================================================================================

	/**
	 * Return true or false if the player is already initialized
	 *
	 * @private
	 * @return {boolean}
	 */
	_hasPlayer() {
		return !!this._player;
	}

	/**
	 * Render player
	 *
	 * @private
	 */
	_renderPlayer() {
		if (!this._player) {
			// Add loading class
			this.$el.addClass(this.options.classLoading);

			// Use ApiLoader service
			this.options.loader.requestPlayer().done(this._onPlayerReceived);
		}
	}

	/**
	 * Update interval
	 *
	 * @private
	 */
	_updateInterval() {
		if (!this._interval) {
			this._interval = window.setInterval(
				this._onInterval,
				this.options.playerProgressInterval
			);
			this._logger.log('updateInterval');
		}
	}

	/**
	 * Reset interval
	 *
	 * @private
	 */
	_resetInterval() {
		if (this._interval) {
			window.clearInterval(this._interval);
			this._interval = undefined;
			delete(this._interval);
			this._logger.log('resetInterval');
		}
	}

	/**
	 * Update video progress
	 *
	 * @private
	 */
	_updateProgress() {
		if (this._hasPlayer()) {
			var self = this;

			self._player.getCurrentTime().then(function(seconds) {
				self._player.getDuration().then(function(duration) {
					self._setProgress(seconds, duration);
				});
			});
		}
	}

	/**
	 * Set video progress depending on seconds and duration
	 *
	 * @param {number} seconds
	 * @param {number} duration
	 * @private
	 */
	_setProgress(seconds, duration) {
		var
			progress = seconds / duration * 100,
			steps = this.options.playerProgressSteps
		;

		progress = Math.floor(progress / steps) * steps;
		progress = Math.max(this._progress, progress);

		if (progress !== this._progress) {
			this._progress = progress;
			this._dispatch(EVENT_UPDATEPROGRESS);
			this._logger.log('updateProgress', this._progress);
		}
	}

	/**
	 * Reset video progress
	 *
	 * @private
	 */
	_resetProgress() {
		this._progress = -1;
		this._logger.log('resetProgress', this._progress);
	}

	/**
	 * Show player iFrame
	 *
	 * @private
	 */
	_showDisplay() {
		if (this.$player) {
			this.$player.show();
			this.$el.addClass(this.options.classPlaying);
		}
	}

	/**
	 * Hide player iFrame
	 *
	 * @private
	 */
	_hideDisplay() {
		if (this.$player) {
			this.$player.fadeOut(this.options.playerHideSpeed);
			this.$el.removeClass(this.options.classPlaying);
		}
	}

	/**
	 * Dispatch the event name onto the Context's Event Bus
	 *
	 * @private
	 * @param {string} eventName
	 */
	_dispatch(eventName) {
		this.context.dispatch(this.options.eventNamespace + ':' + eventName, this);
	}

	//================================================================================
	// Events
	//================================================================================

	/**
	 * Bind events
	 *
	 * @private
	 */
	_bindEvents() {
		_.bindAll(
			this,
			'_onClickPlay',
			'_onPlayerReceived',
			'_onInterval',
			'_onPlay',
			'_onPause',
			'_onEnded',
			'_onLoaded',
			'_onError',
			'_onReady'
		);

		this.$el.on('click.' + this.options.eventNamespace, this.options.trigger, this._onClickPlay);
	}

	/**
	 * Play event handler
	 *
	 * @private
	 */
	_onPlayHandler() {
		this._updateProgress();
		this._updateInterval();
		this._showDisplay();
		this.playMedia();
		this._dispatch(EVENT_PLAY);
	}

	/**
	 * Stop event handler
	 *
	 * @private
	 * @param {string} [eventName=EVENT_STOP] The event name
	 *		to dispatch onto the Context's Event Bus
	 */
	_onStopHandler(eventName) {
		this._resetProgress();
		this._resetInterval();
		this._hideDisplay();
		this._dispatch(eventName || EVENT_STOP);
	}

	/**
	 * Pause event handler
	 *
	 * @private
	 */
	_onPauseHandler() {
		this._resetInterval();
		this.$el.removeClass(this.options.classPlaying);
		this._dispatch(EVENT_PAUSE);
	}

	/**
	 * Click event
	 *
	 * @private
	 * @param {object} e The jQuery event object
	 */
	_onClickPlay(e) {
		e.preventDefault();
		this.play();
	}

	/**
	 * Player received event handler
	 *
	 * @private
	 * @param {object} Player The player class which is sent by the ApiLoader service
	 */
	_onPlayerReceived(Player) {
		var
			options = $.extend({}, {id: this.getVideoId()}, this.options.playerOptions),
			container = this.$el
		;

		this._logger.log('onPlayerReceived', options);

		// Initialize player
		this._player = new Player(container[0], options);

		// Listen Vimeo Player API Events/Methods
		this._player.ready().then(this._onReady);
		this._player.on('play', this._onPlay);
		this._player.on('pause', this._onPause);
		this._player.on('ended', this._onEnded);
		this._player.on('loaded', this._onLoaded);
		this._player.on('error', this._onError);
	}

	/**
	 * Interval event handler
	 *
	 * @private
	 */
	_onInterval() {
		this._updateProgress();
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when the video plays
	 *
	 * @private
	 * @param {object} data Reports back duration, percent and seconds of the video
	 * @see {@link https://github.com/vimeo/player.js#play}
	 */
	_onPlay(data) {
		this._logger.log('onPlay', data);
		this._onPlayHandler();
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when the video pauses
	 *
	 * @private
	 * @param {object} data Reports back duration, percent and seconds of the video
	 * @see {@link https://github.com/vimeo/player.js#pause}
	 */
	_onPause(data) {
		this._logger.log('onPause', data);
		this._onPauseHandler();
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered any time the video playback reaches the end
	 *
	 * @private
	 * @param {object} data Reports back duration, percent and seconds of the video
	 * @see {@link https://github.com/vimeo/player.js#ended}
	 */
	_onEnded(data) {
		this._logger.log('onEnded', data);
		this._onStopHandler(EVENT_COMPLETE);
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when a new video is loaded in the player
	 *
	 * @private
	 * @param {object} data Reports back the id of the video
	 * @see {@link https://github.com/vimeo/player.js#loaded}
	 */
	_onLoaded(data) {
		this._logger.log('onLoaded', data);
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when some kind of error is generated in the player
	 *
	 * @private
	 * @param {object} data Reports back the error informations
	 * @see {@link https://github.com/vimeo/player.js#error}
	 */
	_onError(data) {
		this._logger.log('onError', data);
	}

	/**
	 * Vimeo Player API Method:
	 * Trigger a function when the player iframe has initialized
	 *
	 * @private
	 * @see {@link https://github.com/vimeo/player.js#ready-promisevoid-error}
	 */
	_onReady() {
		this._logger.log('onReady');

		// Store player iFrame
		this.$player = $(this._player.element);

		// Remove loading class
		this.$el.removeClass(this.options.classLoading);

		// Play
		(this.options.playerOptions.autoplay) ? this._onPlayHandler() : this._showDisplay();
	}

}

export default View;
<commit_msg>Update documentation of vimeoplayer<commit_after>import $ from 'jquery';
import _ from 'underscore';
import Mediaplayer from 'picnic/mediaplayer/views/Mediaplayer';
import ApiLoader from 'picnic/vimeoplayer/services/ApiLoader';
import Logger from 'picnic/core/utils/Logger';

var
	MODULE_NAME = 'vimeoplayer',
	DATA_VIDEOID = 'vimeoid',
	EVENT_PLAY = 'play',
	EVENT_STOP = 'stop',
	EVENT_PAUSE = 'pause',
	EVENT_COMPLETE = 'complete',
	EVENT_UPDATEPROGRESS = 'updateprogress',
	DEFAULTS = {
		debug: false,
		loader: new ApiLoader(),
		eventNamespace: 'vimeoplayer',
		trigger: 'a',
		classLoading: 'loading',
		classPlaying: 'playing',
		playerHideSpeed: 300,
		playerProgressSteps: 5,
		playerProgressInterval: 1000,
		playerOptions: {
			autoplay: true
		}
	}
;

/**
 * A module including a view to generate a Vimeo player.
 *
 * The view requires for each element a video id passed by the data attribute
 * `data-vimeoid` and an element that triggers the play event on click, as you can see
 * in the example below.
 *
 * Once the user clicks the link, the vimeo player api is loaded and the
 * player will be initialized. Multiple vimeo player on a single page share the
 * same api. The api will be loaded only once when the first player starts to
 * play.
 *
 * @class Vimeoplayer
 * @see {@link https://github.com/vimeo/player.js|Vimeo Player API}
 * @example
 *

 *
 * 				Play video
 *
 *

 */
class View extends Mediaplayer {

	/**
	 * Creates an instance of the view.
	 *
	 * @constructor
	 * @param {object} options The settings for the view
	 * @param {object} options.context The reference to the backbone.geppetto context
	 * @param {object} options.el The element reference for a backbone.view
	 * @param {boolean} options.debug Enable debug mode. The default value is false
	 * @param {object} options.loader ApiLoader reference
	 * @param {string} options.eventNamespace Set the namespace for events to dispatch
	 *		onto the Context's Event Bus
	 * @param {string} options.trigger Name of the element that triggers the
	 *		inizialize or play event. The default value is "a"
	 * @param {string} options.classLoading Set a CSS class on loading the video.
	 *		The default value is "loading"
	 * @param {string} options.classPlaying Set a CSS class on playing the video.
	 *		The default value is "playing"
	 * @param {number} options.playerHideSpeed Set the speed of the hide animation,
	 *		in miliseconds. The default value is 300
	 * @param {number} options.playerProgressSteps Update progress every x steps,
	 *		in percent. The default value is 5
	 * @param {number} options.playerProgressInterval Set the progress interval,
	 *		in milliseconds. The default value is 1000
	 * @param {object} options.playerOptions Vimeo Player options,
	 *		see https://github.com/vimeo/player.js#embed-options.
	 *		By default the autoplay option is set to true
	 */
	constructor(options) {
		super($.extend(true, {}, DEFAULTS, options));

		if (this.options.debug) {
			this._logger = new Logger({
				modulename: MODULE_NAME + ' (' + this.getVideoId() + ')'
			});
		} else {
			this._logger = {log: function() {}};
		}

		this._resetProgress();
	}

	//================================================================================
	// Public Methods
	//================================================================================

	/**
	 * This renders the content of this view
	 *
	 * @return {object} The instance of this view
	 */
	render() {
		super.render();
		this._bindEvents();
		return this;
	}

	/**
	 * Remove event listeners and destroy inner vimeo player instance.
	 */
	destroy() {
		// Remove click event
		this.$el.off('click.' + this.options.eventNamespace);

		// Remove Vimeo API Event listeners
		if (this._player) {
			this._player.off('play');
			this._player.off('pause');
			this._player.off('ended');
			this._player.off('loaded');
			this._player.off('error');
		}

		super.destroy();
	}

	/**
	 * Play the video if is initialized otherwise render it
	 */
	play() {
		if (this._hasPlayer()) {
			this._player.play();
			this._onPlayHandler();
		} else {
			this._renderPlayer();
		}
	}

	/**
	 * Pause the video
	 */
	pause() {
		if (this._hasPlayer()) {
			this._player.pause();
			this._onPauseHandler();
		}
	}

	/**
	 * Stop the video
	 */
	stop() {
		this.stopMedia();
	}

	/**
	 * Overwrite default stopMedia method from [Mediaplayer](#mediaplayer).
	 */
	stopMedia() {
		if (this._hasPlayer()) {
			this._player.unload();
			this._onStopHandler();
		}
	}

	/**
	 * Get the id of the video
	 *
	 * @return {number} The id of the video
	 */
	getVideoId() {
		return this.$el.data(DATA_VIDEOID);
	}

	/**
	 * Get the progress of the video
	 *
	 * @return {number} The progress of the video
	 */
	getProgress() {
		return this._progress;
	}

	//================================================================================
	// Private Methods
	//================================================================================

	/**
	 * Return true or false if the player is already initialized
	 *
	 * @private
	 * @return {boolean}
	 */
	_hasPlayer() {
		return !!this._player;
	}

	/**
	 * Render player
	 *
	 * @private
	 */
	_renderPlayer() {
		if (!this._player) {
			// Add loading class
			this.$el.addClass(this.options.classLoading);

			// Use ApiLoader service
			this.options.loader.requestPlayer().done(this._onPlayerReceived);
		}
	}

	/**
	 * Update interval
	 *
	 * @private
	 */
	_updateInterval() {
		if (!this._interval) {
			this._interval = window.setInterval(
				this._onInterval,
				this.options.playerProgressInterval
			);
			this._logger.log('updateInterval');
		}
	}

	/**
	 * Reset interval
	 *
	 * @private
	 */
	_resetInterval() {
		if (this._interval) {
			window.clearInterval(this._interval);
			this._interval = undefined;
			delete(this._interval);
			this._logger.log('resetInterval');
		}
	}

	/**
	 * Update video progress
	 *
	 * @private
	 */
	_updateProgress() {
		if (this._hasPlayer()) {
			var self = this;

			self._player.getCurrentTime().then(function(seconds) {
				self._player.getDuration().then(function(duration) {
					self._setProgress(seconds, duration);
				});
			});
		}
	}

	/**
	 * Set video progress depending on seconds and duration
	 *
	 * @param {number} seconds
	 * @param {number} duration
	 * @private
	 */
	_setProgress(seconds, duration) {
		var
			progress = seconds / duration * 100,
			steps = this.options.playerProgressSteps
		;

		progress = Math.floor(progress / steps) * steps;
		progress = Math.max(this._progress, progress);

		if (progress !== this._progress) {
			this._progress = progress;
			this._dispatch(EVENT_UPDATEPROGRESS);
			this._logger.log('updateProgress', this._progress);
		}
	}

	/**
	 * Reset video progress
	 *
	 * @private
	 */
	_resetProgress() {
		this._progress = -1;
		this._logger.log('resetProgress', this._progress);
	}

	/**
	 * Show player iFrame
	 *
	 * @private
	 */
	_showDisplay() {
		if (this.$player) {
			this.$player.show();
			this.$el.addClass(this.options.classPlaying);
		}
	}

	/**
	 * Hide player iFrame
	 *
	 * @private
	 */
	_hideDisplay() {
		if (this.$player) {
			this.$player.fadeOut(this.options.playerHideSpeed);
			this.$el.removeClass(this.options.classPlaying);
		}
	}

	/**
	 * Dispatch the event name onto the Context's Event Bus
	 *
	 * @private
	 * @param {string} eventName
	 */
	_dispatch(eventName) {
		this.context.dispatch(this.options.eventNamespace + ':' + eventName, this);
	}

	//================================================================================
	// Events
	//================================================================================

	/**
	 * Bind events
	 *
	 * @private
	 */
	_bindEvents() {
		_.bindAll(
			this,
			'_onClickPlay',
			'_onPlayerReceived',
			'_onInterval',
			'_onPlay',
			'_onPause',
			'_onEnded',
			'_onLoaded',
			'_onError',
			'_onReady'
		);

		this.$el.on('click.' + this.options.eventNamespace, this.options.trigger, this._onClickPlay);
	}

	/**
	 * Play event handler
	 *
	 * @private
	 */
	_onPlayHandler() {
		this._updateProgress();
		this._updateInterval();
		this._showDisplay();
		this.playMedia();
		this._dispatch(EVENT_PLAY);
	}

	/**
	 * Stop event handler
	 *
	 * @private
	 * @param {string} [eventName=EVENT_STOP] The event name
	 *		to dispatch onto the Context's Event Bus
	 */
	_onStopHandler(eventName) {
		this._resetProgress();
		this._resetInterval();
		this._hideDisplay();
		this._dispatch(eventName || EVENT_STOP);
	}

	/**
	 * Pause event handler
	 *
	 * @private
	 */
	_onPauseHandler() {
		this._resetInterval();
		this.$el.removeClass(this.options.classPlaying);
		this._dispatch(EVENT_PAUSE);
	}

	/**
	 * Click event
	 *
	 * @private
	 * @param {object} e The jQuery event object
	 */
	_onClickPlay(e) {
		e.preventDefault();
		this.play();
	}

	/**
	 * Player received event handler
	 *
	 * @private
	 * @param {object} Player The player class which is sent by the ApiLoader service
	 */
	_onPlayerReceived(Player) {
		var
			options = $.extend({}, {id: this.getVideoId()}, this.options.playerOptions),
			container = this.$el
		;

		this._logger.log('onPlayerReceived', options);

		// Initialize player
		this._player = new Player(container[0], options);

		// Listen Vimeo Player API Events/Methods
		this._player.ready().then(this._onReady);
		this._player.on('play', this._onPlay);
		this._player.on('pause', this._onPause);
		this._player.on('ended', this._onEnded);
		this._player.on('loaded', this._onLoaded);
		this._player.on('error', this._onError);
	}

	/**
	 * Interval event handler
	 *
	 * @private
	 */
	_onInterval() {
		this._updateProgress();
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when the video plays
	 *
	 * @private
	 * @param {object} data Reports back duration, percent and seconds of the video
	 * @see {@link https://github.com/vimeo/player.js#play}
	 */
	_onPlay(data) {
		this._logger.log('onPlay', data);
		this._onPlayHandler();
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when the video pauses
	 *
	 * @private
	 * @param {object} data Reports back duration, percent and seconds of the video
	 * @see {@link https://github.com/vimeo/player.js#pause}
	 */
	_onPause(data) {
		this._logger.log('onPause', data);
		this._onPauseHandler();
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered any time the video playback reaches the end
	 *
	 * @private
	 * @param {object} data Reports back duration, percent and seconds of the video
	 * @see {@link https://github.com/vimeo/player.js#ended}
	 */
	_onEnded(data) {
		this._logger.log('onEnded', data);
		this._onStopHandler(EVENT_COMPLETE);
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when a new video is loaded in the player
	 *
	 * @private
	 * @param {object} data Reports back the id of the video
	 * @see {@link https://github.com/vimeo/player.js#loaded}
	 */
	_onLoaded(data) {
		this._logger.log('onLoaded', data);
	}

	/**
	 * Vimeo Player API Event:
	 * Triggered when some kind of error is generated in the player
	 *
	 * @private
	 * @param {object} data Reports back the error informations
	 * @see {@link https://github.com/vimeo/player.js#error}
	 */
	_onError(data) {
		this._logger.log('onError', data);
	}

	/**
	 * Vimeo Player API Method:
	 * Trigger a function when the player iframe has initialized
	 *
	 * @private
	 * @see {@link https://github.com/vimeo/player.js#ready-promisevoid-error}
	 */
	_onReady() {
		this._logger.log('onReady');

		// Store player iFrame
		this.$player = $(this._player.element);

		// Remove loading class
		this.$el.removeClass(this.options.classLoading);

		// Play
		(this.options.playerOptions.autoplay) ? this._onPlayHandler() : this._showDisplay();
	}

}

export default View;
<|endoftext|>