<commit_before>var Class = require('../utils/Class');
var Extend = require('../utils/object/Extend');
var EventDispatcher = require('../events/EventDispatcher');
//  Phaser.Sound.BaseSound
var BaseSound = new Class({
    initialize: function BaseSound(manager, key, config) {
        /**
         * Local reference to the sound manager.
         *
         * @property {Phaser.Sound.BaseSoundManager} manager
         */
        this.manager = manager;
        /**
         * [description]
         *
         * @property {string} key
         */
        this.key = key;
        /**
         * [description]
         *
         * Duration set explicitly, rest of default values
         * will be set by other properties setters.
         *
         * @property {ISoundConfig} config
         */
        this.config = {};
        /**
         * Reference to the currently used config.
         * It could be default config or marker config.
         *
         * @property {ISoundConfig} currentConfig
         */
        this.currentConfig = this.config;
        /**
         * [description]
         *
         * @property {boolean} mute
         */
        this.mute = false;
        /**
         * [description]
         *
         * @property {number} volume
         */
        this.volume = 1;
        /**
         * Defines the speed at which the audio asset will be played.
         * Value of 1.0 plays the audio at full speed, 0.5 plays the audio
         * at half speed and 2.0 doubles the audio's playback speed.
         * This value gets multiplied by global rate to have the final playback speed.
         *
         * @property {number} rate
         */
        this.rate = 1;
        /**
         * Represents detuning of sound in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
         * The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
         *
         * Standards based Web Audio implementation only.
         * Webkit Web Audio implementation and HTML5 Audio don't support this.
         *
         * @property {number} detune
         */
        this.detune = 0;
        /**
         * [description]
         *
         * @property {number} seek
         */
        this.seek = 0;
        /**
         * [description]
         *
         * @property {boolean} loop
         */
        this.loop = false;
        /**
         * [description]
         *
         * @property {number} pan
         */
        this.pan = 0;
        this.config = Extend(this.config, config);
        /**
         * Flag indicating if sound is currently playing.
         *
         * @property {boolean} isPlaying
         */
        this.isPlaying = false;
        /**
         * Flag indicating if sound is currently paused.
         *
         * @property {boolean} isPaused
         */
        this.isPaused = false;
        /**
         * Object containing markers definitions.
         *
         * @property {{}} markers
         */
        this.markers = {};
        /**
         * Name of the currently played marker.
         * If no marker is played, but instead the whole sound
         * the value is an empty string - ''.
         *
         * @property {string} currentMarker
         */
        this.currentMarker = '';
        /**
         * [description]
         *
         * @property {Phaser.Tween}
         */
        this.fadeTween = null; // TODO see how to use global tween
        /**
         * Event dispatches used to handle all sound instance
         * relevant events.
         *
         * @property {Phaser.Events.EventDispatcher}
         */
        this.events = new EventDispatcher();
    },
    // TODO set default methods to NOOP if not used
    addMarker: function (marker) {
        return false;
    },
    removeMarker: function (markerName) {
        return false;
    },
    play: function (marker, config) {
        if (marker === void 0) { marker = ''; }
        if (typeof marker === 'object') {
            config = marker;
            marker = '';
        }
        if (typeof marker !== 'string') {
            console.error('Sound marker name has to be a string!');
            return null;
        }
        if (!marker) {
            this.currentConfig = this.config;
        }
        else {
            if (!this.markers[marker]) {
                console.error('No marker with name \'' + marker + '\' found for sound \'' + this.key + '\'!');
                return null;
            }
            this.currentMarker = marker;
            this.currentConfig = this.markers[marker].config;
        }
        this.currentConfig = Extend(this.currentConfig, config);
        this.isPlaying = true;
        this.isPaused = false;
        return this;
    },
    pause: function () {
        if (this.isPaused || !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = true;
        return true;
    },
    resume: function () {
        if (!this.isPaused || this.isPlaying) {
            return false;
        }
        this.isPlaying = true;
        this.isPaused = false;
        return true;
    },
    stop: function () {
        if (!this.isPaused && !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = false;
        return true;
    },
    applyConfig: function () {
        this.mute = this.currentConfig.mute;
        this.volume = this.currentConfig.volume;
        this.rate = this.currentConfig.rate;
        this.detune = this.currentConfig.detune;
        // TODO assign other config values to buffer source
    },
    fadeTo: function (volume, duration) {
        return null;
    },
    update: function () {
    },
    destroy: function () {
    }
});
module.exports = BaseSound;
<commit_msg>Added duration property to BaseSound class<commit_after>var Class = require('../utils/Class');
var Extend = require('../utils/object/Extend');
var EventDispatcher = require('../events/EventDispatcher');
//  Phaser.Sound.BaseSound
var BaseSound = new Class({
    initialize: function BaseSound(manager, key, config) {
        /**
         * Local reference to the sound manager.
         *
         * @property {Phaser.Sound.BaseSoundManager} manager
         */
        this.manager = manager;
        /**
         * [description]
         *
         * @property {string} key
         */
        this.key = key;
        /**
         * [description]
         *
         * Duration set explicitly, rest of default values
         * will be set by other properties setters.
         *
         * @property {ISoundConfig} config
         */
        this.config = {};
        /**
         * Reference to the currently used config.
         * It could be default config or marker config.
         *
         * @property {ISoundConfig} currentConfig
         */
        this.currentConfig = this.config;
        /**
         * [description]
         *
         * @property {boolean} mute
         */
        this.mute = false;
        /**
         * [description]
         *
         * @property {number} volume
         */
        this.volume = 1;
        /**
         * Defines the speed at which the audio asset will be played.
         * Value of 1.0 plays the audio at full speed, 0.5 plays the audio
         * at half speed and 2.0 doubles the audio's playback speed.
         * This value gets multiplied by global rate to have the final playback speed.
         *
         * @property {number} rate
         */
        this.rate = 1;
        /**
         * Represents detuning of sound in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).
         * The range of the value is -1200 to 1200, but we recommend setting it to [50](https://en.wikipedia.org/wiki/50_Cent).
         *
         * Standards based Web Audio implementation only.
         * Webkit Web Audio implementation and HTML5 Audio don't support this.
         *
         * @property {number} detune
         */
        this.detune = 0;
        /**
         * [description]
         *
         * @property {number} seek
         */
        this.seek = 0;
        /**
         * [description]
         *
         * @property {boolean} loop
         */
        this.loop = false;
        /**
         * [description]
         *
         * @property {number} pan
         */
        this.pan = 0;
        this.config = Extend(this.config, config);
        /**
         * A value representing the duration, in seconds.
         * It could be total sound duration or a marker duration.
         *
         * @readonly
         * @property {number} duration
         */
        this.duration = 0;
        /**
         * Flag indicating if sound is currently playing.
         *
         * @property {boolean} isPlaying
         */
        this.isPlaying = false;
        /**
         * Flag indicating if sound is currently paused.
         *
         * @property {boolean} isPaused
         */
        this.isPaused = false;
        /**
         * Object containing markers definitions.
         *
         * @property {{}} markers
         */
        this.markers = {};
        /**
         * Name of the currently played marker.
         * If no marker is played, but instead the whole sound
         * the value is an empty string - ''.
         *
         * @property {string} currentMarker
         */
        this.currentMarker = '';
        /**
         * [description]
         *
         * @property {Phaser.Tween}
         */
        this.fadeTween = null; // TODO see how to use global tween
        /**
         * Event dispatches used to handle all sound instance
         * relevant events.
         *
         * @property {Phaser.Events.EventDispatcher}
         */
        this.events = new EventDispatcher();
    },
    // TODO set default methods to NOOP if not used
    addMarker: function (marker) {
        return false;
    },
    removeMarker: function (markerName) {
        return false;
    },
    play: function (marker, config) {
        if (marker === void 0) { marker = ''; }
        if (typeof marker === 'object') {
            config = marker;
            marker = '';
        }
        if (typeof marker !== 'string') {
            console.error('Sound marker name has to be a string!');
            return null;
        }
        if (!marker) {
            this.currentConfig = this.config;
        }
        else {
            if (!this.markers[marker]) {
                console.error('No marker with name \'' + marker + '\' found for sound \'' + this.key + '\'!');
                return null;
            }
            this.currentMarker = marker;
            this.currentConfig = this.markers[marker].config;
        }
        this.currentConfig = Extend(this.currentConfig, config);
        this.isPlaying = true;
        this.isPaused = false;
        return this;
    },
    pause: function () {
        if (this.isPaused || !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = true;
        return true;
    },
    resume: function () {
        if (!this.isPaused || this.isPlaying) {
            return false;
        }
        this.isPlaying = true;
        this.isPaused = false;
        return true;
    },
    stop: function () {
        if (!this.isPaused && !this.isPlaying) {
            return false;
        }
        this.isPlaying = false;
        this.isPaused = false;
        return true;
    },
    applyConfig: function () {
        this.mute = this.currentConfig.mute;
        this.volume = this.currentConfig.volume;
        this.rate = this.currentConfig.rate;
        this.detune = this.currentConfig.detune;
        // TODO assign other config values to buffer source
    },
    fadeTo: function (volume, duration) {
        return null;
    },
    update: function () {
    },
    destroy: function () {
    }
});
module.exports = BaseSound;
<|endoftext|>


<commit_before>import React from 'react';
import { selectProps, selectStatus } from './routerModule';

export default class RouterHookContainer extends React.Component {
  static propTypes = {
    children: React.PropTypes.node,
    location: React.PropTypes.object.isRequired,
  }

  static contextTypes = {
    routerHookContext: React.PropTypes.object.isRequired,
  };

  constructor(props, context) {
    super(props, context);
    this.Component = props.children.type;
    this.state = {};
  }

  componentDidMount() {
    this.trySubscribe();
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.location !== nextProps.location) {
      return true;
    }
    return nextState.componentStatus !== 'init' &&
      (this.state.routerLoading !== nextState.routerLoading ||
        this.state.componentStatus !== nextState.componentStatus);
  }

  componentWillUnmount() {
    this.tryUnsubscribe();
    this.clearCache();
  }

  trySubscribe() {
    if (!this.unsubscribe) {
      this.unsubscribe = this.context.routerHookContext.subscribe(this.handleChange.bind(this));
      this.handleChange();
    }
  }

  tryUnsubscribe() {
    if (this.unsubscribe) {
      this.unsubscribe();
      this.unsubscribe = null;
    }
  }

  clearCache() {
    this.hasStoreStateChanged = null;
  }

  handleChange() {
    if (!this.unsubscribe) {
      return;
    }

    const storeState = this.context.routerHookContext.getState();
    if (!storeState) {
      console.error('storeState is empty', storeState, this.context.routerHookContext);
    }
    const prevStoreState = this.state.storeState;
    if (prevStoreState === storeState) {
      return;
    }

    this.hasStoreStateChanged = true;
    this.setState({
      storeState,
      componentProps: selectProps(storeState, this.Component),
      componentStatus: selectStatus(storeState, this.Component),
      routerLoading: storeState.routerLoading,
    });
  }

  render() {
    this.hasStoreStateChanged = false;
    const {
      componentProps = {},
      componentStatus,
      routerLoading,
    } = this.state;
    const {
      reloadComponent,
    } = this.context.routerHookContext;

    if (componentStatus === 'init') {
      return null;
    }

    return React.cloneElement(this.props.children, {
      ...componentProps,
      componentStatus,
      reloadComponent: () => reloadComponent(this.Component),
      routerLoading,
    });
  }
}
<commit_msg>pass renderProps to children<commit_after>import React from 'react';
import { selectProps, selectStatus } from './routerModule';

export default class RouterHookContainer extends React.Component {
  static propTypes = {
    children: React.PropTypes.node,
    location: React.PropTypes.object.isRequired,
  }

  static contextTypes = {
    routerHookContext: React.PropTypes.object.isRequired,
  };

  constructor(props, context) {
    super(props, context);
    this.Component = props.children.type;
    this.state = {};
  }

  componentDidMount() {
    this.trySubscribe();
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.location !== nextProps.location) {
      return true;
    }
    return nextState.componentStatus !== 'init' &&
      (this.state.routerLoading !== nextState.routerLoading ||
        this.state.componentStatus !== nextState.componentStatus);
  }

  componentWillUnmount() {
    this.tryUnsubscribe();
    this.clearCache();
  }

  trySubscribe() {
    if (!this.unsubscribe) {
      this.unsubscribe = this.context.routerHookContext.subscribe(this.handleChange.bind(this));
      this.handleChange();
    }
  }

  tryUnsubscribe() {
    if (this.unsubscribe) {
      this.unsubscribe();
      this.unsubscribe = null;
    }
  }

  clearCache() {
    this.hasStoreStateChanged = null;
  }

  handleChange() {
    if (!this.unsubscribe) {
      return;
    }

    const storeState = this.context.routerHookContext.getState();
    if (!storeState) {
      console.error('storeState is empty', storeState, this.context.routerHookContext);
    }
    const prevStoreState = this.state.storeState;
    if (prevStoreState === storeState) {
      return;
    }

    this.hasStoreStateChanged = true;
    this.setState({
      storeState,
      componentProps: selectProps(storeState, this.Component),
      componentStatus: selectStatus(storeState, this.Component),
      routerLoading: storeState.routerLoading,
    });
  }

  render() {
    this.hasStoreStateChanged = false;
    const {
      componentProps = {},
      componentStatus,
      routerLoading,
    } = this.state;

    if (componentStatus === 'init') {
      return null;
    }

    const { reloadComponent } = this.context.routerHookContext;
    const {
      children, // eslint-disable-line no-unused-vars
      ...restProps,
    } = this.props;

    return React.cloneElement(this.props.children, {
      ...restProps,
      ...componentProps,
      componentStatus,
      reloadComponent: () => reloadComponent(this.Component),
      routerLoading,
    });
  }
}
<|endoftext|>


<commit_before>/*

	tdapp_controller_auth.js

*/
var tdapp = require('./tdapp');

tdapp.controller("AuthCtrl",function($scope,$http,$auth,$cookies,$window,$timeout,appdata,TDMgr,Backend,Autologin, $firebaseAuth){

	// Injection

	Autologin.setScope($scope);
	Backend.setScope($scope);

	//* Satellizer
	$scope.authenticate = function(provider){
		$auth.authenticate(provider)
		.then(function(res){
			if($auth.isAuthenticated){
				var dtok = jwt_decode(res.data.token);
				$scope.user = {};
				$scope.user.id = dtok.sub;
			}
		});
	};
	*/

	// Login

	function gomain(){
		$timeout(function(){
			$window.location = "/#/main";
		},1000);
	}

	function locallogin(){ // No basic authentication (just communicate with localhost)
		$window.location = "/#/working";
		appdata.server = appdata.localserver;
		var now = new Date();
		var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
		$cookies.put(appdata.cookiename,'bla',{expires:exp});
		$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
		$scope.errormsg = "";
		gomain();
	}

	/* Old login
	$scope.dologin = function(){
		if($window.location.host=="localhost"){
			locallogin();
			return;
		}
		$auth.login($scope.user)
			.then(function(response){
				$window.location = "/#/working";
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,response.data.token,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + response.data.token;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			})
			.catch(function(error){
				$scope.errormsg = "Login-Error.";
				console.log(error);
			});
	}
	*/

	// Login via firebase
	$scope.dologin = function(){
		if($window.location.host=="localhost"){
			locallogin();
			return;
		}
		var ref = new Firebase("https://drtodolittle.firebaseio.com");
		ref.authWithPassword({
			email: $scope.user.email,
			password: $scope.user.password
		},function(error, authData){
			if (error) {
				console.log("Error: Login failed: ", error);
			} else {
				console.log("Authenticated successfully with payload:", authData);
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,authData,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + authData;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			}
		});
		/* Old login
		$auth.login($scope.user)
			.then(function(response){
				$window.location = "/#/working";
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,response.data.token,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + response.data.token;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			})
			.catch(function(error){
				$scope.errormsg = "Login-Error.";
				console.log(error);
			});
		*/
	}

	$scope.dologinWithGoogle = function(){
		var auth = $firebaseAuth();
		// Login with Firebase/Google
		auth.$signInWithPopup("google").then(function(firebaseUser){
			console.log("Signed in as: ", firebaseUser.user.email);
			console.log("Credentials: ", firebaseUser.credential);
			$scope.email = firebaseUser.user.email;
			firebaseUser.user.getToken(false).then(function(idToken){
				console.log("Token: ", idToken);
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,idToken,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + idToken;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			});
		}).catch(function(error){
			$scope.errormsg = "Login-Error."
			console.log("Authentication failed: ", error);
		});
	}

	// Keyboard

	$scope.loginKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			$scope.dologin();
		}
	}

	// Register

	$scope.showRegister = function(){
		$window.location = "/#/register";
	};

	// Finish

	$("#liusername").focus()

	Autologin.check(); // do automatic login if cookie/token is available
});
<commit_msg>Bugfix Firebase Login<commit_after>/*

	tdapp_controller_auth.js

*/
var tdapp = require('./tdapp');

