<commit_before>#!/usr/bin/env node

var posthtml = require('posthtml');
var fs = require('fs');
var argv = require('yargs')
	.usage('Usage: $0 --output|-o output.html --input|-i input.html [--config|-c config.json]')
	.example('posthtml -o output.html -i input.html', 'Default example')
	.demand(['o', 'i'])
	.alias('i', 'input')
	.alias('o', 'output')
	.pkgConf('posthtml')
	.config('c')
	.alias('c', 'config')
	.version(function () {
		return require('./package.json').version;
	})
	.alias('v', 'version')
	.help('h')
	.alias('h', 'help')
	.argv;

// get htmls
var html = fs.readFileSync(argv.input, 'utf8');

// get plugins
var plugins = [];
if (argv.require) {
	plugins = argv.require.map(function (name) {
		return require(name)(argv[name]);
	});
}

// processing
posthtml(plugins)
	.process(html)
	.then(function (result) {
		fs.writeFileSync(argv.output, result.html);
	});
<commit_msg>Change cmod<commit_after>#!/usr/bin/env node
var posthtml = require('posthtml');
var fs = require('fs');
var argv = require('yargs')
	.usage('Usage: $0 --output|-o output.html --input|-i input.html [--config|-c config.json]')
	.example('posthtml -o output.html -i input.html', 'Default example')
	.demand(['o', 'i'])
	.alias('i', 'input')
	.alias('o', 'output')
	.pkgConf('posthtml')
	.config('c')
	.alias('c', 'config')
	.version(function () {
		return require('./package.json').version;
	})
	.alias('v', 'version')
	.help('h')
	.alias('h', 'help')
	.argv;

// get htmls
var html = fs.readFileSync(argv.input, 'utf8');

// get plugins
var plugins = [];
if (argv.require) {
	plugins = argv.require.map(function (name) {
		return require(name)(argv[name]);
	});
}

// processing
posthtml(plugins)
	.process(html)
	.then(function (result) {
		fs.writeFileSync(argv.output, result.html);
	});
<|endoftext|>


<commit_before>import classnames from 'classnames';
import React, { PropTypes } from 'react';

function Form ({ className, component, type, ...props }) {
	const Component = component;
	props.className = classnames('Form', ('Form--' + type), className);

	return <Component {...props} />;
};

Form.propTypes = {
	component: PropTypes.oneOfType([
		React.PropTypes.element,
		React.PropTypes.func,
	]),
	type: PropTypes.oneOf(['basic', 'horizontal', 'inline']),
};
Form.defaultProps = {
	component: 'form',
	type: 'basic',
};

module.exports = Form;
<commit_msg>Form: fix typo<commit_after>import classnames from 'classnames';
import React, { PropTypes } from 'react';

function Form ({ className, component, type, ...props }) {
	const Component = component;
	props.className = classnames('Form', ('Form--' + type), className);

	return <Component {...props} />;
};

Form.propTypes = {
	component: PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.func,
	]),
	type: PropTypes.oneOf(['basic', 'horizontal', 'inline']),
};
Form.defaultProps = {
	component: 'form',
	type: 'basic',
};

module.exports = Form;
<|endoftext|>


<commit_before>Crafty.c('Hero',
{
	Pickups : null,
	Spells : null,
	ActiveSpells : null,

	init: function()
	{
		this.requires('Pawn');
		this.bind("EnterFrame", this._updateHero);
		this.bind("Appeared", this._heroAppeared);
		this.bind("Remove", this._heroDied);
		this.bind("BodyMoved", this._heroMoved);

		this.Pickups = {};
		this.Spells = {};
		this.ActiveSpells = [];

		this.IncreasePickup('soul', 500);

		return this;
	},

	_heroAppeared : function()
	{
		var oldPlayer = this._world.Player;
		if (oldPlayer != null)
		{
			if (!oldPlayer.IsDestroyed)
				throw ("cannot have two living players in the world!");

			this.Pickups = oldPlayer.Pickups;
			this._checkActivateSpells();
		}
		this._world.Player = this;
		Crafty.trigger("HeroReborn", { hero : this });
	},

	AddSpell : function(name, costs, icon)
	{
		this.Spells[name] = { costs : costs, active : false, icon : icon };
	},

	GetSpellIcon : function(name)
	{
		return this.Spells[name].icon;
	},

	IsSpellActive : function(name)
	{
		return this.Spells[name].active;
	},

	CastSpell : function(index)
	{
		if (index < 0 || index >= this.ActiveSpells.length)
			return;

		var spell = this.ActiveSpells[index];

		var hit = this._toTileSpace(Crafty.mousePos.x, Crafty.mousePos.y);
		var center = this.GetCenter();
		var dir = Math3D.Direction(center, hit);
		this.UseSlot(spell, {dir : dir});

		var data = this.Spells[spell];
		for (var name in data.costs)
		{
			this.Pickups[name] -= data.costs[name];
		}

		this._checkDeactivateSpells();
	},

	_updateHero : function()
	{
		var result = this._world.PickupMap.RadiusCheck(this.GetCenter(), 3);
		var hits = result.hits;

		for (var i = 0; i < hits.length; i++)
		{
			var pickup = hits[i].entity;
			pickup.PickedUpBy(this);
		}
	},

	ReceivedPickup : function(pickup)
	{
		var name = pickup.PickupName;
		this.IncreasePickup(name, 1);
	},

	IncreasePickup : function(pickupName, amount)
	{
		if (this.Pickups[pickupName])
		{
			this.Pickups[pickupName] += amount;
		}
		else
		{
			this.Pickups[pickupName] = amount;
		}
		this._checkActivateSpells();
	},

	_checkActivateSpells : function()
	{
		var changed = false;
		for (var name in this.Spells)
		{
			var data = this.Spells[name];
			if (!data.active)
			{
				if (this._canAfford(data.costs))
				{
					data.active = true;
					this.ActiveSpells.push(name);
					changed = true;
				}
			}
		}

		if (changed)
			this.trigger("SpellChanged");
	},

	_checkDeactivateSpells : function()
	{
		var changed = false;
		for (var i = this.ActiveSpells.length-1; i >= 0; i--)
		{
			var spell = this.ActiveSpells[i];
			var data = this.Spells[spell];
			if (!this._canAfford(data.costs))
			{
				data.active = false;
				this.ActiveSpells.splice(i, 1);
				changed = true;
			}
		}

		if (changed)
			this.trigger("SpellChanged");
	},

	_canAfford : function(costs)
	{
		for (var name in costs)
		{
			var count = this.Pickups[name] || 0;
			if (count < costs[name])
				return false;
		}
		return true;
	},

	_heroDied : function()
	{
		var playerSpawnPoint = this._world.GetPlayerSpawnPoint();
		var x0 = (playerSpawnPoint.x + 0.5) * this._world.TileSize - Crafty.viewport.width / 2,
			y0 = (playerSpawnPoint.y + 0.5) * this._world.TileSize - Crafty.viewport.height / 2;
		Crafty.viewport.scrollTo(-x0, -y0);

		Crafty.trigger("HeroDied", { hero : this });
	},

	_heroMoved : function(e)
	{
		var from = e.from;
		var to = e.to;

		var hit = this._world.TerrainMap.LineCheck(from, to, this.GetRadius());
		if (hit != null)
		{
			var newCenter = hit.location;
			this._tileX = newCenter.x - (this.TileWidth - 1) / 2.0;
			this._tileY = newCenter.y - (this.TileHeight - 1) / 2.0;
		}
	}
});
<commit_msg>fix the stickiness of movement, now will slide<commit_after>Crafty.c('Hero',
{
	Pickups : null,
	Spells : null,
	ActiveSpells : null,

	init: function()
	{
		this.requires('Pawn');
		this.bind("EnterFrame", this._updateHero);
		this.bind("Appeared", this._heroAppeared);
		this.bind("Remove", this._heroDied);
		this.bind("BodyMoved", this._heroMoved);

		this.Pickups = {};
		this.Spells = {};
		this.ActiveSpells = [];

		this.IncreasePickup('soul', 500);

		return this;
	},

	_heroAppeared : function()
	{
		var oldPlayer = this._world.Player;
		if (oldPlayer != null)
		{
			if (!oldPlayer.IsDestroyed)
				throw ("cannot have two living players in the world!");

			this.Pickups = oldPlayer.Pickups;
			this._checkActivateSpells();
		}
		this._world.Player = this;
		Crafty.trigger("HeroReborn", { hero : this });
	},

	AddSpell : function(name, costs, icon)
	{
		this.Spells[name] = { costs : costs, active : false, icon : icon };
	},

	GetSpellIcon : function(name)
	{
		return this.Spells[name].icon;
	},

	IsSpellActive : function(name)
	{
		return this.Spells[name].active;
	},

	CastSpell : function(index)
	{
		if (index < 0 || index >= this.ActiveSpells.length)
			return;

		var spell = this.ActiveSpells[index];

		var hit = this._toTileSpace(Crafty.mousePos.x, Crafty.mousePos.y);
		var center = this.GetCenter();
		var dir = Math3D.Direction(center, hit);
		this.UseSlot(spell, {dir : dir});

		var data = this.Spells[spell];
		for (var name in data.costs)
		{
			this.Pickups[name] -= data.costs[name];
		}

		this._checkDeactivateSpells();
	},

	_updateHero : function()
	{
		var result = this._world.PickupMap.RadiusCheck(this.GetCenter(), 3);
		var hits = result.hits;

		for (var i = 0; i < hits.length; i++)
		{
			var pickup = hits[i].entity;
			pickup.PickedUpBy(this);
		}
	},

	ReceivedPickup : function(pickup)
	{
		var name = pickup.PickupName;
		this.IncreasePickup(name, 1);
	},

	IncreasePickup : function(pickupName, amount)
	{
		if (this.Pickups[pickupName])
		{
			this.Pickups[pickupName] += amount;
		}
		else
		{
			this.Pickups[pickupName] = amount;
		}
		this._checkActivateSpells();
	},

	_checkActivateSpells : function()
	{
		var changed = false;
		for (var name in this.Spells)
		{
			var data = this.Spells[name];
			if (!data.active)
			{
				if (this._canAfford(data.costs))
				{
					data.active = true;
					this.ActiveSpells.push(name);
					changed = true;
				}
			}
		}

		if (changed)
			this.trigger("SpellChanged");
	},

	_checkDeactivateSpells : function()
	{
		var changed = false;
		for (var i = this.ActiveSpells.length-1; i >= 0; i--)
		{
			var spell = this.ActiveSpells[i];
			var data = this.Spells[spell];
			if (!this._canAfford(data.costs))
			{
				data.active = false;
				this.ActiveSpells.splice(i, 1);
				changed = true;
			}
		}

		if (changed)
			this.trigger("SpellChanged");
	},

	_canAfford : function(costs)
	{
		for (var name in costs)
		{
			var count = this.Pickups[name] || 0;
			if (count < costs[name])
				return false;
		}
		return true;
	},

	_heroDied : function()
	{
		var playerSpawnPoint = this._world.GetPlayerSpawnPoint();
		var x0 = (playerSpawnPoint.x + 0.5) * this._world.TileSize - Crafty.viewport.width / 2,
			y0 = (playerSpawnPoint.y + 0.5) * this._world.TileSize - Crafty.viewport.height / 2;
		Crafty.viewport.scrollTo(-x0, -y0);

		Crafty.trigger("HeroDied", { hero : this });
	},

	_heroMoved : function(e)
	{
		var from = e.from;
		var to = e.to;

		var hit = this._world.TerrainMap.LineCheck(from, to, this.GetRadius());
		if (hit != null)
		{
			var dir = Math3D.Delta(from, to);
			var realDir = Math3D.Delta(from, hit.location);
			var off = Math3D.Delta(realDir, dir);
			var loc = hit.location;
			var shiftX = Math3D.Add(loc, { x : off.x, y : 0 });
			var shiftY = Math3D.Add(loc, { x : 0, y : off.y });
			if (Math.abs(off.x) > Math.abs(off.y))
			{
				if (this._world.TerrainMap.LineCheck(loc, shiftX, this.GetRadius()) === null)
					loc = shiftX;
				else if (off.y != 0 && this._world.TerrainMap.LineCheck(loc, shiftY, this.GetRadius()) === null)
					loc = shiftY;
			}
			else
			{
				if (this._world.TerrainMap.LineCheck(loc, shiftY, this.GetRadius()) === null)
					loc = shiftY;
				else if (off.x != 0 && this._world.TerrainMap.LineCheck(loc, shiftX, this.GetRadius()) === null)
					loc = shiftX;
			}

			this._tileX = loc.x - (this.TileWidth - 1) / 2.0;
			this._tileY = loc.y - (this.TileHeight - 1) / 2.0;
		}
	}
});
<|endoftext|>


