<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);

var ImgFigure = React.createClass({
	/*
	 *	imgFigure的点击处理函数
	 */
	handleClick: function(e){
		if(this.props.arrange.isCenter){
			this.props.inverse();
		}else{
			this.props.center();
		}

		e.preventDefault();
		e.stopPropagation();
	},

	render: function(){
		var styleObj = {};

		//如果props属性中指定了这张图片的位置，则使用
		if(this.props.arrange.pos){
			styleObj = this.props.arrange.pos;
		}

		//如果图片的旋转角度有值并且不为0，添加旋转角度
		if(this.props.arrange.rotate){
			['Moz','ms','Webkit',''].forEach(function(value){
				styleObj[value + 'Transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)';
			}.bind(this));
		}

		var imgFigureClassName = 'img-figure';

		imgFigureClassName += this.props.arrange.isCenter ? ' center' : '';
		imgFigureClassName += this.props.arrange.isInverse ? ' inverse' : '';

		return (

{this.props.data.title}

							{this.props.data.desc}

		);
	}
});

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

/*
	获取 0-30°之间的一个任意正负值
 */
function get30DegRandom(){
	return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30));
}

var AppComponent = 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]
		}
	},

	/*
	 * 翻转图片
	 * @param index 当前被执行inverse操作的图片对应的图片信息数组的索引
	 * @return {Function} 返回一个闭包函数，其内返回一个真正待被执行的函数
	 */
	inverse: function(index){
		return function(){
			var imgsArrangeArr = this.state.imgsArrangeArr;

			imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

			this.setState({
				imgsArrangeArr: imgsArrangeArr
			});

		}.bind(this);
	},

	//组件加载以后，为每张图片计算其位置的范围
	componentDidMount: function(){

		//首先拿到舞台的大小
		var stageDOM = ReactDOM.findDOMNode(this.refs.stage),
			stageW = stageDOM.scrollWidth,
			stageH = stageDOM.scrollHeight,
			halfStageW = Math.ceil(stageW / 2),
			halfStageH = Math.ceil(stageH / 2);

		//拿到单个imageFigure的大小
		var imgFigureDOM = ReactDOM.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 * 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 - halfStageH;

		//计算上侧区域图片排布位置的取值范围
		this.Constant.vPosRange.topY[0] = -halfImgH;
		this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
		this.Constant.vPosRange.x[0] = halfStageW - halfImgW;
		this.Constant.vPosRange.x[1] = halfStageW;

		this.rearrange(0);
	},

	/*
	 * 重新布局所有图片
	 * @param centerIndex 指定居中排布的图片的索引
	 */
	rearrange: function(centerIndex){
		var imgsArrangeArr = this.state.imgsArrangeArr,
			Constant = this.Constant,
			centerPos = Constant.centerPos,
			hPosRange = Constant.hPosRange,
			vPosRange = Constant.vPosRange,
			hPosRangeLeftSecX = hPosRange.leftSecX,
			hPosRangeRigthSecX = hPosRange.rightSecX,
			hPosRangeY = hPosRange.y,
			vPosRangeTopY = vPosRange.topY,
			vPosRangeX = vPosRange.x,

			imgsArrangeTopArr = [],
			topImgNum = Math.ceil(Math.random() * 2), //上区域取一张或者不取图片
			topImgSpliceIndex = 0,

			//获取中心图片的位置信息
			imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);

			//首先居中中心图片
			imgsArrangeCenterArr[0] = {
				pos: centerPos,
				rotate: 0,
				isCenter: true
			};

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

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

			//剔除掉中心和上侧的图片后，剩下的图片布局在左右两侧
			for(var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i ++){
				var hPosRangeLORX = null;

				//前半部分布局左侧，有半部分布局右侧
				if(i < k){
					hPosRangeLORX = hPosRangeLeftSecX;
				}else{
					hPosRangeLORX = hPosRangeRigthSecX;
				}

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

			if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
				imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]);
			}

			imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]);

			this.setState({
				imgsArrangeArr: imgsArrangeArr
			});

	},

	/*
	 *  利用rearrange函数，居中对应index的图片
	 *  @param index,需要被居中的图片对应的图片信息的索引
	 *  @return {Function}
	 */
	center: function(index){
		return function(){
			this.rearrange(index);
		}.bind(this);
	},

	//获取每张图片的状态值
	getInitialState: function(){
		return {
			imgsArrangeArr: [
				/*{
					pos: {
						left: '0',
						top: '0'
					},
					rotate: 0,
					isCenter: false,
					isInverse: false
				}*/
			]
		};
	},

	render: function(){

		var controllerUnits = [],
			imgFigures = [];

		imageDatas.forEach(function(value,index){
			//初始化每张图片的状态
			if(!this.state.imgsArrangeArr[index]){
				this.state.imgsArrangeArr[index] = {
					pos: {
						left: 0,
						top: 0
					},
					rotate: 0,
					isCenter: false,
					isInverse: false
				}
			}

			//将每张图片的React对象添加数组imgFigures中
			imgFigures.push(<ImgFigure data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);

		}.bind(this));

		return (

		 			{imgFigures}

		 			{controllerUnits}

		);
	}
});

export default AppComponent;<commit_msg>lesson2<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);

var ImgFigure = React.createClass({
	/*
	 *	imgFigure的点击处理函数
	 */
	handleClick: function(e){
		if(this.props.arrange.isCenter){
			this.props.inverse();
		}else{
			this.props.center();
		}

		e.preventDefault();
		e.stopPropagation();
	},

	render: function(){
		var styleObj = {};

		//如果props属性中指定了这张图片的位置，则使用
		if(this.props.arrange.pos){
			styleObj = this.props.arrange.pos;
		}

		//如果图片的旋转角度有值并且不为0，添加旋转角度
		if(this.props.arrange.rotate){
			['Moz','ms','Webkit',''].forEach(function(value){
				styleObj[value + 'Transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)';
			}.bind(this));
		}

		var imgFigureClassName = 'img-figure';

		imgFigureClassName += this.props.arrange.isCenter ? ' center' : '';
		imgFigureClassName += this.props.arrange.isInverse ? ' inverse' : '';

		return (

{this.props.data.title}

							{this.props.data.desc}

		);
	}
});

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

/*
	获取 0-30°之间的一个任意正负值
 */
function get30DegRandom(){
	return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30));
}

var AppComponent = 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]
		}
	},

	/*
	 * 翻转图片
	 * @param index 当前被执行inverse操作的图片对应的图片信息数组的索引
	 * @return {Function} 返回一个闭包函数，其内返回一个真正待被执行的函数
	 */
	inverse: function(index){
		return function(){
			var imgsArrangeArr = this.state.imgsArrangeArr;

			imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

			this.setState({
				imgsArrangeArr: imgsArrangeArr
			});

		}.bind(this);
	},

	//组件加载以后，为每张图片计算其位置的范围
	componentDidMount: function(){

		//首先拿到舞台的大小
		var stageDOM = ReactDOM.findDOMNode(this.refs.stage),
			stageW = stageDOM.scrollWidth,
			stageH = stageDOM.scrollHeight,
			halfStageW = Math.ceil(stageW / 2),
			halfStageH = Math.ceil(stageH / 2);

		//拿到单个imageFigure的大小
		var imgFigureDOM = ReactDOM.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 * 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 - halfStageH;

		//计算上侧区域图片排布位置的取值范围
		this.Constant.vPosRange.topY[0] = -halfImgH;
		this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
		this.Constant.vPosRange.x[0] = halfStageW - halfImgW;
		this.Constant.vPosRange.x[1] = halfStageW;

		this.rearrange(0);
	},

	/*
	 * 重新布局所有图片
	 * @param centerIndex 指定居中排布的图片的索引
	 */
	rearrange: function(centerIndex){
		var imgsArrangeArr = this.state.imgsArrangeArr,
			Constant = this.Constant,
			centerPos = Constant.centerPos,
			hPosRange = Constant.hPosRange,
			vPosRange = Constant.vPosRange,
			hPosRangeLeftSecX = hPosRange.leftSecX,
			hPosRangeRigthSecX = hPosRange.rightSecX,
			hPosRangeY = hPosRange.y,
			vPosRangeTopY = vPosRange.topY,
			vPosRangeX = vPosRange.x,

			imgsArrangeTopArr = [],
			topImgNum = Math.ceil(Math.random() * 2), //上区域取一张或者不取图片
			topImgSpliceIndex = 0,

			//获取中心图片的位置信息
			imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);

			//首先居中中心图片
			imgsArrangeCenterArr[0] = {
				pos: centerPos,
				rotate: 0,
				isCenter: true
			};

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

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

			//剔除掉中心和上侧的图片后，剩下的图片布局在左右两侧
			for(var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i ++){
				var hPosRangeLORX = null;

				//前半部分布局左侧，有半部分布局右侧
				if(i < k){
					hPosRangeLORX = hPosRangeLeftSecX;
				}else{
					hPosRangeLORX = hPosRangeRigthSecX;
				}

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

			if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
				imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]);
			}

			imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]);

			this.setState({
				imgsArrangeArr: imgsArrangeArr
			});

	},

	/*
	 *  利用rearrange函数，居中对应index的图片
	 *  @param index,需要被居中的图片对应的图片信息的索引
	 *  @return {Function}
	 */
	center: function(index){
		return function(){
			this.rearrange(index);
		}.bind(this);
	},

	//获取每张图片的状态值
	getInitialState: function(){
		return {
			imgsArrangeArr: [
				/*{
					pos: {
						left: '0',
						top: '0'
					},
					rotate: 0,
					isCenter: false,
					isInverse: false
				}*/
			]
		};
	},

	render: function(){

		var controllerUnits = [],
			imgFigures = [];

		imageDatas.forEach(function(value,index){
			//初始化每张图片的状态
			if(!this.state.imgsArrangeArr[index]){
				this.state.imgsArrangeArr[index] = {
					pos: {
						left: 0,
						top: 0
					},
					rotate: 0,
					isCenter: false,
					isInverse: false
				}
			}

			//将每张图片的React对象添加数组imgFigures中
			imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);

		}.bind(this));

		return (

		 			{imgFigures}

		 			{controllerUnits}

		);
	}
});