tdapp.controller("AuthCtrl",function($scope,$http,$auth,$cookies,$window,$timeout,appdata,TDMgr,Backend,Autologin, $firebaseAuth){

	// Injection

	Autologin.setScope($scope);
	Backend.setScope($scope);

	/* Satellizer
	$scope.authenticate = function(provider){
		$auth.authenticate(provider)
		.then(function(res){
			if($auth.isAuthenticated){
				var dtok = jwt_decode(res.data.token);
				$scope.user = {};
				$scope.user.id = dtok.sub;
			}
		});
	};
	*/

	// Login

	function gomain(){
		$timeout(function(){
			$window.location = "/#/main";
		},1000);
	}

	function locallogin(){ // No basic authentication (just communicate with localhost)
		$window.location = "/#/working";
		appdata.server = appdata.localserver;
		var now = new Date();
		var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
		$cookies.put(appdata.cookiename,'bla',{expires:exp});
		$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
		$scope.errormsg = "";
		gomain();
	}

	/* Old login
	$scope.dologin = function(){
		if($window.location.host=="localhost"){
			locallogin();
			return;
		}
		$auth.login($scope.user)
			.then(function(response){
				$window.location = "/#/working";
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,response.data.token,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + response.data.token;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			})
			.catch(function(error){
				$scope.errormsg = "Login-Error.";
				console.log(error);
			});
	}
	*/

	// Login via firebase
	$scope.dologin = function(){
		if($window.location.host=="localhost"){
			locallogin();
			return;
		}
		var ref = new Firebase("https://drtodolittle.firebaseio.com");
		ref.authWithPassword({
			email: $scope.user.email,
			password: $scope.user.password
		},function(error, authData){
			if (error) {
				console.log("Error: Login failed: ", error);
			} else {
				console.log("Authenticated successfully with payload:", authData);
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,authData,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + authData;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			}
		});
		/* Old login
		$auth.login($scope.user)
			.then(function(response){
				$window.location = "/#/working";
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,response.data.token,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + response.data.token;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			})
			.catch(function(error){
				$scope.errormsg = "Login-Error.";
				console.log(error);
			});
		*/
	}

	$scope.dologinWithGoogle = function(){
		var auth = $firebaseAuth();
		// Login with Firebase/Google
		auth.$signInWithPopup("google").then(function(firebaseUser){
			console.log("Signed in as: ", firebaseUser.user.email);
			console.log("Credentials: ", firebaseUser.credential);
			$scope.email = firebaseUser.user.email;
			firebaseUser.user.getToken(false).then(function(idToken){
				console.log("Token: ", idToken);
				// Create cookie
				var now = new Date();
				var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
				$cookies.put(appdata.cookiename,idToken,{expires:exp});
				// Modifiy headers
				$http.defaults.headers.common['Authorization'] = "Basic " + idToken;
				$scope.filtertag = 'All'; // set filtertag before calling Backend.getTodos()
				$scope.errormsg = "";
				gomain();
			});
		}).catch(function(error){
			$scope.errormsg = "Login-Error."
			console.log("Authentication failed: ", error);
		});
	}

	// Keyboard

	$scope.loginKeydown = function(e){
		var k = e.keyCode;
		if(k==13){//ret
			e.preventDefault();
			$scope.dologin();
		}
	}

	// Register

	$scope.showRegister = function(){
		$window.location = "/#/register";
	};

	// Finish

	$("#liusername").focus()

	Autologin.check(); // do automatic login if cookie/token is available
});
<|endoftext|>


