<commit_before>/* Copyright (c) 2016 https://github.com/askeet/.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

var _root;
function InitAS2() {
	SetDefaultNames();
	_root = exportRoot;
	Test();
}

var isStop = false;
function SetFPS(value){

	if(value ===0){
	    if(!isStop){
			createjs.Ticker.removeEventListener("tick", stage);
			isStop = true;
			UpdatePaint();
		}
	}
	else{
		createjs.Ticker.setFPS(value);
	    if(isStop){
			createjs.Ticker.addEventListener("tick", stage);
			isStop = false;
		}
	}
}

function UpdatePaint(){
   if(isStop){
        var event1 = new Object();
	event1.paused = false;
	handleTick(event1);
   }
   stage.update();
}

// Library AS2

function SetDefaultNames() {
	var i, key;
	var clip = exportRoot; // movieclip content to be processed
	var clipch = clip.children; // movieclip's children
	// iterate over every property name in the clip
	for (key in clip) {
		// is this a CreateJS container object?
		if (clip[key] instanceof createjs.Container) {
			// scan the clip's list of children
			for (i = 0; i < clipch.length; i++) {
				// are they both pointing to the same object?
				if (clip[key] === clipch[i]) {
					// assign key value to "name" property
					clip[key].name = key;
					break;
				}
			}
		}
	}
}

function fscommand(arg,command){
	if(window.external!=null &&  typeof window.external.EventForFSCommand!=='undefined')
		window.external.EventForFSCommand(arg,command);
}

var arrChildByName = [];
function eval(Value) {
	var object = GetValue(Value);
	if(object) arrChildByName[Value] = object;
	return object;
}

function SetValue( nameProperty ,  value , isGotoAndStop ){
        nameProperty = nameProperty.replace( "_root.",'');
	arr = nameProperty.split(".");
	var object = null;

	for (var i = 0; i < arr.length-1; i++) {
	    if(i===0)
		object = _root[arr[0]];
	    else
		if(object)
			object = object[arr[i]];
		}
	if(arr.length > 1 && object ){
		if(!isGotoAndStop){
			object[ arr[arr.length-1]] = value;
		}else{
			object[ arr[arr.length-1]].gotoAndStop(value);
		}
	}
	else{
		if(arr.length === 1){
		    if(!isGotoAndStop){
				_root[arr[0]] = value;
		    }else{
				_root[arr[0]].gotoAndStop(value);
		    }
		}
	}
}

function GetValue( nameProperty){
    nameProperty = nameProperty.replace( "_root.",'');
    arr = nameProperty.split(".");
	var object = null;

	for (var i = 0; i < arr.length; i++) {
	    if(i===0){
		object = _root[arr[0]];
	    	if(!object){
			object = _root.getChildByName(arr[0]);
			if(object){
				_root[arr[0]] = object;
				//object[arr[0]] = object;
			}else{
				break;
			}
		}
	      }
    	      else
		if(object){
			var obj = object[arr[i]];
			if(!obj){ // not find
				obj = object.getChildByName(arr[i]);
			}

			if(obj){
				object[arr[i]] = obj;
				object = obj;
			}else{
				object = undefined;
				break;
			}
		}
	}

	return (arr.length > 0 && object )? object : undefined;
}

var removeObject = createjs.DisplayObject.prototype.removeObject = function () {
	var path = (this.parent) ? this.parent : this;
	var fullPath = this.GetAbsolutePath();

	findBeginStr(arrChildByName, fullPath, function (elem) {
		RemoveShape(arrChildByName[elem]);
		delete arrChildByName[elem];
	});

	RemoveShape(this);
	var ret = path.removeChild(this);
	path[this.name] = undefined;
	return ret;
}

var findBeginStr = function (array, value, callback, fullConsilience) {
	var findElem = false;

	if (value != "") {
		for (arr in array) {
			if (
				(!fullConsilience && String(arr).indexOf(value) === 0) ||
			    (fullConsilience && String(arr)===value)
			) {
				findElem = true;
				//alert("find "+String(arr) + " "+value)
				if (callback(arr)) {
					break;
				}
			}
		}
	}
	return findElem;
}

var GetAbsolutePath = createjs.DisplayObject.prototype.GetAbsolutePath = function () {
	var Name = (this.name) ? this.name : "";
	if (Name) {
		//if(yyyy) alert(this.parent.name);
		var Parent = this.parent;
		while (Parent && Parent.name) {
			Name = Parent.name + "." + Name;
			Parent = Parent.parent;
		}
	}
	return Name;
}

var createEmptyMovieClip = createjs.DisplayObject.prototype.createEmptyMovieClip = function (NameMovieClip, depth) {
	var FindName = this.GetAbsolutePath();
	FindName = (FindName != "") ? FindName + "." + NameMovieClip : NameMovieClip;
	var myMC = new createjs.MovieClip();
	myMC.name = NameMovieClip;
	if (!findBeginStr(arrChildByName, FindName, function (elem) {
			return true;
		})) {
		(!depth && depth != 0) ? this.addChild(myMC) : this.addChildAt(myMC, depth);
		eval(FindName);
		arrChildByName[FindName] = myMC;

	}else{
		myMC = eval(FindName);
	}
	return myMC;
}
//

var createTextField = createjs.DisplayObject.prototype.createTextField = function (NameTextField, depth, X, Y, Font, MaxWidth, MaxHeight) {

	var FindName = this.GetAbsolutePath();
	//alert(FindName + " " +  NameTextField);
	FindName = (FindName != "") ? FindName + "." + NameTextField : NameTextField;

	var tf = new createjs.Text('', (Font) ? Font : 'Arial 12px');
	tf.name = NameTextField;
	tf.x = X;
	tf.y = Y;
	tf.maxHeigth = MaxHeight;
	tf.maxWidth = MaxWidth;
	if (!findBeginStr(arrChildByName, FindName, function (elem) {
			return true;
		}), true) {
		(!depth && depth != 0) ? this.addChild(tf) : this.addChildAt(tf, depth);
		eval(FindName);
		arrChildByName[FindName] = tf;
	}else{
		tf = eval(FindName);
	}
	return tf;
}

var attachMovie = createjs.DisplayObject.prototype.attachMovie = function (idName, newName, depth, initObject) {
	var FindName = this.GetAbsolutePath();
	FindName = (FindName != "") ? FindName + "." + newName : newName;

	var classDefintion = (idName)?lib[idName]:this.constructor;
	if(!classDefintion) classDefintion = this.constructor;
	var instance = new classDefintion();
	instance.idName = idName;
	instance.name = newName;
	if (initObject)
		for (var key in initObject)
			instance[key] = initObject[key];

	if (!findBeginStr(arrChildByName, FindName, function (elem) {
			return true;
		})) {
		(!depth && depth != 0) ? this.addChild(instance) : this.addChildAt(instance, depth);
		eval(FindName);
		arrChildByName[FindName] = instance;
	}else{
		instance = eval(FindName);
	}
	return instance;
}

var duplicateMovieClip = createjs.DisplayObject.prototype.duplicateMovieClip = function (newname, depth ,initObject){
	var path = (this.parent) ? this.parent : this;
	var cm;
	if(this.idName){
		cm = path.attachMovie(this.idName,newname,depth,initObject);
		if(this.paused);
			cm.gotoAndStop(this.currentFrame);
		cm.x = this.x;
		cm.y = this.y;
	}
	else
		cm = path.createEmptyMovieClip(newname, depth ,initObject);
	var Shape =  this.UserShape;
    if(Shape){
		cm.UserShape = Shape.clone(true);
		cm.addChild(cm.UserShape);
	}
	return cm;
}

function trace(Value){
	console.log(Value);
}

function GetShape(Value){
	if(!Value.UserShape){
		Value.UserShape = new createjs.Shape();
		Value.addChild(Value.UserShape);
	}
	return Value.UserShape;
}

function RemoveShape(Value){
	if(Value.UserShape){
		Value.removeChild(Value.UserShape);
		Value.UserShape = undefined;
	}
}

//my_mc.lineTo(x:Number, y:Number) : Void
var lineTo = createjs.DisplayObject.prototype.lineTo = function (x,y){
	GetShape(this).graphics.lineTo(x,y);
}
//my_mc.moveTo(x:Number, y:Number) : Void
var moveTo = createjs.DisplayObject.prototype.moveTo = function (x,y){
	GetShape(this).graphics.moveTo(x,y);
}

//my_mc.lineStyle([thickness:Number[, rgb:Number[, alpha:Number]]]) : Void
var lineStyle = createjs.DisplayObject.prototype.lineStyle = function (thickness,rgb,alpha){
	var Shape = GetShape(this);

	if(thickness!=undefined){
		Shape.graphics.setStrokeStyle(thickness);
	}
	if(rgb!=undefined){
		Shape.graphics.endStroke();
		var color = createjs.Graphics.getRGB(rgb, alpha);
		Shape.graphics.beginStroke(color);
	}
}

//my_mc.beginFill([rgb:Number[, alpha:Number]]) : Void
var beginFill = createjs.DisplayObject.prototype.beginFill = function (rgb,alpha){
	var r = (rgb & 0xFF0000) >> 16;
	var g = (rgb & 0x00FF00) >> 8;
	var b = (rgb & 0x0000FF) >> 0;
	var color = (alpha)? 'rgba(' +r+','+g+','+b+','+alpha+')': 'rgb(' +r+','+g+','+b+')';
	GetShape(this).graphics.beginFill(color);
}
//endFill ()
var endFill = createjs.DisplayObject.prototype.endFill = function (rgb,alpha){
	GetShape(this).graphics.endFill();
}
var clear = createjs.DisplayObject.prototype.clear = function (){
	GetShape(this).graphics.clear();
}
// Property
function  AddNewProperty(CurNameProperty,NewNameProperty, Class, funcGet,funcSet ){
	if(Class == undefined) Class = createjs.DisplayObject.prototype;
	Object.defineProperty(Class, NewNameProperty, {
		get: (!funcGet)? function(){ return (CurNameProperty)? this[CurNameProperty] : undefined; }      : funcGet,
		set: (!funcSet)? function (value){ if(CurNameProperty)this[CurNameProperty] = value; }: funcSet,
		enumerable: true,
		configurable: true
    });
}

var addProperty = createjs.DisplayObject.prototype.addProperty = function (NameProperty, GetStatus, SetStatus){
	AddNewProperty(undefined,NameProperty,this,GetStatus,SetStatus);
	/*Object.defineProperty(this, NameProperty, {
		get: GetStatus,
		set: SetStatus,
		enumerable: true,
		configurable: true
	});	*/
}

AddNewProperty('alpha','_alpha');
AddNewProperty('x','_x');
AddNewProperty('y','_y');
AddNewProperty('rotation','_rotation');
AddNewProperty('xscale','_xscale');
AddNewProperty('yscale','_yscale');
AddNewProperty('parrent','_parrent');
AddNewProperty('visible','_visible');
AddNewProperty('currentFrame','_currentframe',createjs.MovieClip.prototype);

AddNewProperty(undefined,"_width", undefined,
	function(){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds) return bounds.width;
			else{
				if(this.currentFrame == 0 && this.nominalBounds)
					return this.nominalBounds.width;
			}
			return undefined;
		}
	},
	function(value){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds){
				this.setTransform(bounds.x,bounds.y,value/bounds.width,1);
			}
		}
	}

);

AddNewProperty(undefined,"_height", undefined,
	function(){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds) return bounds.height;
			else{
				if(this.currentFrame == 0 && this.nominalBounds)
					return this.nominalBounds.height;
			}
			return undefined;
		}
	},
	function(value){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds){
				this.setTransform(bounds.x,bounds.y,1,value/bounds.height);
			}
		}
	}
);

