<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Viewport = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();
	container.setId( 'viewport' );
	container.setPosition( 'absolute' );

	container.add( new Viewport.Info( editor ) );

	//

	var renderer = null;

	var camera = editor.camera;
	var scene = editor.scene;
	var sceneHelpers = editor.sceneHelpers;

	var objects = [];

	// helpers

	var grid = new THREE.GridHelper( 60, 60 );
	sceneHelpers.add( grid );

	//

	var box = new THREE.Box3();

	var selectionBox = new THREE.BoxHelper();
	selectionBox.material.depthTest = false;
	selectionBox.material.transparent = true;
	selectionBox.visible = false;
	sceneHelpers.add( selectionBox );

	var objectPositionOnDown = null;
	var objectRotationOnDown = null;
	var objectScaleOnDown = null;

	var transformControls = new THREE.TransformControls( camera, container.dom );
	transformControls.addEventListener( 'change', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

			if ( editor.helpers[ object.id ] !== undefined ) {

				editor.helpers[ object.id ].update();

			}

			signals.refreshSidebarObject3D.dispatch( object );

		}

		render();

	} );
	transformControls.addEventListener( 'mouseDown', function () {

		var object = transformControls.object;

		objectPositionOnDown = object.position.clone();
		objectRotationOnDown = object.rotation.clone();
		objectScaleOnDown = object.scale.clone();

		controls.enabled = false;

	} );
	transformControls.addEventListener( 'mouseUp', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			switch ( transformControls.getMode() ) {

				case 'translate':

					if ( ! objectPositionOnDown.equals( object.position ) ) {

						editor.execute( new SetPositionCommand( object, object.position, objectPositionOnDown ) );

					}

					break;

				case 'rotate':

					if ( ! objectRotationOnDown.equals( object.rotation ) ) {

						editor.execute( new SetRotationCommand( object, object.rotation, objectRotationOnDown ) );

					}

					break;

				case 'scale':

					if ( ! objectScaleOnDown.equals( object.scale ) ) {

						editor.execute( new SetScaleCommand( object, object.scale, objectScaleOnDown ) );

					}

					break;

			}

		}

		controls.enabled = true;

	} );

	sceneHelpers.add( transformControls );

	// object picking

	var raycaster = new THREE.Raycaster();
	var mouse = new THREE.Vector2();

	// events

	function getIntersects( point, objects ) {

		mouse.set( ( point.x * 2 ) - 1, - ( point.y * 2 ) + 1 );

		raycaster.setFromCamera( mouse, camera );

		return raycaster.intersectObjects( objects );

	}

	var onDownPosition = new THREE.Vector2();
	var onUpPosition = new THREE.Vector2();
	var onDoubleClickPosition = new THREE.Vector2();

	function getMousePosition( dom, x, y ) {

		var rect = dom.getBoundingClientRect();
		return [ ( x - rect.left ) / rect.width, ( y - rect.top ) / rect.height ];

	}

	function handleClick() {

		if ( onDownPosition.distanceTo( onUpPosition ) === 0 ) {

			var intersects = getIntersects( onUpPosition, objects );

			//if ( editor.getAntennaSnapping() ) {

				if (intersects.length>0) {
					var localPoint = interestsRay[0].point;
					var geometry = new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
            		var material = new THREE.MeshBasicMaterial( {color: 0xff0000} );
            		var mesh = new THREE.Mesh( geometry, material );
            		mesh.name = 'Antenna' + ( ++ meshCount );

            		editor.execute( new SetPositionCommand( mesh, new THREE.Vector3( localPoint.x, loclaPoint.y, localPoint.z ) ) );     // move object to desired coordinates
            		editor.execute( new AddObjectCommand( mesh ) );

				}
			//} else {

				if ( intersects.length > 0 ) {

					var object = intersects[ 0 ].object;

					if ( object.userData.object !== undefined ) {

					// helper

						editor.select( object.userData.object );

					} else {

						editor.select( object );

					}

				} else {

					editor.select( null );

				}
			//}

			render();

		}

	}

	function onMouseDown( event ) {

		event.preventDefault();

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'mouseup', onMouseUp, false );

	}

	function onMouseUp( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'mouseup', onMouseUp, false );

	}

	function onTouchStart( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'touchend', onTouchEnd, false );

	}

	function onTouchEnd( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'touchend', onTouchEnd, false );

	}

	function onDoubleClick( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDoubleClickPosition.fromArray( array );

		var intersects = getIntersects( onDoubleClickPosition, objects );

		if ( intersects.length > 0 ) {

			var intersect = intersects[ 0 ];

			signals.objectFocused.dispatch( intersect.object );

		}

	}

	container.dom.addEventListener( 'mousedown', onMouseDown, false );
	container.dom.addEventListener( 'touchstart', onTouchStart, false );
	container.dom.addEventListener( 'dblclick', onDoubleClick, false );

	// controls need to be added *after* main logic,
	// otherwise controls.enabled doesn't work.

	var controls = new THREE.EditorControls( camera, container.dom );
	controls.addEventListener( 'change', function () {

		transformControls.update();
		signals.cameraChanged.dispatch( camera );

	} );

	// signals

	signals.editorCleared.add( function () {

		controls.center.set( 0, 0, 0 );
		render();

	} );

	signals.themeChanged.add( function ( value ) {

		switch ( value ) {

			case '/static/css/light.css':
				sceneHelpers.remove( grid );
				grid = new THREE.GridHelper( 60, 60, 0x444444, 0x888888 );
				sceneHelpers.add( grid );
				break;
			case '/static/css/dark.css':
				sceneHelpers.remove( grid );
				grid = new THREE.GridHelper( 60, 60, 0xbbbbbb, 0x888888 );
				sceneHelpers.add( grid );
				break;

		}

		render();

	} );

	signals.transformModeChanged.add( function ( mode ) {

		transformControls.setMode( mode );

	} );

	signals.snapChanged.add( function ( dist ) {

		transformControls.setTranslationSnap( dist );

	} );

	signals.spaceChanged.add( function ( space ) {

		transformControls.setSpace( space );

	} );

	signals.rendererChanged.add( function ( newRenderer ) {

		if ( renderer !== null ) {

			container.dom.removeChild( renderer.domElement );

		}

		renderer = newRenderer;

		renderer.autoClear = false;
		renderer.autoUpdateScene = false;
		renderer.setPixelRatio( window.devicePixelRatio );
		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		container.dom.appendChild( renderer.domElement );

		render();

	} );

	signals.sceneGraphChanged.add( function () {

		render();

	} );

	signals.cameraChanged.add( function () {

		render();

	} );

	signals.objectSelected.add( function ( object ) {

		selectionBox.visible = false;
		transformControls.detach();

		if ( object !== null && object !== scene && object !== camera ) {

			box.setFromObject( object );

			if ( box.isEmpty() === false ) {

				selectionBox.setFromObject( object );
				selectionBox.visible = true;

			}

			transformControls.attach( object );

		}

		render();

	} );

	signals.objectFocused.add( function ( object ) {

		controls.focus( object );

	} );

	signals.geometryChanged.add( function ( object ) {

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

		}

		render();

	} );

	signals.objectAdded.add( function ( object ) {

		object.traverse( function ( child ) {

			objects.push( child );

		} );

	} );

	signals.objectChanged.add( function ( object ) {

		if ( editor.selected === object ) {

			selectionBox.setFromObject( object );
			transformControls.update();

		}

		if ( object instanceof THREE.PerspectiveCamera ) {

			object.updateProjectionMatrix();

		}

		if ( editor.helpers[ object.id ] !== undefined ) {

			editor.helpers[ object.id ].update();

		}

		render();

	} );

	signals.objectRemoved.add( function ( object ) {

		object.traverse( function ( child ) {

			objects.splice( objects.indexOf( child ), 1 );

		} );

	} );

	signals.helperAdded.add( function ( object ) {

		objects.push( object.getObjectByName( 'picker' ) );

	} );

	signals.helperRemoved.add( function ( object ) {

		objects.splice( objects.indexOf( object.getObjectByName( 'picker' ) ), 1 );

	} );

	signals.materialChanged.add( function ( material ) {

		render();

	} );

	// fog

	signals.sceneBackgroundChanged.add( function ( backgroundColor ) {

		scene.background.setHex( backgroundColor );

		render();

	} );

	var currentFogType = null;

	signals.sceneFogChanged.add( function ( fogType, fogColor, fogNear, fogFar, fogDensity ) {

		if ( currentFogType !== fogType ) {

			switch ( fogType ) {

				case 'None':
					scene.fog = null;
					break;
				case 'Fog':
					scene.fog = new THREE.Fog();
					break;
				case 'FogExp2':
					scene.fog = new THREE.FogExp2();
					break;

			}

			currentFogType = fogType;

		}

		if ( scene.fog instanceof THREE.Fog ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.near = fogNear;
			scene.fog.far = fogFar;

		} else if ( scene.fog instanceof THREE.FogExp2 ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.density = fogDensity;

		}

		render();

	} );

	//

	signals.windowResize.add( function () {

		// TODO: Move this out?

		editor.DEFAULT_CAMERA.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		editor.DEFAULT_CAMERA.updateProjectionMatrix();

		camera.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		camera.updateProjectionMatrix();

		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		render();

	} );

	signals.showGridChanged.add( function ( showGrid ) {

		grid.visible = showGrid;
		render();

	} );

	//

	function render() {

		sceneHelpers.updateMatrixWorld();
		scene.updateMatrixWorld();

		renderer.render( scene, camera );

		if ( renderer instanceof THREE.RaytracingRenderer === false ) {

			renderer.render( sceneHelpers, camera );

		}

	}

	return container;

};
<commit_msg>antenna snapping<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Viewport = function ( editor ) {

	var signals = editor.signals;

	var container = new UI.Panel();
	container.setId( 'viewport' );
	container.setPosition( 'absolute' );

	container.add( new Viewport.Info( editor ) );

	//

	var renderer = null;

	var camera = editor.camera;
	var scene = editor.scene;
	var sceneHelpers = editor.sceneHelpers;

	var objects = [];

	// helpers

	var grid = new THREE.GridHelper( 60, 60 );
	sceneHelpers.add( grid );

	//

	var box = new THREE.Box3();

	var selectionBox = new THREE.BoxHelper();
	selectionBox.material.depthTest = false;
	selectionBox.material.transparent = true;
	selectionBox.visible = false;
	sceneHelpers.add( selectionBox );

	var objectPositionOnDown = null;
	var objectRotationOnDown = null;
	var objectScaleOnDown = null;

	var transformControls = new THREE.TransformControls( camera, container.dom );
	transformControls.addEventListener( 'change', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

			if ( editor.helpers[ object.id ] !== undefined ) {

				editor.helpers[ object.id ].update();

			}

			signals.refreshSidebarObject3D.dispatch( object );

		}

		render();

	} );
	transformControls.addEventListener( 'mouseDown', function () {

		var object = transformControls.object;

		objectPositionOnDown = object.position.clone();
		objectRotationOnDown = object.rotation.clone();
		objectScaleOnDown = object.scale.clone();

		controls.enabled = false;

	} );
	transformControls.addEventListener( 'mouseUp', function () {

		var object = transformControls.object;

		if ( object !== undefined ) {

			switch ( transformControls.getMode() ) {

				case 'translate':

					if ( ! objectPositionOnDown.equals( object.position ) ) {

						editor.execute( new SetPositionCommand( object, object.position, objectPositionOnDown ) );

					}

					break;

				case 'rotate':

					if ( ! objectRotationOnDown.equals( object.rotation ) ) {

						editor.execute( new SetRotationCommand( object, object.rotation, objectRotationOnDown ) );

					}

					break;

				case 'scale':

					if ( ! objectScaleOnDown.equals( object.scale ) ) {

						editor.execute( new SetScaleCommand( object, object.scale, objectScaleOnDown ) );

					}

					break;

			}

		}

		controls.enabled = true;

	} );

	sceneHelpers.add( transformControls );

	// object picking

	var raycaster = new THREE.Raycaster();
	var mouse = new THREE.Vector2();

	// events

	function getIntersects( point, objects ) {

		mouse.set( ( point.x * 2 ) - 1, - ( point.y * 2 ) + 1 );

		raycaster.setFromCamera( mouse, camera );

		return raycaster.intersectObjects( objects );

	}

	var onDownPosition = new THREE.Vector2();
	var onUpPosition = new THREE.Vector2();
	var onDoubleClickPosition = new THREE.Vector2();

	function getMousePosition( dom, x, y ) {

		var rect = dom.getBoundingClientRect();
		return [ ( x - rect.left ) / rect.width, ( y - rect.top ) / rect.height ];

	}

	function handleClick() {

		if ( onDownPosition.distanceTo( onUpPosition ) === 0 ) {

			var intersects = getIntersects( onUpPosition, objects );

			if ( editor.getAntennaSnapping() ) {

				if (intersects.length>0) {
					var right_wing = editor.getModel()[0];
            		var left_wing = editor.getModel()[1];
					var radius = 64;      // create sphere object according to model size
            		var widthSegments = 32;
            		var heightSegments = 16;
            		var phiStart = 0;
            		var phiLength = Math.PI * 2;
            		var thetaStart = 0;
            		var thetaLength = Math.PI;

					var localPoint = intersects[0].point;
					var geometrySphere = new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
            		var materialAntenna = new THREE.MeshBasicMaterial( {color: 0xff0000} );
            		var mesh = new THREE.Mesh( geometrySphere, materialAntenna );
            		mesh.name = 'Antenna';

            		editor.execute( new SetPositionCommand( mesh, new THREE.Vector3( localPoint.x, localPoint.y, localPoint.z ) ) );     // move object to desired coordinates
            		editor.execute( new AddObjectCommand( mesh ) );

				}
			} else {

				if ( intersects.length > 0 ) {

					var object = intersects[ 0 ].object;

					if ( object.userData.object !== undefined ) {

					// helper

						editor.select( object.userData.object );

					} else {

						editor.select( object );

					}

				} else {

					editor.select( null );

				}
			}

			render();

		}

	}

	function onMouseDown( event ) {

		event.preventDefault();

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'mouseup', onMouseUp, false );

	}

	function onMouseUp( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'mouseup', onMouseUp, false );

	}

	function onTouchStart( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onDownPosition.fromArray( array );

		document.addEventListener( 'touchend', onTouchEnd, false );

	}

	function onTouchEnd( event ) {

		var touch = event.changedTouches[ 0 ];

		var array = getMousePosition( container.dom, touch.clientX, touch.clientY );
		onUpPosition.fromArray( array );

		handleClick();

		document.removeEventListener( 'touchend', onTouchEnd, false );

	}

	function onDoubleClick( event ) {

		var array = getMousePosition( container.dom, event.clientX, event.clientY );
		onDoubleClickPosition.fromArray( array );

		var intersects = getIntersects( onDoubleClickPosition, objects );

		if ( intersects.length > 0 ) {

			var intersect = intersects[ 0 ];

			signals.objectFocused.dispatch( intersect.object );

		}

	}

	container.dom.addEventListener( 'mousedown', onMouseDown, false );
	container.dom.addEventListener( 'touchstart', onTouchStart, false );
	container.dom.addEventListener( 'dblclick', onDoubleClick, false );

	// controls need to be added *after* main logic,
	// otherwise controls.enabled doesn't work.

	var controls = new THREE.EditorControls( camera, container.dom );
	controls.addEventListener( 'change', function () {

		transformControls.update();
		signals.cameraChanged.dispatch( camera );

	} );

	// signals

	signals.editorCleared.add( function () {

		controls.center.set( 0, 0, 0 );
		render();

	} );

	signals.themeChanged.add( function ( value ) {

		switch ( value ) {

			case '/static/css/light.css':
				sceneHelpers.remove( grid );
				grid = new THREE.GridHelper( 60, 60, 0x444444, 0x888888 );
				sceneHelpers.add( grid );
				break;
			case '/static/css/dark.css':
				sceneHelpers.remove( grid );
				grid = new THREE.GridHelper( 60, 60, 0xbbbbbb, 0x888888 );
				sceneHelpers.add( grid );
				break;

		}

		render();

	} );

	signals.transformModeChanged.add( function ( mode ) {

		transformControls.setMode( mode );

	} );

	signals.snapChanged.add( function ( dist ) {

		transformControls.setTranslationSnap( dist );

	} );

	signals.spaceChanged.add( function ( space ) {

		transformControls.setSpace( space );

	} );

	signals.rendererChanged.add( function ( newRenderer ) {

		if ( renderer !== null ) {

			container.dom.removeChild( renderer.domElement );

		}

		renderer = newRenderer;

		renderer.autoClear = false;
		renderer.autoUpdateScene = false;
		renderer.setPixelRatio( window.devicePixelRatio );
		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		container.dom.appendChild( renderer.domElement );

		render();

	} );

	signals.sceneGraphChanged.add( function () {

		render();

	} );

	signals.cameraChanged.add( function () {

		render();

	} );

	signals.objectSelected.add( function ( object ) {

		selectionBox.visible = false;
		transformControls.detach();

		if ( object !== null && object !== scene && object !== camera ) {

			box.setFromObject( object );

			if ( box.isEmpty() === false ) {

				selectionBox.setFromObject( object );
				selectionBox.visible = true;

			}

			transformControls.attach( object );

		}

		render();

	} );

	signals.objectFocused.add( function ( object ) {

		controls.focus( object );

	} );

	signals.geometryChanged.add( function ( object ) {

		if ( object !== undefined ) {

			selectionBox.setFromObject( object );

		}

		render();

	} );

	signals.objectAdded.add( function ( object ) {

		object.traverse( function ( child ) {

			objects.push( child );

		} );

	} );

	signals.objectChanged.add( function ( object ) {

		if ( editor.selected === object ) {

			selectionBox.setFromObject( object );
			transformControls.update();

		}

		if ( object instanceof THREE.PerspectiveCamera ) {

			object.updateProjectionMatrix();

		}

		if ( editor.helpers[ object.id ] !== undefined ) {

			editor.helpers[ object.id ].update();

		}

		render();

	} );

	signals.objectRemoved.add( function ( object ) {

		object.traverse( function ( child ) {

			objects.splice( objects.indexOf( child ), 1 );

		} );

	} );

	signals.helperAdded.add( function ( object ) {

		objects.push( object.getObjectByName( 'picker' ) );

	} );

	signals.helperRemoved.add( function ( object ) {

		objects.splice( objects.indexOf( object.getObjectByName( 'picker' ) ), 1 );

	} );

	signals.materialChanged.add( function ( material ) {

		render();

	} );

	// fog

	signals.sceneBackgroundChanged.add( function ( backgroundColor ) {

		scene.background.setHex( backgroundColor );

		render();

	} );

	var currentFogType = null;

	signals.sceneFogChanged.add( function ( fogType, fogColor, fogNear, fogFar, fogDensity ) {

		if ( currentFogType !== fogType ) {

			switch ( fogType ) {

				case 'None':
					scene.fog = null;
					break;
				case 'Fog':
					scene.fog = new THREE.Fog();
					break;
				case 'FogExp2':
					scene.fog = new THREE.FogExp2();
					break;

			}

			currentFogType = fogType;

		}

		if ( scene.fog instanceof THREE.Fog ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.near = fogNear;
			scene.fog.far = fogFar;

		} else if ( scene.fog instanceof THREE.FogExp2 ) {

			scene.fog.color.setHex( fogColor );
			scene.fog.density = fogDensity;

		}

		render();

	} );

	//

	signals.windowResize.add( function () {

		// TODO: Move this out?

		editor.DEFAULT_CAMERA.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		editor.DEFAULT_CAMERA.updateProjectionMatrix();

		camera.aspect = container.dom.offsetWidth / container.dom.offsetHeight;
		camera.updateProjectionMatrix();

		renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight );

		render();

	} );

	signals.showGridChanged.add( function ( showGrid ) {

		grid.visible = showGrid;
		render();

	} );

	//

	function render() {

		sceneHelpers.updateMatrixWorld();
		scene.updateMatrixWorld();

		renderer.render( scene, camera );

		if ( renderer instanceof THREE.RaytracingRenderer === false ) {

			renderer.render( sceneHelpers, camera );

		}

	}

	return container;

};
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var logger = require( 'debug' );
var indexOf = require( '@stdlib/utils/index-of' );
var ORIENTATIONS = require( './orientations.json' );