<commit_before>/**
 * Visual Blocks Editor
 *
 * Copyright 2011 Google Inc.
 * http://blockly.googlecode.com/
 *
 * 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 Click-drag panning interaction handler for BlockSpaces
 */
'use strict';

goog.provide('Blockly.PanDragHandler');

/**
 * @param {!Blockly.BlockSpace} blockSpace
 * @constructor
 */
Blockly.PanDragHandler = function (blockSpace) {
  /**
   * @private {Blockly.BlockSpace}
   */
  this.blockSpace_ = blockSpace;

  /**
   * Element which initiates pan-drag mode when clicked directly.
   * @private {EventTarget}
   */
  this.target_ = null;

  /**
   * @private {function}
   */
  this.onTargetMouseDown_ = null;

  /**
   * @private {BindData}
   */
  this.mouseDownEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.wheelEventBindData_ = null;

  /**
   * (for Safari)
   * @private {BindData}
   */
  this.mousewheelEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.contextMenuBlockEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.mouseMoveEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.mouseUpEventBindData_ = null;

  /**
   * @private {number}
   */
  this.startMouseX_ = null;

  /**
   * @private {number}
   */
  this.startMouseY_ = null;

  /**
   * @private {number}
   */
  this.startScrollX_ = null;

  /**
   * @private {number}
   */
  this.startScrollY_ = null;
};

/**
 * Establish a mousedown handler on the given dragTarget that will put the
 * blockspace into a pan-drag mode as long as the mouse is down.
 * @param {!EventTarget} target - Element which initiates pan-drag mode when
 *        clicked directly.
 * @param {function} [onDragTargetMouseDown] - optional function called when
 *        click on the drag target begins (used for hideChaff by BSE)
 */
Blockly.PanDragHandler.prototype.bindBeginPanDragHandler = function (target,
    onDragTargetMouseDown) {
  this.unbindBeginPanDragHandler();
  this.target_ = target;
  this.onTargetMouseDown_ = onDragTargetMouseDown;
  this.mouseDownEventBindData_ = Blockly.bindEvent_(
      target, 'mousedown', this, this.onPanDragTargetMouseDown_);

  // Also block the context menu on the pan-drag target element
  this.contextMenuBlockEventBindData_ = Blockly.bindEvent_(
      target, 'contextmenu', null, Blockly.blockContextMenu);
};

/**
 * Unbinds previously bound handler to begin pan-drag.  Safe to call if no
 * such handler is bound.
 */
Blockly.PanDragHandler.prototype.unbindBeginPanDragHandler = function () {
  if (this.mouseDownEventBindData_) {
    Blockly.unbindEvent_(this.mouseDownEventBindData_);
    this.mouseDownEventBindData_ = null;
  }

  if (this.contextMenuBlockEventBindData_) {
    Blockly.unbindEvent_(this.contextMenuBlockEventBindData_);
    this.contextMenuBlockEventBindData_ = null;
  }

  this.target_ = null;
};

/**
 * Binds temporary mousemove and mouseup handlers against window,
 * so that drag behavior and ending the drag work no matter where the cursor
 * goes after the initial mousedown.
 * @private
 */
Blockly.PanDragHandler.prototype.bindDuringPanDragHandlers_ = function () {
  this.unbindDuringPanDragHandlers_();

  // We bind against "capture" (instead of the default "bubble") so that we
  // receive the event before the actual event target - pan-drag mode should
  // pretty much override everything.
  var onCapture = true;
  this.mouseMoveEventBindData_ = Blockly.bindEvent_(
      window, 'mousemove', this, this.onPanDragMouseMove_, onCapture);
  this.mouseUpEventBindData_ = Blockly.bindEvent_(
      window, 'mouseup', this, this.onPanDragMouseUp_, onCapture);
};