<commit_before>require('normalize.css/normalize.css');
require('styles/App.scss');

import React from 'react';
import ReactDOM from 'react-dom';

// 获取图片相关的数据
var imageDatas = require('../data/imageDatas.json');

// 利用自执行函数， 将图片名信息转成图片URL路径信息
imageDatas = (function genImageURL(imageDatasArr) {
  for (var i = 0, j = imageDatasArr.length; i < j; i++) {
    var singleImageData = imageDatasArr[i];
    singleImageData.imageURL = require('../images/' + singleImageData.fileName);
    imageDatasArr[i] = singleImageData;
  }
  return imageDatasArr;
})(imageDatas);

//构建单幅画的组件
let ImgFigure = React.createClass({
  render : function(){
    return(

{this.props.data.title}

    )
  }
});

let GalleryByReactApp = React.createClass({
  render: function(){
    //声明两个组件用来包含所有的图片
    var controllerUnits = [],
    imgFigures = [];

    imageDatas.forEach(function(item,index){
      imgFigures.push(<ImgFigure key={index} data={item}/>);
    })

    return(

          {imgFigures}

          {controllerUnits}

    );
  }
});

ReactDOM.render(<GalleryByReactApp /> , document.getElementById('app'));
module.exports = GalleryByReactApp;

<commit_msg>图片随机布局<commit_after>require('normalize.css/normalize.css');
require('styles/App.scss');

import React from 'react';
import ReactDOM from 'react-dom';

// 获取图片相关的数据
var imageDatas = require('../data/imageDatas.json');

// 利用自执行函数， 将图片名信息转成图片URL路径信息
imageDatas = (function genImageURL(imageDatasArr) {
  for (var i = 0, j = imageDatasArr.length; i < j; i++) {
    var singleImageData = imageDatasArr[i];
    singleImageData.imageURL = require('../images/' + singleImageData.fileName);
    imageDatasArr[i] = singleImageData;
  }
  return imageDatasArr;
})(imageDatas);

/*
* 获取区间内的一个随机值
* */
function getRangeRandom(low, high) {
  return Math.ceil(Math.random() * (high - low) + low);
}

//构建单幅画的组件
let ImgFigure = React.createClass({
  render : function(){
    var styleObj = {};
    // 如果props属性中指定了这张图片的位置，则使用
    if (this.props.arrange.pos) {
      styleObj = this.props.arrange.pos;
    }

    return(

{this.props.data.title}

    )
  }
});

let GalleryByReactApp = React.createClass({
  Constant : {
    centerPos :{//居中位置图片的取值范围
      left : 0,
      right:0
    },
    hPosRange : { //水平方向的取值范围
      leftSecX : [0 , 0],
      rightSecX : [0 ,0],
      y:[0 , 0]
    },
    vPosRange : {// 垂直方向的取值范围
      x: [0, 0],
      topY: [0, 0]
    }
  },
  /*
  * 重新布局所有图片
  * 指定居中排布哪一张图片
  * */
  rearrage : function(centerIndex){
    var imgsArrangeArr = this.state.imgsArrangeArr,
        Constant = this.Constant,
        centerPos = Constant.centerPos,
        hPosRange = Constant.hPosRange,
        vPosRange = Constant.vPosRange,
        hPosRangeLeftSecX = hPosRange.leftSecX,
        hPosRangeRightSecX = hPosRange.rightSecX,
        hPosRangeY = hPosRange.y,
        vPosRangeTopY = vPosRange.topY,
        vPosRangeX = vPosRange.x,

        imgsArrangeTopArr = [], //用来存储我们布局在上侧图片的状态信息
        topImgNum = Math.floor(Math.random() * 2), //取一个或者不取 值为0或1
        topImgSpliceIndex = 0, //用来标记布局在上侧的图是在数组的哪个位置
        imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);  //中心图片的状态

        //首先居中centerIndex的图片
        imgsArrangeCenterArr[0].pos = centerPos;

        //取出要布局上侧图片的状态信息
        topImgSpliceIndex = Math.ceil( Math.random() * (imgsArrangeArr.length - topImgNum));
        imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum);

        //布局位于上侧的图片
        imgsArrangeTopArr.forEach(function(value,index){
          imgsArrangeTopArr[index].pos = {
            top:getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]),
            left:getRangeRandom(vPosRangeX[0],vPosRangeX[1])
          }
        });

        //布局位于左右两侧的图片
        for(var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++){
          var hPosRangeLORX = null;

          //前半部分布局在左边 右半部分布局在右边
          if(i < k){
            hPosRangeLORX = hPosRangeLeftSecX;
          }else{
            hPosRangeLORX = hPosRangeRightSecX;
          };

          imgsArrangeArr[i].pos = {
            top:getRangeRandom(hPosRangeY[0],hPosRangeY[1]),
            left:getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1])
          };
        }

        if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
          imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]);  //位于上侧的图片信息放到数组中
        };
        imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]); //位于中心的图片信息放回到数组中

        this.setState({
          imgsArrangeArr:imgsArrangeArr
        });
  },
  getInitialState : function(){
    return {
      imgsArrangeArr : [ //初始化状态对象
        /*{
          pos : {
            left : '0',
            top : '0'
          }
        }*/
      ]
    }
  },
  //组件加载以后，为每张图片计算其位置的范围
  componentDidMount : function(){
    //拿到舞台的大小
    var stageDOM = React.findDOMNode(this.refs.stage), //舞台
        stageW = stageDOM.scrollWidth,   //舞台大小
        stageH = stageDOM.scrollHeight,
        halfStageW = Math.ceil(stageW / 2),
        halfStageH = Math.ceil(stageH / 2);

    //拿到一个imgfigure的大小
    var imgFigureDOM = React.findDOMNode(this.refs.imgFigure0),
        imgW = imgFigureDOM.scrollWidth,
        imgH = imgFigureDOM.scrollHeight,
        halfImgW = Math.ceil(imgW / 2),
        halfImgH = Math.ceil(imgH / 2);

    //计算中心图片的位置点
    this.Constant.centerPos = {
        left : halfStageW - halfImgW,
        top : halfStageH - halfImgH
    }

    //计算左侧 右侧区域图片的排布位置的取值范围
    this.Constant.hPosRange.leftSecX[0] = -halfImgW;
    this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW / 2*3;
    this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
    this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
    this.Constant.hPosRange.y[0] = -halfImgH;
    this.Constant.hPosRange.y[1] = stageH - halfImgH;

    this.Constant.vPosRange.topY[0] = -halfImgH;
    this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
    this.Constant.vPosRange.x[0] = halfImgW - imgW;
    this.Constant.vPosRange.x[1] = halfImgW;

    //调用图片排布位置的方法
    this.rearrage(0); //指定图片数组中的第一张居中
  },
  render: function(){
    //声明两个组件用来包含所有的图片
    var controllerUnits = [],
    imgFigures = [];

    imageDatas.forEach(function(item,index){
      if(!this.state.imgsArrangeArr[index]){
        this.state.imgsArrangeArr[index] = {
          pos : { //初始化状态对象，定位到左上角
            left : 0,
            top : 0
          }
        }
      }
      imgFigures.push(<ImgFigure key={index} data={item} ref={'imgFigure' + index} arrange = {this.state.imgsArrangeArr[index]}/>);
    }.bind(this))

    return(

          {imgFigures}

          {controllerUnits}

    );
  }
});