// VARIABLES //

var debug = logger( 'plot:set:y-axis-orient' );

// MAIN //

/**
* Sets the y-axis orientation.
*
* @private
* @param {string} orientation - axis orientation
* @throws {TypeError} must be either `'left'` or `'right'`
* @returns {void}
*/
function set( orientation ) {
	/* eslint-disable no-invalid-this */
	if ( indexOf( ORIENTATIONS, orientation ) === -1 ) {
		throw new TypeError( 'invalid value. `yAxisOrient` must be one of `[' + ORIENTATIONS.join(',') + ']`. Value: `' + orientation + '.`' );
	}
	debug( 'Current value: %s.', this._yAxisOrient );

	this._yAxisOrient = orientation;
	debug( 'New value: %s.', this._yAxisOrient );

	this.emit( 'change' );
}

// EXPORTS //

module.exports = set;
<commit_msg>Only emit a `change` event if set to a new value<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var logger = require( 'debug' );
var indexOf = require( '@stdlib/utils/index-of' );
var ORIENTATIONS = require( './orientations.json' );

// VARIABLES //

var debug = logger( 'plot:set:y-axis-orient' );

// MAIN //

/**
* Sets the y-axis orientation.
*
* @private
* @param {string} orientation - axis orientation
* @throws {TypeError} must be either `'left'` or `'right'`
*/
function set( orientation ) {
	/* eslint-disable no-invalid-this */
	if ( indexOf( ORIENTATIONS, orientation ) === -1 ) {
		throw new TypeError( 'invalid value. `yAxisOrient` must be one of `[' + ORIENTATIONS.join(',') + ']`. Value: `' + orientation + '.`' );
	}
	if ( orientation !== this._yAxisOrient ) {
		debug( 'Current value: %s.', this._yAxisOrient );

		this._yAxisOrient = orientation;
		debug( 'New value: %s.', this._yAxisOrient );

		this.emit( 'change' );
	}
}

// EXPORTS //