function Test(){

}
<commit_msg>Update AS2_Library.js<commit_after>/* Copyright (c) 2016 https://github.com/askeet/.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/

var _root;
function InitAS2() {
	_root = exportRoot;
	SetDefaultNames();
	Test();
}

var isStop = false;
function SetFPS(value){

	if(value ===0){
	    if(!isStop){
			createjs.Ticker.removeEventListener("tick", stage);
			isStop = true;
			UpdatePaint();
		}
	}
	else{
		createjs.Ticker.setFPS(value);
	    if(isStop){
			createjs.Ticker.addEventListener("tick", stage);
			isStop = false;
		}
	}
}

function UpdatePaint(){
   if(isStop){
        var event1 = new Object();
	event1.paused = false;
	handleTick(event1);
   }
   stage.update();
}

// Library AS2

function SetDefaultNames() {
	var i, key;
	var clip = exportRoot; // movieclip content to be processed
	var clipch = clip.children; // movieclip's children
	// iterate over every property name in the clip
	for (key in clip) {
		// is this a CreateJS container object?
		if (clip[key] instanceof createjs.Container) {
			// scan the clip's list of children
			for (i = 0; i < clipch.length; i++) {
				// are they both pointing to the same object?
				if (clip[key] === clipch[i]) {
					// assign key value to "name" property
					clip[key].name = key;
					break;
				}
			}
		}
	}
}

function fscommand(arg,command){
	if(window.external!=null &&  typeof window.external.EventForFSCommand!=='undefined')
		window.external.EventForFSCommand(arg,command);
}

var arrChildByName = [];
function eval(Value) {
	var object = GetValue(Value);
	if(object) arrChildByName[Value] = object;
	return object;
}

function SetValue( nameProperty ,  value , isGotoAndStop ){
        nameProperty = nameProperty.replace( "_root.",'');
	arr = nameProperty.split(".");
	var object = null;

	for (var i = 0; i < arr.length-1; i++) {
	    if(i===0)
		object = _root[arr[0]];
	    else
		if(object)
			object = object[arr[i]];
		}
	if(arr.length > 1 && object ){
		if(!isGotoAndStop){
			object[ arr[arr.length-1]] = value;
		}else{
			object[ arr[arr.length-1]].gotoAndStop(value);
		}
	}
	else{
		if(arr.length === 1){
		    if(!isGotoAndStop){
				_root[arr[0]] = value;
		    }else{
				_root[arr[0]].gotoAndStop(value);
		    }
		}
	}
}

function GetValue( nameProperty){
    nameProperty = nameProperty.replace( "_root.",'');
    arr = nameProperty.split(".");
	var object = null;

	for (var i = 0; i < arr.length; i++) {
	    if(i===0){
		object = _root[arr[0]];
	    	if(!object){
			object = _root.getChildByName(arr[0]);
			if(object){
				_root[arr[0]] = object;
				//object[arr[0]] = object;
			}else{
				break;
			}
		}
	      }
    	      else
		if(object){
			var obj = object[arr[i]];
			if(!obj){ // not find
				obj = object.getChildByName(arr[i]);
			}

			if(obj){
				object[arr[i]] = obj;
				object = obj;
			}else{
				object = undefined;
				break;
			}
		}
	}

	return (arr.length > 0 && object )? object : undefined;
}

var removeObject = createjs.DisplayObject.prototype.removeObject = function () {
	var path = (this.parent) ? this.parent : this;
	var fullPath = this.GetAbsolutePath();

	findBeginStr(arrChildByName, fullPath, function (elem) {
		RemoveShape(arrChildByName[elem]);
		delete arrChildByName[elem];
	});

	RemoveShape(this);
	var ret = path.removeChild(this);
	path[this.name] = undefined;
	return ret;
}

var findBeginStr = function (array, value, callback, fullConsilience) {
	var findElem = false;

	if (value != "") {
		for (arr in array) {
			if (
				(!fullConsilience && String(arr).indexOf(value) === 0) ||
			    (fullConsilience && String(arr)===value)
			) {
				findElem = true;
				//alert("find "+String(arr) + " "+value)
				if (callback(arr)) {
					break;
				}
			}
		}
	}
	return findElem;
}

var GetAbsolutePath = createjs.DisplayObject.prototype.GetAbsolutePath = function () {
	var Name = (this.name) ? this.name : "";
	if (Name) {
		//if(yyyy) alert(this.parent.name);
		var Parent = this.parent;
		while (Parent && Parent.name) {
			Name = Parent.name + "." + Name;
			Parent = Parent.parent;
		}
	}
	return Name;
}

var createEmptyMovieClip = createjs.DisplayObject.prototype.createEmptyMovieClip = function (NameMovieClip, depth) {
	var FindName = this.GetAbsolutePath();
	FindName = (FindName != "") ? FindName + "." + NameMovieClip : NameMovieClip;
	var myMC = new createjs.MovieClip();
	myMC.name = NameMovieClip;
	if (!findBeginStr(arrChildByName, FindName, function (elem) {
			return true;
		})) {
		(!depth && depth != 0) ? this.addChild(myMC) : this.addChildAt(myMC, depth);
		eval(FindName);
		arrChildByName[FindName] = myMC;

	}else{
		myMC = eval(FindName);
	}
	return myMC;
}
//

var createTextField = createjs.DisplayObject.prototype.createTextField = function (NameTextField, depth, X, Y, Font, MaxWidth, MaxHeight) {

	var FindName = this.GetAbsolutePath();
	//alert(FindName + " " +  NameTextField);
	FindName = (FindName != "") ? FindName + "." + NameTextField : NameTextField;

	var tf = new createjs.Text('', (Font) ? Font : 'Arial 12px');
	tf.name = NameTextField;
	tf.x = X;
	tf.y = Y;
	tf.maxHeigth = MaxHeight;
	tf.maxWidth = MaxWidth;
	if (!findBeginStr(arrChildByName, FindName, function (elem) {
			return true;
		}), true) {
		(!depth && depth != 0) ? this.addChild(tf) : this.addChildAt(tf, depth);
		eval(FindName);
		arrChildByName[FindName] = tf;
	}else{
		tf = eval(FindName);
	}
	return tf;
}

var attachMovie = createjs.DisplayObject.prototype.attachMovie = function (idName, newName, depth, initObject) {
	var FindName = this.GetAbsolutePath();
	FindName = (FindName != "") ? FindName + "." + newName : newName;

	var classDefintion = (idName)?lib[idName]:this.constructor;
	if(!classDefintion) classDefintion = this.constructor;
	var instance = new classDefintion();
	instance.idName = idName;
	instance.name = newName;
	if (initObject)
		for (var key in initObject)
			instance[key] = initObject[key];

	if (!findBeginStr(arrChildByName, FindName, function (elem) {
			return true;
		})) {
		(!depth && depth != 0) ? this.addChild(instance) : this.addChildAt(instance, depth);
		eval(FindName);
		arrChildByName[FindName] = instance;
	}else{
		instance = eval(FindName);
	}
	return instance;
}

var duplicateMovieClip = createjs.DisplayObject.prototype.duplicateMovieClip = function (newname, depth ,initObject){
	var path = (this.parent) ? this.parent : this;
	var cm;
	if(this.idName){
		cm = path.attachMovie(this.idName,newname,depth,initObject);
		if(this.paused);
			cm.gotoAndStop(this.currentFrame);
		cm.x = this.x;
		cm.y = this.y;
	}
	else
		cm = path.createEmptyMovieClip(newname, depth ,initObject);
	var Shape =  this.UserShape;
    if(Shape){
		cm.UserShape = Shape.clone(true);
		cm.addChild(cm.UserShape);
	}
	return cm;
}

function trace(Value){
	console.log(Value);
}

function GetShape(Value){
	if(!Value.UserShape){
		Value.UserShape = new createjs.Shape();
		Value.addChild(Value.UserShape);
	}
	return Value.UserShape;
}

function RemoveShape(Value){
	if(Value.UserShape){
		Value.removeChild(Value.UserShape);
		Value.UserShape = undefined;
	}
}

//my_mc.lineTo(x:Number, y:Number) : Void
var lineTo = createjs.DisplayObject.prototype.lineTo = function (x,y){
	GetShape(this).graphics.lineTo(x,y);
}
//my_mc.moveTo(x:Number, y:Number) : Void
var moveTo = createjs.DisplayObject.prototype.moveTo = function (x,y){
	GetShape(this).graphics.moveTo(x,y);
}

//my_mc.lineStyle([thickness:Number[, rgb:Number[, alpha:Number]]]) : Void
var lineStyle = createjs.DisplayObject.prototype.lineStyle = function (thickness,rgb,alpha){
	var Shape = GetShape(this);

	if(thickness!=undefined){
		Shape.graphics.setStrokeStyle(thickness);
	}
	if(rgb!=undefined){
		Shape.graphics.endStroke();
		var color = createjs.Graphics.getRGB(rgb, alpha);
		Shape.graphics.beginStroke(color);
	}
}

//my_mc.beginFill([rgb:Number[, alpha:Number]]) : Void
var beginFill = createjs.DisplayObject.prototype.beginFill = function (rgb,alpha){
	var r = (rgb & 0xFF0000) >> 16;
	var g = (rgb & 0x00FF00) >> 8;
	var b = (rgb & 0x0000FF) >> 0;
	var color = (alpha)? 'rgba(' +r+','+g+','+b+','+alpha+')': 'rgb(' +r+','+g+','+b+')';
	GetShape(this).graphics.beginFill(color);
}
//endFill ()
var endFill = createjs.DisplayObject.prototype.endFill = function (rgb,alpha){
	GetShape(this).graphics.endFill();
}
var clear = createjs.DisplayObject.prototype.clear = function (){
	GetShape(this).graphics.clear();
}
// Property
function  AddNewProperty(CurNameProperty,NewNameProperty, Class, funcGet,funcSet ){
	if(Class == undefined) Class = createjs.DisplayObject.prototype;
	Object.defineProperty(Class, NewNameProperty, {
		get: (!funcGet)? function(){ return (CurNameProperty)? this[CurNameProperty] : undefined; }      : funcGet,
		set: (!funcSet)? function (value){ if(CurNameProperty)this[CurNameProperty] = value; }: funcSet,
		enumerable: true,
		configurable: true
    });
}

var addProperty = createjs.DisplayObject.prototype.addProperty = function (NameProperty, GetStatus, SetStatus){
	AddNewProperty(undefined,NameProperty,this,GetStatus,SetStatus);
	/*Object.defineProperty(this, NameProperty, {
		get: GetStatus,
		set: SetStatus,
		enumerable: true,
		configurable: true
	});	*/
}

AddNewProperty('alpha','_alpha');
AddNewProperty('x','_x');
AddNewProperty('y','_y');
AddNewProperty('rotation','_rotation');
AddNewProperty('xscale','_xscale');
AddNewProperty('yscale','_yscale');
AddNewProperty('parrent','_parrent');
AddNewProperty('visible','_visible');
AddNewProperty('currentFrame','_currentframe',createjs.MovieClip.prototype);

AddNewProperty(undefined,"_width", undefined,
	function(){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds) return bounds.width;
			else{
				if(this.currentFrame == 0 && this.nominalBounds)
					return this.nominalBounds.width;
			}
			return undefined;
		}
	},
	function(value){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds){
				this.setTransform(bounds.x,bounds.y,value/bounds.width,1);
			}
		}
	}

);

AddNewProperty(undefined,"_height", undefined,
	function(){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds) return bounds.height;
			else{
				if(this.currentFrame == 0 && this.nominalBounds)
					return this.nominalBounds.height;
			}
			return undefined;
		}
	},
	function(value){
		if(this.getTransformedBounds){
			var bounds = this.getTransformedBounds();
			if(bounds){
				this.setTransform(bounds.x,bounds.y,1,value/bounds.height);
			}
		}
	}
);