export default AppComponent;<|endoftext|>


<commit_before>(function (angular, buildfire) {
    "use strict";
    angular
        .module('folderPluginWidget')

    .directive("loadImage", function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.attr("src", "../../../styles/media/holder-" + attrs.loadImage + ".gif");

                attrs.$observe('finalSrc', function () {
                    var _img = attrs.finalSrc;

                    if (attrs.cropType == 'resize') {
                        buildfire.imageLib.local.resizeImage(_img, {
                            width: attrs.cropWidth,
                            height: attrs.cropHeight
                        }, function (err, imgUrl) {
                            _img = imgUrl;
                            replaceImg(_img);
                        });
                    } else {
                        buildfire.imageLib.local.cropImage(_img, {
                            width: attrs.cropWidth,
                            height: attrs.cropHeight
                        }, function (err, imgUrl) {
                            _img = imgUrl;
                            replaceImg(_img);
                        });
                    }
                });

                function replaceImg(finalSrc) {
                    var elem = $("<img>");
                    elem[0].onload = function () {
                        element.attr("src", finalSrc);
                        elem.remove();
                    };
                    elem.attr("src", finalSrc);
                }
            }
        };
    })

    .directive('backImg', ["$rootScope", function ($rootScope) {
        return function (scope, element, attrs) {
            attrs.$observe('backImg', function (value) {
                if (value) {
                    var imgUrl = buildfire.imageLib.resizeImage(value, {
                        width: window.innerWidth
                    });
                    if (imgUrl) {
                        element.attr("style", 'background:url(' + imgUrl + ') !important ; background-size: 100% 100% !important;');
                    } else {
                        element.attr("style", 'background-color:white');
                    }
                    element.css({
                        'background-size': '100% 100% !important'
                    });
                }
                else {
                    element.attr("style", 'background-color:white');
                    element.css({
                        'background-size': 'cover !important'
                    });
                }
            });
        };
    }])

    .directive('imgPreload', ['$rootScope', function ($rootScope) {
        return {
            restrict: 'A',
            scope: {
                ngSrc: '@'
            },
            link: function (scope, element, attrs) {
                element.on('load', function () {
                    element.addClass('in');
                }).on('error', function () {
                    //
                });

                scope.$watch('ngSrc', function (newVal) {
                    element.removeClass('in');
                });
            }
        };
    }])

    .directive('emitLastRepeaterElement', function () {
        return function (scope) {
            if (scope.$last) {
                scope.$emit('LastRepeaterElement');
            }
        };
    })

    .directive('imageCarousel', function ($timeout) {
        return {
            restrict: 'A',
            scope: {},
            link: function (scope, elem, attrs) {
                scope.carousel = null;
                scope.timeout = null;
                function initCarousel() {
                    if (scope.timeout) {
                        $timeout.cancel(scope.timeout);
                    }
                    if (scope.carousel) {
                        scope.carousel.trigger("destroy.owl.carousel");
                        $(elem).find(".owl-stage-outer").remove();
                    }
                    scope.carousel = null;
                    scope.timeout = $timeout(function () {
                        var obj = {
                            loop: false,
                            nav: false,
                            items: 1
                        };
                        scope.carousel = $(elem).owlCarousel(obj);
                    }, 100);
                }

                initCarousel();
                attrs.$observe("imageCarousel", function (newVal, oldVal) {
                    if (newVal) {
                        if (scope.carousel) {
                            initCarousel();
                        }
                    }
                });
            }
        }
    });
})(window.angular, window.buildfire);<commit_msg>disable Pixel Ratio when resizing image on widget<commit_after>(function (angular, buildfire) {
    "use strict";
    angular
        .module('folderPluginWidget')

    .directive("loadImage", function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.attr("src", "../../../styles/media/holder-" + attrs.loadImage + ".gif");

                attrs.$observe('finalSrc', function () {
                    var _img = attrs.finalSrc;

                    if (attrs.cropType == 'resize') {
                        buildfire.imageLib.local.resizeImage(_img, {
                            width: attrs.cropWidth,
                            height: attrs.cropHeight
                        }, function (err, imgUrl) {
                            _img = imgUrl;
                            replaceImg(_img);
                        });
                    } else {
                        buildfire.imageLib.local.cropImage(_img, {
                            width: attrs.cropWidth,
                            height: attrs.cropHeight
                        }, function (err, imgUrl) {
                            _img = imgUrl;
                            replaceImg(_img);
                        });
                    }
                });

                function replaceImg(finalSrc) {
                    var elem = $("<img>");
                    elem[0].onload = function () {
                        element.attr("src", finalSrc);
                        elem.remove();
                    };
                    elem.attr("src", finalSrc);
                }
            }
        };
    })

    .directive('backImg', ["$rootScope", function ($rootScope) {
        return function (scope, element, attrs) {
            attrs.$observe('backImg', function (value) {
                if (value) {
                    var imgUrl = buildfire.imageLib.resizeImage(value, {
                        width: window.innerWidth,
                        disablePixelRation : true
                    });
                    if (imgUrl) {
                        element.attr("style", 'background:url(' + imgUrl + ') !important ; background-size: 100% 100% !important;');
                    } else {
                        element.attr("style", 'background-color:white');
                    }
                    element.css({
                        'background-size': '100% 100% !important'
                    });
                }
                else {
                    element.attr("style", 'background-color:white');
                    element.css({
                        'background-size': 'cover !important'
                    });
                }
            });
        };
    }])

    .directive('imgPreload', ['$rootScope', function ($rootScope) {
        return {
            restrict: 'A',
            scope: {
                ngSrc: '@'
            },
            link: function (scope, element, attrs) {
                element.on('load', function () {
                    element.addClass('in');
                }).on('error', function () {
                    //
                });

                scope.$watch('ngSrc', function (newVal) {
                    element.removeClass('in');
                });
            }
        };
    }])

    .directive('emitLastRepeaterElement', function () {
        return function (scope) {
            if (scope.$last) {
                scope.$emit('LastRepeaterElement');
            }
        };
    })

    .directive('imageCarousel', function ($timeout) {
        return {
            restrict: 'A',
            scope: {},
            link: function (scope, elem, attrs) {
                scope.carousel = null;
                scope.timeout = null;
                function initCarousel() {
                    if (scope.timeout) {
                        $timeout.cancel(scope.timeout);
                    }
                    if (scope.carousel) {
                        scope.carousel.trigger("destroy.owl.carousel");
                        $(elem).find(".owl-stage-outer").remove();
                    }
                    scope.carousel = null;
                    scope.timeout = $timeout(function () {
                        var obj = {
                            loop: false,
                            nav: false,
                            items: 1
                        };
                        scope.carousel = $(elem).owlCarousel(obj);
                    }, 100);
                }

                initCarousel();
                attrs.$observe("imageCarousel", function (newVal, oldVal) {
                    if (newVal) {
                        if (scope.carousel) {
                            initCarousel();
                        }
                    }
                });
            }
        }
    });
})(window.angular, window.buildfire);<|endoftext|>


<commit_before>'use strict';

const start = (commandText) => { return 'i have no idea on how to use javascript'

};
module.exports = ({ reply }) => reply(start());
<commit_msg>Delete start.js<commit_after><|endoftext|>


<commit_before>/*!
 * warp.js
 *
 * MIT licensed
 *
 * Copyright (C) 2014 Paul Zellmer, http://pazellmer.com
 */

//////////////////////////////
//                          //
//      document setup      //
//                          //
//////////////////////////////

// functions

function position(item, i) {
    item.attr("id", "warp" + arrayCoord[i].index);
    item.animate({
        left: arrayCoord[i].x_axis,
        top: arrayCoord[i].y_axis,
        "z-index": arrayCoord[i].z_index,
        width: arrayCoord[i].width,
        height: arrayCoord[i].height,
        opacity: arrayCoord[i].opacity
    }, 2000)
}

function rndItems(){
    for (i = 0; i < 4; i++){
        if ((numItems + i) % 4 == 0){
            return (numItems + i);
        }
    }
}

function Coord(index, x_axis, y_axis, z_index, width, height, opacity){
    this.index = index;
    this.x_axis = x_axis;
    this.y_axis = y_axis;
    this.z_index = z_index;
    this.width = width;
    this.height = height;
    this.opacity = opacity;
}