module.exports = set;
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var discreteUniform = require( '@stdlib/random/base/discrete-uniform' );
var isObject = require( '@stdlib/assert/is-object' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var pkg = require( './../package.json' ).name;
var leveneTest = require( './../lib' );

// MAIN //

bench( pkg, function benchmark( b ) {
	var result;
	var len;
	var x;
	var y;
	var z;
	var i;

	x = new Array( 50 );
	y = new Array( 50 );
	z = new Array( 50 );
	len = x.length;
	for ( i = 0; i < len; i++ ) {
		x[ i ] = ( randu()*50.0 );
		y[ i ] = ( randu()*50.0 ) + 10.0;
		z[ i ] = ( randu()*50.0 ) + 20.0;
	}

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		y[ i % y.length ] = ( randu()*50.0 ) + 10.0;
		result = leveneTest( x, y, z );
		if ( typeof result !== 'object' ) {
			b.fail( 'should return an object' );
		}
	}
	b.toc();
	if ( !isObject( result ) ) {
		b.fail( 'should return an object' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::groups', function benchmark( b ) {
	var result;
	var group;
	var vals;
	var len;
	var i;

	vals = new Array( 150 );
	group = new Array( 150 );
	len = vals.length;
	for ( i = 0; i < len; i++ ) {
		group[ i ] = discreteUniform( 0, 2 );
		vals[ i ] = ( randu()*50.0 ) + ( 10.0*group[ i ] );
	}

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		vals[ i % vals.length ] = ( randu()*50.0 ) + ( 10.0*group[ i ] );
		result = leveneTest( vals, {
			'groups': group
		});
		if ( typeof result !== 'object' ) {
			b.fail( 'should return an object' );
		}
	}
	b.toc();
	if ( !isObject( result ) ) {
		b.fail( 'should return an object' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':print', function benchmark( b ) {
	var digits;
	var result;
	var output;
	var group;
	var vals;
	var len;
	var i;

	vals = new Array( 100 );
	group = new Array( 100 );
	len = vals.length;
	for ( i = 0; i < len; i++ ) {
		group[ i ] = discreteUniform( 0, 2 );
		vals[ i ] = ( randu()*50.0 ) + ( 10.0*group[ i ] );
	}
	result = leveneTest( vals, {
		'groups': group
	});

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		digits = ( i % 8 ) + 1;
		output = result.print({
			'digits': digits
		});
		if ( typeof output !== 'string' ) {
			b.fail( 'should return a string' );
		}
	}
	b.toc();
	if ( !isString( output ) ) {
		b.fail( 'should return a string' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<commit_msg>Avoid de-optimizations due to sparse arrays<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var discreteUniform = require( '@stdlib/random/base/discrete-uniform' );
var isObject = require( '@stdlib/assert/is-object' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var pkg = require( './../package.json' ).name;
var leveneTest = require( './../lib' );

// MAIN //

bench( pkg, function benchmark( b ) {
	var result;
	var x;
	var y;
	var z;
	var i;

	x = [];
	y = [];
	z = [];
	for ( i = 0; i < 50; i++ ) {
		x.push( ( randu()*50.0 ) );
		y.push( ( randu()*50.0 ) + 10.0 );
		z.push( ( randu()*50.0 ) + 20.0 );
	}

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		y[ i%y.length ] = ( randu()*50.0 ) + 10.0;
		result = leveneTest( x, y, z );
		if ( typeof result !== 'object' ) {
			b.fail( 'should return an object' );
		}
	}
	b.toc();
	if ( !isObject( result ) ) {
		b.fail( 'should return an object' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::groups', function benchmark( b ) {
	var result;
	var group;
	var v;
	var i;

	v = [];
	group = [];
	for ( i = 0; i < 150; i++ ) {
		group[ i ] = discreteUniform( 0, 2 );
		v[ i ] = ( randu()*50.0 ) + ( 10.0*group[ i ] );
	}

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		v[ i%v.length ] = ( randu()*50.0 ) + ( 10.0*group[ i%group.length ] );
		result = leveneTest( v, {
			'groups': group
		});
		if ( typeof result !== 'object' ) {
			b.fail( 'should return an object' );
		}
	}
	b.toc();
	if ( !isObject( result ) ) {
		b.fail( 'should return an object' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+':print', function benchmark( b ) {
	var digits;
	var result;
	var output;
	var group;
	var v;
	var i;

	v = [];
	group = [];
	for ( i = 0; i < 100; i++ ) {
		group[ i ] = discreteUniform( 0, 2 );
		v[ i ] = ( randu()*50.0 ) + ( 10.0*group[ i ] );
	}
	result = leveneTest( v, {
		'groups': group
	});

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		digits = ( i%8 ) + 1;
		output = result.print({
			'digits': digits
		});
		if ( typeof output !== 'string' ) {
			b.fail( 'should return a string' );
		}
	}
	b.toc();
	if ( !isString( output ) ) {
		b.fail( 'should return a string' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<|endoftext|>


<commit_before>$(document).on('ready', function() {

    var bulkActionForm = $('.bulk-actions');
    if (bulkActionForm.length) {
        bulkActionForm.submit(function (e) {
            var action = $('.bulk-actions .bulk-action-submit select').val();
            if (!action) {
                return e.preventDefault();
            }

            bulkActionForm.attr('action', action);
        });
    }

    $('[role=datetime-picker]').each(function() {
        $(this).datetimepicker({
            locale: $(this).data('locale'),
            format: $(this).data('format'),
            date: new Date($(this).data('timestamp') * 1000)
        });
    });

    $('select:not(.autocomplete, .no-selectize)').selectize({plugins: ['remove_button']});

    $('input.autocomplete, select.autocomplete').each(function (i, e) {
        e = $(e);
        e.selectize({
            maxItems: 1,
            create: !$(e).data('exact-match'),
            persist: false,
            render: {
                'option_create': function(data, escape) {
                    return '
🔍  ' + escape(data.input) + '…
';
                }
            },
            load: function (query, callback) {
                var data = {};

                data[e.data('filter-field') || e.attr('name')] = query;

                if (e.data('dependent-on') && $('#' + e.data('dependent-on')).val()) {
                    data[e.data('dependent-on-field')] = $('#' + e.data('dependent-on')).val();
                }
                $.ajax({
                    url: e.data('url'),
                    dataType: 'json',
                    data: data,
                    error: function() {
                        callback();
                    },
                    success: function(res) {
                        callback($.map(res.data, function (name, id) {
                            return {value: id, text: name};
                        }));
                    }
                });
            }
        });
    });

    $.DirtyForms.dialog = false;
    $('form[data-dirty-check=1]').dirtyForms();

    $('.dropdown-toggle').dropdown();

    // recommended hack to get dropdowns correctly work inside responsive table
    $('.table-responsive').on('show.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "inherit" );
    });
    $('.table-responsive').on('hide.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "auto" );
    })
});
<commit_msg>Added support for default empty datetime value<commit_after>$(document).on('ready', function() {

    var bulkActionForm = $('.bulk-actions');
    if (bulkActionForm.length) {
        bulkActionForm.submit(function (e) {
            var action = $('.bulk-actions .bulk-action-submit select').val();
            if (!action) {
                return e.preventDefault();
            }

            bulkActionForm.attr('action', action);
        });
    }

    $('[role=datetime-picker]').each(function() {
        var date = new Date($(this).data('timestamp') * 1000);
        if ($(this).data('timestamp') === '') {
            date = '' ;
        };
        $(this).datetimepicker({
            locale: $(this).data('locale'),
            format: $(this).data('format'),
            date: date
        });
    });

    $('select:not(.autocomplete, .no-selectize)').selectize({plugins: ['remove_button']});

    $('input.autocomplete, select.autocomplete').each(function (i, e) {
        e = $(e);
        e.selectize({
            maxItems: 1,
            create: !$(e).data('exact-match'),
            persist: false,
            render: {
                'option_create': function(data, escape) {
                    return '
🔍  ' + escape(data.input) + '…
';
                }
            },
            load: function (query, callback) {
                var data = {};

                data[e.data('filter-field') || e.attr('name')] = query;

                if (e.data('dependent-on') && $('#' + e.data('dependent-on')).val()) {
                    data[e.data('dependent-on-field')] = $('#' + e.data('dependent-on')).val();
                }
                $.ajax({
                    url: e.data('url'),
                    dataType: 'json',
                    data: data,
                    error: function() {
                        callback();
                    },
                    success: function(res) {
                        callback($.map(res.data, function (name, id) {
                            return {value: id, text: name};
                        }));
                    }
                });
            }
        });
    });

    $.DirtyForms.dialog = false;
    $('form[data-dirty-check=1]').dirtyForms();

    $('.dropdown-toggle').dropdown();

    // recommended hack to get dropdowns correctly work inside responsive table
    $('.table-responsive').on('show.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "inherit" );
    });
    $('.table-responsive').on('hide.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "auto" );
    })
});
<|endoftext|>


<commit_before>(function(exports){

  var Project = Backbone.Model.extend({
    urlRoot: "/api/projects/",
    defaults: {
      name: "",
      description: "",
      url: "",
      slug: "",
    },
  });

  var ProjectCollection = Backbone.Collection.extend({
    url: "/api/projects/",
    model: Project,
  });

  var AddProjectView = Backbone.View.extend({
    el: "#addProjectContainer",
    template: _.template($("#addProjectTemplate").html()),
    initialize: function(collection){
      this.collection = collection;
      _.bindAll(this, 'render');
      console.log("Initialized.");
      this.render()
    },
    render: function(){
      console.log("Rendering.");
      this.$el.html(this.template());
    },
    addProject: function(event){
      console.log("Submitting");
      event.preventDefault();
      var formObjects = ajaxForms.toJson($("#addProjectForm"));
      this.collection.add(formObjects);
    },
    events: {
      "submit #addProjectForm": "addProject",
    }
  });

  var ProjectView = Backbone.View.extend({
    el: "#projects",
    template: _.template($("#indexProjectItem").html()),
    initialize: function(model){
      this.model = model;
      _.bindAll(this, 'render');
      var that = this;
      this.render();
    },
    render: function(){
      this.$el.append(this.template(this.model.toJSON()));
    },
  });

  var ProjectCollectionView = Backbone.View.extend({
    initialize: function(collection){
      this.collection = collection;
      window.collection = collection;
      _.bindAll(this, 'render');
      var that = this;
      this.collection.fetch({
        success: function(){
          that.render();
        }
      });
    },
    render: function(){
      this.collection.each(function(project){
        var projectView = new ProjectView(project);
      });
    },
  });

  var ProjectRouter = Backbone.Router.extend({
    routes: {
      "": "index",
    },
    index: function(){
      var projectCollection = new ProjectCollection();
      var collectionView = new ProjectCollectionView(projectCollection);
      var addProjectView = new AddProjectView(collection);
    },
  });

  $(document).ready(function(){
    var appRouter = new ProjectRouter();
    Backbone.history.start();
  });

})(this.projects = {});
<commit_msg>Project saves on form submit.<commit_after>(function(exports){

  var Project = Backbone.Model.extend({
    urlRoot: "/api/projects/",
    defaults: {
      name: "",
      description: "",
      url: "",
      slug: "",
    },
  });

  var ProjectCollection = Backbone.Collection.extend({
    url: "/api/projects/",
    model: Project,
  });

  var AddProjectView = Backbone.View.extend({
    el: "#addProjectContainer",
    template: _.template($("#addProjectTemplate").html()),
    initialize: function(collection){
      this.collection = collection;
      _.bindAll(this, 'render');
      console.log("Initialized.");
      this.render()
    },
    render: function(){
      console.log("Rendering.");
      this.$el.html(this.template());
    },
    addProject: function(event){
      console.log("Submitting");
      event.preventDefault();
      var formObjects = ajaxForms.toJson($("#addProjectForm"));
      var newProject = new Project(formObjects);
      window.newProject = newProject;
      this.collection.add(newProject);
      newProject.save({}, {
        success: function(){
          console.log("success");
        },
        failure: function(){
          console.log("failure");
        },
      });
    },
    events: {
      "submit #addProjectForm": "addProject",
    }
  });

  var ProjectView = Backbone.View.extend({
    el: "#projects",
    template: _.template($("#indexProjectItem").html()),
    initialize: function(model){
      this.model = model;
      _.bindAll(this, 'render');
      var that = this;
      this.render();
    },
    render: function(){
      this.$el.append(this.template(this.model.toJSON()));
    },
  });

  var ProjectCollectionView = Backbone.View.extend({
    initialize: function(collection){
      this.collection = collection;
      window.collection = collection;
      _.bindAll(this, 'render');
      var that = this;
      this.collection.fetch({
        success: function(){
          that.render();
        }
      });
    },
    render: function(){
      this.collection.each(function(project){
        var projectView = new ProjectView(project);
      });
    },
  });

  var ProjectRouter = Backbone.Router.extend({
    routes: {
      "": "index",
    },
    index: function(){
      var projectCollection = new ProjectCollection();
      var collectionView = new ProjectCollectionView(projectCollection);
      var addProjectView = new AddProjectView(collection);
    },
  });

  $(document).ready(function(){
    var appRouter = new ProjectRouter();
    Backbone.history.start();
  });

})(this.projects = {});
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {
var argFetch = exports;

var dom = require('gcli/util').dom;
var Status = require('gcli/types').Status;

var getField = require('gcli/ui/field').getField;
var Templater = require('gcli/ui/domtemplate').Templater;

var editorCss = require('text!gcli/ui/arg_fetch.css');
var argFetchHtml = require('text!gcli/ui/arg_fetch.html');

/**
 * A widget to display an inline dialog which allows the user to fill out
 * the arguments to a command.
 * @param options An object containing the customizations, which include:
 * - document: The document to use in creating widgets
 * - requisition: The Requisition to fill out
 * - argFetcherClass: Custom class name when generating the top level element
 *   which allows different layout systems
 */
function ArgFetcher(options) {
  this.document = options.document || document;
  this.requisition = options.requisition;

  // FF can be really hard to debug if doc is null, so we check early on
  if (!this.document) {
    throw new Error('No document');
  }

  this.element =  dom.createElement(this.document, 'div');
  this.element.className = options.argFetcherClass || 'gcliArgFetcher';
  // We cache the fields we create so we can destroy them later
  this.fields = [];

  this.tmpl = new Templater();
  // Populated by template
  this.okElement = null;

  // Pull the HTML into the DOM, but don't add it to the document
  if (editorCss != null) {
    this.style = dom.importCss(editorCss, this.document);
  }

  var templates = dom.createElement(this.document, 'div');
  dom.setInnerHtml(templates, argFetchHtml);
  this.reqTempl = templates.querySelector('#gcliReqTempl');

  this.requisition.commandChange.add(this.onCommandChange, this);
  this.requisition.inputChange.add(this.onInputChange, this);

  this.onCommandChange();
}

/**
 * Avoid memory leaks
 */
ArgFetcher.prototype.destroy = function() {
  this.requisition.inputChange.remove(this.onInputChange, this);
  this.requisition.commandChange.remove(this.onCommandChange, this);

  if (this.style) {
    this.style.parentNode.removeChild(this.style);
    delete this.style;
  }

  this.fields.forEach(function(field) { field.destroy(); });

  delete this.document;
  delete this.element;
  delete this.okElement;
  delete this.reqTempl;
};

/**
 * Called whenever the command part of the requisition changes
 */
ArgFetcher.prototype.onCommandChange = function(ev) {
  var command = this.requisition.commandAssignment.getValue();
  if (!command || !command.exec) {
    this.element.style.display = 'none';
  }
  else {
    if (ev && ev.oldValue === ev.newValue) {
      // Just the text has changed
      return;
    }

    this.fields.forEach(function(field) { field.destroy(); });
    this.fields = [];

    var reqEle = this.reqTempl.cloneNode(true);
    this.tmpl.processNode(reqEle, this);
    dom.clearElement(this.element);
    this.element.appendChild(reqEle);

    var status = this.requisition.getStatus();
    this.okElement.disabled = (status === Status.VALID);

    this.element.style.display = 'block';
  }
};

/**
 * Called whenever the text input of the requisition changes
 */
ArgFetcher.prototype.onInputChange = function(ev) {
  var command = this.requisition.commandAssignment.getValue();
  if (command && command.exec) {
    var status = this.requisition.getStatus();
    this.okElement.disabled = (status !== Status.VALID);
  }
};

/**
 * Called by the template process in #onCommandChange() to get an instance
 * of field for each assignment.
 */
ArgFetcher.prototype.getInputFor = function(assignment) {
  var newField = getField(assignment.param.type, {
    document: this.document,
    type: assignment.param.type,
    name: assignment.param.name,
    requisition: this.requisition,
    required: assignment.param.isDataRequired(),
    named: !assignment.param.isPositionalAllowed()
  });

  // BUG 664198 - remove on delete
  newField.fieldChanged.add(function(ev) {
    assignment.setConversion(ev.conversion);
  }, this);
  assignment.assignmentChange.add(function(ev) {
    newField.setConversion(ev.conversion);
  }.bind(this));

  this.fields.push(newField);
  newField.setConversion(this.assignment.conversion);

  // Bug 681894: we add the field as a property of the assignment so that
  // #linkMessageElement() can call 'field.setMessageElement(element)'
  assignment.field = newField;

  return newField.element;
};

/**
 * Called by the template to setup an mutable message field
 */
ArgFetcher.prototype.linkMessageElement = function(assignment, element) {
  // Bug 681894: See comment in getInputFor()
  var field = assignment.field;
  delete assignment.field;
  if (field == null) {
    console.error('Missing field for ' + assignment.param.name);
    return 'Missing field';
  }
  field.setMessageElement(element);
  return '';
};

/**
 * Event handler added by the template menu.html
 */
ArgFetcher.prototype.onFormOk = function(ev) {
  this.requisition.exec();
};

/**
 * Event handler added by the template menu.html
 */
ArgFetcher.prototype.onFormCancel = function(ev) {
  this.requisition.clear();
};

argFetch.ArgFetcher = ArgFetcher;

});
<commit_msg>Bug 692742 (noscroll): Wrap getInputFor in try/catch It's called from an eval inside the template engine which makes debugging tricky because the template engine can't assume anything nice like console so we do our own logging here<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {
var argFetch = exports;

var dom = require('gcli/util').dom;
var Status = require('gcli/types').Status;

var getField = require('gcli/ui/field').getField;
var Templater = require('gcli/ui/domtemplate').Templater;

var editorCss = require('text!gcli/ui/arg_fetch.css');
var argFetchHtml = require('text!gcli/ui/arg_fetch.html');

/**
 * A widget to display an inline dialog which allows the user to fill out
 * the arguments to a command.
 * @param options An object containing the customizations, which include:
 * - document: The document to use in creating widgets
 * - requisition: The Requisition to fill out
 * - argFetcherClass: Custom class name when generating the top level element
 *   which allows different layout systems
 */
function ArgFetcher(options) {
  this.document = options.document || document;
  this.requisition = options.requisition;

  // FF can be really hard to debug if doc is null, so we check early on
  if (!this.document) {
    throw new Error('No document');
  }

  this.element =  dom.createElement(this.document, 'div');
  this.element.className = options.argFetcherClass || 'gcliArgFetcher';
  // We cache the fields we create so we can destroy them later
  this.fields = [];

  this.tmpl = new Templater();
  // Populated by template
  this.okElement = null;

  // Pull the HTML into the DOM, but don't add it to the document
  if (editorCss != null) {
    this.style = dom.importCss(editorCss, this.document);
  }

  var templates = dom.createElement(this.document, 'div');
  dom.setInnerHtml(templates, argFetchHtml);
  this.reqTempl = templates.querySelector('#gcliReqTempl');

  this.requisition.commandChange.add(this.onCommandChange, this);
  this.requisition.inputChange.add(this.onInputChange, this);

  this.onCommandChange();
}

/**
 * Avoid memory leaks
 */
ArgFetcher.prototype.destroy = function() {
  this.requisition.inputChange.remove(this.onInputChange, this);
  this.requisition.commandChange.remove(this.onCommandChange, this);

  if (this.style) {
    this.style.parentNode.removeChild(this.style);
    delete this.style;
  }

  this.fields.forEach(function(field) { field.destroy(); });

  delete this.document;
  delete this.element;
  delete this.okElement;
  delete this.reqTempl;
};

/**
 * Called whenever the command part of the requisition changes
 */
ArgFetcher.prototype.onCommandChange = function(ev) {
  var command = this.requisition.commandAssignment.getValue();
  if (!command || !command.exec) {
    this.element.style.display = 'none';
  }
  else {
    if (ev && ev.oldValue === ev.newValue) {
      // Just the text has changed
      return;
    }

    this.fields.forEach(function(field) { field.destroy(); });
    this.fields = [];

    var reqEle = this.reqTempl.cloneNode(true);
    this.tmpl.processNode(reqEle, this);
    dom.clearElement(this.element);
    this.element.appendChild(reqEle);

    var status = this.requisition.getStatus();
    this.okElement.disabled = (status === Status.VALID);

    this.element.style.display = 'block';
  }
};

/**
 * Called whenever the text input of the requisition changes
 */
ArgFetcher.prototype.onInputChange = function(ev) {
  var command = this.requisition.commandAssignment.getValue();
  if (command && command.exec) {
    var status = this.requisition.getStatus();
    this.okElement.disabled = (status !== Status.VALID);
  }
};

/**
 * Called by the template process in #onCommandChange() to get an instance
 * of field for each assignment.
 */
ArgFetcher.prototype.getInputFor = function(assignment) {
  try {
    var newField = getField(assignment.param.type, {
      document: this.document,
      type: assignment.param.type,
      name: assignment.param.name,
      requisition: this.requisition,
      required: assignment.param.isDataRequired(),
      named: !assignment.param.isPositionalAllowed()
    });

    // BUG 664198 - remove on delete
    newField.fieldChanged.add(function(ev) {
      assignment.setConversion(ev.conversion);
    }, this);
    assignment.assignmentChange.add(function(ev) {
      newField.setConversion(ev.conversion);
    }.bind(this));

    this.fields.push(newField);
    newField.setConversion(this.assignment.conversion);

    // Bug 681894: we add the field as a property of the assignment so that
    // #linkMessageElement() can call 'field.setMessageElement(element)'
    assignment.field = newField;

    return newField.element;
  }
  catch (ex) {
    // This is called from within Templater which can make tracing errors hard
    // so we log here if anything goes wrong
    console.error(ex);
    return '';
  }
};

/**
 * Called by the template to setup an mutable message field
 */
ArgFetcher.prototype.linkMessageElement = function(assignment, element) {
  // Bug 681894: See comment in getInputFor()
  var field = assignment.field;
  delete assignment.field;
  if (field == null) {
    console.error('Missing field for ' + assignment.param.name);
    return 'Missing field';
  }
  field.setMessageElement(element);
  return '';
};

/**
 * Event handler added by the template menu.html
 */
ArgFetcher.prototype.onFormOk = function(ev) {
  this.requisition.exec();
};

/**
 * Event handler added by the template menu.html
 */
ArgFetcher.prototype.onFormCancel = function(ev) {
  this.requisition.clear();
};

/**
 * Change how much vertical space this dialog can take up
 */
ArgFetcher.prototype.setMaxHeight = function(height, isTooBig) {
  this.fields.forEach(function(field) {
    if (field.menu) {
      // Magic number alert: 105 is roughly the size taken up by the rest of
      // the dialog for the '{' command. We could spend ages calculating 105
      // by doing math on the various components that contribute to the 105,
      // but I don't think that would make it significantly less fragile under
      // refactoring. Plus this works.
      field.menu.setMaxHeight(height - 105);
    }
  });
};

argFetch.ArgFetcher = ArgFetcher;

});
<|endoftext|>


<commit_before>"use strict";

const Telegraf = require("telegraf");
const { Telegram } = require("telegraf");
const { json } = require("req");
const cowsay = require("cowsay");
// const cron = require("node-cron");
const key = process.argv[2];
const readline = require("readline");
const Danbooru = require("danbooru");
// const fs = require("fs");

const args = text => text.split(" ").slice(1);
const argstring = text => args(text).join(" ").trim();

const bot = new Telegraf(key);
bot.telegram.getMe().then(data =>
	bot.options.username = data.username);

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
	prompt: "chat: "
});

const tg = new Telegram(key);

const booru = new Danbooru();

const feature = ({ reply }) =>
	reply("This feature is either under construction " +
	"or I'm too retarded to implement it");

const cow = `

         (__)
         (oo)
   /------\\/
  / |    ||
 *  /\\---/\\
    ~~   ~~
...."Have you mooed today?"...
`;

const cows = ["beavis.zen", "bong", "bud-frogs", "bunny", "cheese", "cower", "daemon", "default", "doge", "dragon-and-cow", "dragon", "elephant-in-snake", "elephant", "eyes", "flaming-sheep", "ghostbusters", "goat", "head-in", "hedgehog", "hellokitty", "kiss", "kitty", "koala", "kosh", "luke-koala", "mech-and-cow", "meow", "milk", "moofasa", "moose", "mutilated", "ren", "satanic", "sheep", "skeleton", "small", "sodomized", "squirrel", "stegosaurus", "stimpy", "supermilker", "surgery", "telebears", "turkey", "turtle", "tux", "vader-koala", "vader", "whale", "www"];

bot.command("start", ({ reply }) =>
	reply("fuck off"));

bot.command("moo", ({ reply }) =>
	reply(cow, { parse_mode: "HTML" }));

bot.command("test", feature);

bot.command("rogue", feature);

bot.command("info", feature);

bot.command("danbooru", ({ message, reply, replyWithPhoto }) => {
	const tags = args(message.text);
	let errors = "Following errors occured:\n";
	if(tags == "")
		reply("you forgot to specify tags retard");
	else booru.posts(tags)
		.then(posts => posts[Math.floor(Math.random()*posts.length)])
		.then(post => booru.posts.get(post))
		.catch(function(e) {
			errors += e + "\n";
		})
		.then(postInfo => {
			const file = postInfo.file;
			const caption = `Post ID: ${postInfo.id}\n` +
			`Artist: ${postInfo.tags.artist}\n` +
			`Characters: ${postInfo.tags.character}\n` +
			`Copyright info: ${postInfo.tags.copyright}`;
			if(!("request" in file))
				reply("image unavailable\n" + caption);
			else replyWithPhoto(`https://danbooru.donmai.us/data/${file.name}`, { caption })
				.catch(function(e) {
					if(e.toString().includes("400"))
						replyWithPhoto(`https://danbooru.donmai.us/cached/data/${file.name}`, { caption });
					else {
						errors += e + " (image unavailable)\n";
						reply(errors);
					}
				});
		})
		.catch(function(e) {
			errors += e + "\n";
			reply(errors + "You propably used nonexisting tags.");
		});
});

bot.command("price", ({ message, reply }) => {
	if(args(message.text)[0] == undefined)
		reply("input a valid ticker symbol retard");
	else json("https://api.coinmarketcap.com/v1/ticker/?limit=0")
		.then(crap => crap.find(obj =>
			obj.symbol === args(message.text)[0].toUpperCase()))
		.then(balls => {
			if(balls == undefined)
				reply("input a valid ticker symbol retard");
			else balls.percent_change_24h.includes("-")
				? reply(balls.name + ": " + balls.price_usd + "$ " + balls.percent_change_24h + "% 📉")
				: reply(balls.name + ": " + balls.price_usd + "$ +" + balls.percent_change_24h + "% 📈");
		});
});

bot.command("weather", ({ message, reply }) => {
	const K = 273.15;
	const icons = {
		"01d": "☀", "01n": "🌕",
		"02d": "🌤", "02n": "🌤",
		"03d": "⛅", "03n": "⛅",
		"04d": "☁", "04n": "☁",
		"09d": "🌧", "09n": "🌧",
		"10d": "🌦", "10n": "🌦",
		"11d": "🌩", "11n": "🌩",
		"13d": "🌨", "13n": "🌨",
		"50d": "🌫", "50n": "🌫"
	};
	return json("http://api.openweathermap.org/data/2.5/weather?q=" +
		encodeURIComponent(argstring(message.text)) +
		"&APPID=1566ed87c9944f0df94332da29ee817c").then(data =>
		data.cod !== 200
			? reply(`Error:\n${data.cod}: ${data.message}`)
			: reply(
				"Weather in " +
				data.name + ", " +
				data.sys.country + ": " +
				Math.floor(data.main.temp - K) + "°C, " +
				data.weather[0].description + " " +
				(icons[data.weather[0].icon] || "") + "\n" +
				" Humidity: " + Math.floor(data.main.humidity) + "%\n" +
				" Air pressure: " + Math.floor(data.main.pressure) + " hPa"));
});

bot.command("skelet", ({ reply }) => {
	let skelets = "";
	for (let i = 0; i < Math.floor((Math.random() * 20) + 1 ); i++)
		skelets += Math.random() < 0.5 ? "💀" : "☠";
	return reply(skelets);
});

bot.command("cowsay", ({ message, reply }) => {
	const arg = args(message.text);
	let text = arg.slice();
	let notCow = false;
	text.splice(0,1);
	if(arg[0] == undefined) {
		reply("specify animal and/or text");
	} else {
		for(let i = 0; i < cows.length; i++){
			if(arg[0].includes(cows[i])) {
				reply("```" + cowsay.say({
					text : text.join(" ") || "I'm too dumb to type some text",
					f : arg[0]
				}) + "```", { parse_mode: "Markdown" });
				notCow = true;
				break;
			} else continue;
		} if(arg[0].includes("list") && notCow === false) {
			reply(cows);
		} else if(notCow === false) {
			reply("```" + cowsay.say({
				text : arg.join(" ") || "Have you mooed today?",
			}) + "```", { parse_mode: "Markdown" });
		}
	}
});

bot.on("text", ({ message, replyWithSticker, reply, tg }) => {
	let msg = message.chat.title + "\n" + message.from.username + ": " + message.text;
	if (message.from.username == undefined)
		msg = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.text;
	if(message.chat.id == "-1001144567507") {
		tg.sendMessage("-1001064029829", msg);
	} else tg.sendMessage("-1001144567507", msg);
	const text = message.text.toLowerCase();
	if(message.from.id == 353196474 && text.includes("nice") || message.from.id == 128432371 && text.includes("nice"))
		replyWithSticker("CAADBAADPwADulkNFYeAzy5ClSxjAg");
	else if(text == undefined)
		reply("unknown error");
});

bot.on("photo", ({ message, tg }) => {
	let caption = message.chat.title + "\n" + message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id == "-1001144567507"){
		tg.sendPhoto("-1001064029829", message.photo[0].file_id, { caption });
	} else {
		tg.sendPhoto("-1001144567507", message.photo[0].file_id, { caption });
	}
});

bot.on("video", ({ message, tg }) => {
	let caption = message.chat.title + "\n" + message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id == "-1001144567507"){
		tg.sendVideo("-1001064029829", message.video.file_id, { caption });
	} else {
		tg.sendVideo("-1001144567507", message.video.file_id, { caption });
	}
});

bot.on("document", ({ message, tg }) => {
	let caption = message.chat.title + "\n" + message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id == "-1001144567507"){
		tg.sendDocument("-1001064029829", message.document.file_id, { caption });
	} else {
		tg.sendDocument("-1001144567507", message.document.file_id, { caption });
	}
});

let id = "-1001144567507";
rl.prompt();
rl.on("line", (line) => {
	switch (line.trim()) {
	case "/setchat":
		rl.question("set chat id: ", (setid) => {
			id = setid;
			rl.prompt();
		});
		break;
	default:
		tg.sendMessage(id, `${line.trim()}`);
		break;
	}
	rl.prompt();
});

bot.startPolling();
<commit_msg>handle some rejections<commit_after>"use strict";

const Telegraf = require("telegraf");
const { Telegram } = require("telegraf");
const { json } = require("req");
const cowsay = require("cowsay");
// const cron = require("node-cron");
const key = process.argv[2];
const readline = require("readline");
const Danbooru = require("danbooru");
// const fs = require("fs");

const args = text => text.split(" ").slice(1);
const argstring = text => args(text).join(" ").trim();

const bot = new Telegraf(key);
bot.telegram.getMe().then(data =>
	bot.options.username = data.username);

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
	prompt: "chat: "
});

const tg = new Telegram(key);

const booru = new Danbooru();

const feature = ({ reply }) =>
	reply("This feature is either under construction " +
	"or I'm too retarded to implement it");

const cow = `

         (__)
         (oo)
   /------\\/
  / |    ||
 *  /\\---/\\
    ~~   ~~
...."Have you mooed today?"...
`;

const cows = ["beavis.zen", "bong", "bud-frogs", "bunny", "cheese", "cower", "daemon", "default", "doge", "dragon-and-cow", "dragon", "elephant-in-snake", "elephant", "eyes", "flaming-sheep", "ghostbusters", "goat", "head-in", "hedgehog", "hellokitty", "kiss", "kitty", "koala", "kosh", "luke-koala", "mech-and-cow", "meow", "milk", "moofasa", "moose", "mutilated", "ren", "satanic", "sheep", "skeleton", "small", "sodomized", "squirrel", "stegosaurus", "stimpy", "supermilker", "surgery", "telebears", "turkey", "turtle", "tux", "vader-koala", "vader", "whale", "www"];

bot.command("start", ({ reply }) =>
	reply("fuck off"));

bot.command("moo", ({ reply }) =>
	reply(cow, { parse_mode: "HTML" }));

bot.command("test", feature);

bot.command("rogue", feature);

bot.command("info", feature);

bot.command("danbooru", ({ message, reply, replyWithPhoto }) => {
	const tags = args(message.text);
	let errors = "Following errors occured:\n";
	if(tags == "")
		reply("you forgot to specify tags retard");
	else booru.posts(tags)
		.then(posts => posts[Math.floor(Math.random()*posts.length)])
		.then(post => booru.posts.get(post))
		.catch(function(e) {
			errors += e + "\n";
		})
		.then(postInfo => {
			const file = postInfo.file;
			const caption = `Post ID: ${postInfo.id}\n` +
			`Artist: ${postInfo.tags.artist}\n` +
			`Characters: ${postInfo.tags.character}\n` +
			`Copyright info: ${postInfo.tags.copyright}`;
			if(!("request" in file))
				reply("image unavailable\n" + caption);
			else replyWithPhoto(`https://danbooru.donmai.us/data/${file.name}`, { caption })
				.catch(function(e) {
					if(e.toString().includes("400"))
						replyWithPhoto(`https://danbooru.donmai.us/cached/data/${file.name}`, { caption });
					else {
						errors += e + " (image unavailable)\n";
						reply(errors);
					}
				});
		})
		.catch(function(e) {
			errors += e + "\n";
			reply(errors + "You propably used nonexisting tags.");
		});
});

bot.command("price", ({ message, reply }) => {
	if(args(message.text)[0] == undefined)
		reply("input a valid ticker symbol retard");
	else json("https://api.coinmarketcap.com/v1/ticker/?limit=0")
		.then(crap => crap.find(obj =>
			obj.symbol === args(message.text)[0].toUpperCase()))
		.then(balls => {
			if(balls == undefined)
				reply("input a valid ticker symbol retard");
			else balls.percent_change_24h.includes("-")
				? reply(balls.name + ": " + balls.price_usd + "$ " + balls.percent_change_24h + "% 📉")
				: reply(balls.name + ": " + balls.price_usd + "$ +" + balls.percent_change_24h + "% 📈");
		});
});

bot.command("weather", ({ message, reply }) => {
	const K = 273.15;
	const icons = {
		"01d": "☀", "01n": "🌕",
		"02d": "🌤", "02n": "🌤",
		"03d": "⛅", "03n": "⛅",
		"04d": "☁", "04n": "☁",
		"09d": "🌧", "09n": "🌧",
		"10d": "🌦", "10n": "🌦",
		"11d": "🌩", "11n": "🌩",
		"13d": "🌨", "13n": "🌨",
		"50d": "🌫", "50n": "🌫"
	};
	return json("http://api.openweathermap.org/data/2.5/weather?q=" +
		encodeURIComponent(argstring(message.text)) +
		"&APPID=1566ed87c9944f0df94332da29ee817c").then(data =>
		data.cod !== 200
			? reply(`Error:\n${data.cod}: ${data.message}`)
			: reply(
				"Weather in " +
				data.name + ", " +
				data.sys.country + ": " +
				Math.floor(data.main.temp - K) + "°C, " +
				data.weather[0].description + " " +
				(icons[data.weather[0].icon] || "") + "\n" +
				" Humidity: " + Math.floor(data.main.humidity) + "%\n" +
				" Air pressure: " + Math.floor(data.main.pressure) + " hPa"));
});

bot.command("skelet", ({ reply }) => {
	let skelets = "";
	for (let i = 0; i < Math.floor((Math.random() * 20) + 1 ); i++)
		skelets += Math.random() < 0.5 ? "💀" : "☠";
	return reply(skelets);
});

bot.command("cowsay", ({ message, reply }) => {
	const arg = args(message.text);
	let text = arg.slice();
	let notCow = false;
	text.splice(0,1);
	if(arg[0] == undefined) {
		reply("specify animal and/or text");
	} else {
		for(let i = 0; i < cows.length; i++){
			if(arg[0].includes(cows[i])) {
				reply("```" + cowsay.say({
					text : text.join(" ") || "I'm too dumb to type some text",
					f : arg[0]
				}) + "```", { parse_mode: "Markdown" });
				notCow = true;
				break;
			} else continue;
		} if(arg[0].includes("list") && notCow === false) {
			reply(cows);
		} else if(notCow === false) {
			reply("```" + cowsay.say({
				text : arg.join(" ") || "Have you mooed today?",
			}) + "```", { parse_mode: "Markdown" });
		}
	}
});

bot.on("text", ({ message, replyWithSticker, reply, tg }) => {
	let msg = message.chat.title + "\n" + message.from.username + ": " + message.text;
	if (message.from.username == undefined)
		msg = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.text;
	if(message.chat.id == "-1001144567507") {
		tg.sendMessage("-1001064029829", msg);
	} else tg.sendMessage("-1001144567507", msg);
	const text = message.text.toLowerCase();
	if(message.from.id == 353196474 && text.includes("nice") || message.from.id == 128432371 && text.includes("nice"))
		replyWithSticker("CAADBAADPwADulkNFYeAzy5ClSxjAg");
	else if(text == undefined)
		reply("unknown error");
});

bot.on("photo", ({ message, tg }) => {
	let caption = message.chat.title + "\n" + message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id == "-1001144567507"){
		tg.sendPhoto("-1001064029829", message.photo[0].file_id, { caption });
	} else {
		tg.sendPhoto("-1001144567507", message.photo[0].file_id, { caption });
	}
});