ReactDOM.render(<GalleryByReactApp /> , document.getElementById('app'));
module.exports = GalleryByReactApp;

<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';

export default class Todo extends Component {
  render() {
    return (
      <li
        onClick={this.props.onClick}
        style={{
          textDecoration: this.props.completed ? "line-through" : "none",
          cursor: this.props.completed ? "default" : "pointer"
        }}>
        {this.props.text}
      </li>
    );
  }
}

Todo.propTypes = {
  onClick: PropTypes.func.isRequired,
  text: PropTypes.string.isRequired,
  completed: PropTypes.bool.isRequired
};
<commit_msg>fix(Todo): remove unused<commit_after><|endoftext|>


<commit_before>/*
hinclude.js -- HTML Includes (version 0.9)

Copyright (c) 2005-2011 Mark Nottingham <mnot@mnot.net>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

------------------------------------------------------------------------------

See http://www.mnot.net/javascript/hinclude/ for documentation.

TODO:
 - check navigator property to see if browser will handle this without
   javascript

------------------------------------------------------------------------------
*/

var hinclude = {
  set_content_async: function (element, req) {
    if (req.readyState == 4) {
      if (req.status == 200 | req.status == 304) {
        element.innerHTML = req.responseText;
      }
      element.className = "include_" + req.status;
    }
  },

  buffer: new Array(),
  set_content_buffered: function (element, req) {
    if (req.readyState == 4) {
      hinclude.buffer.push(new Array(element, req));
      hinclude.outstanding--;
      if (hinclude.outstanding == 0) {
        hinclude.show_buffered_content();
      }
    }
  },
  show_buffered_content: function () {
    while (hinclude.buffer.length > 0) {
      var include = hinclude.buffer.pop();
      if (include[1].status == 200 | include[1].status == 304) {
        include[0].innerHTML = include[1].responseText;
      }
      include[0].className = "include_" + include[1].status;
    }
  },

  outstanding: 0,
  run: function () {
    var mode = this.get_meta("include_mode", "buffered");
    var callback = function(element, req) {};
    var includes = document.getElementsByTagName("hx:include");
    if (includes.length == 0) { // remove ns for IE
      includes = document.getElementsByTagName("include");
    }
    if (mode == "async") {
      callback = this.set_content_async;
    } else if (mode == "buffered") {
      callback = this.set_content_buffered;
      var timeout = this.get_meta("include_timeout", 2.5) * 1000;
      setTimeout("hinclude.show_buffered_content()", timeout);
    }
    for (var i=0; i < includes.length; i++) {
      this.include(includes[i], includes[i].getAttribute("src"), callback);
    }
  },

  include: function (element, url, incl_cb) {
    scheme = url.substring(0,url.indexOf(":"));
    if (scheme.toLowerCase() == "data") { // just text/plain for now
      data = unescape(url.substring(url.indexOf(",") + 1, url.length));
      element.innerHTML = data;
    } else {
      var req = false;
      if(window.XMLHttpRequest) {
        try {
          req = new XMLHttpRequest();
        } catch(e) {
          req = false;
        }
      } else if (window.ActiveXObject) {
        try {
          req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
          req = false;
        }
      }
      if (req) {
        this.outstanding++;
        req.onreadystatechange = function() {
          incl_cb(element, req);
        };
        try {
          req.open("GET", url, true);
          req.send("");
        } catch (e) {
          this.outstanding--;
          alert("Include error: " + url + " (" + e + ")");
        }
      }
    }
  },

  get_meta: function (name, value_default) {
    var metas = document.getElementsByTagName("meta");
    for (var m=0; m < metas.length; m++) {
      var meta_name = metas[m].getAttribute("name");
      if (meta_name == name) {
        return metas[m].getAttribute("content");
      }
    }
    return value_default;
  },

  /*
   * (c)2006 Dean Edwards/Matthias Miller/John Resig
   * Special thanks to Dan Webb's domready.js Prototype extension
   * and Simon Willison's addLoadEvent
   *
   * For more info, see:
   * http://dean.edwards.name/weblog/2006/06/again/
   *
   * Thrown together by Jesse Skinner (http://www.thefutureoftheweb.com/)
   *
   *
   * To use: call addDOMLoadEvent one or more times with functions, ie:
   *
   *    function something() {
   *       // do something
   *    }
   *    addDOMLoadEvent(something);
   *
   *    addDOMLoadEvent(function() {
   *        // do other stuff
   *    });
   */
  addDOMLoadEvent: function(func) {
    if (!window.__load_events) {
      var init = function () {
        // quit if this function has already been called
        if (arguments.callee.done) return;

        // flag this function so we don't do the same thing twice
        arguments.callee.done = true;

        // kill the timer
        if (window.__load_timer) {
          clearInterval(window.__load_timer);
          window.__load_timer = null;
        }

        // execute each function in the stack in the order they were added
        for (var i=0;i < window.__load_events.length;i++) {
          window.__load_events[i]();
        }
        window.__load_events = null;

        // clean up the __ie_onload event
        /*@cc_on @*/
        /*@if (@_win32)
          document.getElementById("__ie_onload").onreadystatechange = "";
        /*@end @*/
      };

      // for Mozilla/Opera9
      if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", init, false);
      }

      // for Internet Explorer
      /*@cc_on @*/
      /*@if (@_win32)
          document.write(
            "<scr"
            + "ipt id=__ie_onload defer src=javascript:void(0)><\/scr"
            + "ipt>"
          );
          var script = document.getElementById("__ie_onload");
          script.onreadystatechange = function() {
              if (this.readyState == "complete") {
                  init(); // call the onload handler
              }
          };
      /*@end @*/

      // for Safari
      if (/WebKit/i.test(navigator.userAgent)) { // sniff
        window.__load_timer = setInterval(function() {
          if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
          }
        }, 10);
      }

      // for other browsers
      window.onload = init;

      // create event function stack
      window.__load_events = [];
    }

    // add function to event stack
    window.__load_events.push(func);
  }
};

hinclude.addDOMLoadEvent(function() { hinclude.run(); });
<commit_msg>declare scheme variable<commit_after>/*
hinclude.js -- HTML Includes (version 0.9)

Copyright (c) 2005-2011 Mark Nottingham <mnot@mnot.net>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

------------------------------------------------------------------------------

See http://www.mnot.net/javascript/hinclude/ for documentation.

TODO:
 - check navigator property to see if browser will handle this without
   javascript

------------------------------------------------------------------------------
*/

var hinclude = {
  set_content_async: function (element, req) {
    if (req.readyState == 4) {
      if (req.status == 200 | req.status == 304) {
        element.innerHTML = req.responseText;
      }
      element.className = "include_" + req.status;
    }
  },

  buffer: new Array(),
  set_content_buffered: function (element, req) {
    if (req.readyState == 4) {
      hinclude.buffer.push(new Array(element, req));
      hinclude.outstanding--;
      if (hinclude.outstanding == 0) {
        hinclude.show_buffered_content();
      }
    }
  },
  show_buffered_content: function () {
    while (hinclude.buffer.length > 0) {
      var include = hinclude.buffer.pop();
      if (include[1].status == 200 | include[1].status == 304) {
        include[0].innerHTML = include[1].responseText;
      }
      include[0].className = "include_" + include[1].status;
    }
  },

  outstanding: 0,
  run: function () {
    var mode = this.get_meta("include_mode", "buffered");
    var callback = function(element, req) {};
    var includes = document.getElementsByTagName("hx:include");
    if (includes.length == 0) { // remove ns for IE
      includes = document.getElementsByTagName("include");
    }
    if (mode == "async") {
      callback = this.set_content_async;
    } else if (mode == "buffered") {
      callback = this.set_content_buffered;
      var timeout = this.get_meta("include_timeout", 2.5) * 1000;
      setTimeout("hinclude.show_buffered_content()", timeout);
    }
    for (var i=0; i < includes.length; i++) {
      this.include(includes[i], includes[i].getAttribute("src"), callback);
    }
  },

  include: function (element, url, incl_cb) {
    var scheme = url.substring(0,url.indexOf(":"));
    if (scheme.toLowerCase() == "data") { // just text/plain for now
      data = unescape(url.substring(url.indexOf(",") + 1, url.length));
      element.innerHTML = data;
    } else {
      var req = false;
      if(window.XMLHttpRequest) {
        try {
          req = new XMLHttpRequest();
        } catch(e) {
          req = false;
        }
      } else if (window.ActiveXObject) {
        try {
          req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
          req = false;
        }
      }
      if (req) {
        this.outstanding++;
        req.onreadystatechange = function() {
          incl_cb(element, req);
        };
        try {
          req.open("GET", url, true);
          req.send("");
        } catch (e) {
          this.outstanding--;
          alert("Include error: " + url + " (" + e + ")");
        }
      }
    }
  },

  get_meta: function (name, value_default) {
    var metas = document.getElementsByTagName("meta");
    for (var m=0; m < metas.length; m++) {
      var meta_name = metas[m].getAttribute("name");
      if (meta_name == name) {
        return metas[m].getAttribute("content");
      }
    }
    return value_default;
  },

  /*
   * (c)2006 Dean Edwards/Matthias Miller/John Resig
   * Special thanks to Dan Webb's domready.js Prototype extension
   * and Simon Willison's addLoadEvent
   *
   * For more info, see:
   * http://dean.edwards.name/weblog/2006/06/again/
   *
   * Thrown together by Jesse Skinner (http://www.thefutureoftheweb.com/)
   *
   *
   * To use: call addDOMLoadEvent one or more times with functions, ie:
   *
   *    function something() {
   *       // do something
   *    }
   *    addDOMLoadEvent(something);
   *
   *    addDOMLoadEvent(function() {
   *        // do other stuff
   *    });
   */
  addDOMLoadEvent: function(func) {
    if (!window.__load_events) {
      var init = function () {
        // quit if this function has already been called
        if (arguments.callee.done) return;

        // flag this function so we don't do the same thing twice
        arguments.callee.done = true;

        // kill the timer
        if (window.__load_timer) {
          clearInterval(window.__load_timer);
          window.__load_timer = null;
        }

        // execute each function in the stack in the order they were added
        for (var i=0;i < window.__load_events.length;i++) {
          window.__load_events[i]();
        }
        window.__load_events = null;

        // clean up the __ie_onload event
        /*@cc_on @*/
        /*@if (@_win32)
          document.getElementById("__ie_onload").onreadystatechange = "";
        /*@end @*/
      };

      // for Mozilla/Opera9
      if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", init, false);
      }

      // for Internet Explorer
      /*@cc_on @*/
      /*@if (@_win32)
          document.write(
            "<scr"
            + "ipt id=__ie_onload defer src=javascript:void(0)><\/scr"
            + "ipt>"
          );
          var script = document.getElementById("__ie_onload");
          script.onreadystatechange = function() {
              if (this.readyState == "complete") {
                  init(); // call the onload handler
              }
          };
      /*@end @*/

      // for Safari
      if (/WebKit/i.test(navigator.userAgent)) { // sniff
        window.__load_timer = setInterval(function() {
          if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
          }
        }, 10);
      }

      // for other browsers
      window.onload = init;

      // create event function stack
      window.__load_events = [];
    }

    // add function to event stack
    window.__load_events.push(func);
  }
};