/**
 * Unbinds mousemove and mouseup handlers that only apply during pan-drag mode.
 * @private
 */
Blockly.PanDragHandler.prototype.unbindDuringPanDragHandlers_ = function () {
  if (this.mouseMoveEventBindData_) {
    Blockly.unbindEvent_(this.mouseMoveEventBindData_);
    this.mouseMoveEventBindData_ = null;
  }

  if (this.mouseUpEventBindData_) {
    Blockly.unbindEvent_(this.mouseUpEventBindData_);
    this.mouseUpEventBindData_ = null;
  }
};

/**
 * When a mousedown event occurs over the pan-drag target, deselect blocks
 * and decide whether we can actually begin pan-drag mode.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.onPanDragTargetMouseDown_ = function (e) {
  if (this.onTargetMouseDown_) {
    this.onTargetMouseDown_();
  }

  var isClickDirectlyOnDragTarget = e.target && e.target === this.target_;

  // Clicking on the flyout background clears the global selection
  if (Blockly.selected && !Blockly.readOnly && isClickDirectlyOnDragTarget) {
    Blockly.selected.unselect();
  }

  // On left-click on scrollable area, begin scroll-drag
  // In readonly mode, we scroll-drag when clicking through a block, too.
  if (this.blockSpace_.scrollbarPair && !Blockly.isRightButton(e) &&
      (isClickDirectlyOnDragTarget || Blockly.readOnly)) {
    this.beginDragScroll_(e);

    // Don't click through to the workspace drag handler, or the browser
    // default drag/scroll handlers
    e.stopPropagation();
    e.preventDefault();
  }
};

/**
 * Actually begin pan-drag mode.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.beginDragScroll_ = function (e) {
  // Record the current mouse position.
  this.startMouseX_ = e.clientX;
  this.startMouseY_ = e.clientY;
  this.startScrollX_ = this.blockSpace_.getScrollOffsetX();
  this.startScrollY_ = this.blockSpace_.getScrollOffsetY();

  this.bindDuringPanDragHandlers_();
};

/**
 * Mouse-move handler that is only bound and active during pan-drag mode
 * for this blockspace.  Causes scroll and stops the event.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.onPanDragMouseMove_ = function (e) {
  // Prevent text selection on page
  Blockly.removeAllRanges();

  var mouseDx = e.clientX - this.startMouseX_; // + if mouse right
  var mouseDy = e.clientY - this.startMouseY_; // + if mouse down

  // to pan, scroll opposite direction of drag
  var scrollDx = -mouseDx; // scroll - (down) if mouse up
  var scrollDy = -mouseDy; // scroll - (left) if mouse right

  this.blockSpace_.scrollTo(
    this.startScrollX_ + scrollDx,
    this.startScrollY_ + scrollDy);
  e.stopPropagation();
  e.preventDefault();
};

/**
 * Mouse-up handler that is only bound and active during pan-drag mode
 * for this flyout.  Ends pan-drag mode.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.onPanDragMouseUp_ = function (e) {
  this.unbindDuringPanDragHandlers_();
  e.stopPropagation();
  e.preventDefault();
};
<commit_msg>Pan drag through unmovable blocks.<commit_after>/**
 * Visual Blocks Editor
 *
 * Copyright 2011 Google Inc.
 * http://blockly.googlecode.com/
 *
 * 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 Click-drag panning interaction handler for BlockSpaces
 */
'use strict';

goog.provide('Blockly.PanDragHandler');

/**
 * @param {!Blockly.BlockSpace} blockSpace
 * @constructor
 */
Blockly.PanDragHandler = function (blockSpace) {
  /**
   * @private {Blockly.BlockSpace}
   */
  this.blockSpace_ = blockSpace;

  /**
   * Element which initiates pan-drag mode when clicked directly.
   * @private {EventTarget}
   */
  this.target_ = null;

  /**
   * @private {function}
   */
  this.onTargetMouseDown_ = null;

  /**
   * @private {BindData}
   */
  this.mouseDownEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.wheelEventBindData_ = null;

  /**
   * (for Safari)
   * @private {BindData}
   */
  this.mousewheelEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.contextMenuBlockEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.mouseMoveEventBindData_ = null;

  /**
   * @private {BindData}
   */
  this.mouseUpEventBindData_ = null;

  /**
   * @private {number}
   */
  this.startMouseX_ = null;

  /**
   * @private {number}
   */
  this.startMouseY_ = null;

  /**
   * @private {number}
   */
  this.startScrollX_ = null;

  /**
   * @private {number}
   */
  this.startScrollY_ = null;
};

/**
 * Establish a mousedown handler on the given dragTarget that will put the
 * blockspace into a pan-drag mode as long as the mouse is down.
 * @param {!EventTarget} target - Element which initiates pan-drag mode when
 *        clicked directly.
 * @param {function} [onDragTargetMouseDown] - optional function called when
 *        click on the drag target begins (used for hideChaff by BSE)
 */
Blockly.PanDragHandler.prototype.bindBeginPanDragHandler = function (target,
    onDragTargetMouseDown) {
  this.unbindBeginPanDragHandler();
  this.target_ = target;
  this.onTargetMouseDown_ = onDragTargetMouseDown;
  this.mouseDownEventBindData_ = Blockly.bindEvent_(
      target, 'mousedown', this, this.onPanDragTargetMouseDown_);

  // Also block the context menu on the pan-drag target element
  this.contextMenuBlockEventBindData_ = Blockly.bindEvent_(
      target, 'contextmenu', null, Blockly.blockContextMenu);
};

/**
 * Unbinds previously bound handler to begin pan-drag.  Safe to call if no
 * such handler is bound.
 */
Blockly.PanDragHandler.prototype.unbindBeginPanDragHandler = function () {
  if (this.mouseDownEventBindData_) {
    Blockly.unbindEvent_(this.mouseDownEventBindData_);
    this.mouseDownEventBindData_ = null;
  }

  if (this.contextMenuBlockEventBindData_) {
    Blockly.unbindEvent_(this.contextMenuBlockEventBindData_);
    this.contextMenuBlockEventBindData_ = null;
  }

  this.target_ = null;
};

/**
 * Binds temporary mousemove and mouseup handlers against window,
 * so that drag behavior and ending the drag work no matter where the cursor
 * goes after the initial mousedown.
 * @private
 */
Blockly.PanDragHandler.prototype.bindDuringPanDragHandlers_ = function () {
  this.unbindDuringPanDragHandlers_();

  // We bind against "capture" (instead of the default "bubble") so that we
  // receive the event before the actual event target - pan-drag mode should
  // pretty much override everything.
  var onCapture = true;
  this.mouseMoveEventBindData_ = Blockly.bindEvent_(
      window, 'mousemove', this, this.onPanDragMouseMove_, onCapture);
  this.mouseUpEventBindData_ = Blockly.bindEvent_(
      window, 'mouseup', this, this.onPanDragMouseUp_, onCapture);
};

/**
 * Unbinds mousemove and mouseup handlers that only apply during pan-drag mode.
 * @private
 */
Blockly.PanDragHandler.prototype.unbindDuringPanDragHandlers_ = function () {
  if (this.mouseMoveEventBindData_) {
    Blockly.unbindEvent_(this.mouseMoveEventBindData_);
    this.mouseMoveEventBindData_ = null;
  }

  if (this.mouseUpEventBindData_) {
    Blockly.unbindEvent_(this.mouseUpEventBindData_);
    this.mouseUpEventBindData_ = null;
  }
};