bot.on("video", ({ message, tg }) => {
	let caption = message.chat.title + "\n" + message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id == "-1001144567507"){
		tg.sendVideo("-1001064029829", message.video.file_id, { caption });
	} else {
		tg.sendVideo("-1001144567507", message.video.file_id, { caption });
	}
});

bot.on("document", ({ message, tg }) => {
	let caption = message.chat.title + "\n" + message.from.username + ": " + message.caption;
	if (message.from.username == undefined)
		caption = message.chat.title + "\n" + message.from.first_name + " " + message.from.last_name + ": " + message.caption;
	if(message.chat.id == "-1001144567507"){
		tg.sendDocument("-1001064029829", message.document.file_id, { caption });
	} else {
		tg.sendDocument("-1001144567507", message.document.file_id, { caption });
	}
});

let id = "-1001144567507";
rl.prompt();
rl.on("line", (line) => {
	switch (line.trim()) {
	case "/setchat":
		rl.question("set chat id: ", (setid) => {
			id = setid;
			rl.prompt();
		});
		break;
	default:
		tg.sendMessage(id, `${line.trim()}`)
			.catch(function(e){
				console.log(e);
			});
		break;
	}
	rl.prompt();
});

bot.startPolling();
<|endoftext|>


<commit_before>module.exports = function(skill, info, bot, message) {
const { hears, storage: { channels } } = bot;

function privateConvo(bot, message) {
  const { user, channel } = message;

  return (err, convo) => {
    if (err) throw err;

    convo.ask('Do you want to play `paper`, `rock`, or `scissors`?', [
      {
        pattern: 'paper|rock|scissors',
        callback(response, convo) {
          // since no further messages are queued after this,
          // the conversation will end naturally with status === 'completed'
          convo.next();
        },
      }, {
        default: true,
        callback(response, convo) {
          convo.repeat();
          convo.next();
        },
      },
    ], { key: 'rockPaperScissors' }); // store the results in a field called rockPaperScissors

    convo.on('end', (convo) => {
      if (convo.status === 'completed') {
        const prc = convo.extractResponse('rockPaperScissors');

        channels.get(channel, (err, data) => {
          if (err) throw err;

          const updateData = data;
          updateData.players[user].played = prc;

          const { players } = updateData;
          const playerIDs = Object.keys(players);

          // check if only one player has played
          const onlyOnePlayed = playerIDs.find((id) => players[id].played === '');

          if (onlyOnePlayed) {
            channels.save(updateData, (err) => {
              if (err) throw err;

              bot.reply(message, `<@${user}> has played!`);
            });
          } else {
            const gameResults = playerIDs.map((id) => `<@${id}> played ${players[id].played}`);

            bot.reply(message, gameResults.join(' & '));

            // reset the game data
            channels.save({ id: updateData.id }, (err) => {
              if (err) throw err;
            });
          }
        });
      } else {
        // this happens if the conversation ended prematurely for some reason
        bot.reply(message, 'OK, nevermind!');
      }
    });
  };
}

hears(['rps'], 'direct_message,direct_mention,mention', (bot, message) => {
  const { user, channel, text } = message;
  const userData = text.match(/<@([A-Z0-9]{9})>/);

  if (userData) {
    const playerTwo = userData[1];
    const gameData = {
      id: channel,
      players: {
        [user]: {
          accepted: true,
          played: '',
        },
        [playerTwo]: {
          accepted: false,
          played: '',
        },
      },
    };

    channels.save(gameData, (err) => {
      if (err) throw err;

      bot.say({
        text: `<@${playerTwo}> you've been challenged to a game of ROCK:mountain: PAPER:spiral_note_pad: SCISSORS:scissors: by <@${user}>,  say \`accept\` unless you're chicken :chicken:`,
        channel,
      });

      bot.startPrivateConversation(message, privateConvo(bot, message));
    });
  } else {
    bot.reply(message, 'You didn\'t challenge anyone...');
  }
});

hears(['accept'], 'ambient', (bot, message) => {
  const { channel } = message;

  channels.get(channel, (err, data) => {
    if (err) throw err;

    if (data && 'players' in data) {
      const { user } = message;
      const { players } = data;

      if (user in players && !players[user].accepted) {
        bot.reply(message, 'GREAT, LET THE BATTLE BEGIN!!! :mountain::spiral_note_pad::scissors:');

        bot.startPrivateConversation(message, privateConvo(bot, message));
      } else {
        const player = Object.keys(players).find((p) => !players[p].accepted);

        bot.reply(message, `Not you <@${user}>, waiting for <@${player}>.`);
      }
    }
  });
});

};
<commit_msg>Update RPS.js<commit_after>module.exports = function(skill, info, bot, message) {
const { hears, storage: { channels } } = controller;

function privateConvo(bot, message) {
  const { user, channel } = message;

  return (err, convo) => {
    if (err) throw err;

    convo.ask('Do you want to play `paper`, `rock`, or `scissors`?', [
      {
        pattern: 'paper|rock|scissors',
        callback(response, convo) {
          // since no further messages are queued after this,
          // the conversation will end naturally with status === 'completed'
          convo.next();
        },
      }, {
        default: true,
        callback(response, convo) {
          convo.repeat();
          convo.next();
        },
      },
    ], { key: 'rockPaperScissors' }); // store the results in a field called rockPaperScissors

    convo.on('end', (convo) => {
      if (convo.status === 'completed') {
        const prc = convo.extractResponse('rockPaperScissors');

        channels.get(channel, (err, data) => {
          if (err) throw err;

          const updateData = data;
          updateData.players[user].played = prc;

          const { players } = updateData;
          const playerIDs = Object.keys(players);

          // check if only one player has played
          const onlyOnePlayed = playerIDs.find((id) => players[id].played === '');

          if (onlyOnePlayed) {
            channels.save(updateData, (err) => {
              if (err) throw err;

              bot.reply(message, `<@${user}> has played!`);
            });
          } else {
            const gameResults = playerIDs.map((id) => `<@${id}> played ${players[id].played}`);

            bot.reply(message, gameResults.join(' & '));

            // reset the game data
            channels.save({ id: updateData.id }, (err) => {
              if (err) throw err;
            });
          }
        });
      } else {
        // this happens if the conversation ended prematurely for some reason
        bot.reply(message, 'OK, nevermind!');
      }
    });
  };
}

hears(['rps'], 'direct_message,direct_mention,mention', (bot, message) => {
  const { user, channel, text } = message;
  const userData = text.match(/<@([A-Z0-9]{9})>/);

  if (userData) {
    const playerTwo = userData[1];
    const gameData = {
      id: channel,
      players: {
        [user]: {
          accepted: true,
          played: '',
        },
        [playerTwo]: {
          accepted: false,
          played: '',
        },
      },
    };

    channels.save(gameData, (err) => {
      if (err) throw err;

      bot.say({
        text: `<@${playerTwo}> you've been challenged to a game of ROCK:mountain: PAPER:spiral_note_pad: SCISSORS:scissors: by <@${user}>,  say \`accept\` unless you're chicken :chicken:`,
        channel,
      });

      bot.startPrivateConversation(message, privateConvo(bot, message));
    });
  } else {
    bot.reply(message, 'You didn\'t challenge anyone...');
  }
});

hears(['accept'], 'ambient', (bot, message) => {
  const { channel } = message;

  channels.get(channel, (err, data) => {
    if (err) throw err;

    if (data && 'players' in data) {
      const { user } = message;
      const { players } = data;

      if (user in players && !players[user].accepted) {
        bot.reply(message, 'GREAT, LET THE BATTLE BEGIN!!! :mountain::spiral_note_pad::scissors:');

        bot.startPrivateConversation(message, privateConvo(bot, message));
      } else {
        const player = Object.keys(players).find((p) => !players[p].accepted);

        bot.reply(message, `Not you <@${user}>, waiting for <@${player}>.`);
      }
    }
  });
});

};
<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating Kiwifroot Kiwifroot for event blocks.
 * @author rani_sputnik@hotmail.com (Ryan Loader)
 * @author benjamin.p.harding@gmail.com (Benjamin Harding)
 */