hinclude.addDOMLoadEvent(function() { hinclude.run(); });
<|endoftext|>


<commit_before>/*
 * Backpack - Skyscanner's Design System
 *
 * Copyright 2018 Skyscanner Ltd
 *
 * 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.
 */
/* @flow */
import React from 'react';
import { storiesOf } from '@storybook/react-native';
import { StyleSheet, View } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import {
  spacingBase,
  spacingXxl,
  borderRadiusSm,
} from 'bpk-tokens/tokens/base.react.native';
import BpkText from 'react-native-bpk-component-text';

import CenterDecorator from '../../storybook/CenterDecorator';
import { gradients } from './index';

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    flex: 1,
    flexWrap: 'wrap',
  },
  swatch: {
    width: spacingXxl * 3,
    height: spacingXxl * 3,
    borderRadius: borderRadiusSm,
  },
  swatchContainer: {
    flexDirection: 'column',
    marginBottom: spacingBase,
  },
});

storiesOf('react-native-bpk-styles', module)
  .addDecorator(CenterDecorator)
  .add('docs:gradients', () => (
    <View style={styles.container}>
      {Object.keys(gradients.ANGLES).map(key => (
        <View key={key} style={styles.swatchContainer}>
          <BpkText>{key}</BpkText>
          <LinearGradient
            style={styles.swatch}
            {...gradients.primary(gradients.ANGLES[key])}
          />
        </View>
      ))}
    </View>
  ))
  .add('docs:full', () => (
    <LinearGradient style={styles.container} {...gradients.primary()} />
  ));
<commit_msg>[No JIRA] Add performance gradient story<commit_after>/*
 * Backpack - Skyscanner's Design System
 *
 * Copyright 2018 Skyscanner Ltd
 *
 * 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.
 */

/* @flow */
import React, { Component } from 'react';
import { storiesOf } from '@storybook/react-native';
import { StyleSheet, View } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import {
  spacingBase,
  spacingXxl,
  borderRadiusSm,
} from 'bpk-tokens/tokens/base.react.native';
import BpkText from 'react-native-bpk-component-text';

import CenterDecorator from '../../storybook/CenterDecorator';
import { gradients } from './index';

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    flex: 1,
    flexWrap: 'wrap',
  },
  swatch: {
    width: spacingXxl * 3,
    height: spacingXxl * 3,
    borderRadius: borderRadiusSm,
  },
  swatchContainer: {
    flexDirection: 'column',
    marginBottom: spacingBase,
  },
});

const getRandomColor = () => {
  const letters = '0123456789ABCDEF';
  let color = '#';

  for (let i = 0; i < 6; i += 1) {
    color += letters[Math.floor(Math.random() * 16)];
  }

  return color;
};

type State = {
  startColor: string,
  endColor: string,
};
class RandomGradient extends Component<{}, State> {
  state: State;

  intervalId: ?IntervalID;

  constructor() {
    super();

    this.state = {
      startColor: getRandomColor(),
      endColor: getRandomColor(),
    };
  }

  componentDidMount() {
    this.intervalId = setInterval(() => {
      this.setState(() => ({
        startColor: getRandomColor(),
        endColor: getRandomColor(),
      }));
    }, 500);
  }

  componentWillUnmount() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }

  render() {
    const { startColor, endColor } = this.state;

    return (
      <LinearGradient
        style={styles.container}
        {...gradients.primary()}
        colors={[startColor, endColor]}
      />
    );
  }
}

storiesOf('react-native-bpk-styles', module)
  .addDecorator(CenterDecorator)
  .add('docs:gradients', () => (
    <View style={styles.container}>
      {Object.keys(gradients.ANGLES).map(key => (
        <View key={key} style={styles.swatchContainer}>
          <BpkText>{key}</BpkText>
          <LinearGradient
            style={styles.swatch}
            {...gradients.primary(gradients.ANGLES[key])}
          />
        </View>
      ))}
    </View>
  ))
  .add('docs:full', () => (
    <LinearGradient style={styles.container} {...gradients.primary()} />
  ))
  .add('performance:random-gradient', () => <RandomGradient />);
<|endoftext|>