function Test(){

}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Copyright (C) 2015-2016 Quildreen Motta.
// Licensed under the MIT licence.
//
// See LICENCE for licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

const assertType = require('folktale/helpers/assertType');
const assertFunction = require('folktale/helpers/assertFunction');
const { data, show, setoid, serialize } = require('folktale/core/adt');
const provideAliases = require('folktale/helpers/provide-fantasy-land-aliases');

/*~
 * ---
 * category: Representing Failures
 * authors:
 *   - "@boris-marinov"
 *   - Quildreen Motta
 */
const Maybe = data('folktale:Data.Maybe', {
  /*~
   * ---
   * category: Constructing
   * type: |
   *   forall a: () => Maybe a
   */
  Nothing() {
  },

  /*~
   * ---
   * category: Constructing
   * type: |
   *   forall a: (a) => Maybe a
   */
  Just(value) {
    return { value };
  }
}).derive(setoid, show, serialize);

const { Nothing, Just } = Maybe;
const assertMaybe = assertType(Maybe);

// -- Functor ----------------------------------------------------------
/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe a).((a) => b) => Maybe b
 */
Nothing.prototype.map = function(transformation) {
  assertFunction('Maybe.Nothing#map', transformation);
  return this;
};

/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe a).((a) => b) => Maybe b
 */
Just.prototype.map = function(transformation) {
  assertFunction('Maybe.Nothing#map',  transformation);
  return Just(transformation(this.value));
};

// -- Apply ------------------------------------------------------------
/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe (a) => b).(Maybe a) => Maybe b
 */
Nothing.prototype.apply = function(aMaybe) {
  assertMaybe('Maybe.Nothing#apply', aMaybe);
  return this;
};

/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe (a) => b).(Maybe a) => Maybe b
 */
Just.prototype.apply = function(aMaybe) {
  assertMaybe('Maybe.Just#apply', aMaybe);
  return aMaybe.map(this.value);
};

// -- Applicative ------------------------------------------------------
/*~
 * ---
 * category: Constructing
 * type: |
 *   forall a: (a) => Maybe a
 */
Maybe.of = function(value) {
  return Just(value);
};

// -- Chain ------------------------------------------------------------
/*~
 * ---
 * category: Transforming Maybes
 * type: |
 *   forall a: (Maybe a).((a) => Maybe b) => Maybe b
 */
Nothing.prototype.chain = function(transformation) {
  assertFunction('Maybe.Nothing#chain', transformation);
  return this;
};

/*~
 * ---
 * category: Transforming Maybes
 * type: |
 *   forall a: (Maybe a).((a) => Maybe b) => Maybe b
 */
Just.prototype.chain = function(transformation) {
  assertFunction('Maybe.Just#chain', transformation);
  return transformation(this.value);
};

// -- Extracting values and recovering ---------------------------------

// NOTE:
// `get` is similar to Comonad's `extract`. The reason we don't implement
// Comonad here is that `get` is partial, and not defined for Nothing
// values.

Nothing.prototype.get = function() {
  throw new TypeError(`Can't extract the value of a Nothing.

Since Nothing holds no values, it's not possible to extract one from them.
You might consider switching from Maybe#get to Maybe#getOrElse, or some other method
that is not partial.
  `);
};

Just.prototype.get = function() {
  return this.value;
};

Nothing.prototype.getOrElse = function(default_) {
  return default_;
};

Just.prototype.getOrElse = function(_default_) {
  return this.value;
};

Nothing.prototype.orElse = function(handler) {
  return handler();
};

Just.prototype.orElse = function() {
  return this;
};

// -- Conversions -------------------------------------------------
Maybe.toEither = function(...args) {
  return require('folktale/data/conversions/maybe-to-either')(this, ...args);
};

Maybe.toValidation = function(...args) {
  return require('folktale/data/conversions/maybe-to-validation')(this, ...args);
};

// -- Exports ----------------------------------------------------------
provideAliases(Just.prototype);
provideAliases(Nothing.prototype);
provideAliases(Maybe);

module.exports = Maybe;
<commit_msg>(!!) deprecate .get in favour of .unsafeGet (#42)<commit_after>//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Copyright (C) 2015-2016 Quildreen Motta.
// Licensed under the MIT licence.
//
// See LICENCE for licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

const assertType = require('folktale/helpers/assertType');
const assertFunction = require('folktale/helpers/assertFunction');
const { data, show, setoid, serialize } = require('folktale/core/adt');
const provideAliases = require('folktale/helpers/provide-fantasy-land-aliases');
const warnDeprecation = require('folktale/helpers/warnDeprecation');

/*~
 * ---
 * category: Representing Failures
 * authors:
 *   - "@boris-marinov"
 *   - Quildreen Motta
 */
const Maybe = data('folktale:Data.Maybe', {
  /*~
   * ---
   * category: Constructing
   * type: |
   *   forall a: () => Maybe a
   */
  Nothing() {
  },

  /*~
   * ---
   * category: Constructing
   * type: |
   *   forall a: (a) => Maybe a
   */
  Just(value) {
    return { value };
  }
}).derive(setoid, show, serialize);

const { Nothing, Just } = Maybe;
const assertMaybe = assertType(Maybe);

// -- Functor ----------------------------------------------------------
/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe a).((a) => b) => Maybe b
 */
Nothing.prototype.map = function(transformation) {
  assertFunction('Maybe.Nothing#map', transformation);
  return this;
};

/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe a).((a) => b) => Maybe b
 */
Just.prototype.map = function(transformation) {
  assertFunction('Maybe.Nothing#map',  transformation);
  return Just(transformation(this.value));
};

// -- Apply ------------------------------------------------------------
/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe (a) => b).(Maybe a) => Maybe b
 */
Nothing.prototype.apply = function(aMaybe) {
  assertMaybe('Maybe.Nothing#apply', aMaybe);
  return this;
};

/*~
 * ---
 * category: Transforming Maybe values
 * type: |
 *   forall a, b: (Maybe (a) => b).(Maybe a) => Maybe b
 */
Just.prototype.apply = function(aMaybe) {
  assertMaybe('Maybe.Just#apply', aMaybe);
  return aMaybe.map(this.value);
};

// -- Applicative ------------------------------------------------------
/*~
 * ---
 * category: Constructing
 * type: |
 *   forall a: (a) => Maybe a
 */
Maybe.of = function(value) {
  return Just(value);
};

// -- Chain ------------------------------------------------------------
/*~
 * ---
 * category: Transforming Maybes
 * type: |
 *   forall a: (Maybe a).((a) => Maybe b) => Maybe b
 */
Nothing.prototype.chain = function(transformation) {
  assertFunction('Maybe.Nothing#chain', transformation);
  return this;
};

/*~
 * ---
 * category: Transforming Maybes
 * type: |
 *   forall a: (Maybe a).((a) => Maybe b) => Maybe b
 */
Just.prototype.chain = function(transformation) {
  assertFunction('Maybe.Just#chain', transformation);
  return transformation(this.value);
};

// -- Extracting values and recovering ---------------------------------

/*~
 * ---
 * category: Extracting values
 * stability: deprecated
 * type: |
 *   forall a: (Maybe a).() => a :: (throws TypeError)
 */
Nothing.prototype.get = function() {
  warnDeprecation('`.get()` is deprecated, and has been renamed to `.unsafeGet()`.');
  return this.unsafeGet();
};

/*~
 * ---
 * category: Extracting values
 * stability: deprecated
 * type: |
 *   forall a: (Maybe a).() => a :: (throws TypeError)
 */
Just.prototype.get = function() {
  warnDeprecation('`.get()` is deprecated, and has been renamed to `.unsafeGet()`.');
  return this.unsafeGet();
};

/*~
 * ---
 * category: Extracting values
 * type: |
 *   forall a: (Maybe a).() => a :: (throws TypeError)
 */
Nothing.prototype.unsafeGet = function() {
  throw new TypeError(`Can't extract the value of a Nothing.

Since Nothing holds no values, it's not possible to extract one from them.
You might consider switching from Maybe#get to Maybe#getOrElse, or some other method
that is not partial.
  `);
};

/*~
 * ---
 * category: Extracting values
 * type: |
 *   forall a: (Maybe a).() => a :: (throws TypeError)
 */
Just.prototype.unsafeGet = function() {
  return this.value;
}

Nothing.prototype.getOrElse = function(default_) {
  return default_;
};

Just.prototype.getOrElse = function(_default_) {
  return this.value;
};

Nothing.prototype.orElse = function(handler) {
  return handler();
};

Just.prototype.orElse = function() {
  return this;
};

// -- Conversions -------------------------------------------------
Maybe.toEither = function(...args) {
  return require('folktale/data/conversions/maybe-to-either')(this, ...args);
};

Maybe.toValidation = function(...args) {
  return require('folktale/data/conversions/maybe-to-validation')(this, ...args);
};

// -- Exports ----------------------------------------------------------
provideAliases(Just.prototype);
provideAliases(Nothing.prototype);
provideAliases(Maybe);

module.exports = Maybe;
<|endoftext|>


<commit_before>var express = require('express'),
	compress = require('compression'),
	serveStatic = require('serve-static'),
	app = express(),
	port = process.env.PORT || 8080;

app.use(compress());

// rewrite
app.use(function(req, res, next) {
	if (!req.url.match(/(^\/?(static|docs)\/|\.[a-z]+$)(\?.*)?/g)) {
		req.url = '/';
	}
	next();
});

app.use(serveStatic('demo/'));

app.use('/docs', serveStatic('docs/'));

app.listen(port, function() {
	console.log('Server listening on localhost:'+port);
});
<commit_msg>Serve up dist/ from paasive & friends<commit_after>var express = require('express'),
	compress = require('compression'),
	serveStatic = require('serve-static'),
	app = express(),
	port = process.env.PORT || 8080;

app.use(compress());

// rewrite
app.use(function(req, res, next) {
	if (!req.url.match(/(^\/?(static|docs)\/|\.[a-z]+$)(\?.*)?/g)) {
		req.url = '/';
	}
	next();
});

app.use(serveStatic('demo/'));

app.use('/docs', serveStatic('docs/'));

app.use('/dist', serveStatic('dist/'));

app.listen(port, function() {
	console.log('Server listening on localhost:'+port);
});
<|endoftext|>