'use strict';

goog.provide('Blockly.Kiwifroot.events');

goog.require('Blockly.Kiwifroot');

Blockly.Kiwifroot['kiwi_event_create'] = function(block) {
	var funcName = defineFunctionFromBranch('onCreate', block);

	var bootCode = '//Attach the information to the boot method.\n' +
		'\t//This is to make sure all the components are loaded/attached before executing any code.\n' +
		'\tthis.' + funcName + '();';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.BOOT_END, bootCode);
	return null;
};

Blockly.Kiwifroot['kiwi_event_remove'] = function(block) {
	var funcName = defineFunctionFromBranch('onRemove', block);

	var destructorCode = 'this.'+funcName + '();';
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

	return null;
};

Blockly.Kiwifroot['kiwi_event_constantly'] = function(block){
	var funcName = defineFunctionFromBranch('onUpdate', block);
	var constructorCode = 'this.state.robots.onUpdate.add(this.'+funcName + ', this);';
	var destructorCode = 'this.state.robots.onUpdate.remove(this.'+funcName+ ', this);';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);
	return null;
};

// Pressed / Released

Blockly.Kiwifroot['kiwi_event_stage_input'] = function(block) {

  var dropdown_type = block.getFieldValue( 'TYPE' );

  var funcName = defineFunctionFromBranch('onStageInput', block);

  var constructorCode = 'this.game.input.' + dropdown_type + '.add(this.'+funcName+', this, 25);';
  var destructorCode = 'this.game.input.' + dropdown_type + '.remove(this.'+funcName+', this);';

  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);
  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);
  return null;
};