<commit_before>module.exports = function(app) {
  app.config([
    'formioComponentsProvider',
    function(formioComponentsProvider) {
      formioComponentsProvider.register('form', {
        fbtemplate: 'formio/formbuilder/form.html',
        icon: 'fa fa-wpforms',
        views: [
          {
            name: 'Display',
            template: 'formio/components/form/display.html'
          },
          {
            name: 'Data',
            template: 'formio/components/common/data.html'
          },
          {
            name: 'API',
            template: 'formio/components/common/api.html'
          },
          {
            name: 'Conditional',
            template: 'formio/components/common/conditional.html'
          }
        ],
        documentation: 'http://help.form.io/userguide/#form',
        onEdit: ['$scope', function($scope) {
          $scope.forms = [];
          $scope.component.project = $scope.formio.projectId;
          $scope.formio.loadForms({params: {limit: 4294967295}}).then(function(forms) {
            var data = [];
            if ($scope.form._id) {
              angular.forEach(forms, function(form) {
                if (form._id !== $scope.form._id) {
                  data.push(form);
                }
              });
              $scope.forms = data;
            }
            else {
              $scope.forms = forms;
            }

            if (!$scope.component.form) {
              $scope.component.form = forms[0]._id;
            }
          });
        }]
      });

      // Override the controller for form building.
      var formComponent = formioComponentsProvider.$get().components.form;
      var formController = formComponent.controller;
      formComponent.controller = [
        '$scope',
        '$controller',
        function(
          $scope,
          $controller
        ) {
          if (!$scope.builder) {
            return $controller(formController, {$scope: $scope});
          }

          var forms = {};
          $scope.form = {title: 'Unknown form'};
          $scope.formio.loadForms({params: {limit: 4294967295}}).then(function(formioForms) {
            angular.forEach(formioForms, function(form) {
              forms[form._id] = form;
            });

            if (
              $scope.component.form &&
              ($scope.form._id !== $scope.component.form) &&
              forms.hasOwnProperty($scope.component.form)
            ) {
              $scope.form = forms[$scope.component.form];
            }
          });

          $scope.$watch('component.form', function(formId) {
            if (!formId || !forms.hasOwnProperty(formId)) {
              return;
            }
            $scope.form = forms[formId];
          });
        }
      ];
    }
  ]);
  app.run([
    '$templateCache',
    function($templateCache) {
      $templateCache.put('formio/formbuilder/form.html', '{{ form.title }} {{ form.type }}');

      // Create the settings markup.
      $templateCache.put('formio/components/form/display.html',
        '<ng-form>' +
          '<form-builder-option property="label" label="Name" placeholder="Enter the name for this form field" title="The name for this field. It is only used for administrative purposes such as generating the automatic property name in the API tab (which may be changed manually)."></form-builder-option>' +
        '<form-builder-option property="hideLabel"></form-builder-option>' +
          '<form-builder-option-label-position></form-builder-option-label-position>' +
          '
' +
            '{{\'Form\' | formioTranslate}}' +
            '<select class="form-control" id="form" name="form" ng-options="value._id as value.title for value in forms" ng-model="component.form"></select>' +
          '
' +
          '<form-builder-option property="customClass"></form-builder-option>' +
          '<form-builder-option property="reference"></form-builder-option>' +
          '<form-builder-option property="clearOnHide"></form-builder-option>' +
          '<form-builder-option property="protected"></form-builder-option>' +
          '<form-builder-option property="persistent"></form-builder-option>' +
          '<form-builder-option property="encrypted" class="form-builder-premium"></form-builder-option>' +
          '<form-builder-option property="tableView"></form-builder-option>' +
        '</ng-form>'
      );
    }
  ]);
};
<commit_msg>Update form.js<commit_after>module.exports = function(app) {
  app.config([
    'formioComponentsProvider',
    function(formioComponentsProvider) {
      formioComponentsProvider.register('form', {
        fbtemplate: 'formio/formbuilder/form.html',
        icon: 'fa fa-wpforms',
        views: [
          {
            name: 'Display',
            template: 'formio/components/form/display.html'
          },
          {
            name: 'Data',
            template: 'formio/components/common/data.html'
          },
          {
            name: 'API',
            template: 'formio/components/common/api.html'
          },
          {
            name: 'Conditional',
            template: 'formio/components/common/conditional.html'
          }
        ],
        documentation: 'http://help.form.io/userguide/#form',
        onEdit: ['$scope', function($scope) {
          $scope.forms = [];
          $scope.component.project = $scope.formio.projectId;
          $scope.formio.loadForms({params: {limit: 4294967295}}).then(function(forms) {
            var data = [];
            if ($scope.form._id) {
              angular.forEach(forms, function(form) {
                if (form._id !== $scope.form._id) {
                  data.push(form);
                }
              });
              $scope.forms = data;
            }
            else {
              $scope.forms = forms;
            }

            if (!$scope.component.form) {
              $scope.component.form = forms[0]._id;
            }
          });
        }]
      });

      // Override the controller for form building.
      var formComponent = formioComponentsProvider.$get().components.form;
      var formController = formComponent.controller;
      formComponent.controller = [
        '$scope',
        '$controller',
        function(
          $scope,
          $controller
        ) {
          if (!$scope.builder) {
            return $controller(formController, {$scope: $scope});
          }

          var forms = {};
          $scope.form = {title: 'Unknown form'};
          $scope.formio.loadForms({params: {limit: 4294967295}}).then(function(formioForms) {
            angular.forEach(formioForms, function(form) {
              forms[form._id] = form;
            });

            if (
              $scope.component.form &&
              ($scope.form._id !== $scope.component.form) &&
              forms.hasOwnProperty($scope.component.form)
            ) {
              $scope.form = forms[$scope.component.form];
            }
          });

          $scope.$watch('component.form', function(formId) {
            if (!formId || !forms.hasOwnProperty(formId)) {
              return;
            }
            $scope.form = forms[formId];
          });
        }
      ];
    }
  ]);
  app.run([
    '$templateCache',
    function($templateCache) {
      $templateCache.put('formio/formbuilder/form.html', '{{ form.title }} {{ form.type }}');

      // Create the settings markup.
      $templateCache.put('formio/components/form/display.html',
        '<ng-form>' +
          '<form-builder-option property="label" label="Name" placeholder="Enter the name for this form field" title="The name for this field. It is only used for administrative purposes such as generating the automatic property name in the API tab (which may be changed manually)."></form-builder-option>' +
          '<form-builder-option property="hideLabel"></form-builder-option>' +
          '<form-builder-option-label-position></form-builder-option-label-position>' +
          '
' +
            '{{\'Form\' | formioTranslate}}' +
            '<select class="form-control" id="form" name="form" ng-options="value._id as value.title for value in forms" ng-model="component.form"></select>' +
          '
' +
          '<form-builder-option property="customClass"></form-builder-option>' +
          '<form-builder-option property="reference"></form-builder-option>' +
          '<form-builder-option property="clearOnHide"></form-builder-option>' +
          '<form-builder-option property="protected"></form-builder-option>' +
          '<form-builder-option property="persistent"></form-builder-option>' +
          '<form-builder-option property="encrypted" class="form-builder-premium"></form-builder-option>' +
          '<form-builder-option property="tableView"></form-builder-option>' +
        '</ng-form>'
      );
    }
  ]);
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

import '../index.css';
import Board from './board.js';
import calculateWinner from '../helpers/calculate-winner.js'

export default class Game extends React.Component {
  constructor(){
    super();
    this.state = {
      squares: initialiseChessBoard(),
      player: 1,
      sourceSelection: -1,
      status: 'Next player: 1'
    }
  }

  handleClick(i){
    const squares = this.state.squares.slice();

    // if (calculateWinner(squares) || squares[i]) {
    //   return;
    // }
    // squares[i] = this.state.xIsNext? 'X' : 'O';

    if(this.state.sourceSelection === -1){
      if(!squares[i] || squares[i].player !== this.state.player){
        this.setState({status: "Wrong selection. Choose player " + this.state.player + " pieces."});
        squares[i]? delete squares[i].style.backgroundColor: null;
      }
      else{
        squares[i].style = {...squares[i].style, backgroundColor: "lightblue"};
        this.setState({
          status: "Choose destination for the selected piece",
          sourceSelection: i
        });
      }
    }

    else if(this.state.sourceSelection > -1){
      delete squares[this.state.sourceSelection].style.backgroundColor;
      if(squares[i] && squares[i].player === this.state.player){
        this.setState({
          status: "Wrong selection. Choose valid source and destination again.",
          sourceSelection: -1,
        })
      }
      else{

        const squares = this.state.squares;
        const isDestEnemyOccupied = squares[i]? true : false;
        const isMovePossible = squares[this.state.sourceSelection].isMovePossible(this.state.sourceSelection, i, isDestEnemyOccupied);
        const srcToDestPath = squares[this.state.sourceSelection].getSrcToDestPath(this.state.sourceSelection, i);
        const isMoveLegal = this.isMoveLegal(srcToDestPath);

        console.log("isMovePossible", isMovePossible);
        console.log("srcToDestPath", srcToDestPath);
        console.log("isMoveLegal", isMoveLegal);

        squares[i] = squares[this.state.sourceSelection];
        squares[this.state.sourceSelection] = null;
        let player = this.state.player === 1? 2: 1;
        this.setState({
          status: "",
          sourceSelection: -1,
          squares: squares,
          player: player,
          status: 'Next player: ' + player
        });
      }
    }

  }

  /**
   * Check all path indices are null. For one steps move of pawn/others or jumping moves of knight array is empty, so  move is legal.
   * @param  {[type]}  srcToDestPath [array of board indices comprising path between src and dest ]
   * @return {Boolean}
   */
  isMoveLegal(srcToDestPath){
    let isLegal = true;
    for(let i = 0; i < srcToDestPath.length; i++){
      if(this.state.squares[srcToDestPath[i]] !== null){
        isLegal = false;
      }
    }
    return isLegal;
  }

  render() {
    const squares = this.state.squares.slice();
    let winner;
    let winningSquares = calculateWinner(squares);
    let status = this.state.status;

    return (

            <Board
            squares = {squares}
            winningSquares = {winningSquares}
            onClick = {(i) => this.handleClick(i)}
            />

{status}

  Chess Icons And Favicon (extracted) By en:User:Cburnett [GFDL, CC-BY-SA-3.0, BSD or GPL], via Wikimedia Commons

      );
  }
}

class Piece {
  constructor(player, iconUrl){
    this.player = player;
    this.style = {backgroundImage: "url('"+iconUrl+"')"};
  }
}

class Rook extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/72/Chess_rlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/ff/Chess_rdt45.svg"));
  }

  isMovePossible(src, dest){
    let mod = src % 8;
    let diff = 8 - mod;
    return (Math.abs(src - dest) % 8 === 0 || (dest >= (src - mod) && dest < (src + diff)));
  }

  /**
   * get path between src and dest (src and dest exclusive)
   * @param  {num} src
   * @param  {num} dest
   * @return {[array]}
   */
  getSrcToDestPath(src, dest){
    let path = [], pathStart, pathEnd, incrementBy;
    if(src > dest){
      pathStart = dest;
      pathEnd = src;
    }
    else{
      pathStart = src;
      pathEnd = dest;
    }
    if(Math.abs(src - dest) % 8 === 0){
      incrementBy = 8;
      pathStart += 8;
    }
    else{
      incrementBy = 1;
      pathStart += 1;
    }

    for(let i = pathStart; i < pathEnd; i+=incrementBy){
      path.push(i);
    }
    return path;
  }
}

class Bishop extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/b/b1/Chess_blt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/9/98/Chess_bdt45.svg"));
  }

  isMovePossible(src, dest){
    return (Math.abs(src - dest) % 9 === 0 || Math.abs(src - dest) % 7 === 0);
  }

    /**
   * get path between src and dest (src and dest exclusive)
   * @param  {num} src
   * @param  {num} dest
   * @return {[array]}
   */
  getSrcToDestPath(src, dest){
    let path = [], pathStart, pathEnd, incrementBy;
    if(src > dest){
      pathStart = dest;
      pathEnd = src;
    }
    else{
      pathStart = src;
      pathEnd = dest;
    }
    if(Math.abs(src - dest) % 9 === 0){
      incrementBy = 9;
      pathStart += 9;
    }
    else{
      incrementBy = 7;
      pathStart += 7;
    }

    for(let i = pathStart; i < pathEnd; i+=incrementBy){
      path.push(i);
    }
    return path;
  }
}

class Queen extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/1/15/Chess_qlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/4/47/Chess_qdt45.svg"));
  }

  isMovePossible(src, dest){
    let mod = src % 8;
    let diff = 8 - mod;

    return (Math.abs(src - dest) % 9 === 0 || Math.abs(src - dest) % 7 === 0) ||
      (Math.abs(src - dest) % 8 === 0 || (dest >= (src - mod) && dest < (src + diff)));
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class Knight extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/70/Chess_nlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/e/ef/Chess_ndt45.svg"));
  }

  isMovePossible(src, dest){
    return (src - 17 === dest ||
      src - 10 === dest ||
      src + 6 === dest ||
      src + 15 === dest ||
      src - 15 === dest ||
      src - 6 === dest ||
      src + 10 === dest ||
      src + 17 === dest);
  }

  /**
   * always returns empty array because of jumping
   * @return {[]}
   */
  getSrcToDestPath(){
    return [];
  }
}

class King extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/4/42/Chess_klt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/f0/Chess_kdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class Pawn extends Piece {
  constructor(player){
    super(player, (player === 1?  "https://upload.wikimedia.org/wikipedia/commons/4/45/Chess_plt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/c/c7/Chess_pdt45.svg"));
    this.initialPositions = {
      1: [48, 49, 50, 51, 52, 53, 54, 55],
      2: [8, 9, 10, 11, 12, 13, 14, 15]
    }
  }

  isMovePossible(src, dest, isDestEnemyOccupied){

    if(this.player === 1){
      if(dest === src - 8 || (dest === src - 16 && this.initialPositions[1].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src - 9 || dest === src - 7)){
        return true;
      }
    }
    else if(this.player === 2){
      if(dest === src + 8 || (dest === src + 16 && this.initialPositions[2].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src + 9 || dest === src + 7)){
        return true;
      }
    }
    return false;
  }

  getSrcToDestPath(src, dest){
    if(dest === src - 16){
      return [src - 8];
    }
    else if(dest === src + 16){
      return [src + 8];
    }
    return [];
  }
}