/**
 * When a mousedown event occurs over the pan-drag target, deselect blocks
 * and decide whether we can actually begin pan-drag mode.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.onPanDragTargetMouseDown_ = function (e) {
  if (this.onTargetMouseDown_) {
    this.onTargetMouseDown_();
  }

  var clickIsOnTarget = e.target && e.target === this.target_;

  // Clicking on the flyout background clears the global selection
  if (Blockly.selected && !Blockly.readOnly && clickIsOnTarget) {
    Blockly.selected.unselect();
  }

  var blockUnmovable = Blockly.selected && !Blockly.selected.isMovable();

  // On left-click on scrollable area, begin scroll-drag
  // In readonly mode, we scroll-drag when clicking through a block, too.
  var shouldDrag = clickIsOnTarget || blockUnmovable || Blockly.readOnly;
  var isLeftClick = !Blockly.isRightButton(e);

  if (this.blockSpace_.scrollbarPair && isLeftClick && shouldDrag) {
    this.beginDragScroll_(e);

    // Don't click through to the workspace drag handler, or the browser
    // default drag/scroll handlers
    e.stopPropagation();
    e.preventDefault();
  }
};

/**
 * Actually begin pan-drag mode.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.beginDragScroll_ = function (e) {
  // Record the current mouse position.
  this.startMouseX_ = e.clientX;
  this.startMouseY_ = e.clientY;
  this.startScrollX_ = this.blockSpace_.getScrollOffsetX();
  this.startScrollY_ = this.blockSpace_.getScrollOffsetY();

  this.bindDuringPanDragHandlers_();
};

/**
 * Mouse-move handler that is only bound and active during pan-drag mode
 * for this blockspace.  Causes scroll and stops the event.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.onPanDragMouseMove_ = function (e) {
  // Prevent text selection on page
  Blockly.removeAllRanges();

  var mouseDx = e.clientX - this.startMouseX_; // + if mouse right
  var mouseDy = e.clientY - this.startMouseY_; // + if mouse down

  // to pan, scroll opposite direction of drag
  var scrollDx = -mouseDx; // scroll - (down) if mouse up
  var scrollDy = -mouseDy; // scroll - (left) if mouse right

  this.blockSpace_.scrollTo(
    this.startScrollX_ + scrollDx,
    this.startScrollY_ + scrollDy);
  e.stopPropagation();
  e.preventDefault();
};

/**
 * Mouse-up handler that is only bound and active during pan-drag mode
 * for this flyout.  Ends pan-drag mode.
 * @param {!Event} e
 * @private
 */
Blockly.PanDragHandler.prototype.onPanDragMouseUp_ = function (e) {
  this.unbindDuringPanDragHandlers_();
  e.stopPropagation();
  e.preventDefault();
};
<|endoftext|>


<commit_before>//= require ./object

(function ($) {
    "use strict";

    Object.defineProperties($.prototype, {

        copy: {
            value: function () {
                var
                    self = this,
                    copy = [];
                self.forEach(function (v) {
                    copy.push(v);
                });
                return copy;
            }
        },

        difference: {
            value: function () {
                var
                    args = [],
                    differences = [],
                    i;

                if (arguments.length > 0) {
                    for (i in arguments) {
                        if (arguments.hasOwnProperty(i)) {
                            args.push((arguments[i]).uniq());
                        }
                    }
                } else {
                    return this;
                }

                args.unshift(this);
                differences = args.reduce(function (prev, curr, i) {

                    if (i === 1) {
                        differences = prev.filter(function (v) {
                            return curr.indexOf(v) === -1;
                        });
                    } else {
                        differences = differences.filter(function (v) {
                            return curr.indexOf(v) === -1;
                        });
                    }

                    return differences;
                });

                return differences;
            }
        },

        intersection: {
            value: function () {
                var
                    args = [],
                    intersects = [],
                    self,
                    i;

                self = this;
                if (arguments.length > 0) {
                    for (i in arguments) {
                        if (arguments.hasOwnProperty(i)) {
                            args.push((arguments[i]).uniq());
                        }
                    }
                } else if (self.length > 0) {
                    self.forEach(function (v) {
                        args.push(v.uniq());
                    });
                } else {
                    return [];
                }

                intersects = args.asc().reduce(function (prev, curr, i) {
                    if (i === 1) {
                        intersects = prev.filter(function (v) {
                            // returns to filter method
                            return curr.indexOf(v) > -1;
                        });
                    } else {
                        intersects = intersects.filter(function (v) {
                            return curr.indexOf(v) > -1;
                        });
                    }
                    //console.log(i);
                    //console.log(_intersects);
                    // returns to reduce
                    return intersects;
                });

                return intersects;
            }
        },

        asc: {
            // ordena através do método "insertion sort", de forma
            // decrescente. Ordenara-lo-á ao final da fila da esquerda
            //para a direita, como num baralho de cartas dependendo se o
            // valor de b-a for > < ou = 0
            value: function () {
                var
                    copy = this.copyWithin();

                copy.sort(function (a, b) {
                    return a > b;
                });
                return copy;
            }
        },

        desc: {
            value: function () {
                var
                    copy = this.copyWithin();

                copy.sort(function (a, b) {
                    return a < b;
                });
                return copy;
            }
        },

        min: {
            value: function () {
                return Math.min.apply(null, this);
            }
        },

        max: {
            value: function () {
                return Math.max.apply(null, this);
            }
        },

        last: {
            value: function () {
                return this[this.length -1];
            }
        },

        uniq: {
            value: function () {
                return this.reduce(function (init, v) {
                    if (!init.indexOfEquivalent(v)) {
                        init.push(v);
                    }
                    return init;
                }, []);
            }
        },

        // retorna a quantidade de um item
        countItem: {
            value: function (comparison) {
                var
                    arr = this.asc(),
                    count = 0;

                // talvez fosse interessante não usar o forEach para otimizar,
                // testando até determinado item se diferente do próximo
                arr.forEach(function (item) {
                    if (item === comparison) {
                        count += 1;
                    }
                });
                return count;
            }
        },

        indexOfEquivalent: {
            value: function () {
                var
                    self = this,
                    i;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        if ((self[i]).isEquivalent(arguments[0])) {
                            if (i !== "0") {
                                return parseInt(i, 10);
                            } else {
                                return i;
                            }
                        }
                    }
                }

                return false;
            }
        },

        delete: {
            value: function () {
                var
                    self = this,
                    i;

                for (i in arguments) {
                    if (arguments.hasOwnProperty(i)) {
                        // index = self.indexOfEquivalent(arguments[i]);
                        // self.splice(index, 1);
                        self.splice(arguments[i], 1);
                    }
                }
                return self;
            }
        },

        deleteByValue: {
            value: function () {
                var
                    self = this,
                    index,
                    i;

                for (i in arguments) {
                    if (arguments.hasOwnProperty(i)) {
                        index = self.indexOfEquivalent(arguments[i]);
                        if (index) {
                            self.splice(index, 1);
                        }
                    }
                }
                return self;
            }
        },

        without: {
            value: function () {
                var
                    self = this,
                    another = [],
                    index,
                    i;

                another = self.copy();

                for (i in arguments) {
                    index = another.indexOfEquivalent(arguments[i]);
                    another.delete(index);
                }

                return another;
            }
        },

        prev: {
            value: function () {
                var collection = [];

                this.forEach(function (e) {
                    if (e.previousElementSibling) {
                        collection.push(e.previousElementSibling);
                    }
                });
                return collection;
            }
        }

    });

    /*$.prototype.parents = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/

    /*
    HTMLElement.prototype.is = function (selector) {
        if (selector.charAt(0) === ":") {
            switch (selector) {
                case ":hidden":
                    if (obj.style.display === "none") {
                        return true;
                    }
                    break;
            }
        } else {
            if (document.querySelector(selector)) {
                return true;
            }
        }
        return false;
    };*/

})(Array);
<commit_msg>ajusta bug em método without<commit_after>//= require ./object