//Instance Pressed / Released

Blockly.Kiwifroot['kiwi_event_inst_input'] = function(block) {
  // Create an onPressed function with the onPressed section
  var dropdown_type = block.getFieldValue( 'TYPE' );
  var dropdown_namespace = dropdown_type.toUpperCase();

  var t = Blockly.Kiwifroot.INDENT;
  var SECTION_EVENT = 'EVENT_PRESSED_' +dropdown_namespace ;

  var funcName = Blockly.Kiwifroot.provideFunction_(
    ( 'onInstanceInput' + dropdown_namespace ),
    [ Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = function(x, y, timeDown, timeUp, duration, pointer) {',
    	t + 'var point = this.game.cameras.defaultCamera.transformPoint( pointer.point );\n',
        '{{,' + SECTION_EVENT + ',\n}}',
        '};']);
  // Add the add/remove listeners in the constructor/desctructor
  var constructorCode = 'this.game.input.' + dropdown_type + '.add(this.'+funcName+', this, 50);';
  var destructorCode = 'this.game.input.' + dropdown_type + '.remove(this.'+funcName+', this);';

  Blockly.Kiwifroot.provideAdditionOnce('EventInstanceInput' + dropdown_namespace , Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);
  Blockly.Kiwifroot.provideAdditionOnce('EventInstanceInput' + dropdown_namespace , Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  // Add the code into the onPressed function
  var inst = Blockly.Kiwifroot.valueToCode(block, 'INST', Blockly.Kiwifroot.ORDER_ATOMIC) || '(null)';

  var branch = Blockly.Kiwifroot.statementToCode(block, 'STACK');
    var code = 'if ('+inst+'.box.worldHitbox.containsPoint( point )) {\n' + branch + '}';
    code = Blockly.Kiwifroot.prefixLines(code, Blockly.Kiwifroot.INDENT);

  Blockly.Kiwifroot.provideAddition( SECTION_EVENT, code );

  return null;
};

Blockly.Kiwifroot['kiwi_event_key_input'] = function(block) {
  	var dropdown_type = block.getFieldValue( 'TYPE' );
  	var dropdown_namespace = dropdown_type.toUpperCase();

	var t = Blockly.Kiwifroot.INDENT;
	var SECTION_EVENT = 'EVENT_KEY_' + dropdown_namespace;

	var funcName = Blockly.Kiwifroot.provideFunction_(
		( 'onKeyPressed' + dropdown_namespace ),
		[ Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = function(keyCode) {',
        t + 'switch (keyCode) {',
        '{{'+t+t+',' + SECTION_EVENT + ',\n}}',
        t + '}',
        '};']);

	// Add the remove function
	var destructorCode = 'this.game.input.keyboard.' + dropdown_type + '.remove(this.' + funcName + ', this);';
	Blockly.Kiwifroot.provideAdditionOnce('EventKeyInput' + dropdown_namespace, Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

	var constructorCode = 'this.game.input.keyboard.' + dropdown_type + '.add(this.' + funcName + ', this);';
	Blockly.Kiwifroot.provideAdditionOnce('EventKeyInput' + dropdown_namespace, Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);

	// Generate the new function
	var keyCode = Blockly.Kiwifroot.valueToCode(block, 'KEY', Blockly.Kiwifroot.ORDER_ASSIGNMENT);
	var funcName = defineFunctionFromBranch('onKeyInput', block);
	var code = 'case '+keyCode+': this.'+funcName+'(); break;';

	Blockly.Kiwifroot.provideAddition( SECTION_EVENT, code);
	return null;
};

Blockly.Kiwifroot['kiwi_event_time'] = function(block) {

	var funcName = defineFunctionFromBranch('onTick', block);

	var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT);

	var constructorCode = 'this.' + funcName + '_ = this.game.time.clock.setInterval( this.' + funcName + ', ' + tick + ', this);';
	var destructorCode = 'this.game.time.clock.removeTimer( this.' + funcName + '_ );';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR,constructorCode);
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

	return null;
};

Blockly.Kiwifroot['kiwi_event_time_single'] = function(block) {

	var funcName = defineFunctionFromBranch('onSingleTick', block);

	var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT);

	var code = 'this.' + funcName + '_ = this.game.time.clock.setTimeout( function() { \n\t\t if( this.owner) this.' + funcName + '();\n }, ' + tick + ', this);\n';

	return code;
};

Blockly.Kiwifroot['kiwi_event_message'] = function(block) {

	var t = Blockly.Kiwifroot.INDENT;
	var funcName = Blockly.Kiwifroot.provideFunction_(
		'onMessageRecieved',
		[ Blockly.Kiwifroot.FUNCTION_NAME_PLACEHOLDER_ + ' = function( name, message ) {',
        t + 'switch( message ) {',
        '{{'+t+t+',EVENT_MESSAGE_RELEASED,\n}}',
        t + '}',
        '};']);

	var constructorCode = 'this.owner.properties.onUpdate( this.' + funcName + ', this, "_messaging_");';
	Blockly.Kiwifroot.provideAdditionOnce('EventMessageRecieved', Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);

	var funcName = defineFunctionFromBranch('executeMessageRecieved', block);
	var message = Blockly.Kiwifroot.valueToCode(block, 'MESSAGE', Blockly.Kiwifroot.ORDER_ASSIGNMENT);

	// Generate the code for the switch
	var code = 'case ' + message + ': this.'+funcName+'(); break;';
	Blockly.Kiwifroot.provideAddition('EVENT_MESSAGE_RELEASED', code);

	return null;
};

Blockly.Kiwifroot['kiwi_event_animation'] = function(block) {

  	Blockly.Kiwifroot.addAnimationToConstructor_();

  	var value_anim = Blockly.Kiwifroot.valueToCode( block, 'ANIM', Blockly.Kiwifroot.ORDER_ATOMIC );
  	var dropdown_type = block.getFieldValue( 'TYPE' );

	var funcName = defineFunctionFromBranch( 'onAnimation', block );

	var bootCode  = 'var anim = ' + Blockly.Kiwifroot.animation.COMPONENT_PREFIX + '.getAnimation(' + value_anim + ');\n';
		bootCode += '\tif( anim ) {\n';
		bootCode += '\t\tanim.' + dropdown_type + '.add(this.' + funcName + ', this);\n';
		bootCode += '\t}\n';

	var destructorCode  = 'var anim = ' + Blockly.Kiwifroot.animation.COMPONENT_PREFIX + '.getAnimation(' + value_anim + ');\n';
		destructorCode += '\tif( anim ) {\n';
		destructorCode += '\t\tanim.' + dropdown_type + '.remove(this.' + funcName + ', this);\n';
		destructorCode += '\t}\n';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.BOOT, bootCode);
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  	return null;
};