function initialiseChessBoard(){

  const squares = Array(64).fill(null);

  for(let i = 8; i < 16; i++){
    squares[i] = new Pawn(2);
    squares[i+40] = new Pawn(1);
  }
  squares[0] = new Rook(2);
  squares[7] = new Rook(2);
  squares[56] = new Rook(1);
  squares[63] = new Rook(1);

  squares[1] = new Knight(2);
  squares[6] = new Knight(2);
  squares[57] = new Knight(1);
  squares[62] = new Knight(1);

  squares[2] = new Bishop(2);
  squares[5] = new Bishop(2);
  squares[58] = new Bishop(1);
  squares[61] = new Bishop(1);

  squares[3] = new Queen(2);
  squares[4] = new King(2);

  squares[59] = new Queen(1);
  squares[60] = new King(1);

  return squares;
}<commit_msg>Queen's getSrcToDestPath<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

import '../index.css';
import Board from './board.js';
import calculateWinner from '../helpers/calculate-winner.js'

export default class Game extends React.Component {
  constructor(){
    super();
    this.state = {
      squares: initialiseChessBoard(),
      player: 1,
      sourceSelection: -1,
      status: 'Next player: 1'
    }
  }

  handleClick(i){
    const squares = this.state.squares.slice();

    // if (calculateWinner(squares) || squares[i]) {
    //   return;
    // }
    // squares[i] = this.state.xIsNext? 'X' : 'O';

    if(this.state.sourceSelection === -1){
      if(!squares[i] || squares[i].player !== this.state.player){
        this.setState({status: "Wrong selection. Choose player " + this.state.player + " pieces."});
        squares[i]? delete squares[i].style.backgroundColor: null;
      }
      else{
        squares[i].style = {...squares[i].style, backgroundColor: "lightblue"};
        this.setState({
          status: "Choose destination for the selected piece",
          sourceSelection: i
        });
      }
    }

    else if(this.state.sourceSelection > -1){
      delete squares[this.state.sourceSelection].style.backgroundColor;
      if(squares[i] && squares[i].player === this.state.player){
        this.setState({
          status: "Wrong selection. Choose valid source and destination again.",
          sourceSelection: -1,
        })
      }
      else{

        const squares = this.state.squares;
        const isDestEnemyOccupied = squares[i]? true : false;
        const isMovePossible = squares[this.state.sourceSelection].isMovePossible(this.state.sourceSelection, i, isDestEnemyOccupied);
        const srcToDestPath = squares[this.state.sourceSelection].getSrcToDestPath(this.state.sourceSelection, i);
        const isMoveLegal = this.isMoveLegal(srcToDestPath);

        console.log("isMovePossible", isMovePossible);
        console.log("srcToDestPath", srcToDestPath);
        console.log("isMoveLegal", isMoveLegal);

        squares[i] = squares[this.state.sourceSelection];
        squares[this.state.sourceSelection] = null;
        let player = this.state.player === 1? 2: 1;
        this.setState({
          status: "",
          sourceSelection: -1,
          squares: squares,
          player: player,
          status: 'Next player: ' + player
        });
      }
    }

  }

  /**
   * Check all path indices are null. For one steps move of pawn/others or jumping moves of knight array is empty, so  move is legal.
   * @param  {[type]}  srcToDestPath [array of board indices comprising path between src and dest ]
   * @return {Boolean}
   */
  isMoveLegal(srcToDestPath){
    let isLegal = true;
    for(let i = 0; i < srcToDestPath.length; i++){
      if(this.state.squares[srcToDestPath[i]] !== null){
        isLegal = false;
      }
    }
    return isLegal;
  }

  render() {
    const squares = this.state.squares.slice();
    let winner;
    let winningSquares = calculateWinner(squares);
    let status = this.state.status;

    return (

            <Board
            squares = {squares}
            winningSquares = {winningSquares}
            onClick = {(i) => this.handleClick(i)}
            />

{status}

  Chess Icons And Favicon (extracted) By en:User:Cburnett [GFDL, CC-BY-SA-3.0, BSD or GPL], via Wikimedia Commons

      );
  }
}

class Piece {
  constructor(player, iconUrl){
    this.player = player;
    this.style = {backgroundImage: "url('"+iconUrl+"')"};
  }
}

class Rook extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/72/Chess_rlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/ff/Chess_rdt45.svg"));
  }

  isMovePossible(src, dest){
    let mod = src % 8;
    let diff = 8 - mod;
    return (Math.abs(src - dest) % 8 === 0 || (dest >= (src - mod) && dest < (src + diff)));
  }

  /**
   * get path between src and dest (src and dest exclusive)
   * @param  {num} src
   * @param  {num} dest
   * @return {[array]}
   */
  getSrcToDestPath(src, dest){
    let path = [], pathStart, pathEnd, incrementBy;
    if(src > dest){
      pathStart = dest;
      pathEnd = src;
    }
    else{
      pathStart = src;
      pathEnd = dest;
    }
    if(Math.abs(src - dest) % 8 === 0){
      incrementBy = 8;
      pathStart += 8;
    }
    else{
      incrementBy = 1;
      pathStart += 1;
    }

    for(let i = pathStart; i < pathEnd; i+=incrementBy){
      path.push(i);
    }
    return path;
  }
}

class Bishop extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/b/b1/Chess_blt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/9/98/Chess_bdt45.svg"));
  }

  isMovePossible(src, dest){
    return (Math.abs(src - dest) % 9 === 0 || Math.abs(src - dest) % 7 === 0);
  }

  /**
   * get path between src and dest (src and dest exclusive)
   * @param  {num} src
   * @param  {num} dest
   * @return {[array]}
   */
  getSrcToDestPath(src, dest){
    let path = [], pathStart, pathEnd, incrementBy;
    if(src > dest){
      pathStart = dest;
      pathEnd = src;
    }
    else{
      pathStart = src;
      pathEnd = dest;
    }
    if(Math.abs(src - dest) % 9 === 0){
      incrementBy = 9;
      pathStart += 9;
    }
    else{
      incrementBy = 7;
      pathStart += 7;
    }

    for(let i = pathStart; i < pathEnd; i+=incrementBy){
      path.push(i);
    }
    return path;
  }
}

class Queen extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/1/15/Chess_qlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/4/47/Chess_qdt45.svg"));
  }

  isMovePossible(src, dest){
    let mod = src % 8;
    let diff = 8 - mod;

    return (Math.abs(src - dest) % 9 === 0 || Math.abs(src - dest) % 7 === 0) ||
      (Math.abs(src - dest) % 8 === 0 || (dest >= (src - mod) && dest < (src + diff)));
  }

  /**
   * get path between src and dest (src and dest exclusive)
   * @param  {num} src
   * @param  {num} dest
   * @return {[array]}
   */
  getSrcToDestPath(src, dest){
    let path = [], pathStart, pathEnd, incrementBy;
    if(src > dest){
      pathStart = dest;
      pathEnd = src;
    }
    else{
      pathStart = src;
      pathEnd = dest;
    }
    if(Math.abs(src - dest) % 8 === 0){
      incrementBy = 8;
      pathStart += 8;
    }
    else if(Math.abs(src - dest) % 9 === 0){
      incrementBy = 9;
      pathStart += 9;
    }
    else if(Math.abs(src - dest) % 7 === 0){
      incrementBy = 7;
      pathStart += 7;
    }
    else{
      incrementBy = 1;
      pathStart += 1;
    }

    for(let i = pathStart; i < pathEnd; i+=incrementBy){
      path.push(i);
    }
    return path;
  }
}

class Knight extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/70/Chess_nlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/e/ef/Chess_ndt45.svg"));
  }

  isMovePossible(src, dest){
    return (src - 17 === dest ||
      src - 10 === dest ||
      src + 6 === dest ||
      src + 15 === dest ||
      src - 15 === dest ||
      src - 6 === dest ||
      src + 10 === dest ||
      src + 17 === dest);
  }

  /**
   * always returns empty array because of jumping
   * @return {[]}
   */
  getSrcToDestPath(){
    return [];
  }
}

class King extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/4/42/Chess_klt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/f0/Chess_kdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class Pawn extends Piece {
  constructor(player){
    super(player, (player === 1?  "https://upload.wikimedia.org/wikipedia/commons/4/45/Chess_plt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/c/c7/Chess_pdt45.svg"));
    this.initialPositions = {
      1: [48, 49, 50, 51, 52, 53, 54, 55],
      2: [8, 9, 10, 11, 12, 13, 14, 15]
    }
  }

  isMovePossible(src, dest, isDestEnemyOccupied){

    if(this.player === 1){
      if(dest === src - 8 || (dest === src - 16 && this.initialPositions[1].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src - 9 || dest === src - 7)){
        return true;
      }
    }
    else if(this.player === 2){
      if(dest === src + 8 || (dest === src + 16 && this.initialPositions[2].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src + 9 || dest === src + 7)){
        return true;
      }
    }
    return false;
  }

  getSrcToDestPath(src, dest){
    if(dest === src - 16){
      return [src - 8];
    }
    else if(dest === src + 16){
      return [src + 8];
    }
    return [];
  }
}

function initialiseChessBoard(){

  const squares = Array(64).fill(null);

  for(let i = 8; i < 16; i++){
    squares[i] = new Pawn(2);
    squares[i+40] = new Pawn(1);
  }
  squares[0] = new Rook(2);
  squares[7] = new Rook(2);
  squares[56] = new Rook(1);
  squares[63] = new Rook(1);

  squares[1] = new Knight(2);
  squares[6] = new Knight(2);
  squares[57] = new Knight(1);
  squares[62] = new Knight(1);

  squares[2] = new Bishop(2);
  squares[5] = new Bishop(2);
  squares[58] = new Bishop(1);
  squares[61] = new Bishop(1);

  squares[3] = new Queen(2);
  squares[4] = new King(2);

  squares[59] = new Queen(1);
  squares[60] = new King(1);

  return squares;
}<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

import '../index.css';
import Board from './board.js';
import calculateWinner from '../helpers/calculate-winner.js'

export default class Game extends React.Component {
  constructor(){
    super();
    this.state = {
      squares: initialiseChessBoard(),
      player: 1,
      sourceSelection: -1,
      status: 'Next player: 1'
    }
  }