$(".warp_desc, #warp_display").hide();
$("#warpContainer").parent().prepend("

");

var offset = parseInt($("#warpContainer").attr("data-offset"));
var numItems = $('.warp').length;

if (numItems > 0) {
    //variables

    var width = $(".warp").width();
    var height = $(".warp").height();

    var xCenter = $(window).width() / 2;
    var xLeft = $(window).width() / 4;
    var yTop = $(window).height() / 4 + offset;
    var yCenter = ($(window).height() + offset) / 2;

    var xInc = (xCenter - xLeft) / (numItems / 4);
    var xMov = xInc;
    var yInc = (yCenter - yTop) / (numItems / 4);
    var yMov = yInc;

    var counter = 1;
    var zIndex = 200;
    var zIndexInc = parseInt(800 / numItems);

    var limit = rndItems();

    // Gather objects, count and organize array, coordinates and structure
    arrayCoord = [];

    for (var i = 0; i < limit; i++) {
        if (counter == 1) {
            //left
            xAxis = Math.round(((xCenter + xMov - (width * zIndex / 1000) / 2) / $(window).width()) * 100);
            arrayCoord[i] = new Coord(i + "left", xAxis + "%", Math.round((yCenter - (height * zIndex / 1000) / 2) / $(window).height() * 100) + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
        } else if (counter == 2) {
            //top
            yAxis = Math.round(((yCenter + yMov - (height * zIndex / 1000) / 2) / $(window).height()) * 100);
            arrayCoord[i] = new Coord(i + "top", Math.round((xCenter - (width * zIndex / 1000) / 2) / $(window).width() * 100) + "%", yAxis + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
        } else if (counter == 3) {
            //right
            xAxis = Math.round(((xCenter - xMov - (width * zIndex / 1000) / 2) / $(window).width()) * 100);
            arrayCoord[i] = new Coord(i + "right", xAxis + "%", Math.round((yCenter - (height * zIndex / 1000) / 2) / $(window).height() * 100) + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
            xMov += xInc;
        } else {
            //bottom
            yAxis = Math.round(((yCenter - yMov - (height * zIndex / 1000) / 2) / $(window).height()) * 100);
            arrayCoord[i] = new Coord(i + "bottom", Math.round((xCenter - (width * zIndex / 1000) / 2) / $(window).width() * 100) + "%", yAxis + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
            yMov += yInc;
            counter = 0;
        }
        zIndex += zIndexInc;
        counter++;
    }
    arrayCoord[arrayCoord.length - 1].z_index = 1000;

    // Assign items location and z-index and show items
    $($(".warp").get().reverse()).each(function(i) {
        $(this).attr("id", "warp" + arrayCoord[i].index);
        $(this).css("left", arrayCoord[i].x_axis);
        $(this).css("top", arrayCoord[i].y_axis);
        $(this).css("z-index", arrayCoord[i].z_index);
        $(this).css("width", arrayCoord[i].width);
        $(this).css("height", arrayCoord[i].height);
        $(this).css("opacity", arrayCoord[i].opacity);
    })

    // Arrow click to item

    $(document).on("keydown", function(e) {
        // up
        if (e.keyCode == 38) {
            $("#warpContainer").append($("#warpContainer").children(".warp:first"));
            $(".warp").each(function (i){
                position($(this), i);
            });
        // down
        } else if (e.keyCode == 40) {
            $("#warpContainer").prepend($("#warpContainer").children(".warp:last"));
            $(".warp").each(function (i){
                position($(this), i);
            });
        }
    })

    // Mouse click to item

    $(".warp:not(.warp:last)").click(function() {
        var id = $(this).attr("id");
        var cycle = arrayCoord.length - 1 - parseInt(id.slice(4));
        for (i = 0; i < cycle; i++) {
            $("#warpContainer").prepend($("#warpContainer").children(".warp:last"));
            $(".warp").each(function(i) {
                $(this).attr("id", "warp" + arrayCoord[i].index);
                $(this).animate({
                    left: arrayCoord[i].x_axis,
                    top: arrayCoord[i].y_axis,
                    "z-index": arrayCoord[i].z_index,
                    width: arrayCoord[i].width,
                    height: arrayCoord[i].height,
                    opacity: arrayCoord[i].opacity
                }, 1000)
            });
        }
    });

    // Mouse click front item to open iFrame
    $(document).on("click", ".warp:last", function() {
        $("#warp_display").html($(this).html());
        $("#warp_display").children().show();
        $("#warp_display").fadeToggle();
    });

    $("#warp_display").click(function() {
        $("#warp_display").fadeToggle();
    });

}<commit_msg>bug fixes<commit_after>/*!
 * warp.js
 *
 * MIT licensed
 *
 * Copyright (C) 2014 Paul Zellmer, http://pazellmer.com
 */

//////////////////////////////
//                          //
//      document setup      //
//                          //
//////////////////////////////

// functions

function position(item, i) {
    item.attr("id", "warp" + arrayCoord[i].index);
    item.animate({
        left: arrayCoord[i].x_axis,
        top: arrayCoord[i].y_axis,
        "z-index": arrayCoord[i].z_index,
        width: arrayCoord[i].width,
        height: arrayCoord[i].height,
        opacity: arrayCoord[i].opacity
    }, 2000)
}

function rndItems(){
    for (i = 0; i < 4; i++){
        if ((numItems + i) % 4 == 0){
            return (numItems + i);
        }
    }
}

function Coord(index, xAxis, yAxis, zIndex, width, height, opacity){
    this.index = index;
    this.x_axis = xAxis;
    this.y_axis = yAxis;
    this.z_index = zIndex;
    this.width = width;
    this.height = height;
    this.opacity = opacity;
}

$(".warp_desc, #warp_display").hide();
$("#warpContainer").parent().prepend("

");

var offset = parseInt($("#warpContainer").attr("data-offset"));
var numItems = $('.warp').length;

if (numItems > 0) {
    //variables

    var width = $(".warp").width();
    var height = $(".warp").height();

    var xCenter = $(window).width() / 2;
    var xLeft = $(window).width() / 4;
    var yTop = $(window).height() / 4 + offset;
    var yCenter = ($(window).height() + offset) / 2;

    var xInc = (xCenter - xLeft) / (numItems / 4);
    var xMov = xInc;
    var yInc = (yCenter - yTop) / (numItems / 4);
    var yMov = yInc;

    var counter = 1;
    var zIndex = 200;
    var zIndexInc = parseInt(800 / numItems);

    var limit = rndItems();

    // Gather objects, count and organize array, coordinates and structure
    arrayCoord = [];

    for (var i = 0; i < limit; i++) {
        if (counter == 1) {
            //left
            xAxis = Math.round(((xCenter + xMov - (width * zIndex / 1000) / 2) / $(window).width()) * 100);
            arrayCoord[i] = new Coord(i, xAxis + "%", Math.round((yCenter - (height * zIndex / 1000) / 2) / $(window).height() * 100) + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
        } else if (counter == 2) {
            //top
            yAxis = Math.round(((yCenter + yMov - (height * zIndex / 1000) / 2) / $(window).height()) * 100);
            arrayCoord[i] = new Coord(i, Math.round((xCenter - (width * zIndex / 1000) / 2) / $(window).width() * 100) + "%", yAxis + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
        } else if (counter == 3) {
            //right
            xAxis = Math.round(((xCenter - xMov - (width * zIndex / 1000) / 2) / $(window).width()) * 100);
            arrayCoord[i] = new Coord(i, xAxis + "%", Math.round((yCenter - (height * zIndex / 1000) / 2) / $(window).height() * 100) + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
            xMov += xInc;
        } else {
            //bottom
            yAxis = Math.round(((yCenter - yMov - (height * zIndex / 1000) / 2) / $(window).height()) * 100);
            arrayCoord[i] = new Coord(i, Math.round((xCenter - (width * zIndex / 1000) / 2) / $(window).width() * 100) + "%", yAxis + "%", zIndex, (width * zIndex / 1000), (height * zIndex / 1000), (1 * zIndex / 1000));
            yMov += yInc;
            counter = 0;
        }
        zIndex += zIndexInc;
        counter++;
    }

    arrayCoord[arrayCoord.length - 1].z_index = 1000;

    // Assign items location and z-index and show items
    $($(".warp").get().reverse()).each(function(i) {
        $(this).attr("id", "warp" + arrayCoord[i].index);
        $(this).css("left", arrayCoord[i].x_axis);
        $(this).css("top", arrayCoord[i].y_axis);
        $(this).css("z-index", arrayCoord[i].z_index);
        $(this).css("width", arrayCoord[i].width);
        $(this).css("height", arrayCoord[i].height);
        $(this).css("opacity", arrayCoord[i].opacity);
    })

    // Arrow click to item

    $(document).on("keydown", function(e) {
        // up
        if (e.keyCode == 38) {
            $("#warpContainer").append($("#warpContainer").children(".warp:first"));
            $(".warp").each(function (i){
                position($(this), i);
            });
        // down
        } else if (e.keyCode == 40) {
            $("#warpContainer").prepend($("#warpContainer").children(".warp:last"));
            $(".warp").each(function (i){
                position($(this), i);
            });
        }
    })

    // Mouse click to item

    $(".warp:not(.warp:last)").click(function() {
        var id = $(this).attr("id");
        var cycle = arrayCoord.length - parseInt(id.slice(4));
        for (i = 0; i < cycle; i++) {
            $("#warpContainer").prepend($("#warpContainer").children(".warp:last"));
            $(".warp").each(function(i) {
                $(this).attr("id", "warp" + arrayCoord[i].index);
                $(this).animate({
                    left: arrayCoord[i].x_axis,
                    top: arrayCoord[i].y_axis,
                    "z-index": arrayCoord[i].z_index,
                    width: arrayCoord[i].width,
                    height: arrayCoord[i].height,
                    opacity: arrayCoord[i].opacity
                }, 1000)
            });
        }
    });

    // Mouse click front item to open iFrame
    $(document).on("click", ".warp:last", function() {
        $("#warp_display").html($(this).html());
        $("#warp_display").children().show();
        $("#warp_display").fadeToggle();
    });

    $("#warp_display").click(function() {
        $("#warp_display").fadeToggle();
    });

}<|endoftext|>


<commit_before>/**
 * templateHelper.spec.js
 *
 * @author: Harish Anchu <harishanchu@gmail.com>
 * @copyright 2015, Harish Anchu. All rights reserved.
 * @license Licensed under MIT (https://github.com/quorrajs/Ouch/blob/master/LICENSE)
 */

var TemplateHelper = require("../../../util/TemplateHelper");
var path = require("path");
var os = require("os");

describe("TemplateHelper", function(){

    var helper;

    beforeEach(function () {
        helper = new TemplateHelper();
    });

    afterEach(function () {
        helper = undefined;
    });

    /**
     * @covers #getVAriables()
     */
    describe("#setVariables()", function(){
        it("should set template variables which should be available with getVariables method", function(done){
            var variables = {
                name: "Ouch",
                type: "node module"
            };

            helper.setVariables(variables);

            helper.getVariables().should.be.equal(variables);

            done();
        });
    });

    describe("#render()", function(){
        it("should render and ejs template file.", function(done){
            var template = path.join(__dirname, "../../fixtures/template.ejs");
            helper.render(template, {"name": "B<o>b"}).should.be.equal("hello-world\r\nMy name is B<o>b\r\n");
            done();
        });
    });

    describe("#slug()", function(){
        it("should convert a string to slug version", function(done){
            "hello-world".should.be.equal(helper.slug("Hello, world!"));
            "potato-class".should.be.equal(helper.slug("Potato class"));
            done();
        })
    });

    describe("#escapeButPreserveUris()", function(){
       it("should html escape string but preseve url's and convert it to clickable anchor elements", function(done){
           var original = "This is a http://google.com test string";

           helper.escapeButPreserveUris(original)
               .should.be
               .equal("This is a <a href=''>http://google.com</a> test string");

           done();
       });
    });

});
<commit_msg>fix cross platform EOL character issue in test<commit_after>/**
 * templateHelper.spec.js
 *
 * @author: Harish Anchu <harishanchu@gmail.com>
 * @copyright 2015, Harish Anchu. All rights reserved.
 * @license Licensed under MIT (https://github.com/quorrajs/Ouch/blob/master/LICENSE)
 */

var TemplateHelper = require("../../../util/TemplateHelper");
var path = require("path");
var os = require("os");

describe("TemplateHelper", function(){

    var helper;

    beforeEach(function () {
        helper = new TemplateHelper();
    });

    afterEach(function () {
        helper = undefined;
    });

    /**
     * @covers #getVAriables()
     */
    describe("#setVariables()", function(){
        it("should set template variables which should be available with getVariables method", function(done){
            var variables = {
                name: "Ouch",
                type: "node module"
            };

            helper.setVariables(variables);

            helper.getVariables().should.be.equal(variables);

            done();
        });
    });

    describe("#render()", function(){
        it("should render and ejs template file.", function(done){
            var template = path.join(__dirname, "../../fixtures/template.ejs");
            var html = helper.render(template, {"name": "B<o>b"});
            html.replace(/\r?\n/g, "\r\n"); // fix cross platform issues
            html.should.be.equal("hello-world\r\nMy name is B<o>b\r\n");
            done();
        });
    });

    describe("#slug()", function(){
        it("should convert a string to slug version", function(done){
            "hello-world".should.be.equal(helper.slug("Hello, world!"));
            "potato-class".should.be.equal(helper.slug("Potato class"));
            done();
        })
    });

    describe("#escapeButPreserveUris()", function(){
       it("should html escape string but preseve url's and convert it to clickable anchor elements", function(done){
           var original = "This is a http://google.com test string";

           helper.escapeButPreserveUris(original)
               .should.be
               .equal("This is a <a href=''>http://google.com</a> test string");

           done();
       });
    });

});
<|endoftext|>


<commit_before>$(function () {

    lightbox();
    sticky();
    utils();
    map();
    demo();

});

/* for demo purpose only - can be deleted */

function demo() {

    $("#page").change(function () {

        if ($(this).val() !== '') {

            window.location.href = $(this).val();

        }

        return false;
    });
}

/* =========================================
 *  lightbox
 *  =======================================*/

function lightbox() {

    $(document).delegate('*[data-toggle="lightbox"]', 'click', function (event) {
        event.preventDefault();
        $(this).ekkoLightbox();
    });
}

/* =========================================
 *  sticky header
 *  =======================================*/

function sticky() {

    $(".header").sticky();

}

/* =========================================
 *  map
 *  =======================================*/

function map() {

    var styles = [{"featureType": "landscape", "stylers": [{"saturation": -100}, {"lightness": 65}, {"visibility": "on"}]}, {"featureType": "poi", "stylers": [{"saturation": -100}, {"lightness": 51}, {"visibility": "simplified"}]}, {"featureType": "road.highway", "stylers": [{"saturation": -100}, {"visibility": "simplified"}]}, {"featureType": "road.arterial", "stylers": [{"saturation": -100}, {"lightness": 30}, {"visibility": "on"}]}, {"featureType": "road.local", "stylers": [{"saturation": -100}, {"lightness": 40}, {"visibility": "on"}]}, {"featureType": "transit", "stylers": [{"saturation": -100}, {"visibility": "simplified"}]}, {"featureType": "administrative.province", "stylers": [{"visibility": "off"}]}, {"featureType": "water", "elementType": "labels", "stylers": [{"visibility": "on"}, {"lightness": -25}, {"saturation": -100}]}, {"featureType": "water", "elementType": "geometry", "stylers": [{"hue": "#ffff00"}, {"lightness": -25}, {"saturation": -97}]}];
    map = new GMaps({
        el: '#map',
        lat: -12.043333,
        lng: -77.028333,
        zoomControl: true,
        zoomControlOpt: {
            style: 'SMALL',
            position: 'TOP_LEFT'
        },
        panControl: false,
        streetViewControl: false,
        mapTypeControl: false,
        overviewMapControl: false,
        scrollwheel: false,
        draggable: false,
        styles: styles
    });

    var image = 'img/marker.png';

    map.addMarker({
        lat: -12.043333,
        lng: -77.028333,
        icon: image/* ,
         title: '',
         infoWindow: {
         content: '
HTML Content
'
         }*/
    });
}

function utils() {

    /* tooltips */

    $('[data-toggle="tooltip"]').tooltip();

    /* click on the box activates the radio */

    $('#checkout').on('click', '.box.shipping-method, .box.payment-method', function (e) {
        var radio = $(this).find(':radio');
        radio.prop('checked', true);
    });
    /* click on the box activates the link in it */

    $('.box.clickable').on('click', function (e) {

        window.location = $(this).find('a').attr('href');
    });
    /* external links in new window*/

    $('.external').on('click', function (e) {

        e.preventDefault();
        window.open($(this).attr("href"));
    });
    /* animated scrolling */

    /* animated scrolling */

    $('.scroll-to, #navigation a').click(function (event) {
        event.preventDefault();
        var full_url = this.href;
        var parts = full_url.split("#");
        var trgt = parts[1];

        $('body').scrollTo($('#' + trgt), 800, {offset: -40});

    });

}

$.fn.alignElementsSameHeight = function () {
    $('.same-height-row').each(function () {

        var maxHeight = 0;
        var children = $(this).find('.same-height');
        children.height('auto');
        if ($(window).width() > 768) {
            children.each(function () {
                if ($(this).innerHeight() > maxHeight) {
                    maxHeight = $(this).innerHeight();
                }
            });
            children.innerHeight(maxHeight);
        }

        maxHeight = 0;
        children = $(this).find('.same-height-always');
        children.height('auto');
        children.each(function () {
            if ($(this).innerHeight() > maxHeight) {
                maxHeight = $(this).innerHeight();
            }
        });
        children.innerHeight(maxHeight);
    });
}

$(window).load(function () {

    windowWidth = $(window).width();
    windowHeight = $(window).height();

    $(this).alignElementsSameHeight();

});
$(window).resize(function () {

    newWindowWidth = $(window).width();
    newWindowHeight = $(window).height();

    if (windowWidth !== newWindowWidth) {
        setTimeout(function () {
            $(this).alignElementsSameHeight();
        }, 100);
        windowWidth = newWindowWidth;
        windowHeight = newWindowHeight;
    }

});
<commit_msg>remove gmaps from front.js<commit_after>$(function () {

    lightbox();
    sticky();
    utils();
    map();
    demo();

});

/* for demo purpose only - can be deleted */

function demo() {

    $("#page").change(function () {

        if ($(this).val() !== '') {

            window.location.href = $(this).val();

        }

        return false;
    });
}

/* =========================================
 *  lightbox
 *  =======================================*/

function lightbox() {

    $(document).delegate('*[data-toggle="lightbox"]', 'click', function (event) {
        event.preventDefault();
        $(this).ekkoLightbox();
    });
}

/* =========================================
 *  sticky header
 *  =======================================*/

function sticky() {

    $(".header").sticky();

}

function utils() {

    /* tooltips */

    $('[data-toggle="tooltip"]').tooltip();

    /* click on the box activates the radio */

    $('#checkout').on('click', '.box.shipping-method, .box.payment-method', function (e) {
        var radio = $(this).find(':radio');
        radio.prop('checked', true);
    });
    /* click on the box activates the link in it */

    $('.box.clickable').on('click', function (e) {

        window.location = $(this).find('a').attr('href');
    });
    /* external links in new window*/

    $('.external').on('click', function (e) {

        e.preventDefault();
        window.open($(this).attr("href"));
    });
    /* animated scrolling */

    /* animated scrolling */

    $('.scroll-to, #navigation a').click(function (event) {
        event.preventDefault();
        var full_url = this.href;
        var parts = full_url.split("#");
        var trgt = parts[1];

        $('body').scrollTo($('#' + trgt), 800, {offset: -40});

    });

}

$.fn.alignElementsSameHeight = function () {
    $('.same-height-row').each(function () {

        var maxHeight = 0;
        var children = $(this).find('.same-height');
        children.height('auto');
        if ($(window).width() > 768) {
            children.each(function () {
                if ($(this).innerHeight() > maxHeight) {
                    maxHeight = $(this).innerHeight();
                }
            });
            children.innerHeight(maxHeight);
        }

        maxHeight = 0;
        children = $(this).find('.same-height-always');
        children.height('auto');
        children.each(function () {
            if ($(this).innerHeight() > maxHeight) {
                maxHeight = $(this).innerHeight();
            }
        });
        children.innerHeight(maxHeight);
    });
}

$(window).load(function () {

    windowWidth = $(window).width();
    windowHeight = $(window).height();

    $(this).alignElementsSameHeight();

});
$(window).resize(function () {

    newWindowWidth = $(window).width();
    newWindowHeight = $(window).height();

    if (windowWidth !== newWindowWidth) {
        setTimeout(function () {
            $(this).alignElementsSameHeight();
        }, 100);
        windowWidth = newWindowWidth;
        windowHeight = newWindowHeight;
    }

});
<|endoftext|>


<commit_before>import React from 'react';
import { default as TitleBarContainer } from './TitleBarContainer';
import { mount } from 'enzyme';
import sinon from 'sinon';

const moment = require('moment');

const emptyFunc = () => {
  // intentionally left blank
};
const emptyObj = {
  // intentionally left blank
};

describe('(Component) TitleBarContainer', () => {
  let _component;
  const _logoutaction = sinon.spy();
  const _loginaction = sinon.spy();

  beforeEach(() => {
    _component = mount(<TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }} mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
      user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }} adagucProperties={emptyObj} dispatch={emptyFunc} routes={[{ path: 'testpath' }]} />);
  });
  it('Renders nested routes', () => {
    _component = mount(<TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
      userActions={{ login: _loginaction, logout: _logoutaction }}
      adagucProperties={emptyObj}
      mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
      dispatch={emptyFunc}
      user={{ roles: [], isLoggedIn: false }}
      routes={[
        { path: 'testpathA', indexRoute: { title: 'testpathAtitle' } },
        { path: 'testpathB', indexRoute: { title: 'testpathBtitle' } },
        { path: 'testpathC', indexRoute: { title: 'testpathCtitle' } }
      ]}
    />);
    expect(_component.type()).to.eql(TitleBarContainer);
  });
  it('Renders a TitleBarContainer', () => {
    expect(_component.type()).to.eql(TitleBarContainer);
  });
  it('Renders initially with the current time', () => {
    const currentTime = moment.utc().format('YYYY MMM DD - HH:mm').toString();
    expect(_component.state().currentTime).to.equal(currentTime);
  });
  it('Calls the login function when the login button is clicked', () => {
    _component.doLogin = sinon.spy();
    _component.toggleLoginModal = sinon.spy();
    const loginComponent = _component.find('#loginIcon');
    expect(loginComponent.length).to.equal(1);
    loginComponent.simulate('click');
  });

  it('Checks setLoggedOut method', () => {
    const _logoutaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        adagucProperties={{ user: { isLoggedIn: true, userName: 'Blah' } }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().setLoggedOutCallback('testmessage');
    expect(_component.state().loginModalMessage).to.equal('testmessage');
    expect(_component.instance().inputfieldUserName).to.equal('');
    expect(_component.instance().inputfieldPassword).to.equal('');
    _logoutaction.should.have.been.calledOnce();
  });

  it('Checks checkCredentialsOKCallback method with user test', () => {
    const _loginaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().checkCredentialsOKCallback({ userName: 'test' });
    expect(_component.state().loginModal).to.equal(false);
    expect(_component.state().loginModalMessage).to.equal('Signed in as user test');
    _loginaction.should.have.been.calledOnce();
  });

  it('Checks checkCredentialsBadCallback', () => {
    const _logoutaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().checkCredentialsBadCallback({
      response: {
        data: {
          message: 'invalid_user'
        }
      }
    });
    expect(_component.state().loginModalMessage).to.equal('invalid_user');
    _logoutaction.should.have.been.calledOnce();
  });

  it('Checks checkCredentialsOKCallback method with invalid username \'\' ', () => {
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().inputfieldUserName = 'someuser';
    _component.instance().checkCredentialsOKCallback({ userName: '' });
    expect(_component.state().loginModalMessage).to.equal('Unauthorized');
  });

  it('Checks if logout method works and if logout action is triggered once', () => {
    const _logoutaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        adagucProperties={{ user: { isLoggedIn: true, userName: 'Blah' } }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().doLogout();
    expect(_component.instance().inputfieldUserName).to.equal('');
    expect(_component.instance().inputfieldPassword).to.equal('');
  });

  it('Calls the setTime function and checks wheter state is updated', () => {
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        adagucProperties={{ user: { isLoggedIn: true, userName: 'Blah' } }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    const currentTime = moment.utc().format('YYYY MMM DD - HH:mm').toString();
    _component.instance().setTime();
    expect(_component.state().currentTime).to.equal(currentTime);
  });
});
<commit_msg>Forgot to commit updated unit test<commit_after>import React from 'react';
import { default as TitleBarContainer } from './TitleBarContainer';
import { mount } from 'enzyme';
import sinon from 'sinon';

const moment = require('moment');

const emptyFunc = () => {
  // intentionally left blank
};
const emptyObj = {
  // intentionally left blank
};

describe('(Component) TitleBarContainer', () => {
  let _component;
  const _logoutaction = sinon.spy();
  const _loginaction = sinon.spy();

  beforeEach(() => {
    _component = mount(<TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }} mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
      user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }} adagucProperties={emptyObj} dispatch={emptyFunc} routes={[{ path: 'testpath' }]} />);
  });
  it('Renders nested routes', () => {
    _component = mount(<TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
      userActions={{ login: _loginaction, logout: _logoutaction }}
      adagucProperties={emptyObj}
      mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
      dispatch={emptyFunc}
      user={{ roles: [], isLoggedIn: false }}
      routes={[
        { path: 'testpathA', indexRoute: { title: 'testpathAtitle' } },
        { path: 'testpathB', indexRoute: { title: 'testpathBtitle' } },
        { path: 'testpathC', indexRoute: { title: 'testpathCtitle' } }
      ]}
    />);
    expect(_component.type()).to.eql(TitleBarContainer);
  });
  it('Renders a TitleBarContainer', () => {
    expect(_component.type()).to.eql(TitleBarContainer);
  });
  it('Renders initially with the current time', () => {
    const currentTime = moment.utc().format('ddd DD MMM YYYY HH:mm [UTC]').toString();
    expect(_component.state().currentTime).to.equal(currentTime);
  });
  it('Calls the login function when the login button is clicked', () => {
    _component.doLogin = sinon.spy();
    _component.toggleLoginModal = sinon.spy();
    const loginComponent = _component.find('#loginIcon');
    expect(loginComponent.length).to.equal(1);
    loginComponent.simulate('click');
  });

  it('Checks setLoggedOut method', () => {
    const _logoutaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        adagucProperties={{ user: { isLoggedIn: true, userName: 'Blah' } }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().setLoggedOutCallback('testmessage');
    expect(_component.state().loginModalMessage).to.equal('testmessage');
    expect(_component.instance().inputfieldUserName).to.equal('');
    expect(_component.instance().inputfieldPassword).to.equal('');
    _logoutaction.should.have.been.calledOnce();
  });

  it('Checks checkCredentialsOKCallback method with user test', () => {
    const _loginaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().checkCredentialsOKCallback({ userName: 'test' });
    expect(_component.state().loginModal).to.equal(false);
    expect(_component.state().loginModalMessage).to.equal('Signed in as user test');
    _loginaction.should.have.been.calledOnce();
  });

  it('Checks checkCredentialsBadCallback', () => {
    const _logoutaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().checkCredentialsBadCallback({
      response: {
        data: {
          message: 'invalid_user'
        }
      }
    });
    expect(_component.state().loginModalMessage).to.equal('invalid_user');
    _logoutaction.should.have.been.calledOnce();
  });

  it('Checks checkCredentialsOKCallback method with invalid username \'\' ', () => {
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().inputfieldUserName = 'someuser';
    _component.instance().checkCredentialsOKCallback({ userName: '' });
    expect(_component.state().loginModalMessage).to.equal('Unauthorized');
  });

  it('Checks if logout method works and if logout action is triggered once', () => {
    const _logoutaction = sinon.spy();
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        adagucProperties={{ user: { isLoggedIn: true, userName: 'Blah' } }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    _component.instance().doLogout();
    expect(_component.instance().inputfieldUserName).to.equal('');
    expect(_component.instance().inputfieldPassword).to.equal('');
  });

  it('Calls the setTime function and checks wheter state is updated', () => {
    _component = mount(
      <TitleBarContainer urls={{ BACKEND_SERVER_URL: 'http://localhost:8080' }}
        mapProperties={{ boundingBox: emptyObj, projection: emptyObj }}
        user={{ roles: [], isLoggedIn: false }} userActions={{ login: _loginaction, logout: _logoutaction }}
        adagucProperties={{ user: { isLoggedIn: true, userName: 'Blah' } }}
        dispatch={emptyFunc}
        routes={[{ path: 'testpath' }]}
      />
    );
    const currentTime = moment.utc().format('ddd DD MMM YYYY HH:mm [UTC]').toString();
    _component.instance().setTime();
    expect(_component.state().currentTime).to.equal(currentTime);
  });
});
<|endoftext|>


<commit_before>const SpecReporter = require('jasmine-spec-reporter');
const path = require('path');

exports.config = {
  baseUrl: 'http://localhost:4200',
  specs: [
    path.resolve(__dirname, '../e2e/**/*.e2e.ts')
  ],
  exclude: [],
  framework: 'jasmine2',
  allScriptsTimeout: 120000,
  jasmineNodeOpts: {
    showTiming: true,
    showColors: true,
    isVerbose: false,
    includeStackTrace: false,
    defaultTimeoutInterval: 400000
  },
  directConnect: true,
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: ['show-fps-counter=true', 'no-sandbox']
    }
  },
  useAllAngular2AppRoots: true,
  beforeLaunch: () => {
    require('ts-node').register({
      project: path.resolve(__dirname, '../e2e')
    });
  },
  onPrepare: () => {
    jasmine.getEnv().addReporter(new SpecReporter());
  }
};
<commit_msg>fix(): protractor config<commit_after>const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
const path = require('path');

exports.config = {
  baseUrl: 'http://localhost:8000',
  specs: [
    path.resolve(__dirname, '../e2e/**/*.e2e.ts')
  ],
  exclude: [],
  framework: 'jasmine2',
  allScriptsTimeout: 120000,
  jasmineNodeOpts: {
    showTiming: true,
    showColors: true,
    isVerbose: false,
    includeStackTrace: false,
    defaultTimeoutInterval: 400000
  },
  directConnect: true,
  capabilities: {
    browserName: 'chrome',
    chromeOptions: {
      args: ['show-fps-counter=true', 'no-sandbox']
    }
  },
  useAllAngular2AppRoots: true,
  beforeLaunch: () => {
    require('ts-node').register({
      project: path.resolve(__dirname, '../e2e')
    });
  },
  onPrepare: () => {
    jasmine.getEnv().addReporter(new SpecReporter());
  }
};
<|endoftext|>


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

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BosClient
} from 'bce-sdk-js';

import AMUIReact from 'amazeui-react';
var Button = AMUIReact.Button;
//var Input = AMUIReact.Input;
// var Icon = AMUIReact.Icon;
const config = {
  endpoint: 'http://gz.bcebos.com', //传入Bucket所在区域域名
  credentials: {
    ak: '6bb013b74f43441aa2961130a550837d', //您的AccessKey
    sk: '114576782dd448b89c8e4b2b2db551be' //您的SecretAccessKey
  }
};

let bucket = 'my-bucket';
let key = 'hello.js';
let client = new BosClient(config);

/*
  client.putObjectFromString(bucket, key, 'hello world')
    .then(response => console.log(response))    // 成功
    .catch(error => console.error(error));
    */

//拿到储存章节信息的json文件，转化为数组

let Datas = require('../data/chapData.json');
let chapterDatas = Datas.data;
let child = [];

//单个章节节点组件
class ChapIndexs extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      mainindex: chapterDatas.length + 1,
      chidvisible: false,
      key: 0,
      namevaluechange: false,
      childcount: 0
    };
  }

  componentWillMount() {
    child = chapterDatas[0].childChap;
  }

  //点击为chapterDatas数组添加新的一组章节数据项

  _add() {
    let date = new Date();
    let time = date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate();
    time += date.getTime().toString().substr(11);
    let count = this.state.count;
    count++;
    let main = this.state.mainindex + 1;
    this.setState({
      count: count,
      mainindex: main
    })
    let nextChap = {
      mainIndex: this.state.mainindex,
      chapterId: time.substr(4),
      chapterName: '请点击编辑命名',
      mirror: false,
      chapterSum: '',
      childChap: []
    }

    // console.log(count + 'add')
    chapterDatas.push(nextChap);
  }

  //点击删除某一章节节点信息
  _delete(obj) {
    let main;
    let count = this.state.count;
    count--;
    if (!obj.mirror) {
      main = this.state.mainindex;
      main--;
    } else {
      main = this.state.mainindex;
    }
    this.setState({
      count: count,
      mainindex: main,
      childcount: 0
    })

    child = [];
    chapterDatas.splice(chapterDatas.indexOf(obj), 1);
  }

  //创建副本
  _createBre(obj) {
    let date = new Date();
    let time = date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate();
    time += date.getTime().toString().substr(11);
    let count = this.state.count;
    count++;
    this.setState({
      count: count
    })

    let nextChap = {
      mainIndex: obj.mainIndex,
      chapterId: time.substr(4),
      chapterName: '请点击编辑命名',
      mirror: true,
      chapterSum: '',
      childChap: []
    };

    chapterDatas.splice(chapterDatas.indexOf(obj) + 1, 0, nextChap);
  }

  _showChid(key, e) {
    let parent = chapterDatas[key];

    child = parent.childChap;
    //console.log(child[0].chapterName);
    this.setState({
      key: key,
      chidvisible: true,
      childcount: child.length
    });
    e.stopPropagation();
    e.preventDefault();
  }

  // 显示编辑区域
  _showInputChap(key) {
    let obj = this.refs['inputChap' + key];
    obj.style.display = 'block';
  }

  // 点击全选文本
  _select(key) {
    let obj = this.refs['inputChap' + key];
    obj.select();
  }

  //编辑章节名
  _settingName(key) {
    chapterDatas[key].chapterName = this.refs['inputChap' + key].value;
    this.setState({
      namevaluechange: true
    });
  }

  // 隐藏编辑区域
  _hide(e, key) {
    let obj = this.refs['inputChap' + key];
    if (e && e.keyCode == 13) { // enter 键
      // alert('enter')
      obj.style.display = 'none';
    }
  }

  //创建新的子章节
  _newchild() {

    child.push({
      mirror: false,
      chapterId: '',
      chapterName: '子章节'
    });
    chapterDatas[this.state.key].childChap = child;
    this.setState({
      chidvisible: true,
      childcount: child.length
    });
  }

  //删除子章节
  _deletechild(child, key) {
    this.setState({
      chidvisible: true,
      childcount: child.length - 1
    })
    child.splice(key, 1);
    chapterDatas[this.state.key].childChap = child;
  }

  //显示子章节文本输入框
  _showInputChild(key) {
      let obj = this.refs['inputChild' + key];
      obj.style.display = 'block';
    }
    // 编辑子章节名
  _settingChildName(child, key) {
      child[key].chapterName = this.refs['inputChild' + key].value;
      this.setState({
        namevaluechange: true
      });
    }
    // 隐藏子章节文本输入框
  _hideChild(e, key) {
    let obj = this.refs['inputChild' + key];
    if (e && e.keyCode == 13) { // enter 键
      // alert('enter')
      obj.style.display = 'none';
    }
  }

  _createChildBre(child, key) {
    let date = new Date();
    let time = date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate();
    time += date.getTime().toString().substr(11);

    let nextChap = {
      mirror: true,
      chapterId: time.substr(4),
      chapterName: '请点击编辑命名',
    };
    this.setState({
      childcount: child.length + 1
    });
    child.splice(key + 1, 0, nextChap);
    console.log(child)
    chapterDatas[this.state.key].childChap = child;
  }

  render() {

    return (

top

              <Button
                className="newChap"
                onClick = {
                 this._add.bind(this)
                }
              >
                +
              </Button>
              {
                chapterDatas.map((data)=>{
                  let key = chapterDatas.indexOf(data);
                  let index = data.mainIndex;
                  let name = data.chapterName;
                  let text = data.chapterSum;
                  return(

{this._showChid(key,event)}}
                    >

                        章节:{key+1}

章节名: {name}

章节简介: {text}{data.mirror?'副本':null}

                          <Button amSize="xs" onClick={()=>{this._showInputChap(key)}}>编辑</Button>
                          <Button amSize="xs" onClick={()=>{this._delete(data)}}>删除</Button>
                          <Button amSize="xs" onClick={()=>{this._createBre(data)}}>创建副本</Button>
                          <input
                            className="inputChap"
                            ref={'inputChap'+key}
                            placeholder="输入章节名"
                            type="text"
                            onChange={()=>{this._settingName(key)}}
                            onKeyDown={(e)=>{this._hide(e,key)}}
                            onFocus={()=>{this._select(key)}}
                          />

                  );
                })
              }

            <Button className="newchild" onClick={()=>this._newchild()}>创建新的子章节   </Button>
            {

                child.map((data)=>{
                  let key = child.indexOf(data);
                  let childId = data.chapterId;
                  let childName = data.chapterName;

                  return(

                        {childId}
                        {childName}

                        <Button amSize="xs" onClick={()=>{this._showInputChild(key)}}>编辑</Button>
                        <Button amSize="xs" onClick={()=>{this._deletechild(child,key)}}>删除</Button>
                        <Button amSize="xs" onClick={()=>{this._createChildBre(child,key)}}>创建副本</Button>
                        <input
                          className="inputChild"
                          ref={'inputChild'+key}
                          type="text"
                          placeholder="输入子章节名"
                          onChange={()=>{this._settingChildName(child,key)}}
                          onKeyDown={(e)=>{this._hideChild(e,key)}}
                        />

                  );
                })

            }

            <Chaptree/>

center

right

bottom

    );
  }
}