<commit_before>/// <reference path="common.js"/>
/// <reference path="codegen_common.js"/>
function codegen_php_tran(prog) {
	/// <param name="prog" type="Array">AST</param>
	/// <returns type="String" />
	var s_indent = '';

	function indent() {
		//s_indent += '  ';
	}
	function outdent() {
		//s_indent = s_indent.substr(0, s_indent.length - 2);
	}

	function emit(t) {
		s += t;
	}
	function compileEval(stmt) {
		var t = walkExpr(stmt[1]);
		if (stmt[2]) {
			t = 'crox_encode(' + t + ')';
		} else {
			t = 'crox_ToString(' + t + ')';
		}
		emit('echo ' + t + ';');
	}
	function compileContent(stmt) {
		var t = stmt[1];
		if (/<\?(?:php)?|\?>/.test(t))
			emit('echo ' + phpQuote(stmt[1]) + ';');
		else {
			emit('?>' + t + '<?php ');
		}
	}
	function compileIf(stmt) {
		emit('if(' + walkExpr(stmt[1]) + '){');
		indent();
		compileStmts(stmt[2]);
		outdent();
		emit('}');
		if (stmt[3]) {
			emit('else{');
			indent();
			compileStmts(stmt[3]);
			outdent();
			emit('}');
		}
	}
	function compileEach(stmt) {
		var idKey = stmt[3] ? '$crox_' + stmt[3] + '=>' : '';
		emit('foreach(' + walkExpr(stmt[1]) + ' as ' + idKey + '$crox_' + stmt[4] + ')');
		emit('{');
		indent();
		compileStmts(stmt[2]);
		outdent();
		emit('}');
	}
	function compileSet(stmt) {
		emit('$crox_' + stmt[1] + ' = ' + walkExpr(stmt[2]) + ';');
	}
	function compileStmt(a) {
		switch (a[0]) {
			case 'if': compileIf(a); break;
			case 'each': compileEach(a); break;
			case 'set': compileSet(a); break;
			case 'eval': compileEval(a); break;
			case 'text': compileContent(a); break;
			case 'inc':
				emit("include '" + changeExt(a[1], 'php') + "';");
				break;
			default: throw Error('unknown stmt: ' + a[0]);
		}
	}
	function compileStmts(a) {
		for (var i = 0; i < a.length; ++i)
			compileStmt(a[i]);
	}

	function exprToStr(x, check) {
		var t = walkExpr(x);
		if (check && !check(x[0])) t = '(' + t + ')';
		return t;
	}
	function walkExpr(x) {
		switch (x[0]) {
			case 'id':
				return '$crox_' + x[1];
			case 'lit':
				if (typeof x[1] == 'string')
					return phpQuote(x[1]);
				return String(x[1]);
			case '.':
				return exprToStr(x[1], isMember) + "->" + x[2];
			case '[]':
				return exprToStr(x[1], isMember) + '[' + walkExpr(x[2]) + ']';
			case '!':
				return '!crox_ToBoolean(' + exprToStr(x[1], isUnary) + ')';
			case 'u-':
				return '- ' + exprToStr(x[1], isUnary);
			case '*': case '/': case '%':
				return exprToStr(x[1], isMul) + x[0] + exprToStr(x[2], isUnary);
			case '+':
				return 'crox_plus(' + exprToStr(x[1], null) + ', ' + exprToStr(x[2], null) + ')';
			case '-':
				return exprToStr(x[1], isAdd) + '- ' + exprToStr(x[2], isMul);
			case '<': case '>': case '<=': case '>=':
				return exprToStr(x[1], isRel) + x[0] + exprToStr(x[2], isAdd);
			case 'eq': case 'ne':
				var op = x[0] == 'eq' ? '===' : '!==';
				return exprToStr(x[1], isEquality) + op + exprToStr(x[2], isRel);
			case '&&':
				return 'crox_logical_and(' + exprToStr(x[1], null) + ', ' + exprToStr(x[2], null) + ')';
			case '||':
				return 'crox_logical_or(' + exprToStr(x[1], null) + ', ' + exprToStr(x[2], null) + ')';
			default:
				throw Error("unknown expr: " + x[0]);
		}
	}

	var s = "";
	compileStmts(prog[1]);
	if (s.slice(0, 2) == '?>')
		s = s.slice(2);
	else s = '<?php ' + s;
	if (s.slice(-6) == '<?php ')
		s = s.slice(0, -6);
	else s += '?>';
	return s;
}
<commit_msg>去掉多余的 indent、outdent<commit_after>/// <reference path="common.js"/>
/// <reference path="codegen_common.js"/>
function codegen_php_tran(prog) {
	/// <param name="prog" type="Array">AST</param>
	/// <returns type="String" />

	function emit(t) {
		s += t;
	}
	function compileEval(stmt) {
		var t = walkExpr(stmt[1]);
		if (stmt[2]) {
			t = 'crox_encode(' + t + ')';
		} else {
			t = 'crox_ToString(' + t + ')';
		}
		emit('echo ' + t + ';');
	}
	function compileContent(stmt) {
		var t = stmt[1];
		if (/<\?(?:php)?|\?>/.test(t))
			emit('echo ' + phpQuote(stmt[1]) + ';');
		else {
			emit('?>' + t + '<?php ');
		}
	}
	function compileIf(stmt) {
		emit('if(' + walkExpr(stmt[1]) + '){');
		compileStmts(stmt[2]);
		emit('}');
		if (stmt[3]) {
			emit('else{');
			compileStmts(stmt[3]);
			emit('}');
		}
	}
	function compileEach(stmt) {
		var idKey = stmt[3] ? '$crox_' + stmt[3] + '=>' : '';
		emit('foreach(' + walkExpr(stmt[1]) + ' as ' + idKey + '$crox_' + stmt[4] + ')');
		emit('{');
		compileStmts(stmt[2]);
		emit('}');
	}
	function compileSet(stmt) {
		emit('$crox_' + stmt[1] + ' = ' + walkExpr(stmt[2]) + ';');
	}
	function compileStmt(a) {
		switch (a[0]) {
			case 'if': compileIf(a); break;
			case 'each': compileEach(a); break;
			case 'set': compileSet(a); break;
			case 'eval': compileEval(a); break;
			case 'text': compileContent(a); break;
			case 'inc':
				emit("include '" + changeExt(a[1], 'php') + "';");
				break;
			default: throw Error('unknown stmt: ' + a[0]);
		}
	}
	function compileStmts(a) {
		for (var i = 0; i < a.length; ++i)
			compileStmt(a[i]);
	}

	function exprToStr(x, check) {
		var t = walkExpr(x);
		if (check && !check(x[0])) t = '(' + t + ')';
		return t;
	}
	function walkExpr(x) {
		switch (x[0]) {
			case 'id':
				return '$crox_' + x[1];
			case 'lit':
				if (typeof x[1] == 'string')
					return phpQuote(x[1]);
				return String(x[1]);
			case '.':
				return exprToStr(x[1], isMember) + "->" + x[2];
			case '[]':
				return exprToStr(x[1], isMember) + '[' + walkExpr(x[2]) + ']';
			case '!':
				return '!crox_ToBoolean(' + exprToStr(x[1], isUnary) + ')';
			case 'u-':
				return '- ' + exprToStr(x[1], isUnary);
			case '*': case '/': case '%':
				return exprToStr(x[1], isMul) + x[0] + exprToStr(x[2], isUnary);
			case '+':
				return 'crox_plus(' + exprToStr(x[1], null) + ', ' + exprToStr(x[2], null) + ')';
			case '-':
				return exprToStr(x[1], isAdd) + '- ' + exprToStr(x[2], isMul);
			case '<': case '>': case '<=': case '>=':
				return exprToStr(x[1], isRel) + x[0] + exprToStr(x[2], isAdd);
			case 'eq': case 'ne':
				var op = x[0] == 'eq' ? '===' : '!==';
				return exprToStr(x[1], isEquality) + op + exprToStr(x[2], isRel);
			case '&&':
				return 'crox_logical_and(' + exprToStr(x[1], null) + ', ' + exprToStr(x[2], null) + ')';
			case '||':
				return 'crox_logical_or(' + exprToStr(x[1], null) + ', ' + exprToStr(x[2], null) + ')';
			default:
				throw Error("unknown expr: " + x[0]);
		}
	}

	var s = "";
	compileStmts(prog[1]);
	if (s.slice(0, 2) == '?>')
		s = s.slice(2);
	else s = '<?php ' + s;
	if (s.slice(-6) == '<?php ')
		s = s.slice(0, -6);
	else s += '?>';
	return s;
}
<|endoftext|>


<commit_before>const TAU = 2 * Math.PI;
// This many arbitrary units of time is one perfect loop.
const AUTS_PER_LOOP = 5544;
const SECONDS_PER_LOOP = 10;
const LARGEST_ORBIT_RADIUS = 386;

// The number of revolutions a planet makes per perfect loop starts at this number
// and increases by 1 for each orbit closer to the center.
const OUTERMOST_REVOLUTIONS_PER_LOOP = 2;
// Don't draw any orbits smaller than this one.
const INNERMOST_ORBIT_INDEX = 3;

const orbitCount = 12;
let startAuts = 0;
let playing = false;

const getX = function(index, auts) {
    const [r, theta] = getPolarCoordinates(index, auts);
    return r * Math.sin(theta);
};

const getY = function(index, auts) {
    const [r, theta] = getPolarCoordinates(index, auts);
    return r * Math.cos(theta);
};

const getPolarCoordinates = function(index, auts) {
    const radius = orbitRadius(index);
    const speed = orbitCount + INNERMOST_ORBIT_INDEX + OUTERMOST_REVOLUTIONS_PER_LOOP - index;
    const revolutions = auts / AUTS_PER_LOOP * speed;
    return [radius, revolutions * TAU];
};

const orbitRadius = function(index) {
    return index / (orbitCount + INNERMOST_ORBIT_INDEX) * LARGEST_ORBIT_RADIUS;
};

const togglePlay = function(value) {
    if (value === undefined) {
        value = !playing;
    }
    if (value) {
        playing = true;
        d3.timer(tick);
    } else {
        startAuts = parseInt(timeSlider.property("value"), 10);
        playing = false;
    }
    playButton.text(playing ? "❚❚ Pause" : "▶ Play");
};

const seek = function() {
    togglePlay(false);
    draw(startAuts);
};

const parse = function() {
    let inputValue = parseInt(timeInput.property("value"), 10);
    if (isNaN(inputValue) || inputValue < 0) {
        inputValue = 0;
    } else if (inputValue > AUTS_PER_LOOP) {
        inputValue = AUTS_PER_LOOP - 1;
    }
    timeInput.property("value", inputValue);
    if (parseInt(timeSlider.property("value"), 10) != inputValue) {
        timeSlider.property("value", inputValue);
        seek();
    }
};

const draw = function(auts) {
    planets
        .attr("cx", o => { return getX(o, auts) })
        .attr("cy", o => { return getY(o, auts) });
    timeSlider.property("value", Math.floor(auts));
    timeInput.property("value", Math.floor(auts));
};

const tick = function(time) {
    if (playing) {
        auts = (startAuts + (time / 1000) * (SECONDS_PER_LOOP / AUTS_PER_LOOP)) % AUTS_PER_LOOP;
        draw(auts);
    }
    return !playing;
};

const surface = d3.select("svg");

const orbits = surface
    .selectAll(".orbit")
    .data(_.range(INNERMOST_ORBIT_INDEX, orbitCount + INNERMOST_ORBIT_INDEX))
    .enter().append("circle")
        .classed("orbit", true)
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", orbitRadius)
        .attr("stroke", "#88f")
        .attr("fill-opacity", 0);

const planets = surface
    .selectAll(".planet")
    .data(_.range(INNERMOST_ORBIT_INDEX, orbitCount + INNERMOST_ORBIT_INDEX))
    .enter().append("circle")
        .classed("planet", true)
        .attr("cx", getX)
        .attr("cy", getY)
        .attr("r", 8)
        .attr("stroke", "black")
        .attr("fill", "purple");

const playButton = d3.select(".play-button")
    .on("click", togglePlay);

const timeSlider = d3.select(".time-slider")
    .attr("min", 0)
    .attr("max", AUTS_PER_LOOP - 1)
    .on("input", seek);

const timeInput = d3.select(".time-input")
    .on("input", parse);

draw(0);
togglePlay(false);
<commit_msg>Change indices to start at 0<commit_after>const TAU = 2 * Math.PI;
// This many arbitrary units of time is one perfect loop.
const AUTS_PER_LOOP = 5544;
const SECONDS_PER_LOOP = 10;
const LARGEST_ORBIT_RADIUS = 386;

// The number of revolutions a planet makes per perfect loop starts at this number
// and increases by 1 for each orbit closer to the center.
const OUTERMOST_REVOLUTIONS_PER_LOOP = 2;
// Don't draw any orbits smaller than this one.
const INNERMOST_ORBIT_INDEX = 3;