  handleClick(i){
    const squares = this.state.squares.slice();

    // if (calculateWinner(squares) || squares[i]) {
    //   return;
    // }
    // squares[i] = this.state.xIsNext? 'X' : 'O';

    if(this.state.sourceSelection === -1){
      if(!squares[i] || squares[i].player !== this.state.player){
        this.setState({status: "Wrong selection. Choose player " + this.state.player + " pieces."});
        squares[i]? delete squares[i].style.backgroundColor: null;
      }
      else{
        squares[i].style = {...squares[i].style, backgroundColor: "lightblue"};
        this.setState({
          status: "Choose destination for the selected piece",
          sourceSelection: i
        });
      }
    }

    else if(this.state.sourceSelection > -1){
      delete squares[this.state.sourceSelection].style.backgroundColor;
      if(squares[i] && squares[i].player === this.state.player){
        this.setState({
          status: "Wrong selection. Choose valid source and destination again.",
          sourceSelection: -1,
        })
      }
      else{

        const squares = this.state.squares;
        const isDestEnemyOccupied = squares[i]? true : false;
        const isMovePossible = squares[this.state.sourceSelection].isMovePossible(this.state.sourceSelection, i, isDestEnemyOccupied);
        const srcToDestPath = squares[this.state.sourceSelection].getSrcToDestPath(this.state.sourceSelection, i);
        const isMoveLegal = this.isMoveLegal(srcToDestPath);

        console.log("isMovePossible", isMovePossible);
        console.log("srcToDestPath", srcToDestPath);
        console.log("isMoveLegal", isMoveLegal);

        squares[i] = squares[this.state.sourceSelection];
        squares[this.state.sourceSelection] = null;
        let player = this.state.player === 1? 2: 1;
        this.setState({
          status: "",
          sourceSelection: -1,
          squares: squares,
          player: player,
          status: 'Next player: ' + player
        });
      }
    }

  }

  /**
   * Check all path indices are null. For one steps move of pawn/others or jumping moves of knight array is empty, so  move is legal.
   * @param  {[type]}  srcToDestPath [array of board indices comprising path between src and dest ]
   * @return {Boolean}
   */
  isMoveLegal(srcToDestPath){
    let isLegal = true;
    for(let i = 0; i < srcToDestPath.length; i++){
      if(this.state.squares[srcToDestPath[i]] !== null){
        isLegal = false;
      }
    }
    return isLegal;
  }

  render() {
    const squares = this.state.squares.slice();
    let winner;
    let winningSquares = calculateWinner(squares);
    let status = this.state.status;

    return (

            <Board
            squares = {squares}
            winningSquares = {winningSquares}
            onClick = {(i) => this.handleClick(i)}
            />

{status}

  Chess Icons And Favicon (extracted) By en:User:Cburnett [GFDL, CC-BY-SA-3.0, BSD or GPL], via Wikimedia Commons

      );
  }
}

class Piece {
  constructor(player, iconUrl){
    this.player = player;
    this.style = {backgroundImage: "url('"+iconUrl+"')"};
  }
}

class Rook extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/72/Chess_rlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/ff/Chess_rdt45.svg"));
  }

  isMovePossible(src, dest){
    let mod = src % 8;
    let diff = 8 - mod;
    return (Math.abs(src - dest) % 8 === 0 || (dest >= (src - mod) && dest < (src + diff)));
  }

  /**
   * get path between src and dest (src and dest exclusive)
   * @param  {num} src
   * @param  {num} dest
   * @return {[array]}
   */
  getSrcToDestPath(src, dest){
    let path = [], pathStart, pathEnd, incrementBy;
    if(src > dest){
      pathStart = dest;
      pathEnd = src;
    }
    else{
      pathStart = src;
      pathEnd = dest;
    }
    if(Math.abs(src - dest) % 8 === 0){
      incrementBy = 8;
      pathStart += 8;
    }
    else{
      incrementBy = 1;
      pathStart += 1;
    }

    for(let i = pathStart; i < pathEnd; i+=incrementBy){
      path.push(i);
    }
    return path;
  }
}

class Knight extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/70/Chess_nlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/e/ef/Chess_ndt45.svg"));
  }

  isMovePossible(src, dest){
    return (src - 17 === dest ||
      src - 10 === dest ||
      src + 6 === dest ||
      src + 15 === dest ||
      src - 15 === dest ||
      src - 6 === dest ||
      src + 10 === dest ||
      src + 17 === dest);
  }

  getSrcToDestPath(){
    return [];
  }
}

class Bishop extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/b/b1/Chess_blt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/9/98/Chess_bdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class Queen extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/1/15/Chess_qlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/4/47/Chess_qdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class King extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/4/42/Chess_klt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/f0/Chess_kdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class Pawn extends Piece {
  constructor(player){
    super(player, (player === 1?  "https://upload.wikimedia.org/wikipedia/commons/4/45/Chess_plt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/c/c7/Chess_pdt45.svg"));
    this.initialPositions = {
      1: [48, 49, 50, 51, 52, 53, 54, 55],
      2: [8, 9, 10, 11, 12, 13, 14, 15]
    }
  }

  isMovePossible(src, dest, isDestEnemyOccupied){

    if(this.player === 1){
      if(dest === src - 8 || (dest === src - 16 && this.initialPositions[1].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src - 9 || dest === src - 7)){
        return true;
      }
    }
    else if(this.player === 2){
      if(dest === src + 8 || (dest === src + 16 && this.initialPositions[2].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src + 9 || dest === src + 7)){
        return true;
      }
    }
    return false;
  }

  getSrcToDestPath(src, dest){
    if(dest === src - 16){
      return [src - 8];
    }
    else if(dest === src + 16){
      return [src + 8];
    }
    return [];
  }
}

function initialiseChessBoard(){

  const squares = Array(64).fill(null);

  for(let i = 8; i < 16; i++){
    squares[i] = new Pawn(2);
    squares[i+40] = new Pawn(1);
  }
  squares[0] = new Rook(2);
  squares[7] = new Rook(2);
  squares[56] = new Rook(1);
  squares[63] = new Rook(1);

  squares[1] = new Knight(2);
  squares[6] = new Knight(2);
  squares[57] = new Knight(1);
  squares[62] = new Knight(1);

  squares[2] = new Bishop(2);
  squares[5] = new Bishop(2);
  squares[58] = new Bishop(1);
  squares[61] = new Bishop(1);

  squares[3] = new Queen(2);
  squares[4] = new King(2);

  squares[59] = new Queen(1);
  squares[60] = new King(1);

  return squares;
}<commit_msg>comment knight's getSrcToDestPath()<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

import '../index.css';
import Board from './board.js';
import calculateWinner from '../helpers/calculate-winner.js'

export default class Game extends React.Component {
  constructor(){
    super();
    this.state = {
      squares: initialiseChessBoard(),
      player: 1,
      sourceSelection: -1,
      status: 'Next player: 1'
    }
  }

  handleClick(i){
    const squares = this.state.squares.slice();

    // if (calculateWinner(squares) || squares[i]) {
    //   return;
    // }
    // squares[i] = this.state.xIsNext? 'X' : 'O';

    if(this.state.sourceSelection === -1){
      if(!squares[i] || squares[i].player !== this.state.player){
        this.setState({status: "Wrong selection. Choose player " + this.state.player + " pieces."});
        squares[i]? delete squares[i].style.backgroundColor: null;
      }
      else{
        squares[i].style = {...squares[i].style, backgroundColor: "lightblue"};
        this.setState({
          status: "Choose destination for the selected piece",
          sourceSelection: i
        });
      }
    }

    else if(this.state.sourceSelection > -1){
      delete squares[this.state.sourceSelection].style.backgroundColor;
      if(squares[i] && squares[i].player === this.state.player){
        this.setState({
          status: "Wrong selection. Choose valid source and destination again.",
          sourceSelection: -1,
        })
      }
      else{

        const squares = this.state.squares;
        const isDestEnemyOccupied = squares[i]? true : false;
        const isMovePossible = squares[this.state.sourceSelection].isMovePossible(this.state.sourceSelection, i, isDestEnemyOccupied);
        const srcToDestPath = squares[this.state.sourceSelection].getSrcToDestPath(this.state.sourceSelection, i);
        const isMoveLegal = this.isMoveLegal(srcToDestPath);

        console.log("isMovePossible", isMovePossible);
        console.log("srcToDestPath", srcToDestPath);
        console.log("isMoveLegal", isMoveLegal);

        squares[i] = squares[this.state.sourceSelection];
        squares[this.state.sourceSelection] = null;
        let player = this.state.player === 1? 2: 1;
        this.setState({
          status: "",
          sourceSelection: -1,
          squares: squares,
          player: player,
          status: 'Next player: ' + player
        });
      }
    }

  }

  /**
   * Check all path indices are null. For one steps move of pawn/others or jumping moves of knight array is empty, so  move is legal.
   * @param  {[type]}  srcToDestPath [array of board indices comprising path between src and dest ]
   * @return {Boolean}
   */
  isMoveLegal(srcToDestPath){
    let isLegal = true;
    for(let i = 0; i < srcToDestPath.length; i++){
      if(this.state.squares[srcToDestPath[i]] !== null){
        isLegal = false;
      }
    }
    return isLegal;
  }

  render() {
    const squares = this.state.squares.slice();
    let winner;
    let winningSquares = calculateWinner(squares);
    let status = this.state.status;

    return (

            <Board
            squares = {squares}
            winningSquares = {winningSquares}
            onClick = {(i) => this.handleClick(i)}
            />

{status}

  Chess Icons And Favicon (extracted) By en:User:Cburnett [GFDL, CC-BY-SA-3.0, BSD or GPL], via Wikimedia Commons

      );
  }
}

class Piece {
  constructor(player, iconUrl){
    this.player = player;
    this.style = {backgroundImage: "url('"+iconUrl+"')"};
  }
}