Blockly.Kiwifroot['kiwi_event_touch_on'] = function(block) {

	Blockly.Kiwifroot.arcadephysics.addArcadePhysicsToConstructor_();

  	var value_inst = Blockly.Kiwifroot.valueToCode(block, 'INST', Blockly.Kiwifroot.ORDER_ATOMIC);

	var funcName = Blockly.Kiwifroot.provideFunction_(
		'onTouch',
		[ Blockly.Kiwifroot.FUNCTION_NAME_PLACEHOLDER_ + ' = function( instanceA, instanceB ) {',
        '{{\t,EVENT_TOUCH_ON,\n}}',
        '};']);

  	var code = Blockly.Kiwifroot.arcadephysics.SYSTEM_PREFIX + '.onCollision.add( this.' + funcName + ', this );';
	Blockly.Kiwifroot.provideAdditionOnce( 'EventMessageRecieved', Blockly.Kiwifroot.BOOT, code );

	var code = Blockly.Kiwifroot.arcadephysics.SYSTEM_PREFIX +'.onCollision.remove( this.' + funcName + ', this );';
	Blockly.Kiwifroot.provideAddition( Blockly.Kiwifroot.DESTRUCTOR, code );

	var funcName = defineFunctionFromBranch( 'touchedByInstance', block );
	var code = 'if( instanceA === this.owner && instanceB === ' + value_inst + ' || \n\tinstanceA === ' + value_inst + ' && instanceB === this.owner) {\n\t\t this.' + funcName + '(); \n\t\t }\n';
	Blockly.Kiwifroot.provideAddition('EVENT_TOUCH_ON', code);

  	return null;
};

function defineFunctionFromBranch(desiredName, block){
	// Define a procedure with a return value.
	var funcName = Blockly.Kiwifroot.variableDB_.getDistinctName(desiredName, Blockly.Procedures.NAME_TYPE);
	var branch = Blockly.Kiwifroot.statementToCode(block, 'STACK');
	if (Blockly.Kiwifroot.STATEMENT_PREFIX) {
		branch = Blockly.Kiwifroot.prefixLines(
			Blockly.Kiwifroot.STATEMENT_PREFIX.replace(/%1/g,
			'\'' + block.id + '\''), Blockly.Kiwifroot.INDENT) + branch;
	}
	if (Blockly.Kiwifroot.INFINITE_LOOP_TRAP) {
		branch = Blockly.Kiwifroot.INFINITE_LOOP_TRAP.replace(/%1/g,
			'\'' + block.id + '\'') + branch;
	}
	branch = Blockly.Kiwifroot.scrub_(block, branch);
	var code = funcName + ' = function() {\n' + branch + '};';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DEFINITIONS,code);
	return funcName;
};