const orbitCount = 12;
let startAuts = 0;
let playing = false;

const getX = function(index, auts) {
    const [r, theta] = getPolarCoordinates(index, auts);
    return r * Math.sin(theta);
};

const getY = function(index, auts) {
    const [r, theta] = getPolarCoordinates(index, auts);
    return r * Math.cos(theta);
};

const getPolarCoordinates = function(index, auts) {
    const radius = orbitRadius(index);
    const speed = orbitCount + OUTERMOST_REVOLUTIONS_PER_LOOP - index;
    const revolutions = auts / AUTS_PER_LOOP * speed;
    return [radius, revolutions * TAU];
};

const orbitRadius = function(index) {
    return (index + INNERMOST_ORBIT_INDEX) / (orbitCount + INNERMOST_ORBIT_INDEX) * LARGEST_ORBIT_RADIUS;
};

const togglePlay = function(value) {
    if (value === undefined) {
        value = !playing;
    }
    if (value) {
        playing = true;
        d3.timer(tick);
    } else {
        startAuts = parseInt(timeSlider.property("value"), 10);
        playing = false;
    }
    playButton.text(playing ? "❚❚ Pause" : "▶ Play");
};

const seek = function() {
    togglePlay(false);
    draw(startAuts);
};

const parse = function() {
    let inputValue = parseInt(timeInput.property("value"), 10);
    if (isNaN(inputValue) || inputValue < 0) {
        inputValue = 0;
    } else if (inputValue > AUTS_PER_LOOP) {
        inputValue = AUTS_PER_LOOP - 1;
    }
    timeInput.property("value", inputValue);
    if (parseInt(timeSlider.property("value"), 10) != inputValue) {
        timeSlider.property("value", inputValue);
        seek();
    }
};

const draw = function(auts) {
    planets
        .attr("cx", o => { return getX(o, auts) })
        .attr("cy", o => { return getY(o, auts) });
    timeSlider.property("value", Math.floor(auts));
    timeInput.property("value", Math.floor(auts));
};

const tick = function(time) {
    if (playing) {
        auts = (startAuts + (time / 1000) * (SECONDS_PER_LOOP / AUTS_PER_LOOP)) % AUTS_PER_LOOP;
        draw(auts);
    }
    return !playing;
};

const surface = d3.select("svg");

const orbits = surface
    .selectAll(".orbit")
    .data(_.range(0, orbitCount))
    .enter().append("circle")
        .classed("orbit", true)
        .attr("cx", 0)
        .attr("cy", 0)
        .attr("r", orbitRadius)
        .attr("stroke", "#88f")
        .attr("fill-opacity", 0);

const planets = surface
    .selectAll(".planet")
    .data(_.range(0, orbitCount))
    .enter().append("circle")
        .classed("planet", true)
        .attr("cx", getX)
        .attr("cy", getY)
        .attr("r", 8)
        .attr("stroke", "black")
        .attr("fill", "purple");

const playButton = d3.select(".play-button")
    .on("click", togglePlay);

const timeSlider = d3.select(".time-slider")
    .attr("min", 0)
    .attr("max", AUTS_PER_LOOP - 1)
    .on("input", seek);

const timeInput = d3.select(".time-input")
    .on("input", parse);

draw(0);
togglePlay(false);
<|endoftext|>


<commit_before>var channel = null;

$(function() {
  if (window.opener || window.parent) {
    var windowChannel = window.opener ? window.opener : window.parent;
    channel = Channel.build({window: windowChannel, origin: '*', scope: 'test'});
  }
});