class Chaptree extends React.Component {

  render() {
    //取到一共有多少个主章节
    let lastindex;
    if(chapterDatas.length==0){
      lastindex = 0;
    } else {
      lastindex = chapterDatas[chapterDatas.length - 1].mainIndex;
    }
    let subChap = [];
    //将mainIndex相同的章节放在一个数组中
    for (let i = 1; i <= lastindex; i++) {
      subChap[i - 1] = [];
      for (let j = 0; j < chapterDatas.length; j++) {
        if (chapterDatas[j].mainIndex == i) {
          subChap[i - 1].push(chapterDatas[j]);
        }
      }
    }

    // console.log(subChap[0]);
    return (

        <Button amSize='lg'>查看我的所有章节结构</Button>

          {
            subChap.map((data) => {
              let key = subChap.indexOf(data);
              return(

                  {
                    data.map((d) => {
                      let childtree = d.childChap;

                      return(

                          {
                            childtree.map((childdata) => {

                              return(

                              )
                            })
                          }

                      );
                    })
                  }

              );
            })
          }

    );
  }
}

class AppComponent extends React.Component {

  render() {
    return (

            <ChapIndexs/>

    );
  }
}

AppComponent.defaultProps = {};

export default AppComponent;
<commit_msg>update<commit_after>require('normalize.css/normalize.css');
require('styles/App.css');

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BosClient
} from 'bce-sdk-js';