class Rook extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/72/Chess_rlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/ff/Chess_rdt45.svg"));
  }

  isMovePossible(src, dest){
    let mod = src % 8;
    let diff = 8 - mod;
    return (Math.abs(src - dest) % 8 === 0 || (dest >= (src - mod) && dest < (src + diff)));
  }

  /**
   * get path between src and dest (src and dest exclusive)
   * @param  {num} src
   * @param  {num} dest
   * @return {[array]}
   */
  getSrcToDestPath(src, dest){
    let path = [], pathStart, pathEnd, incrementBy;
    if(src > dest){
      pathStart = dest;
      pathEnd = src;
    }
    else{
      pathStart = src;
      pathEnd = dest;
    }
    if(Math.abs(src - dest) % 8 === 0){
      incrementBy = 8;
      pathStart += 8;
    }
    else{
      incrementBy = 1;
      pathStart += 1;
    }

    for(let i = pathStart; i < pathEnd; i+=incrementBy){
      path.push(i);
    }
    return path;
  }
}

class Knight extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/7/70/Chess_nlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/e/ef/Chess_ndt45.svg"));
  }

  isMovePossible(src, dest){
    return (src - 17 === dest ||
      src - 10 === dest ||
      src + 6 === dest ||
      src + 15 === dest ||
      src - 15 === dest ||
      src - 6 === dest ||
      src + 10 === dest ||
      src + 17 === dest);
  }

  /**
   * always returns empty array because of jumping
   * @return {[]}
   */
  getSrcToDestPath(){
    return [];
  }
}

class Bishop extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/b/b1/Chess_blt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/9/98/Chess_bdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class Queen extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/1/15/Chess_qlt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/4/47/Chess_qdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class King extends Piece {
  constructor(player){
    super(player, (player === 1? "https://upload.wikimedia.org/wikipedia/commons/4/42/Chess_klt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/f/f0/Chess_kdt45.svg"));
  }

  isMovePossible(){
    return true
  }

  getSrcToDestPath(src, dest){
    return [];
  }
}

class Pawn extends Piece {
  constructor(player){
    super(player, (player === 1?  "https://upload.wikimedia.org/wikipedia/commons/4/45/Chess_plt45.svg" : "https://upload.wikimedia.org/wikipedia/commons/c/c7/Chess_pdt45.svg"));
    this.initialPositions = {
      1: [48, 49, 50, 51, 52, 53, 54, 55],
      2: [8, 9, 10, 11, 12, 13, 14, 15]
    }
  }

  isMovePossible(src, dest, isDestEnemyOccupied){

    if(this.player === 1){
      if(dest === src - 8 || (dest === src - 16 && this.initialPositions[1].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src - 9 || dest === src - 7)){
        return true;
      }
    }
    else if(this.player === 2){
      if(dest === src + 8 || (dest === src + 16 && this.initialPositions[2].indexOf(src) !== -1)){
        return true;
      }
      else if(isDestEnemyOccupied && (dest === src + 9 || dest === src + 7)){
        return true;
      }
    }
    return false;
  }

  getSrcToDestPath(src, dest){
    if(dest === src - 16){
      return [src - 8];
    }
    else if(dest === src + 16){
      return [src + 8];
    }
    return [];
  }
}

function initialiseChessBoard(){

  const squares = Array(64).fill(null);

  for(let i = 8; i < 16; i++){
    squares[i] = new Pawn(2);
    squares[i+40] = new Pawn(1);
  }
  squares[0] = new Rook(2);
  squares[7] = new Rook(2);
  squares[56] = new Rook(1);
  squares[63] = new Rook(1);

  squares[1] = new Knight(2);
  squares[6] = new Knight(2);
  squares[57] = new Knight(1);
  squares[62] = new Knight(1);

  squares[2] = new Bishop(2);
  squares[5] = new Bishop(2);
  squares[58] = new Bishop(1);
  squares[61] = new Bishop(1);

  squares[3] = new Queen(2);
  squares[4] = new King(2);

  squares[59] = new Queen(1);
  squares[60] = new King(1);

  return squares;
}<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2016  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import React, { PropTypes } from 'react';
import classNames from 'classnames';

import * as MdIconPack from 'react-icons/lib/md';
import { FaHashtag, FaAt } from 'react-icons/lib/fa';

const FaIconPack = { FaHashtag, FaAt };

function findIcon(iconName) {
  const camelized = iconName.replace(/(?:^|[-_])(\w)/g, (match, c) =>
    c ? c.toUpperCase() : ''
  );
  const capitalized = camelized.charAt(0).toUpperCase() + camelized.slice(1);

  return MdIconPack[`Md${capitalized}`] || FaIconPack[`Fa${capitalized}`];
}

const IconComponent = ({
  className,
  color,
  disabled,
  icon,
  inactive,
  onClick,
  outline,
  spin,
  size,
  ...props
}) => {
  const Icon = findIcon(icon);

  const classNameIcon = classNames('icon', {
    'icon-outline': outline,
    'icon-disabled': disabled,
    'icon--inactive': inactive,
    'micon-rotate': spin,
    [`micon-${size}`]: size,
    [`icon--size_${size}`]: size,
    [className]: className,
  });

  const classNameIconPic = classNames('micon', {
    [`color-${color}`]: color,
    [`micon-${size}`]: size,
    [`icon--size_${size}`]: size
  });

  let renderedIcon = false;
  if (Icon) {
    renderedIcon = <Icon className={classNameIconPic} />;
  }

  let localOnClick = onClick;
  if (disabled) {
    localOnClick = null;
  }

  return (
    <div
      {...props}
      className={classNameIcon}
      disabled={disabled}
      onClick={localOnClick}
    >
      {renderedIcon}
    </div>
  );
};

IconComponent.propTypes = {
  className: PropTypes.string,
  color: PropTypes.string,
  disabled: PropTypes.bool,
  icon: PropTypes.string,
  onClick: PropTypes.func,
  outline: PropTypes.bool,
  size: PropTypes.string,
  spin: PropTypes.bool
};

IconComponent.defaultProps = {
  icon: ''
};

export default IconComponent;
<commit_msg>Add 'pack' property to Icon component, import FontAwesome<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2016  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import React, { PropTypes } from 'react';
import classNames from 'classnames';

import * as MdIconPack from 'react-icons/lib/md';
import * as FaIconPack from 'react-icons/lib/fa';

function findIcon(iconName, packName) {
  const camelized = iconName.replace(/(?:^|[-_])(\w)/g, (match, c) =>
    c ? c.toUpperCase() : ''
  );
  const capitalized = camelized.charAt(0).toUpperCase() + camelized.slice(1);

  if (packName === 'md') {
    return MdIconPack[`Md${capitalized}`];
  }
  if (packName === 'fa') {
    return FaIconPack[`Fa${capitalized}`];
  }
  return MdIconPack[`Md${capitalized}`] || FaIconPack[`Fa${capitalized}`];
}

const IconComponent = ({
  className,
  color,
  disabled,
  icon,
  inactive,
  onClick,
  outline,
  pack,
  spin,
  size,
  ...props
}) => {
  const Icon = findIcon(icon, pack);

  const classNameIcon = classNames('icon', {
    'icon-outline': outline,
    'icon-disabled': disabled,
    'icon--inactive': inactive,
    'micon-rotate': spin,
    [`micon-${size}`]: size,
    [`icon--size_${size}`]: size,
    [className]: className,
  });

  const classNameIconPic = classNames('micon', {
    [`color-${color}`]: color,
    [`micon-${size}`]: size,
    [`icon--size_${size}`]: size
  });

  let renderedIcon = false;
  if (Icon) {
    renderedIcon = <Icon className={classNameIconPic} />;
  }

  let localOnClick = onClick;
  if (disabled) {
    localOnClick = null;
  }

  return (
    <div
      {...props}
      className={classNameIcon}
      disabled={disabled}
      onClick={localOnClick}
    >
      {renderedIcon}
    </div>
  );
};

IconComponent.propTypes = {
  className: PropTypes.string,
  color: PropTypes.string,
  disabled: PropTypes.bool,
  icon: PropTypes.string,
  onClick: PropTypes.func,
  outline: PropTypes.bool,
  pack: PropTypes.oneOf(['md', 'fa']),
  size: PropTypes.string,
  spin: PropTypes.bool
};

IconComponent.defaultProps = {
  icon: ''
};

export default IconComponent;
<|endoftext|>


<commit_before>/** @jsx React.DOM */
module.exports = function(React) {
  var Job = require('./job')(React)
  var Jobs = React.createClass({
    render: function() {
      var head =

        id
        type
        status
        progress
        actions

      var rows = [];
      this.props.jobs.forEach(function(job) {
        rows.push(<Job
          key={job.id}
          id={job.id}
          type={job.type}
          status={job.status}
          progress={job.progress}
          handler={this.props.controller.redisHandler}
        />)
      }.bind(this));
      var deleteAllButton = ( rows.length ?
                             <button onClick={this.deleteAll}>
                               Delete all
                             </button> : '' )
      return (

                {this.props.category} jobs
                {deleteAllButton}

              {head}

              {rows}

      )
    },
    componentWillMount: function() {
      this.props.controller.fetch()
    }
  });
  return Jobs
}
<commit_msg>plub delete all call<commit_after>/** @jsx React.DOM */
module.exports = function(React) {
  var Job = require('./job')(React)
  var Jobs = React.createClass({
    render: function() {
      var head =

        id
        type
        status
        progress
        actions

      var rows = [];
      this.props.jobs.forEach(function(job) {
        rows.push(<Job
          key={job.id}
          id={job.id}
          type={job.type}
          status={job.status}
          progress={job.progress}
          handler={this.props.controller.redisHandler}
        />)
      }.bind(this));
      var deleteAllButton = ( rows.length ?
                             <button onClick={this.deleteAll}>
                               Delete all
                             </button> : '' )
      return (

                {this.props.category} jobs
                {deleteAllButton}

              {head}

              {rows}

      )
    },
    deleteAll: function() {
      this.props.controller.redisHandler.fn.deleteByStatus(this.props.category)
    },
    componentWillMount: function() {
      this.props.controller.fetch()
    }
  });
  return Jobs
}
<|endoftext|>