<commit_msg>Additional check added to `every x milliseconds` time event<commit_after>/**
 * @license
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating Kiwifroot Kiwifroot for event blocks.
 * @author rani_sputnik@hotmail.com (Ryan Loader)
 * @author benjamin.p.harding@gmail.com (Benjamin Harding)
 */
'use strict';

goog.provide('Blockly.Kiwifroot.events');

goog.require('Blockly.Kiwifroot');

Blockly.Kiwifroot['kiwi_event_create'] = function(block) {
	var funcName = defineFunctionFromBranch('onCreate', block);

	var bootCode = '//Attach the information to the boot method.\n' +
		'\t//This is to make sure all the components are loaded/attached before executing any code.\n' +
		'\tthis.' + funcName + '();';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.BOOT_END, bootCode);
	return null;
};

Blockly.Kiwifroot['kiwi_event_remove'] = function(block) {
	var funcName = defineFunctionFromBranch('onRemove', block);

	var destructorCode = 'this.'+funcName + '();';
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

	return null;
};

Blockly.Kiwifroot['kiwi_event_constantly'] = function(block){
	var funcName = defineFunctionFromBranch('onUpdate', block);
	var constructorCode = 'this.state.robots.onUpdate.add(this.'+funcName + ', this);';
	var destructorCode = 'this.state.robots.onUpdate.remove(this.'+funcName+ ', this);';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);
	return null;
};

// Pressed / Released

Blockly.Kiwifroot['kiwi_event_stage_input'] = function(block) {

  var dropdown_type = block.getFieldValue( 'TYPE' );

  var funcName = defineFunctionFromBranch('onStageInput', block);

  var constructorCode = 'this.game.input.' + dropdown_type + '.add(this.'+funcName+', this, 25);';
  var destructorCode = 'this.game.input.' + dropdown_type + '.remove(this.'+funcName+', this);';

  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);
  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);
  return null;
};

//Instance Pressed / Released

Blockly.Kiwifroot['kiwi_event_inst_input'] = function(block) {
  // Create an onPressed function with the onPressed section
  var dropdown_type = block.getFieldValue( 'TYPE' );
  var dropdown_namespace = dropdown_type.toUpperCase();

  var t = Blockly.Kiwifroot.INDENT;
  var SECTION_EVENT = 'EVENT_PRESSED_' +dropdown_namespace ;

  var funcName = Blockly.Kiwifroot.provideFunction_(
    ( 'onInstanceInput' + dropdown_namespace ),
    [ Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = function(x, y, timeDown, timeUp, duration, pointer) {',
    	t + 'var point = this.game.cameras.defaultCamera.transformPoint( pointer.point );\n',
        '{{,' + SECTION_EVENT + ',\n}}',
        '};']);
  // Add the add/remove listeners in the constructor/desctructor
  var constructorCode = 'this.game.input.' + dropdown_type + '.add(this.'+funcName+', this, 50);';
  var destructorCode = 'this.game.input.' + dropdown_type + '.remove(this.'+funcName+', this);';

  Blockly.Kiwifroot.provideAdditionOnce('EventInstanceInput' + dropdown_namespace , Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);
  Blockly.Kiwifroot.provideAdditionOnce('EventInstanceInput' + dropdown_namespace , Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  // Add the code into the onPressed function
  var inst = Blockly.Kiwifroot.valueToCode(block, 'INST', Blockly.Kiwifroot.ORDER_ATOMIC) || '(null)';

  var branch = Blockly.Kiwifroot.statementToCode(block, 'STACK');
    var code = 'if ('+inst+'.box.worldHitbox.containsPoint( point )) {\n' + branch + '}';
    code = Blockly.Kiwifroot.prefixLines(code, Blockly.Kiwifroot.INDENT);

  Blockly.Kiwifroot.provideAddition( SECTION_EVENT, code );

  return null;
};

Blockly.Kiwifroot['kiwi_event_key_input'] = function(block) {
  	var dropdown_type = block.getFieldValue( 'TYPE' );
  	var dropdown_namespace = dropdown_type.toUpperCase();

	var t = Blockly.Kiwifroot.INDENT;
	var SECTION_EVENT = 'EVENT_KEY_' + dropdown_namespace;

	var funcName = Blockly.Kiwifroot.provideFunction_(
		( 'onKeyPressed' + dropdown_namespace ),
		[ Blockly.JavaScript.FUNCTION_NAME_PLACEHOLDER_ + ' = function(keyCode) {',
        t + 'switch (keyCode) {',
        '{{'+t+t+',' + SECTION_EVENT + ',\n}}',
        t + '}',
        '};']);

	// Add the remove function
	var destructorCode = 'this.game.input.keyboard.' + dropdown_type + '.remove(this.' + funcName + ', this);';
	Blockly.Kiwifroot.provideAdditionOnce('EventKeyInput' + dropdown_namespace, Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

	var constructorCode = 'this.game.input.keyboard.' + dropdown_type + '.add(this.' + funcName + ', this);';
	Blockly.Kiwifroot.provideAdditionOnce('EventKeyInput' + dropdown_namespace, Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);

	// Generate the new function
	var keyCode = Blockly.Kiwifroot.valueToCode(block, 'KEY', Blockly.Kiwifroot.ORDER_ASSIGNMENT);
	var funcName = defineFunctionFromBranch('onKeyInput', block);
	var code = 'case '+keyCode+': this.'+funcName+'(); break;';

	Blockly.Kiwifroot.provideAddition( SECTION_EVENT, code);
	return null;
};

Blockly.Kiwifroot['kiwi_event_time'] = function(block) {

	var funcName = defineFunctionFromBranch('onTick', block);

	var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT);

	var constructorCode = 'this.' + funcName + '_ = this.game.time.clock.setInterval( function() { \n' +
		Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'if( this.owner && this.owner.exists ) {\n' +
		Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'this.' + funcName + '();\n' +
		Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + '}\n' +
		Blockly.Kiwifroot.INDENT + '}, ' + tick + ', this);';
	var destructorCode = 'this.game.time.clock.removeTimer( this.' + funcName + '_ );';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR,constructorCode);
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

	return null;
};

Blockly.Kiwifroot['kiwi_event_time_single'] = function(block) {

	var funcName = defineFunctionFromBranch('onSingleTick', block);

	var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT);

	var code = 'this.' + funcName + '_ = this.game.time.clock.setTimeout( function() { \n' +
		Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'if( this.owner && this.owner.exists ) {\n' +
		Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'this.' + funcName + '();\n' +
		Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + '}\n' +
		Blockly.Kiwifroot.INDENT + '}, ' + tick + ', this);\n';

	return code;
};

Blockly.Kiwifroot['kiwi_event_message'] = function(block) {

	var t = Blockly.Kiwifroot.INDENT;
	var funcName = Blockly.Kiwifroot.provideFunction_(
		'onMessageRecieved',
		[ Blockly.Kiwifroot.FUNCTION_NAME_PLACEHOLDER_ + ' = function( name, message ) {',
        t + 'switch( message ) {',
        '{{'+t+t+',EVENT_MESSAGE_RELEASED,\n}}',
        t + '}',
        '};']);

	var constructorCode = 'this.owner.properties.onUpdate( this.' + funcName + ', this, "_messaging_");';
	Blockly.Kiwifroot.provideAdditionOnce('EventMessageRecieved', Blockly.Kiwifroot.CONSTRUCTOR, constructorCode);

	var funcName = defineFunctionFromBranch('executeMessageRecieved', block);
	var message = Blockly.Kiwifroot.valueToCode(block, 'MESSAGE', Blockly.Kiwifroot.ORDER_ASSIGNMENT);

	// Generate the code for the switch
	var code = 'case ' + message + ': this.'+funcName+'(); break;';
	Blockly.Kiwifroot.provideAddition('EVENT_MESSAGE_RELEASED', code);

	return null;
};

Blockly.Kiwifroot['kiwi_event_animation'] = function(block) {

  	Blockly.Kiwifroot.addAnimationToConstructor_();

  	var value_anim = Blockly.Kiwifroot.valueToCode( block, 'ANIM', Blockly.Kiwifroot.ORDER_ATOMIC );
  	var dropdown_type = block.getFieldValue( 'TYPE' );

	var funcName = defineFunctionFromBranch( 'onAnimation', block );

	var bootCode  = 'var anim = ' + Blockly.Kiwifroot.animation.COMPONENT_PREFIX + '.getAnimation(' + value_anim + ');\n';
		bootCode += '\tif( anim ) {\n';
		bootCode += '\t\tanim.' + dropdown_type + '.add(this.' + funcName + ', this);\n';
		bootCode += '\t}\n';

	var destructorCode  = 'var anim = ' + Blockly.Kiwifroot.animation.COMPONENT_PREFIX + '.getAnimation(' + value_anim + ');\n';
		destructorCode += '\tif( anim ) {\n';
		destructorCode += '\t\tanim.' + dropdown_type + '.remove(this.' + funcName + ', this);\n';
		destructorCode += '\t}\n';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.BOOT, bootCode);
	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  	return null;
};

Blockly.Kiwifroot['kiwi_event_touch_on'] = function(block) {

	Blockly.Kiwifroot.arcadephysics.addArcadePhysicsToConstructor_();

  	var value_inst = Blockly.Kiwifroot.valueToCode(block, 'INST', Blockly.Kiwifroot.ORDER_ATOMIC);

	var funcName = Blockly.Kiwifroot.provideFunction_(
		'onTouch',
		[ Blockly.Kiwifroot.FUNCTION_NAME_PLACEHOLDER_ + ' = function( instanceA, instanceB ) {',
        '{{\t,EVENT_TOUCH_ON,\n}}',
        '};']);

  	var code = Blockly.Kiwifroot.arcadephysics.SYSTEM_PREFIX + '.onCollision.add( this.' + funcName + ', this );';
	Blockly.Kiwifroot.provideAdditionOnce( 'EventMessageRecieved', Blockly.Kiwifroot.BOOT, code );

	var code = Blockly.Kiwifroot.arcadephysics.SYSTEM_PREFIX +'.onCollision.remove( this.' + funcName + ', this );';
	Blockly.Kiwifroot.provideAddition( Blockly.Kiwifroot.DESTRUCTOR, code );

	var funcName = defineFunctionFromBranch( 'touchedByInstance', block );
	var code = 'if( instanceA === this.owner && instanceB === ' + value_inst + ' || \n\tinstanceA === ' + value_inst + ' && instanceB === this.owner) {\n\t\t this.' + funcName + '(); \n\t\t }\n';
	Blockly.Kiwifroot.provideAddition('EVENT_TOUCH_ON', code);

  	return null;
};

function defineFunctionFromBranch(desiredName, block){
	// Define a procedure with a return value.
	var funcName = Blockly.Kiwifroot.variableDB_.getDistinctName(desiredName, Blockly.Procedures.NAME_TYPE);
	var branch = Blockly.Kiwifroot.statementToCode(block, 'STACK');
	if (Blockly.Kiwifroot.STATEMENT_PREFIX) {
		branch = Blockly.Kiwifroot.prefixLines(
			Blockly.Kiwifroot.STATEMENT_PREFIX.replace(/%1/g,
			'\'' + block.id + '\''), Blockly.Kiwifroot.INDENT) + branch;
	}
	if (Blockly.Kiwifroot.INFINITE_LOOP_TRAP) {
		branch = Blockly.Kiwifroot.INFINITE_LOOP_TRAP.replace(/%1/g,
			'\'' + block.id + '\'') + branch;
	}
	branch = Blockly.Kiwifroot.scrub_(block, branch);
	var code = funcName + ' = function() {\n' + branch + '};';

	Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DEFINITIONS,code);
	return funcName;
};

<|endoftext|>