(function ($) {
    "use strict";

    Object.defineProperties($.prototype, {

        copy: {
            value: function () {
                var
                    self = this,
                    copy = [];
                self.forEach(function (v) {
                    copy.push(v);
                });
                return copy;
            }
        },

        difference: {
            value: function () {
                var
                    args = [],
                    differences = [],
                    i;

                if (arguments.length > 0) {
                    for (i in arguments) {
                        if (arguments.hasOwnProperty(i)) {
                            args.push((arguments[i]).uniq());
                        }
                    }
                } else {
                    return this;
                }

                args.unshift(this);
                differences = args.reduce(function (prev, curr, i) {

                    if (i === 1) {
                        differences = prev.filter(function (v) {
                            return curr.indexOf(v) === -1;
                        });
                    } else {
                        differences = differences.filter(function (v) {
                            return curr.indexOf(v) === -1;
                        });
                    }

                    return differences;
                });

                return differences;
            }
        },

        intersection: {
            value: function () {
                var
                    args = [],
                    intersects = [],
                    self,
                    i;

                self = this;
                if (arguments.length > 0) {
                    for (i in arguments) {
                        if (arguments.hasOwnProperty(i)) {
                            args.push((arguments[i]).uniq());
                        }
                    }
                } else if (self.length > 0) {
                    self.forEach(function (v) {
                        args.push(v.uniq());
                    });
                } else {
                    return [];
                }

                intersects = args.asc().reduce(function (prev, curr, i) {
                    if (i === 1) {
                        intersects = prev.filter(function (v) {
                            // returns to filter method
                            return curr.indexOf(v) > -1;
                        });
                    } else {
                        intersects = intersects.filter(function (v) {
                            return curr.indexOf(v) > -1;
                        });
                    }
                    //console.log(i);
                    //console.log(_intersects);
                    // returns to reduce
                    return intersects;
                });

                return intersects;
            }
        },

        asc: {
            // ordena através do método "insertion sort", de forma
            // decrescente. Ordenara-lo-á ao final da fila da esquerda
            //para a direita, como num baralho de cartas dependendo se o
            // valor de b-a for > < ou = 0
            value: function () {
                var
                    copy = this.copyWithin();

                copy.sort(function (a, b) {
                    return a > b;
                });
                return copy;
            }
        },

        desc: {
            value: function () {
                var
                    copy = this.copyWithin();

                copy.sort(function (a, b) {
                    return a < b;
                });
                return copy;
            }
        },

        min: {
            value: function () {
                return Math.min.apply(null, this);
            }
        },

        max: {
            value: function () {
                return Math.max.apply(null, this);
            }
        },

        last: {
            value: function () {
                return this[this.length -1];
            }
        },

        uniq: {
            value: function () {
                return this.reduce(function (init, v) {
                    if (!init.indexOfEquivalent(v)) {
                        init.push(v);
                    }
                    return init;
                }, []);
            }
        },

        // retorna a quantidade de um item
        countItem: {
            value: function (comparison) {
                var
                    arr = this.asc(),
                    count = 0;

                // talvez fosse interessante não usar o forEach para otimizar,
                // testando até determinado item se diferente do próximo
                arr.forEach(function (item) {
                    if (item === comparison) {
                        count += 1;
                    }
                });
                return count;
            }
        },

        indexOfEquivalent: {
            value: function () {
                var
                    self = this,
                    i;

                for (i in self) {
                    if (self.hasOwnProperty(i)) {
                        if ((self[i]).isEquivalent(arguments[0])) {
                            if (i !== "0") {
                                return parseInt(i, 10);
                            } else {
                                return i;
                            }
                        }
                    }
                }

                return false;
            }
        },

        delete: {
            value: function () {
                var
                    self = this,
                    i;

                for (i in arguments) {
                    if (arguments.hasOwnProperty(i)) {
                        // index = self.indexOfEquivalent(arguments[i]);
                        // self.splice(index, 1);
                        self.splice(arguments[i], 1);
                    }
                }
                return self;
            }
        },

        deleteByValue: {
            value: function () {
                var
                    self = this,
                    index,
                    i;

                for (i in arguments) {
                    if (arguments.hasOwnProperty(i)) {
                        index = self.indexOfEquivalent(arguments[i]);
                        if (index) {
                            self.splice(index, 1);
                        }
                    }
                }
                return self;
            }
        },

        without: {
            value: function () {
                var
                    self = this,
                    another = [],
                    index,
                    i;

                another = self.copy();

                for (i in arguments) {
                    index = another.indexOfEquivalent(arguments[i]);
                    if (index) {
                        another.delete(index);
                    }
                }

                return another;
            }
        },

        prev: {
            value: function () {
                var collection = [];

                this.forEach(function (e) {
                    if (e.previousElementSibling) {
                        collection.push(e.previousElementSibling);
                    }
                });
                return collection;
            }
        }

    });

    /*$.prototype.parents = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/

    /*
    HTMLElement.prototype.is = function (selector) {
        if (selector.charAt(0) === ":") {
            switch (selector) {
                case ":hidden":
                    if (obj.style.display === "none") {
                        return true;
                    }
                    break;
            }
        } else {
            if (document.querySelector(selector)) {
                return true;
            }
        }
        return false;
    };*/

})(Array);
<|endoftext|>