function conceptDisplay() {
  var hash = window.location.hash.substr(1);
  if(!hash) { return; }

  var hashSplit = hash.split('-');
  if(hashSplit.length > 1) {
    var lang = hashSplit.shift();
    var target = hashSplit.join('-');
  } else {
    var lang = null;
    var target = hash;
  }

  var targetDiv = $('div[data-id='+target+']');

  if(!targetDiv.length) { return; }

  $('body > div').hide();
  targetDiv.show();
  if(lang) {
    var allLangDivs = targetDiv.find('[data-lang]');
    var langDivs = allLangDivs.filter(function(i, e) {
      var langs = e.getAttribute('data-lang').split(' ');
      return langs.indexOf(lang) != -1;
      });
    if(langDivs.length) {
      allLangDivs.hide();
      langDivs.show();
    } else {
      allLangDivs.show();
    }
  }

  if (channel) {
    var pythonCodes = $('.pythonCode');
    pythonCodes.each(function (index, element) {
      const jQueryElement = $(element);
      if (!jQueryElement.parent().find('.pythonCode-execute').length) {
        const previousCode = $(element).html();
        jQueryElement
          .removeClass('pythonCode')
          .addClass('pythonCode-container')
          .empty()
          .append($("

").html(previousCode))
          .append("<button class='pythonCode-execute'>Utiliser cet exemple</button>")
      }
    })

    $('.pythonCode-execute').click(function () {
      const code = $(this).parent().find('.pythonCode').text();

      channel.call({
        method: 'useCodeExample',
        params: {
          code,
          language: 'python',
        },
        success: function () {
        },
        error: function () {
        }
      });
    });
  }
}

$(window).on('hashchange', conceptDisplay);
$(conceptDisplay);
<commit_msg>Improve concept display interaction with Codecast<commit_after>var channel = null;
var setupCodeSnippets = false;

$(function() {
  if (window.Channel && (window.opener || window.parent)) {
    var windowChannel = window.opener ? window.opener : window.parent;
    channel = Channel.build({window: windowChannel, origin: '*', scope: 'snippet'});

    channel.bind('setupConceptDisplaySnippets', function () {
      setupCodeSnippets = true;
      doSetupCodeSnippets();
    });
  }
});

function conceptDisplay() {
  var hash = window.location.hash.substr(1);
  if(!hash) { return; }

  var hashSplit = hash.split('-');
  if(hashSplit.length > 1) {
    var lang = hashSplit.shift();
    var target = hashSplit.join('-');
  } else {
    var lang = null;
    var target = hash;
  }

  var targetDiv = $('div[data-id='+target+']');

  if(!targetDiv.length) { return; }

  $('body > div').hide();
  targetDiv.show();
  if(lang) {
    var allLangDivs = targetDiv.find('[data-lang]');
    var langDivs = allLangDivs.filter(function(i, e) {
      var langs = e.getAttribute('data-lang').split(' ');
      return langs.indexOf(lang) != -1;
    });
    if(langDivs.length) {
      allLangDivs.hide();
      langDivs.show();
    } else {
      allLangDivs.show();
    }
  }

  if (setupCodeSnippets) {
    doSetupCodeSnippets();
  }
}

function doSetupCodeSnippets() {
  var pythonCodes = $('.pythonCode');
  pythonCodes.each(function (index, element) {
    const jQueryElement = $(element);
    if (!jQueryElement.parent().find('.pythonCode-execute').length) {
      const previousCode = $(element).html();
      jQueryElement
        .removeClass('pythonCode')
        .addClass('pythonCode-container')
        .empty()
        .append($("

").html(previousCode))
        .append("<button class='pythonCode-execute'>Utiliser cet exemple</button>")
    }
  })

  $('.pythonCode-execute').click(function () {
    const code = $(this).parent().find('.pythonCode').text();

    channel.notify({
      method: 'useCodeExample',
      params: {
        code: code,
        language: 'python',
      },
    });
  });
}

$(window).on('hashchange', conceptDisplay);
$(conceptDisplay);
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Color = this.Color = Base.extend(new function() {

	var colorCache = {},
		colorContext;

	function nameToRGBColor(name) {
		var color = colorCache[name];
		if (color)
			return color; // TODO: return a clone of the color
		// Use a canvas to draw to with the given name and then retrieve rgb
		// values from. Build a cache for all the used colors.
		if (!colorContext) {
			var canvas = CanvasProvider.getCanvas(Size.create(1, 1));
			colorContext = canvas.getContext('2d');
			colorContext.globalCompositeOperation = 'copy';
		}
		// Set the current fillStyle to transparent, so that it will be
		// transparent instead of the previously set color in case the new color
		// can not be interpreted.
		colorContext.fillStyle = 'rgba(0, 0, 0, 0)';
		// Set the fillStyle of the context to the passed name and fill the
		// canvas with it, then retrieve the data for the drawn pixel:
		colorContext.fillStyle = name;
		colorContext.fillRect(0, 0, 1, 1);
		var data = colorContext.getImageData(0, 0, 1, 1).data,
			rgb = [data[0] / 255, data[1] / 255, data[2] / 255];
		return colorCache[name] = RGBColor.read(rgb); // TODO: return a clone
	}

	function hexToRGBColor(string) {
		var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
		if (hex.length >= 4) {
			var rgb = new Array(3);
			for (var i = 0; i < 3; i++) {
				var channel = hex[i + 1];
				rgb[i] = parseInt(channel.length == 1
						? channel + channel : channel, 16) / 255;
			}
			return RGBColor.read(rgb);
		}
	}

	var converters = {
		'rgb-hsb': function(color) {
			var r = color._red,
				g = color._green,
				b = color._blue,
				alpha = color._alpha,
				max = Math.max(r, g, b),
				min = Math.min(r, g, b),
				delta = max - min,
				hue,
				saturation = (max != 0) ? delta / max : 0,
				brightness = max;
			if (saturation == 0) {
				hue = 0;
			} else {
				var rr = (max - r) / delta,
					gr = (max - g) / delta,
					br = (max - b) / delta;
				hue = r == max
					? br - gr
					: g == max
						? 2 + rr - br
						: 4 + gr - rr;
				hue /= 6;
				if (hue < 0)
					hue++;
			}
			return new HSBColor(hue * 360, saturation, brightness, alpha);
		},

		'hsb-rgb': function(color) {
			var h = color._hue,
				s = color._saturation,
				b = color._brightness,
				a = color._alpha,
				f = h % 60,
				p = (b * (1 - s)) / 1,
				q = (b * (60 - s * f)) / 60,
				t = (b * (60 - s * (60 - f))) / 60;
			switch (Math.floor(h / 60)) {
				case 0: return new RGBColor(b, t, p, a);
				case 1: return new RGBColor(q, b, p, a);
				case 2: return new RGBColor(p, b, t, a);
				case 3: return new RGBColor(p, q, b, a);
				case 4: return new RGBColor(t, p, b, a);
				case 5: return new RGBColor(b, p, q, a);
			}
		},

		'rgb-gray': function(color) {
			// Using the standard NTSC conversion formula that is used for
			// calculating the effective luminance of an RGB color:
			// http://www.mathworks.com/support/solutions/en/data/1-1ASCU/index.html?solution=1-1ASCU
			return new GrayColor(1 -
					(color._red * 0.2989
					+ color._green * 0.587
					+ color._blue * 0.114),
					color._alpha
				);
		},

		'gray-rgb': function(color) {
			var component = 1 - color.getGray();
			return new RGBColor(component, component, component, color._alpha);
		},

		'hsb-gray': function(color) {
			var rgbColor = converters['hsb-rgb'](color);
			return converters['rgb-gray'](rgbColor);
		},

		'gray-hsb': function(color) {
			return new HSBColor(0, 0, 1 - color._gray, color._alpha);
		}
	};

	var fields = {
		beans: true,
		_readNull: true,

		initialize: function(arg) {
			var isArray = Array.isArray(arg);
			if (typeof arg === 'object' && !isArray) {
				if (!this._colorType) {
					// Called on the abstract Color class. Guess color type
					// from arg
					return arg.red !== undefined
						? new RGBColor(arg.red, arg.green, arg.blue, arg.alpha)
						: arg.gray !== undefined
						? new GrayColor(arg.gray, arg.alpha)
						: arg.hue !== undefined
						? new HSBColor(arg.hue, arg.saturation, arg.brightness,
								arg.alpha)
						: new RGBColor(); // Fallback
				} else {
					// Called on a subclass instance. Return the converted
					// color.
					var color = Color.read(arguments, 0, 1);
					return this._colorType
							? color.convert(this._colorType)
							: color;
				}
			} else if (typeof arg === 'string') {
				var rgbColor = arg.match(/^#[0-9a-f]{3,6}$/i)
						? hexToRGBColor(arg)
						: nameToRGBColor(arg);
				return this._colorType
						? rgbColor.convert(this._colorType)
						: rgbColor;
			} else {
				var components = isArray ? arg
						: Array.prototype.slice.call(arguments);
				if (!this._colorType) {
					// Called on the abstract Color class. Guess color type
					// from arg
					//if (components.length >= 4)
					//	return new CMYKColor(components);
					if (components.length >= 3)
						return new RGBColor(components);
					return new GrayColor(components);
				} else {
					// Called on a subclass instance. Just copy over
					// components.
					Base.each(this._components,
						function(name, i) {
							var value = components[i];
							// TODO: Should we call the setter?
							// this['set' + name.capitalize()]
							this[name] = value !== undefined
									? value
									// TODO: Is this correct?
									// Shouldn't alpha be set to -1?
									: name === 'alpha' ? 1 : null;
						},
					this);
				}
			}
		},

		convert: function(type) {
			return this._colorType == type
				? this
				: converters[this._colorType + '-' + type](this);
		}
	};

	// Produce conversion methods for the various color components known by the
	// possible color types. Requesting any of these components on any color
	// internally converts the color to the required type and then returns its
	// component, using bean access.
	return Base.each({
		rgb: ['red', 'green', 'blue'],
		hsb: ['hue', 'saturation', 'brightness'],
		gray: ['gray']
	}, function(components, colorType) {
		Base.each(components, function(component) {
			this['get' + Base.capitalize(component)] = function() {
				return this.convert(colorType)[component];
			};
			this['set' + Base.capitalize(component)] = function(value) {
				var color = this.convert(colorType);
				color[component] = value;
				color = color.convert(this._colorType);
				for (var i = 0, l = this._components.length; i < l; i++) {
					this[this._components[i]] = color[this._components[i]];
				}
			};
		}, this);
	}, fields);
}, {
	beans: true,

	getType: function() {
		return this._colorType;
	},

	getComponents: function() {
		var l = this._components.length;
		var components = new Array(l);
		for (var i = 0; i < l; i++) {
			components[i] = this['_' + this._components[i]];
		}
		return components;
	},

	/**
	 * A value between 0 and 1 that specifies the color's alpha value.
	 * All colors of the different subclasses support alpha values.
	 */
	getAlpha: function() {
		return this._alpha != null ? this._alpha : 1;
	},

	setAlpha: function(alpha) {
		this._alpha = Math.min(Math.max(alpha, 0), 1);
		this._cssString = null;
	},

	/**
	 * Checks if the color has an alpha value.
	 *
	 * @return true if the color has an alpha value, false otherwise.
	 */
	hasAlpha: function() {
		return this._alpha != null;
	},

	/**
	 * Checks if the component color values of the color are the
	 * same as those of the supplied one.
	 *
	 * @param obj the GrayColor to compare with
	 * @return true if the GrayColor is the same, false otherwise.
	 */
	equals: function(color) {
		if (color && color._colorType === this._colorType) {
			for (var i = 0, l = this._components.length; i < l; i++) {
				var component = '_' + this._components[i];
				if (this[component] !== color[component])
					return false;
			}
			return true;
		}
		return false;
	},

	toString: function() {
		var parts = [],
			format = Base.formatNumber;
		for (var i = 0, l = this._components.length; i < l; i++) {
			var component = this._components[i],
				value = this['_' + component];
			if (component === 'alpha' && value == null)
				value = 1;
			parts.push(component + ': ' + format(value));
		}
		return '{ ' + parts.join(', ') + ' }';
	},

	toCssString: function() {
		if (!this._cssString) {
			var color = this._colorType === 'rgb'
					? this
					: this.convert('rgb');
			var alpha = color.getAlpha();
			var components = [
				Math.round(color.getRed() * 255),
				Math.round(color.getGreen() * 255),
				Math.round(color.getBlue() * 255),
				alpha != null ? this.alpha : 1
			];
			this._cssString = 'rgba(' + components.join(', ') + ')';
		}
		return this._cssString;
	},

	getCanvasStyle: function() {
		return this.toCssString();
	}
});
<commit_msg>Less cryptic code without Base.each() side-car makes more sense here.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Color = this.Color = Base.extend(new function() {

	var colorCache = {},
		colorContext;

	function nameToRGBColor(name) {
		var color = colorCache[name];
		if (color)
			return color; // TODO: return a clone of the color
		// Use a canvas to draw to with the given name and then retrieve rgb
		// values from. Build a cache for all the used colors.
		if (!colorContext) {
			var canvas = CanvasProvider.getCanvas(Size.create(1, 1));
			colorContext = canvas.getContext('2d');
			colorContext.globalCompositeOperation = 'copy';
		}
		// Set the current fillStyle to transparent, so that it will be
		// transparent instead of the previously set color in case the new color
		// can not be interpreted.
		colorContext.fillStyle = 'rgba(0, 0, 0, 0)';
		// Set the fillStyle of the context to the passed name and fill the
		// canvas with it, then retrieve the data for the drawn pixel:
		colorContext.fillStyle = name;
		colorContext.fillRect(0, 0, 1, 1);
		var data = colorContext.getImageData(0, 0, 1, 1).data,
			rgb = [data[0] / 255, data[1] / 255, data[2] / 255];
		return colorCache[name] = RGBColor.read(rgb); // TODO: return a clone
	}

	function hexToRGBColor(string) {
		var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
		if (hex.length >= 4) {
			var rgb = new Array(3);
			for (var i = 0; i < 3; i++) {
				var channel = hex[i + 1];
				rgb[i] = parseInt(channel.length == 1
						? channel + channel : channel, 16) / 255;
			}
			return RGBColor.read(rgb);
		}
	}

	var converters = {
		'rgb-hsb': function(color) {
			var r = color._red,
				g = color._green,
				b = color._blue,
				alpha = color._alpha,
				max = Math.max(r, g, b),
				min = Math.min(r, g, b),
				delta = max - min,
				hue,
				saturation = (max != 0) ? delta / max : 0,
				brightness = max;
			if (saturation == 0) {
				hue = 0;
			} else {
				var rr = (max - r) / delta,
					gr = (max - g) / delta,
					br = (max - b) / delta;
				hue = r == max
					? br - gr
					: g == max
						? 2 + rr - br
						: 4 + gr - rr;
				hue /= 6;
				if (hue < 0)
					hue++;
			}
			return new HSBColor(hue * 360, saturation, brightness, alpha);
		},

		'hsb-rgb': function(color) {
			var h = color._hue,
				s = color._saturation,
				b = color._brightness,
				a = color._alpha,
				f = h % 60,
				p = (b * (1 - s)) / 1,
				q = (b * (60 - s * f)) / 60,
				t = (b * (60 - s * (60 - f))) / 60;
			switch (Math.floor(h / 60)) {
				case 0: return new RGBColor(b, t, p, a);
				case 1: return new RGBColor(q, b, p, a);
				case 2: return new RGBColor(p, b, t, a);
				case 3: return new RGBColor(p, q, b, a);
				case 4: return new RGBColor(t, p, b, a);
				case 5: return new RGBColor(b, p, q, a);
			}
		},

		'rgb-gray': function(color) {
			// Using the standard NTSC conversion formula that is used for
			// calculating the effective luminance of an RGB color:
			// http://www.mathworks.com/support/solutions/en/data/1-1ASCU/index.html?solution=1-1ASCU
			return new GrayColor(1 -
					(color._red * 0.2989
					+ color._green * 0.587
					+ color._blue * 0.114),
					color._alpha
				);
		},

		'gray-rgb': function(color) {
			var component = 1 - color.getGray();
			return new RGBColor(component, component, component, color._alpha);
		},

		'hsb-gray': function(color) {
			var rgbColor = converters['hsb-rgb'](color);
			return converters['rgb-gray'](rgbColor);
		},

		'gray-hsb': function(color) {
			return new HSBColor(0, 0, 1 - color._gray, color._alpha);
		}
	};

	var fields = {
		beans: true,
		_readNull: true,

		initialize: function(arg) {
			var isArray = Array.isArray(arg);
			if (typeof arg === 'object' && !isArray) {
				if (!this._colorType) {
					// Called on the abstract Color class. Guess color type
					// from arg
					return arg.red !== undefined
						? new RGBColor(arg.red, arg.green, arg.blue, arg.alpha)
						: arg.gray !== undefined
						? new GrayColor(arg.gray, arg.alpha)
						: arg.hue !== undefined
						? new HSBColor(arg.hue, arg.saturation, arg.brightness,
								arg.alpha)
						: new RGBColor(); // Fallback
				} else {
					// Called on a subclass instance. Return the converted
					// color.
					var color = Color.read(arguments, 0, 1);
					return this._colorType
							? color.convert(this._colorType)
							: color;
				}
			} else if (typeof arg === 'string') {
				var rgbColor = arg.match(/^#[0-9a-f]{3,6}$/i)
						? hexToRGBColor(arg)
						: nameToRGBColor(arg);
				return this._colorType
						? rgbColor.convert(this._colorType)
						: rgbColor;
			} else {
				var components = isArray ? arg
						: Array.prototype.slice.call(arguments);
				if (!this._colorType) {
					// Called on the abstract Color class. Guess color type
					// from arg
					//if (components.length >= 4)
					//	return new CMYKColor(components);
					if (components.length >= 3)
						return new RGBColor(components);
					return new GrayColor(components);
				} else {
					// Called on a subclass instance. Just copy over
					// components.
					Base.each(this._components,
						function(name, i) {
							var value = components[i];
							// TODO: Should we call the setter?
							// this['set' + name.capitalize()]
							this[name] = value !== undefined
									? value
									// TODO: Is this correct?
									// Shouldn't alpha be set to -1?
									: name === 'alpha' ? 1 : null;
						},
					this);
				}
			}
		},

		convert: function(type) {
			return this._colorType == type
				? this
				: converters[this._colorType + '-' + type](this);
		}
	};

	// Produce conversion methods for the various color components known by the
	// possible color types. Requesting any of these components on any color
	// internally converts the color to the required type and then returns its
	// component, using bean access.
	Base.each({
		rgb: ['red', 'green', 'blue'],
		hsb: ['hue', 'saturation', 'brightness'],
		gray: ['gray']
	}, function(components, colorType) {
		Base.each(components, function(component) {
			fields['get' + Base.capitalize(component)] = function() {
				return this.convert(colorType)[component];
			};
			fields['set' + Base.capitalize(component)] = function(value) {
				var color = this.convert(colorType);
				color[component] = value;
				color = color.convert(this._colorType);
				for (var i = 0, l = this._components.length; i < l; i++) {
					this[this._components[i]] = color[this._components[i]];
				}
			};
		});
	});

	return fields;
}, {
	beans: true,

	getType: function() {
		return this._colorType;
	},

	getComponents: function() {
		var l = this._components.length;
		var components = new Array(l);
		for (var i = 0; i < l; i++) {
			components[i] = this['_' + this._components[i]];
		}
		return components;
	},

	/**
	 * A value between 0 and 1 that specifies the color's alpha value.
	 * All colors of the different subclasses support alpha values.
	 */
	getAlpha: function() {
		return this._alpha != null ? this._alpha : 1;
	},

	setAlpha: function(alpha) {
		this._alpha = Math.min(Math.max(alpha, 0), 1);
		this._cssString = null;
	},

	/**
	 * Checks if the color has an alpha value.
	 *
	 * @return true if the color has an alpha value, false otherwise.
	 */
	hasAlpha: function() {
		return this._alpha != null;
	},

	/**
	 * Checks if the component color values of the color are the
	 * same as those of the supplied one.
	 *
	 * @param obj the GrayColor to compare with
	 * @return true if the GrayColor is the same, false otherwise.
	 */
	equals: function(color) {
		if (color && color._colorType === this._colorType) {
			for (var i = 0, l = this._components.length; i < l; i++) {
				var component = '_' + this._components[i];
				if (this[component] !== color[component])
					return false;
			}
			return true;
		}
		return false;
	},

	toString: function() {
		var parts = [],
			format = Base.formatNumber;
		for (var i = 0, l = this._components.length; i < l; i++) {
			var component = this._components[i],
				value = this['_' + component];
			if (component === 'alpha' && value == null)
				value = 1;
			parts.push(component + ': ' + format(value));
		}
		return '{ ' + parts.join(', ') + ' }';
	},

	toCssString: function() {
		if (!this._cssString) {
			var color = this._colorType === 'rgb'
					? this
					: this.convert('rgb');
			var alpha = color.getAlpha();
			var components = [
				Math.round(color.getRed() * 255),
				Math.round(color.getGreen() * 255),
				Math.round(color.getBlue() * 255),
				alpha != null ? this.alpha : 1
			];
			this._cssString = 'rgba(' + components.join(', ') + ')';
		}
		return this._cssString;
	},

	getCanvasStyle: function() {
		return this.toCssString();
	}
});
<|endoftext|>


<commit_before>export default class Color {
  constructor(space, table) {
    this.space = space;
    this.table = new Map(table);
  }

  toString() {
    let object = Object.create(null);
    this.table.forEach((name, value) => {
      let key = Symbol.keyFor(name);
      if (!key) {
        throw new Error();
      }
      Object.defineProperty(object, key, {'value': value});
    });
    return JSON.strigify(object);
  }

  toBytes() {
    return [0, 0, 0, 0];
  }

  isValid() {
    return false;
  }

  clone() {
    return new this.constructor.name(this.space, this.table);
  }

  space() {
    return Symbol.forKey(this.space);
  }

  access(key, value = null) {
    if (value === null) {
      return this.get(key);
    }
    return this.set(key, value);
  }

  get(key) {
    return this.table.get(key);
  }

  set(key, value) {
    this.table.set(key, value);
    return this;
  }

  values() {
    return this.table.values();
  }

  rgb() {
    throw new Error();
  }

  hsl() {
    throw new Error();
  }

  hsv() {
    throw new Error();
  }
}
<commit_msg>Added a method that convert color value using converter<commit_after>export default class Color {
  constructor(space, table) {
    this.space = space;
    this.table = new Map(table);
  }

  toString() {
    let object = Object.create(null);
    this.table.forEach((name, value) => {
      let key = Symbol.keyFor(name);
      if (!key) {
        throw new Error();
      }
      Object.defineProperty(object, key, {'value': value});
    });
    return JSON.strigify(object);
  }

  toBytes() {
    return [0, 0, 0, 0];
  }

  isValid() {
    return false;
  }

  clone() {
    return new this.constructor.name(this.space, this.table);
  }

  space() {
    return Symbol.forKey(this.space);
  }

  access(key, value = null) {
    if (value === null) {
      return this.get(key);
    }
    return this.set(key, value);
  }

  get(key) {
    return this.table.get(key);
  }

  set(key, value) {
    this.table.set(key, value);
    return this;
  }

  values() {
    return this.table.values();
  }

  rgb() {
    throw new Error();
  }

  hsl() {
    throw new Error();
  }

  hsv() {
    throw new Error();
  }

  convertTo(converter) {
    return converter.convert(this);
  }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qbs.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

var FileInfo = require("qbs.FileInfo");
var ModUtils = require("qbs.ModUtils");

function tagListToString(tagList)
{
    return JSON.stringify(tagList);
}

function stringToTagList(tagListString)
{
    return JSON.parse(tagListString);
}

function writeTargetArtifactGroup(output, tagList, artifactList, moduleInstallDir, moduleFile)
{
    // Do not add our qbs module file itself.
    if (tagListToString(tagList) === tagListToString(output.fileTags))
        return;

    moduleFile.writeLine("    Group {");
    moduleFile.writeLine("        filesAreTargets: true");
    var filteredTagList = tagList.filter(function(t) { return t !== "installable"; });
    moduleFile.writeLine("        fileTags: " + JSON.stringify(filteredTagList));
    moduleFile.writeLine("        files: [");
    for (i = 0; i < artifactList.length; ++i) {
        var artifact = artifactList[i];
        var installedArtifactFilePath = ModUtils.artifactInstalledFilePath(artifact);

        // Use relative file paths for relocatability.
        var relativeInstalledArtifactFilePath = FileInfo.relativePath(moduleInstallDir,
                                                                      installedArtifactFilePath);
        moduleFile.writeLine("            " + JSON.stringify(relativeInstalledArtifactFilePath)
                             + ",");
    }
    moduleFile.writeLine("        ]");
    moduleFile.writeLine("    }");

}

function writeTargetArtifactGroups(product, output, moduleFile)
{
    var relevantArtifacts = [];
    for (var i = 0; i < (product.Exporter.qbs._artifactTypes || []).length; ++i) {
        var tag = product.Exporter.qbs._artifactTypes[i];
        var artifactsForTag = product.artifacts[tag] || [];
        for (var j = 0; j < artifactsForTag.length; ++j) {
            if (!relevantArtifacts.contains(artifactsForTag[j]))
                relevantArtifacts.push(artifactsForTag[j]);
        }
    }
    var artifactsByTags = {};
    var artifactCount = relevantArtifacts ? relevantArtifacts.length : 0;
    for (i = 0; i < artifactCount; ++i) {
        var artifact = relevantArtifacts[i];
        if (!artifact.fileTags.contains("installable"))
            continue;

        // Put all artifacts with the same set of file tags into the same group, so we don't
        // create more groups than necessary.
        var key = tagListToString(artifact.fileTags);
        var currentList = artifactsByTags[key];
        if (currentList)
            currentList.push(artifact);
        else
            currentList = [artifact];
        artifactsByTags[key] = currentList;
    }
    var moduleInstallDir = FileInfo.path(ModUtils.artifactInstalledFilePath(output));
    for (var tagListKey in artifactsByTags) {
        writeTargetArtifactGroup(output, stringToTagList(tagListKey), artifactsByTags[tagListKey],
                   moduleInstallDir, moduleFile);
    }
}

function checkValuePrefix(name, value, forbiddenPrefix, prefixDescription)
{
    if (value.startsWith(forbiddenPrefix)) {
        throw "Value '" + value + "' for exported property '" + name + "' in product '"
                + product.name + "' points into " + prefixDescription + ".\n"
                + "Did you forget to set the prefixMapping property in an Export item?";
    }
}

function stringifyValue(project, product, moduleInstallDir, prop, value)
{
    if (Array.isArray(value)) {
        var repr = "[";
        for (var i = 0; i < value.length; ++i) {
            repr += stringifyValue(project, product, moduleInstallDir, prop, value[i]) + ", ";
        }
        repr += "]";
        return repr;
    }
    if (typeof(value) !== "string") {
        var value = JSON.stringify(value);
        if (prop.type === "variant")
            value = '(' + value + ')';
        return value;
    }

    // Catch user oversights: Paths that point into the project source or build directories
    // make no sense in the module.
    if (!value.startsWith(product.qbs.installRoot)) {
        checkValuePrefix(prop.name, value, project.buildDirectory, "project build directory");
        checkValuePrefix(prop.name, value, project.sourceDirectory, "project source directory");
    }

    // Adapt file paths pointing into the install dir, that is, make them relative to the
    // module file for relocatability. We accept them with or without the install root.
    // The latter form will typically be a result of applying the prefixMapping property,
    // while the first one could be an untransformed path, for instance if the project
    // file is written in such a way that include paths are picked up from the installed
    // location rather than the source directory.
    var valuePrefixToStrip;
    var fullInstallPrefix = FileInfo.joinPaths(product.qbs.installRoot, product.qbs.installPrefix);
    if (fullInstallPrefix.length > 1 && value.startsWith(fullInstallPrefix)) {
        valuePrefixToStrip = fullInstallPrefix;
    } else {
        var installPrefix = FileInfo.joinPaths("/", product.qbs.installPrefix);
        if (installPrefix.length > 1 && value.startsWith(installPrefix))
            valuePrefixToStrip = installPrefix;
    }
    if (valuePrefixToStrip) {
        var deployedModuleInstallDir = moduleInstallDir.slice(fullInstallPrefix.length);
        return "FileInfo.cleanPath(FileInfo.joinPaths(path, FileInfo.relativePath("
                + JSON.stringify(deployedModuleInstallDir) + ", "
                + JSON.stringify(value.slice(valuePrefixToStrip.length)) + ")))";
    }

    return JSON.stringify(value);
}

function writeProperty(project, product, moduleInstallDir, prop, indentation, considerValue,
                       moduleFile)
{
    var line = indentation;
    var separatorIndex = prop.name.lastIndexOf(".");
    var isModuleProperty = separatorIndex !== -1;
    var needsDeclaration = !prop.isBuiltin && !isModuleProperty;
    if (needsDeclaration)
        line += "property " + prop.type +  " ";
    var moduleName;
    if (isModuleProperty) {
        moduleName = prop.name.slice(0, separatorIndex);
        if ((product.Exporter.qbs.excludedDependencies || []).contains(moduleName))
            return;
    }
    line += prop.name + ": ";

    // We emit the literal value, unless the source code clearly refers to values from inside the
    // original project, in which case the evaluated value is used.
    if (considerValue && /(project|product)\./.test(prop.sourceCode)) {
        var value;
        if (isModuleProperty) {
            var propertyName = prop.name.slice(separatorIndex + 1);
            value = product.exports[moduleName][propertyName];
        } else {
            value = product.exports[prop.name];
        }
        line += stringifyValue(project, product, moduleInstallDir, prop, value);
    } else {
        line += prop.sourceCode.replace(/importingProduct\./g, "product.");
    }
    moduleFile.writeLine(line);
}

function writeProperties(project, product, moduleInstallDir, list, indentation, considerValue,
                         moduleFile)
{
    for (var i = 0; i < list.length; ++i) {
        writeProperty(project, product, moduleInstallDir, list[i], indentation, considerValue,
                      moduleFile);
    }
}

// This writes properties set on other modules in the Export item, i.e. property assignments
// like "cpp.includePaths: '...'".
function writeModuleProperties(project, product, output, moduleFile)
{
    var moduleInstallDir = FileInfo.path(ModUtils.artifactInstalledFilePath(output));
    var filteredProps = product.exports.properties.filter(function(p) {
        return p.name !== "name";
    });

    // The right-hand side can refer to values from the exporting product, in which case
    // the evaluated value, rather than the source code, needs to go into the module file.
    var considerValues = true;
    writeProperties(project, product, moduleInstallDir, filteredProps, "    ", considerValues,
                    moduleFile);
}

function writeItem(product, item, indentation, moduleFile)
{
    moduleFile.writeLine(indentation + item.name + " {");
    var newIndentation = indentation + "    ";

    // These are sub-items of the Export item, whose properties entirely live in the context
    // of the importing product. Therefore, they must never use pre-evaluated values.
    var considerValues = false;
    writeProperties(undefined, product, undefined, item.properties, newIndentation, considerValues,
                    moduleFile)

    for (var i = 0; i < item.childItems.length; ++i)
        writeItem(product, item.childItems[i], newIndentation, moduleFile);
    moduleFile.writeLine(indentation + "}");
}

function isExcludedDependency(product, childItem)
{
    if ((product.Exporter.qbs.excludedDependencies || []).length === 0)
        return false;
    if (childItem.name !== "Depends")
        return false;
    for (var i = 0; i < childItem.properties.length; ++i) {
        var prop = childItem.properties[i];
        var unquotedRhs = prop.sourceCode.slice(1, -1);
        if (prop.name === "name" && product.Exporter.qbs.excludedDependencies.contains(unquotedRhs))
            return true;
    }
    return false;
}

function writeChildItems(product, moduleFile)
{
    for (var i = 0; i < product.exports.childItems.length; ++i) {
        var item = product.exports.childItems[i];
        if (!isExcludedDependency(product, item))
            writeItem(product, item, "    ", moduleFile);
    }
}

function writeImportStatements(product, moduleFile)
{
    var imports = product.exports.imports;

    // We potentially use FileInfo ourselves when transforming paths in stringifyValue().
    if (!imports.contains("import qbs.FileInfo"))
        imports.push("import qbs.FileInfo");

    for (var i = 0; i < product.exports.imports.length; ++i)
        moduleFile.writeLine(product.exports.imports[i]);
}
<commit_msg>Exporter.qbs: Prevent passing an empty string to FileInfo.relativePath()<commit_after>/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qbs.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

var FileInfo = require("qbs.FileInfo");
var ModUtils = require("qbs.ModUtils");

function tagListToString(tagList)
{
    return JSON.stringify(tagList);
}

function stringToTagList(tagListString)
{
    return JSON.parse(tagListString);
}

function writeTargetArtifactGroup(output, tagList, artifactList, moduleInstallDir, moduleFile)
{
    // Do not add our qbs module file itself.
    if (tagListToString(tagList) === tagListToString(output.fileTags))
        return;

    moduleFile.writeLine("    Group {");
    moduleFile.writeLine("        filesAreTargets: true");
    var filteredTagList = tagList.filter(function(t) { return t !== "installable"; });
    moduleFile.writeLine("        fileTags: " + JSON.stringify(filteredTagList));
    moduleFile.writeLine("        files: [");
    for (i = 0; i < artifactList.length; ++i) {
        var artifact = artifactList[i];
        var installedArtifactFilePath = ModUtils.artifactInstalledFilePath(artifact);

        // Use relative file paths for relocatability.
        var relativeInstalledArtifactFilePath = FileInfo.relativePath(moduleInstallDir,
                                                                      installedArtifactFilePath);
        moduleFile.writeLine("            " + JSON.stringify(relativeInstalledArtifactFilePath)
                             + ",");
    }
    moduleFile.writeLine("        ]");
    moduleFile.writeLine("    }");

}

function writeTargetArtifactGroups(product, output, moduleFile)
{
    var relevantArtifacts = [];
    for (var i = 0; i < (product.Exporter.qbs._artifactTypes || []).length; ++i) {
        var tag = product.Exporter.qbs._artifactTypes[i];
        var artifactsForTag = product.artifacts[tag] || [];
        for (var j = 0; j < artifactsForTag.length; ++j) {
            if (!relevantArtifacts.contains(artifactsForTag[j]))
                relevantArtifacts.push(artifactsForTag[j]);
        }
    }
    var artifactsByTags = {};
    var artifactCount = relevantArtifacts ? relevantArtifacts.length : 0;
    for (i = 0; i < artifactCount; ++i) {
        var artifact = relevantArtifacts[i];
        if (!artifact.fileTags.contains("installable"))
            continue;

        // Put all artifacts with the same set of file tags into the same group, so we don't
        // create more groups than necessary.
        var key = tagListToString(artifact.fileTags);
        var currentList = artifactsByTags[key];
        if (currentList)
            currentList.push(artifact);
        else
            currentList = [artifact];
        artifactsByTags[key] = currentList;
    }
    var moduleInstallDir = FileInfo.path(ModUtils.artifactInstalledFilePath(output));
    for (var tagListKey in artifactsByTags) {
        writeTargetArtifactGroup(output, stringToTagList(tagListKey), artifactsByTags[tagListKey],
                   moduleInstallDir, moduleFile);
    }
}

function checkValuePrefix(name, value, forbiddenPrefix, prefixDescription)
{
    if (value.startsWith(forbiddenPrefix)) {
        throw "Value '" + value + "' for exported property '" + name + "' in product '"
                + product.name + "' points into " + prefixDescription + ".\n"
                + "Did you forget to set the prefixMapping property in an Export item?";
    }
}

function stringifyValue(project, product, moduleInstallDir, prop, value)
{
    if (Array.isArray(value)) {
        var repr = "[";
        for (var i = 0; i < value.length; ++i) {
            repr += stringifyValue(project, product, moduleInstallDir, prop, value[i]) + ", ";
        }
        repr += "]";
        return repr;
    }
    if (typeof(value) !== "string") {
        var value = JSON.stringify(value);
        if (prop.type === "variant")
            value = '(' + value + ')';
        return value;
    }

    // Catch user oversights: Paths that point into the project source or build directories
    // make no sense in the module.
    if (!value.startsWith(product.qbs.installRoot)) {
        checkValuePrefix(prop.name, value, project.buildDirectory, "project build directory");
        checkValuePrefix(prop.name, value, project.sourceDirectory, "project source directory");
    }

    // Adapt file paths pointing into the install dir, that is, make them relative to the
    // module file for relocatability. We accept them with or without the install root.
    // The latter form will typically be a result of applying the prefixMapping property,
    // while the first one could be an untransformed path, for instance if the project
    // file is written in such a way that include paths are picked up from the installed
    // location rather than the source directory.
    var valuePrefixToStrip;
    var fullInstallPrefix = FileInfo.joinPaths(product.qbs.installRoot, product.qbs.installPrefix);
    if (fullInstallPrefix.length > 1 && value.startsWith(fullInstallPrefix)) {
        valuePrefixToStrip = fullInstallPrefix;
    } else {
        var installPrefix = FileInfo.joinPaths("/", product.qbs.installPrefix);
        if (installPrefix.length > 1 && value.startsWith(installPrefix))
            valuePrefixToStrip = installPrefix;
    }
    if (valuePrefixToStrip) {
        var deployedModuleInstallDir = moduleInstallDir.slice(fullInstallPrefix.length);
        return "FileInfo.cleanPath(FileInfo.joinPaths(path, FileInfo.relativePath("
                + JSON.stringify(deployedModuleInstallDir) + ", "
                + JSON.stringify(value.slice(valuePrefixToStrip.length) || "/") + ")))";
    }

    return JSON.stringify(value);
}

function writeProperty(project, product, moduleInstallDir, prop, indentation, considerValue,
                       moduleFile)
{
    var line = indentation;
    var separatorIndex = prop.name.lastIndexOf(".");
    var isModuleProperty = separatorIndex !== -1;
    var needsDeclaration = !prop.isBuiltin && !isModuleProperty;
    if (needsDeclaration)
        line += "property " + prop.type +  " ";
    var moduleName;
    if (isModuleProperty) {
        moduleName = prop.name.slice(0, separatorIndex);
        if ((product.Exporter.qbs.excludedDependencies || []).contains(moduleName))
            return;
    }
    line += prop.name + ": ";

    // We emit the literal value, unless the source code clearly refers to values from inside the
    // original project, in which case the evaluated value is used.
    if (considerValue && /(project|product)\./.test(prop.sourceCode)) {
        var value;
        if (isModuleProperty) {
            var propertyName = prop.name.slice(separatorIndex + 1);
            value = product.exports[moduleName][propertyName];
        } else {
            value = product.exports[prop.name];
        }
        line += stringifyValue(project, product, moduleInstallDir, prop, value);
    } else {
        line += prop.sourceCode.replace(/importingProduct\./g, "product.");
    }
    moduleFile.writeLine(line);
}

function writeProperties(project, product, moduleInstallDir, list, indentation, considerValue,
                         moduleFile)
{
    for (var i = 0; i < list.length; ++i) {
        writeProperty(project, product, moduleInstallDir, list[i], indentation, considerValue,
                      moduleFile);
    }
}

// This writes properties set on other modules in the Export item, i.e. property assignments
// like "cpp.includePaths: '...'".
function writeModuleProperties(project, product, output, moduleFile)
{
    var moduleInstallDir = FileInfo.path(ModUtils.artifactInstalledFilePath(output));
    var filteredProps = product.exports.properties.filter(function(p) {
        return p.name !== "name";
    });

    // The right-hand side can refer to values from the exporting product, in which case
    // the evaluated value, rather than the source code, needs to go into the module file.
    var considerValues = true;
    writeProperties(project, product, moduleInstallDir, filteredProps, "    ", considerValues,
                    moduleFile);
}

function writeItem(product, item, indentation, moduleFile)
{
    moduleFile.writeLine(indentation + item.name + " {");
    var newIndentation = indentation + "    ";

    // These are sub-items of the Export item, whose properties entirely live in the context
    // of the importing product. Therefore, they must never use pre-evaluated values.
    var considerValues = false;
    writeProperties(undefined, product, undefined, item.properties, newIndentation, considerValues,
                    moduleFile)

    for (var i = 0; i < item.childItems.length; ++i)
        writeItem(product, item.childItems[i], newIndentation, moduleFile);
    moduleFile.writeLine(indentation + "}");
}

function isExcludedDependency(product, childItem)
{
    if ((product.Exporter.qbs.excludedDependencies || []).length === 0)
        return false;
    if (childItem.name !== "Depends")
        return false;
    for (var i = 0; i < childItem.properties.length; ++i) {
        var prop = childItem.properties[i];
        var unquotedRhs = prop.sourceCode.slice(1, -1);
        if (prop.name === "name" && product.Exporter.qbs.excludedDependencies.contains(unquotedRhs))
            return true;
    }
    return false;
}

function writeChildItems(product, moduleFile)
{
    for (var i = 0; i < product.exports.childItems.length; ++i) {
        var item = product.exports.childItems[i];
        if (!isExcludedDependency(product, item))
            writeItem(product, item, "    ", moduleFile);
    }
}

function writeImportStatements(product, moduleFile)
{
    var imports = product.exports.imports;

    // We potentially use FileInfo ourselves when transforming paths in stringifyValue().
    if (!imports.contains("import qbs.FileInfo"))
        imports.push("import qbs.FileInfo");

    for (var i = 0; i < product.exports.imports.length; ++i)
        moduleFile.writeLine(product.exports.imports[i]);
}
<|endoftext|>


<commit_before>// @flow
import * as React from 'react'
import {Box2, ProgressIndicator} from '../../../common-adapters'
import {styleSheetCreate} from '../../../styles'

const Waiting = () => (
  <Box2 direction="vertical" fullWidth={true} fullHeight={true} style={styles.container}>
    <ProgressIndicator type="Small" style={styles.spinner} />
  </Box2>
)
const styles = styleSheetCreate({
  container: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
  },
  spinner: {width: 40},
})

export default Waiting
<commit_msg>unsquish spinner in new convo (#16937)<commit_after>// @flow
import * as React from 'react'
import {Box2, ProgressIndicator} from '../../../common-adapters'
import {styleSheetCreate} from '../../../styles'

const Waiting = () => (
  <Box2 direction="vertical" fullWidth={true} fullHeight={true} style={styles.container}>
    <ProgressIndicator type="Small" style={styles.spinner} />
  </Box2>
)
const styles = styleSheetCreate({
  container: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
  },
  spinner: {height: 40, width: 40},
})

export default Waiting
<|endoftext|>