import AMUIReact from 'amazeui-react';
var Button = AMUIReact.Button;
//var Input = AMUIReact.Input;
// var Icon = AMUIReact.Icon;
const config = {
  endpoint: 'http://gz.bcebos.com', //传入Bucket所在区域域名
  credentials: {
    ak: '6bb013b74f43441aa2961130a550837d', //您的AccessKey
    sk: '114576782dd448b89c8e4b2b2db551be' //您的SecretAccessKey
  }
};

let bucket = 'my-bucket';
let key = 'hello.js';
let client = new BosClient(config);

/*
  client.putObjectFromString(bucket, key, 'hello world')
    .then(response => console.log(response))    // 成功
    .catch(error => console.error(error));
    */

//拿到储存章节信息的json文件，转化为数组

let Datas = require('../data/chapData.json');
let chapterDatas = Datas.data;
let child = [];

//单个章节节点组件
class ChapIndexs extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      mainindex: chapterDatas.length + 1,
      chidvisible: false,
      key: 0,
      namevaluechange: false,
      childcount: 0
    };
  }

  componentWillMount() {
    child = chapterDatas[0].childChap;
  }

  //点击为chapterDatas数组添加新的一组章节数据项

  _add() {
    let date = new Date();
    let time = date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate();
    time += date.getTime().toString().substr(11);
    let count = this.state.count;
    count++;
    let main = this.state.mainindex + 1;
    this.setState({
      count: count,
      mainindex: main
    })
    let nextChap = {
      mainIndex: this.state.mainindex,
      chapterId: time.substr(4),
      chapterName: '请点击编辑命名',
      mirror: false,
      chapterSum: '',
      childChap: []
    }

    // console.log(count + 'add')
    chapterDatas.push(nextChap);
  }

  //点击删除某一章节节点信息
  _delete(obj) {
    let main;
    let count = this.state.count;
    count--;
    if (!obj.mirror) {
      main = this.state.mainindex;
      main--;
    } else {
      main = this.state.mainindex;
    }
    this.setState({
      count: count,
      mainindex: main,
      childcount: 0
    })

    child = [];
    chapterDatas.splice(chapterDatas.indexOf(obj), 1);
  }

  //创建副本
  _createBre(obj) {
    let date = new Date();
    let time = date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate();
    time += date.getTime().toString().substr(11);
    let count = this.state.count;
    count++;
    this.setState({
      count: count
    })

    let nextChap = {
      mainIndex: obj.mainIndex,
      chapterId: time.substr(4),
      chapterName: '请点击编辑命名',
      mirror: true,
      chapterSum: '',
      childChap: []
    };

    chapterDatas.splice(chapterDatas.indexOf(obj) + 1, 0, nextChap);
  }

  _showChid(key, e) {
    let parent = chapterDatas[key];

    child = parent.childChap;
    //console.log(child[0].chapterName);
    this.setState({
      key: key,
      chidvisible: true,
      childcount: child.length
    });
    e.stopPropagation();
    e.preventDefault();
  }

  // 显示编辑区域
  _showInputChap(key) {
    let obj = this.refs['inputChap' + key];
    obj.style.display = 'block';
  }

  // 点击全选文本
  _select(key) {
    let obj = this.refs['inputChap' + key];
    obj.select();
  }

  //编辑章节名
  _settingName(key) {
    chapterDatas[key].chapterName = this.refs['inputChap' + key].value;
    this.setState({
      namevaluechange: true
    });
  }

  // 隐藏编辑区域
  _hide(e, key) {
    let obj = this.refs['inputChap' + key];
    if (e && e.keyCode == 13) { // enter 键
      // alert('enter')
      obj.style.display = 'none';
    }
  }

  //创建新的子章节
  _newchild() {

    child.push({
      mirror: false,
      chapterId: '',
      chapterName: '子章节'
    });
    chapterDatas[this.state.key].childChap = child;
    this.setState({
      chidvisible: true,
      childcount: child.length
    });
  }

  //删除子章节
  _deletechild(child, key) {
    this.setState({
      chidvisible: true,
      childcount: child.length - 1
    })
    child.splice(key, 1);
    chapterDatas[this.state.key].childChap = child;
  }

  //显示子章节文本输入框
  _showInputChild(key) {
      let obj = this.refs['inputChild' + key];
      obj.style.display = 'block';
    }
    // 编辑子章节名
  _settingChildName(child, key) {
      child[key].chapterName = this.refs['inputChild' + key].value;
      this.setState({
        namevaluechange: true
      });
    }
    // 隐藏子章节文本输入框
  _hideChild(e, key) {
    let obj = this.refs['inputChild' + key];
    if (e && e.keyCode == 13) { // enter 键
      // alert('enter')
      obj.style.display = 'none';
    }
  }

  _createChildBre(child, key) {
    let date = new Date();
    let time = date.getFullYear().toString() + (date.getMonth() + 1).toString() + date.getDate();
    time += date.getTime().toString().substr(11);

    let nextChap = {
      mirror: true,
      chapterId: time.substr(4),
      chapterName: '请点击编辑命名',
    };
    this.setState({
      childcount: child.length + 1
    });
    child.splice(key + 1, 0, nextChap);
    console.log(child)
    chapterDatas[this.state.key].childChap = child;
  }

  render() {

    return (

top

              <Button
                className="newChap"
                onClick = {
                 this._add.bind(this)
                }
              >
                +
              </Button>
              {
                chapterDatas.map((data)=>{
                  let key = chapterDatas.indexOf(data);
                  let index = data.mainIndex;
                  let name = data.chapterName;
                  let text = data.chapterSum;
                  return(

{this._showChid(key,event)}}
                    >

                        章节:{key+1}

章节名: {name}

章节简介: {text}{data.mirror?'副本':null}

                          <Button amSize="xs" onClick={()=>{this._showInputChap(key)}}>编辑</Button>
                          <Button amSize="xs" onClick={()=>{this._delete(data)}}>删除</Button>
                          <Button amSize="xs" onClick={()=>{this._createBre(data)}}>创建副本</Button>
                          <input
                            className="inputChap"
                            ref={'inputChap'+key}
                            placeholder="输入章节名，按回车确定"
                            type="text"
                            onChange={()=>{this._settingName(key)}}
                            onKeyDown={(e)=>{this._hide(e,key)}}
                            onFocus={()=>{this._select(key)}}
                          />

                  );
                })
              }

            <Button className="newchild" onClick={()=>this._newchild()}>创建新的子章节   </Button>
            {

                child.map((data)=>{
                  let key = child.indexOf(data);
                  let childId = data.chapterId;
                  let childName = data.chapterName;

                  return(

                        {childId}
                        {childName}

                        <Button amSize="xs" onClick={()=>{this._showInputChild(key)}}>编辑</Button>
                        <Button amSize="xs" onClick={()=>{this._deletechild(child,key)}}>删除</Button>
                        <Button amSize="xs" onClick={()=>{this._createChildBre(child,key)}}>创建副本</Button>
                        <input
                          className="inputChild"
                          ref={'inputChild'+key}
                          type="text"
                          placeholder="输入子章节名，按回车确定"
                          onChange={()=>{this._settingChildName(child,key)}}
                          onKeyDown={(e)=>{this._hideChild(e,key)}}
                        />

                  );
                })

            }

            <Chaptree/>

center

right

bottom

    );
  }
}