<commit_before>define(function() {

  'use strict';

  function VolumeDescriptorView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeDescriptorView.prototype = {
    get typeCode() {
      return this.bytes[0];
    },
    get descriptorType() {
      switch (this.typeCode) {
        case 0: return 'boot';
        case 1: return 'volume'; // primary
        case 2: return 'volume'; // supplementary
        case 3: return 'partition';
        case 255: return 'terminator';
        default: return this.typeCode;
      }
    },
    get isPrimaryVolume() {
      return this.typeCode === 1;
    },
    get signature() {
      return String.fromCharCode(this.bytes[1], this.bytes[2], this.bytes[3], this.bytes[4], this.bytes[5]);
    },
    get hasValidSignature() {
      return this.signature === 'CD001';
    },
    get version() {
      return this.bytes[6];
    },
    get body() {
      var body, buffer = this.dv.buffer, byteOffset = this.dv.byteOffset, byteLength = this.dv.byteLength;
      switch(this.descriptorType) {
        case 'boot': body = new BootRecordView(buffer, byteOffset, byteLength); break;
        case 'volume': body = new VolumeRecordView(buffer, byteOffset, byteLength); break;
        default: body = null; break;
      }
      Object.defineProperty(this, 'body', {value:body});
      return body;
    },
  };

  function readSpacePadded(bytes) {
    return String.fromCharCode.apply(null, bytes).replace(/\s*$/, '');
  }

  function decodeTimeZoneSuffix(tz) {
    tz = (tz - 48) * 15;
    var sign = (tz < 0) ? ('-') : ('+');
    tz = Math.abs(tz);
    return sign + ('0' + Math.floor(tz / 60)).slice(-2) + ':' + ('0' + tz%60).slice(-2);
  }

  function readStringDateTime(bytes, offset) {
    var year = String.fromCharCode(bytes[offset + 0], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);
    if (!/^0*[1-9][0-9]*$/.test(year)) return null;
    var month = String.fromCharCode(bytes[offset + 4], bytes[offset + 5]);
    var day = String.fromCharCode(bytes[offset + 6], bytes[offset + 7]);
    var hour = String.fromCharCode(bytes[offset + 8], bytes[offset + 9]);
    var minute = String.fromCharCode(bytes[offset + 10], bytes[offset + 11]);
    var second = String.fromCharCode(bytes[offset + 12], bytes[offset + 13]);
    var hundredths = String.fromCharCode(bytes[offset + 14], bytes[offset + 15]);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 16]);
    var dateString = year+'-'+month+'-'+day+'T'+hour+':'+minute+':'+second+'.'+hundredths+timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function readBinaryDateTime(bytes, offset) {
    if (bytes[offset + 1] === 0) return null; // month, must be 1-12
    var year = '' + (1900 + bytes[offset]);
    var month = ('0' + bytes[offset + 1]).slice(-2);
    var day = ('0' + bytes[offset + 2]).slice(-2);
    var hour = ('0' + bytes[offset + 3]).slice(-2);
    var minute = ('0' + bytes[offset + 4]).slice(-2);
    var second = ('0' + bytes[offset + 5]).slice(-2);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 6]);
    var dateString = year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second + timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function BootRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.bootData = this.bytes.subarray(71);
  }
  BootRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(7, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(39, 64));
    },
  };

  function VolumeRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(8, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(40, 64));
    },
    get blockCount() {
      return this.dv.getUint32(80, true);
    },
    get diskCount() {
      return this.dv.getUint16(120, true);
    },
    get diskNumber() {
      return this.dv.getUint16(124, true);
    },
    get blockByteLength() {
      return this.dv.getUint16(128, true);
    },
    get pathTableByteLength() {
      return this.dv.getUint32(132, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(140, true);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(144, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(148, false);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(152, false);
    },
    get rootDirectory() {
      var root = new DirectoryRecordView(this.dv.buffer, this.dv.byteOffset + 156, 34);
      Object.defineProperty(this, 'rootDirectory', {value:root});
      return root;
    },
    get setIdentifier() {
      return readStringPadded(this.bytes.subarray(190, 190 + 128));
    },
    get publisher() {
      return readStringPadded(this.bytes.subarray(318, 318 + 128));
    },
    get dataPreparer() {
      return readStringPadded(this.bytes.subarray(446, 446 + 128));
    },
    get application() {
      return readStringPadded(this.bytes.subarray(574, 574 + 128));
    },
    get copyrightFilename() {
      return readStringPadded(this.bytes.subarray(702, 702 + 38));
    },
    get abstractFilename() {
      return readStringPadded(this.bytes.subarray(740, 740 + 36));
    },
    get bibliographyFilename() {
      return readStringPadded(this.bytes.subarray(776, 776 + 37));
    },
    get createdAt() {
      return readStringDateTime(this.bytes, 813);
    },
    get modifiedAt() {
      return readStringDateTime(this.bytes, 830);
    },
    get becomesObsoleteAt() {
      return readStringDateTime(this.bytes, 847);
    },
    get becomesEffectiveAt() {
      return readStringDateTime(this.bytes, 864);
    },
    get fileStructureVersion() {
      return this.bytes[881];
    },
    get applicationData() {
      var section = this.bytes.subarray(883, 883 + 512);
      Object.defineProperty(this, 'applicationData', {value:section});
      return section;
    },
  };

  function DirectoryRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  DirectoryRecordView.prototype = {
    get length() {
      return this.bytes[0];
    },
    get extendedAttributeRecordLength() {
      return this.bytes[1];
    },
    get dataBlockAddress() {
      return this.dv.getUint32(2, true);
    },
    get dataByteLength() {
      return this.dv.getUint32(10, true);
    },
    get recordedAt() {
      return readBinaryDateTime(this.bytes, 18);
    },
    get flags() {
      return this.bytes[25];
    },
    get isHidden() {
      return !!(this.flags & (1 << 0));
    },
    get isDirectory() {
      return !!(this.flags & (1 << 1));
    },
    get isAssociatedFile() {
      return !!(this.flags & (1 << 2));
    },
    get hasExtendedAttributeInfo() {
      return !!(this.flags & (1 << 3));
    },
    get hasPermissionsInExtendedAttributeInfo() {
      return !!(this.flags & (1 << 4));
    },
    get isPartial() {
      return !!(this.flags & (1 << 7));
    },
    get interleavedUnitSize() {
      return this.bytes[26];
    },
    get interleavedGapSize() {
      return this.bytes[27];
    },
    get volumeNumber() {
      return this.dv.getUint16(28, true);
    },
    get nameAndIdentifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(33, 33 + this.bytes[32]));
    },
    get name() {
      return this.nameAndIdentifier.replace(/;\d+$/, '');
    },
    get identifier() {
      return +(this.nameAndIdentifier.match(/;(\d+)$/) || '')[1];
    },
    get after_identifier() {
      var identifierLength = this.bytes[32];
      return 33 + identifierLength + ((identifierLength + 1) % 2);
    },
    get byteLength() {
      var extendedLength = this.extendedAttributeRecordLength;
      return this.after_identifier + extendedLength + extendedLength % 2;
    },
  };

  function PathTableEntryView(littleEndian, buffer, byteOffset, byteLength) {
    this.littleEndian = littleEndian;
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  PathTableEntryView.prototype = {
    get extendedAttributeLength() {
      return this.bytes[1];
    },
    get extentBlockAddress() {
      return this.dv.getUint32(2, this.littleEndian);
    },
    get parentDirectoryIndex() {
      return this.dv.getUint16(6, this.littleEndian);
    },
    get identifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(8, 8 + this.bytes[0]));
    },
    get byteLength() {
      var idLength = this.bytes[0];
      return 8 + idLength + idLength % 2;
    },
  };

  return {
    getStructView: function(segment) {
      switch (segment.getTypeParameter('which')) {
        case 'volume-descriptor': return VolumeDescriptorView;
        case 'path-table-entry': return PathTableEntryView;
        case 'boot-record': return BootRecordView;
        case 'volume-record': return VolumeRecordView;
        case 'folder': return DirectoryRecordView;
        case 'file': return DirectoryRecordView;
        default: return null;
      }
    },
    PathTableEntryView: PathTableEntryView,
    VolumeDescriptorView: VolumeDescriptorView,
    BootRecordView: BootRecordView,
    VolumeRecordView: VolumeRecordView,
    DirectoryRecordView: DirectoryRecordView,
  };

});
<commit_msg>Add offsetof_rootDirectory<commit_after>define(function() {

  'use strict';

  function VolumeDescriptorView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeDescriptorView.prototype = {
    get typeCode() {
      return this.bytes[0];
    },
    get descriptorType() {
      switch (this.typeCode) {
        case 0: return 'boot';
        case 1: return 'volume'; // primary
        case 2: return 'volume'; // supplementary
        case 3: return 'partition';
        case 255: return 'terminator';
        default: return this.typeCode;
      }
    },
    get isPrimaryVolume() {
      return this.typeCode === 1;
    },
    get signature() {
      return String.fromCharCode(this.bytes[1], this.bytes[2], this.bytes[3], this.bytes[4], this.bytes[5]);
    },
    get hasValidSignature() {
      return this.signature === 'CD001';
    },
    get version() {
      return this.bytes[6];
    },
    get body() {
      var body, buffer = this.dv.buffer, byteOffset = this.dv.byteOffset, byteLength = this.dv.byteLength;
      switch(this.descriptorType) {
        case 'boot': body = new BootRecordView(buffer, byteOffset, byteLength); break;
        case 'volume': body = new VolumeRecordView(buffer, byteOffset, byteLength); break;
        default: body = null; break;
      }
      Object.defineProperty(this, 'body', {value:body});
      return body;
    },
  };

  function readSpacePadded(bytes) {
    return String.fromCharCode.apply(null, bytes).replace(/\s*$/, '');
  }

  function decodeTimeZoneSuffix(tz) {
    tz = (tz - 48) * 15;
    var sign = (tz < 0) ? ('-') : ('+');
    tz = Math.abs(tz);
    return sign + ('0' + Math.floor(tz / 60)).slice(-2) + ':' + ('0' + tz%60).slice(-2);
  }

  function readStringDateTime(bytes, offset) {
    var year = String.fromCharCode(bytes[offset + 0], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);
    if (!/^0*[1-9][0-9]*$/.test(year)) return null;
    var month = String.fromCharCode(bytes[offset + 4], bytes[offset + 5]);
    var day = String.fromCharCode(bytes[offset + 6], bytes[offset + 7]);
    var hour = String.fromCharCode(bytes[offset + 8], bytes[offset + 9]);
    var minute = String.fromCharCode(bytes[offset + 10], bytes[offset + 11]);
    var second = String.fromCharCode(bytes[offset + 12], bytes[offset + 13]);
    var hundredths = String.fromCharCode(bytes[offset + 14], bytes[offset + 15]);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 16]);
    var dateString = year+'-'+month+'-'+day+'T'+hour+':'+minute+':'+second+'.'+hundredths+timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function readBinaryDateTime(bytes, offset) {
    if (bytes[offset + 1] === 0) return null; // month, must be 1-12
    var year = '' + (1900 + bytes[offset]);
    var month = ('0' + bytes[offset + 1]).slice(-2);
    var day = ('0' + bytes[offset + 2]).slice(-2);
    var hour = ('0' + bytes[offset + 3]).slice(-2);
    var minute = ('0' + bytes[offset + 4]).slice(-2);
    var second = ('0' + bytes[offset + 5]).slice(-2);
    var timeZone = decodeTimeZoneSuffix(bytes[offset + 6]);
    var dateString = year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second + timeZone;
    console.log(dateString);
    return new Date(dateString);
  }

  function BootRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.bootData = this.bytes.subarray(71);
  }
  BootRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(7, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(39, 64));
    },
  };

  function VolumeRecordView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
  }
  VolumeRecordView.prototype = {
    get systemIdentifier() {
      return readSpacePadded(this.bytes.subarray(8, 32));
    },
    get identifier() {
      return readSpacePadded(this.bytes.subarray(40, 64));
    },
    get blockCount() {
      return this.dv.getUint32(80, true);
    },
    get diskCount() {
      return this.dv.getUint16(120, true);
    },
    get diskNumber() {
      return this.dv.getUint16(124, true);
    },
    get blockByteLength() {
      return this.dv.getUint16(128, true);
    },
    get pathTableByteLength() {
      return this.dv.getUint32(132, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(140, true);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(144, true);
    },
    get pathTableBlockAddressLE() {
      return this.dv.getUint32(148, false);
    },
    get optionalPathTableBlockAddressLE() {
      return this.dv.getUint32(152, false);
    },
    get offsetof_rootDirectory() {
      return 156;
    },
    get rootDirectory() {
      var root = new DirectoryRecordView(this.dv.buffer, this.dv.byteOffset + 156, 34);
      Object.defineProperty(this, 'rootDirectory', {value:root});
      return root;
    },
    get setIdentifier() {
      return readStringPadded(this.bytes.subarray(190, 190 + 128));
    },
    get publisher() {
      return readStringPadded(this.bytes.subarray(318, 318 + 128));
    },
    get dataPreparer() {
      return readStringPadded(this.bytes.subarray(446, 446 + 128));
    },
    get application() {
      return readStringPadded(this.bytes.subarray(574, 574 + 128));
    },
    get copyrightFilename() {
      return readStringPadded(this.bytes.subarray(702, 702 + 38));
    },
    get abstractFilename() {
      return readStringPadded(this.bytes.subarray(740, 740 + 36));
    },
    get bibliographyFilename() {
      return readStringPadded(this.bytes.subarray(776, 776 + 37));
    },
    get createdAt() {
      return readStringDateTime(this.bytes, 813);
    },
    get modifiedAt() {
      return readStringDateTime(this.bytes, 830);
    },
    get becomesObsoleteAt() {
      return readStringDateTime(this.bytes, 847);
    },
    get becomesEffectiveAt() {
      return readStringDateTime(this.bytes, 864);
    },
    get fileStructureVersion() {
      return this.bytes[881];
    },
    get applicationData() {
      var section = this.bytes.subarray(883, 883 + 512);
      Object.defineProperty(this, 'applicationData', {value:section});
      return section;
    },
  };

  function DirectoryRecordView(buffer, byteOffset, byteLength) {
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  DirectoryRecordView.prototype = {
    get length() {
      return this.bytes[0];
    },
    get extendedAttributeRecordLength() {
      return this.bytes[1];
    },
    get dataBlockAddress() {
      return this.dv.getUint32(2, true);
    },
    get dataByteLength() {
      return this.dv.getUint32(10, true);
    },
    get recordedAt() {
      return readBinaryDateTime(this.bytes, 18);
    },
    get flags() {
      return this.bytes[25];
    },
    get isHidden() {
      return !!(this.flags & (1 << 0));
    },
    get isDirectory() {
      return !!(this.flags & (1 << 1));
    },
    get isAssociatedFile() {
      return !!(this.flags & (1 << 2));
    },
    get hasExtendedAttributeInfo() {
      return !!(this.flags & (1 << 3));
    },
    get hasPermissionsInExtendedAttributeInfo() {
      return !!(this.flags & (1 << 4));
    },
    get isPartial() {
      return !!(this.flags & (1 << 7));
    },
    get interleavedUnitSize() {
      return this.bytes[26];
    },
    get interleavedGapSize() {
      return this.bytes[27];
    },
    get volumeNumber() {
      return this.dv.getUint16(28, true);
    },
    get nameAndIdentifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(33, 33 + this.bytes[32]));
    },
    get name() {
      return this.nameAndIdentifier.replace(/;\d+$/, '');
    },
    get identifier() {
      return +(this.nameAndIdentifier.match(/;(\d+)$/) || '')[1];
    },
    get after_identifier() {
      var identifierLength = this.bytes[32];
      return 33 + identifierLength + ((identifierLength + 1) % 2);
    },
    get byteLength() {
      var extendedLength = this.extendedAttributeRecordLength;
      return this.after_identifier + extendedLength + extendedLength % 2;
    },
  };

  function PathTableEntryView(littleEndian, buffer, byteOffset, byteLength) {
    this.littleEndian = littleEndian;
    this.bytes = new Uint8Array(buffer, byteOffset, byteLength);
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  PathTableEntryView.prototype = {
    get extendedAttributeLength() {
      return this.bytes[1];
    },
    get extentBlockAddress() {
      return this.dv.getUint32(2, this.littleEndian);
    },
    get parentDirectoryIndex() {
      return this.dv.getUint16(6, this.littleEndian);
    },
    get identifier() {
      return String.fromCharCode.apply(null, this.bytes.subarray(8, 8 + this.bytes[0]));
    },
    get byteLength() {
      var idLength = this.bytes[0];
      return 8 + idLength + idLength % 2;
    },
  };

  return {
    getStructView: function(segment) {
      switch (segment.getTypeParameter('which')) {
        case 'volume-descriptor': return VolumeDescriptorView;
        case 'path-table-entry': return PathTableEntryView;
        case 'boot-record': return BootRecordView;
        case 'volume-record': return VolumeRecordView;
        case 'folder': return DirectoryRecordView;
        case 'file': return DirectoryRecordView;
        default: return null;
      }
    },
    PathTableEntryView: PathTableEntryView,
    VolumeDescriptorView: VolumeDescriptorView,
    BootRecordView: BootRecordView,
    VolumeRecordView: VolumeRecordView,
    DirectoryRecordView: DirectoryRecordView,
  };

});
<|endoftext|>


<commit_before>/*
 * Global constants and stuff that define how the game works.
 */
define({
  debug: false,

  canvasWidthPx: 640,
  canvasHeightPx: 480,

  player: {
    width: 32,
    height: 32,
    speed: 200,
    collision: {
      xMin: 8,
      xMax: 28,
      yMin: 2,
      yMax: 26,
    },
  },

  gun: {
    width: 15,
    height: 5,
    offsetX: 30,
    offsetY: 10,
  },

  layers: {
    background: 1,
    obstacles: 2,
    enemies: 3,
    gun: 4,
    player: 5,
    bullets: 6,
  },

  bullet: {
    speed: 600,
    maxDistance: 1000,
  },

  tile: {
    width: 32,
    height: 32,
  },

  room: {
    width: 13,
    height: 13,
    spriteWidth: 480,
    spriteHeight: 480,
  },

  map: {
    width: 4,
    height: 4,
    connectedness: 0.5,
  },

  NORTH: 0,
  EAST: 1,
  SOUTH: 2,
  WEST: 3,
});
<commit_msg>Made the game a bit bigger.<commit_after>/*
 * Global constants and stuff that define how the game works.
 */
define({
  debug: false,

  canvasWidthPx: 800,
  canvasHeightPx: 600,

  player: {
    width: 32,
    height: 32,
    speed: 200,
    collision: {
      xMin: 8,
      xMax: 28,
      yMin: 2,
      yMax: 26,
    },
  },

  gun: {
    width: 15,
    height: 5,
    offsetX: 30,
    offsetY: 10,
  },

  layers: {
    background: 1,
    obstacles: 2,
    enemies: 3,
    gun: 4,
    player: 5,
    bullets: 6,
  },

  bullet: {
    speed: 600,
    maxDistance: 1000,
  },

  tile: {
    width: 32,
    height: 32,
  },

  room: {
    width: 13,
    height: 13,
    spriteWidth: 480,
    spriteHeight: 480,
  },

  map: {
    width: 4,
    height: 4,
    connectedness: 0.5,
  },

  NORTH: 0,
  EAST: 1,
  SOUTH: 2,
  WEST: 3,
});
<|endoftext|>