class Chaptree extends React.Component {

  render() {
    //取到一共有多少个主章节
    let lastindex;
    if(chapterDatas.length==0){
      lastindex = 0;
    } else {
      lastindex = chapterDatas[chapterDatas.length - 1].mainIndex;
    }
    let subChap = [];
    //将mainIndex相同的章节放在一个数组中
    for (let i = 1; i <= lastindex; i++) {
      subChap[i - 1] = [];
      for (let j = 0; j < chapterDatas.length; j++) {
        if (chapterDatas[j].mainIndex == i) {
          subChap[i - 1].push(chapterDatas[j]);
        }
      }
    }

    // console.log(subChap[0]);
    return (

        <Button amSize='lg'>查看我的所有章节结构</Button>

          {
            subChap.map((data) => {
              let key = subChap.indexOf(data);
              return(

                  {
                    data.map((d) => {
                      let childtree = d.childChap;

                      return(

                          {
                            childtree.map((childdata) => {

                              return(

                              )
                            })
                          }

                      );
                    })
                  }

              );
            })
          }

    );
  }
}

class AppComponent extends React.Component {

  render() {
    return (

            <ChapIndexs/>

    );
  }
}

AppComponent.defaultProps = {};

export default AppComponent;
<|endoftext|>


<commit_before>exports.names = ['.theme'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.handler = function (data) {

    var input = data.message.split(' ');

    RoomEvent.find({where: {type: 'theme', starts_at: {lte: moment.utc().add(1, 'day').toDate()}, ends_at: {gte: new Date()}}}).on('success', function (row) {
        if (row === null) {
            bot.sendChat('/me ' + config.responses.theme);
        } else {
            if (row.starts_at >= moment.utc().toDate()) {
                row.details = timeUntil(row.starts_at) + ' ' + row.details;
            }
            bot.sendChat('/me ' + row.title + ' - ' + row.details);
        }
    });

};<commit_msg>Update theme.js<commit_after>exports.names = ['!theme'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.handler = function (data) {

    var input = data.message.split(' ');

    RoomEvent.find({where: {type: 'theme', starts_at: {lte: moment.utc().add(1, 'day').toDate()}, ends_at: {gte: new Date()}}}).on('success', function (row) {
        if (row === null) {
            bot.sendChat('/me ' + config.responses.theme);
        } else {
            if (row.starts_at >= moment.utc().toDate()) {
                row.details = timeUntil(row.starts_at) + ' ' + row.details;
            }
            bot.sendChat('/me ' + row.title + ' - ' + row.details);
        }
    });

};
<|endoftext|>


<commit_before>/* eslint-env mocha */
import assert from 'assert';
import Vue from 'vue-test'; // eslint-disable-line
import { shallow } from '@vue/test-utils';
import elapsedTime from '../../src/views/elapsed-time';

const DUMMY_CURRENT_DATE = new Date(2017, 0, 1, 1, 1, 1);

function makeWrapper(options) {
  return shallow(elapsedTime, options);
}

// prettier-ignore
function getTimeText(wrapper) {
  return wrapper.find('span').text().trim();
}

describe('elapsed time component', () => {
  it('should show display a "–" if no date is passed in', () => {
    const wrapper = makeWrapper({ propsData: {} });
    const timeText = getTimeText(wrapper);
    assert.equal(timeText, '–');
  });
  it('should use seconds if the date passed in 1 second ago', () => {
    const date1SecondAgo = new Date(DUMMY_CURRENT_DATE);
    date1SecondAgo.setSeconds(date1SecondAgo.getSeconds() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1SecondAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/second/.test(timeText), true);
  });

  it('should use minutes if the date passed in is 60 seconds ago', () => {
    const date60SecondsAgo = new Date(DUMMY_CURRENT_DATE);
    date60SecondsAgo.setSeconds(date60SecondsAgo.getSeconds() - 60);
    const wrapper = makeWrapper({
      propsData: {
        date: date60SecondsAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/minute/.test(timeText), true);
  });

  it('should use minutes if the date passed in is 1 minute ago', () => {
    const date1MinuteAgo = new Date(DUMMY_CURRENT_DATE);
    date1MinuteAgo.setMinutes(date1MinuteAgo.getMinutes() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1MinuteAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/minute/.test(timeText), true);
  });

  it('should use hours if the date passed is 60 minutes ago', () => {
    const date60MinutesAgo = new Date(DUMMY_CURRENT_DATE);
    date60MinutesAgo.setMinutes(date60MinutesAgo.getMinutes() - 60);
    const wrapper = makeWrapper({
      propsData: {
        date: date60MinutesAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/hour/.test(timeText), true);
  });

  it('should use hours if the date passed is 1 hour ago', () => {
    const date1HourAgo = new Date(DUMMY_CURRENT_DATE);
    date1HourAgo.setHours(date1HourAgo.getHours() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1HourAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/hour/.test(timeText), true);
  });

  it('should use days if the date passed is 24 hours ago', () => {
    const date24HoursAgo = new Date(DUMMY_CURRENT_DATE);
    date24HoursAgo.setHours(date24HoursAgo.getHours() - 24);
    const wrapper = makeWrapper({
      propsData: {
        date: date24HoursAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/day/.test(timeText), true);
  });

  it('should use days if the date passed is 1 day ago', () => {
    const date1DayAgo = new Date(DUMMY_CURRENT_DATE);
    date1DayAgo.setDate(date1DayAgo.getDate() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1DayAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/day/.test(timeText), true);
  });

  it('should use months if the date passed is 4 weeks ago', () => {
    const date4WeeksAgo = new Date(DUMMY_CURRENT_DATE);
    date4WeeksAgo.setMonth(date4WeeksAgo.getMonth() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date4WeeksAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/month/.test(timeText), true);
  });

  it('should use months if the date passed is 1 month ago', () => {
    const date1MonthAgo = new Date(DUMMY_CURRENT_DATE);
    date1MonthAgo.setMonth(date1MonthAgo.getMonth() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1MonthAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/month/.test(timeText), true);
  });

  it('should use years if the date passed is 12 months ago', () => {
    const date12MonthsAgo = new Date(DUMMY_CURRENT_DATE);
    date12MonthsAgo.setMonth(date12MonthsAgo.getMonth() - 12);
    const wrapper = makeWrapper({
      propsData: {
        date: date12MonthsAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/year/.test(timeText), true);
  });

  it('should use years if the date passed is 1 year ago', () => {
    const date1YearAgo = new Date(DUMMY_CURRENT_DATE);
    date1YearAgo.setYear(date1YearAgo.getYear() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1YearAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    assert.equal(/year/.test(timeText), true);
  });
});
<commit_msg>Use chai in elapsed time spec<commit_after>/* eslint-env mocha */
import { expect } from 'chai';
import Vue from 'vue-test'; // eslint-disable-line
import { shallow } from '@vue/test-utils';
import elapsedTime from '../../src/views/elapsed-time';

const DUMMY_CURRENT_DATE = new Date(2017, 0, 1, 1, 1, 1);

function makeWrapper(options) {
  return shallow(elapsedTime, options);
}

// prettier-ignore
function getTimeText(wrapper) {
  return wrapper.find('span').text().trim();
}

describe('elapsed time component', () => {
  it('should show display a "–" if no date is passed in', () => {
    const wrapper = makeWrapper({ propsData: {} });
    const timeText = getTimeText(wrapper);
    expect(timeText).to.equal('–');
  });
  it('should use seconds if the date passed in 1 second ago', () => {
    const date1SecondAgo = new Date(DUMMY_CURRENT_DATE);
    date1SecondAgo.setSeconds(date1SecondAgo.getSeconds() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1SecondAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/second/.test(timeText)).to.be.true;
  });

  it('should use minutes if the date passed in is 60 seconds ago', () => {
    const date60SecondsAgo = new Date(DUMMY_CURRENT_DATE);
    date60SecondsAgo.setSeconds(date60SecondsAgo.getSeconds() - 60);
    const wrapper = makeWrapper({
      propsData: {
        date: date60SecondsAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/minute/.test(timeText)).to.be.true;
  });

  it('should use minutes if the date passed in is 1 minute ago', () => {
    const date1MinuteAgo = new Date(DUMMY_CURRENT_DATE);
    date1MinuteAgo.setMinutes(date1MinuteAgo.getMinutes() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1MinuteAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/minute/.test(timeText)).to.be.true;
  });

  it('should use hours if the date passed is 60 minutes ago', () => {
    const date60MinutesAgo = new Date(DUMMY_CURRENT_DATE);
    date60MinutesAgo.setMinutes(date60MinutesAgo.getMinutes() - 60);
    const wrapper = makeWrapper({
      propsData: {
        date: date60MinutesAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/hour/.test(timeText)).to.be.true;
  });

  it('should use hours if the date passed is 1 hour ago', () => {
    const date1HourAgo = new Date(DUMMY_CURRENT_DATE);
    date1HourAgo.setHours(date1HourAgo.getHours() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1HourAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/hour/.test(timeText)).to.be.true;
  });

  it('should use days if the date passed is 24 hours ago', () => {
    const date24HoursAgo = new Date(DUMMY_CURRENT_DATE);
    date24HoursAgo.setHours(date24HoursAgo.getHours() - 24);
    const wrapper = makeWrapper({
      propsData: {
        date: date24HoursAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/day/.test(timeText)).to.be.true;
  });

  it('should use days if the date passed is 1 day ago', () => {
    const date1DayAgo = new Date(DUMMY_CURRENT_DATE);
    date1DayAgo.setDate(date1DayAgo.getDate() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1DayAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/day/.test(timeText)).to.be.true;
  });

  it('should use months if the date passed is 4 weeks ago', () => {
    const date4WeeksAgo = new Date(DUMMY_CURRENT_DATE);
    date4WeeksAgo.setMonth(date4WeeksAgo.getMonth() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date4WeeksAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/month/.test(timeText)).to.be.true;
  });

  it('should use months if the date passed is 1 month ago', () => {
    const date1MonthAgo = new Date(DUMMY_CURRENT_DATE);
    date1MonthAgo.setMonth(date1MonthAgo.getMonth() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1MonthAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/month/.test(timeText)).to.be.true;
  });

  it('should use years if the date passed is 12 months ago', () => {
    const date12MonthsAgo = new Date(DUMMY_CURRENT_DATE);
    date12MonthsAgo.setMonth(date12MonthsAgo.getMonth() - 12);
    const wrapper = makeWrapper({
      propsData: {
        date: date12MonthsAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/year/.test(timeText)).to.be.true;
  });

  it('should use years if the date passed is 1 year ago', () => {
    const date1YearAgo = new Date(DUMMY_CURRENT_DATE);
    date1YearAgo.setYear(date1YearAgo.getYear() - 1);
    const wrapper = makeWrapper({
      propsData: {
        date: date1YearAgo,
      },
    });
    wrapper.setData({
      now: DUMMY_CURRENT_DATE,
    });
    const timeText = getTimeText(wrapper);
    expect(/year/.test(timeText)).to.be.true;
  });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Attach to any element that needs the skrollr functionality
 */

angular.module('particle.common.directives.skrollr', [])
  .directive('skrollr', function () {

    var _skrollr = skrollr.get();

    // Helper function to recursively traverse an element and extract all child nodes
    function getNodes(el, elements) {
      elements = elements || [];
      elements.push(el);
      var children = el.childNodes;
      for (var i=0; i < children.length; i++) {
        if (children[i].nodeType === 1) {
          elements = getNodes(children[i], elements);
        }
      }
      return elements;
    }

    var directiveDefinitionObject = {
      link: function (scope, element) {
        if ('undefined' === typeof(_skrollr)) {
          _skrollr = skrollr.init();
        }
        else {
          var elements = getNodes(element[0]);
          _skrollr.refresh(elements);
        }
      }
    };

    return directiveDefinitionObject;
  });<commit_msg>cleanup<commit_after><|endoftext|>