<commit_before>'use strict';

angular.module('myApp.apps', ['ngRoute', 'smart-table'])

    .config(['$routeProvider', function ($routeProvider)
    {
        $routeProvider.when('/apps/search', {
            templateUrl: 'sections/apps/apps.html',
            controller: 'AppsCtrl'
        });
    }])

    .controller('AppsCtrl', ['$scope', '$rootScope', function ($scope, $rootScope)
    {
        var params = {
            TableName: "applications"
        };

        if(null === localStorage.getItem("adminApplications"))
        {
            $scope.applications = {};
        }
        else
        {
            $scope.applications = JSON.parse(localStorage.getItem("adminApplications"));
        }

        var docClient = new AWS.DynamoDB.DocumentClient();

        docClient.scan(params,function (err, data)
        {
            if (err)
            {
                console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
            } else
            {
                console.log("Scan succeeded.");
                console.log(data.Items);
                localStorage.setItem("adminApplications", JSON.stringify(data.Items))
                $scope.applications = JSON.parse(localStorage.getItem("adminApplications"));
                $scope.$digest();
                if (typeof data.LastEvaluatedKey != "undefined")
                {
                    console.log("Scanning for more...");
                    params.ExclusiveStartKey = data.LastEvaluatedKey;
                    docClient.scan(params, onScan);
                }
            }
        });

        $scope.formatDate = function (timestamp)
        {
            var date = new Date();
            date.setTime(timestamp);

            var month = date.getMonth() + 1;
            var day = date.getDate();

            month = (month < 10 ? "0" : "") + month;
            day = (day < 10 ? "0" : "") + day;
            return  date.getFullYear() + "-" + month + "-" + day;

        };

        $scope.getStatus = function (status)
        {
            switch (status)
            {
                case 1:
                    return "No enviada";
                case 2:
                    return "Pendiente";
                case 3:
                    return "Aceptado";
                case 4:
                    return "Rechazado";
            }
        };
        $scope.getType = function(type)
        {
            switch (type)
            {
                case 1:
                    return "Educación Básica";

                case 2:
                    return "Educación Media Superior";

                case 3:
                    return "Técnico Superior Universitario";

                case 4:
                    return "Educación Superior";

                case 5:
                    return "Superior";
                default:
                    return "";

            }
        };

        $scope.openDetails = function (appId)
        {
            $scope.go('/applications/review/'+appId);
        };

    }]);<commit_msg>Route Fix<commit_after>'use strict';

angular.module('myApp.apps', ['ngRoute', 'smart-table'])

    .config(['$routeProvider', function ($routeProvider)
    {
        $routeProvider.when('/apps/search', {
            templateUrl: 'sections/apps/apps.html',
            controller: 'AppsCtrl'
        });
    }])

    .controller('AppsCtrl', ['$scope', '$rootScope', function ($scope, $rootScope)
    {
        var params = {
            TableName: "applications"
        };

        if(null === localStorage.getItem("adminApplications"))
        {
            $scope.applications = {};
        }
        else
        {
            $scope.applications = JSON.parse(localStorage.getItem("adminApplications"));
        }

        var docClient = new AWS.DynamoDB.DocumentClient();

        docClient.scan(params,function (err, data)
        {
            if (err)
            {
                console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
            } else
            {
                console.log("Scan succeeded.");
                console.log(data.Items);
                localStorage.setItem("adminApplications", JSON.stringify(data.Items))
                $scope.applications = JSON.parse(localStorage.getItem("adminApplications"));
                $scope.$digest();
                if (typeof data.LastEvaluatedKey != "undefined")
                {
                    console.log("Scanning for more...");
                    params.ExclusiveStartKey = data.LastEvaluatedKey;
                    docClient.scan(params, onScan);
                }
            }
        });

        $scope.formatDate = function (timestamp)
        {
            var date = new Date();
            date.setTime(timestamp);

            var month = date.getMonth() + 1;
            var day = date.getDate();

            month = (month < 10 ? "0" : "") + month;
            day = (day < 10 ? "0" : "") + day;
            return  date.getFullYear() + "-" + month + "-" + day;

        };

        $scope.getStatus = function (status)
        {
            switch (status)
            {
                case 1:
                    return "No enviada";
                case 2:
                    return "Pendiente";
                case 3:
                    return "Aceptado";
                case 4:
                    return "Rechazado";
            }
        };
        $scope.getType = function(type)
        {
            switch (type)
            {
                case 1:
                    return "Educación Básica";

                case 2:
                    return "Educación Media Superior";

                case 3:
                    return "Técnico Superior Universitario";

                case 4:
                    return "Educación Superior";

                case 5:
                    return "Superior";
                default:
                    return "";

            }
        };

        $scope.openDetails = function (appId)
        {
            $scope.go('/review/'+appId);
        };

    }]);<|endoftext|>


<commit_before>import { default as React, Component } from 'react';
import { ItemCheckboxList } from './component/ItemCheckboxList.js';
import { NestedItem } from './component/NestedItem.js';
import classNames from 'classnames';
import { manager } from '../middleware/ChannelManager.js';
import { StaticSearch } from './component/StaticSearch.js';
var helper = require('../middleware/helper.js');
var _ = require('lodash');

export class NestedList extends Component {
	constructor(props, context) {
		super(props);
		this.state = {
			items: [],
			storedItems: [],
			rawData: {
				hits: {
					hits: []
				}
			},
			subItems: [],
			selectedValues: []
		};
		this.nested = [
			'nestedParentaggs',
			'nestedChildaggs'
		];
		this.sortObj = {
			aggSort: this.props.sortBy
		};
		this.channelId = null;
		this.channelListener = null;
		this.defaultSelected = this.props.defaultSelected;
		this.filterBySearch = this.filterBySearch.bind(this);
		this.onItemSelect = this.onItemSelect.bind(this);
		this.defaultQuery = this.defaultQuery.bind(this);
		this.handleSelect = this.handleSelect.bind(this);
		this.type = this.props.multipleSelect ? 'Terms' : 'Term';
	}

	// Get the items from Appbase when component is mounted
	componentWillMount() {
		this.setQueryInfo();
		this.createChannel();
		this.createSubChannel();
	}

	componentDidMount() {
		if(this.props.defaultSelected) {
			this.setValue('', false);
			setTimeout(() => {
				this.handleSelect();
			}, 2000);
		}
	}

	handleSelect() {
		if(this.props.defaultSelected) {
			this.props.defaultSelected.forEach((value, index) => {
				this.onItemSelect(value, index);
			})
		}
	}

	componentWillUpdate() {
		setTimeout(() => {
			if (!_.isEqual(this.defaultSelected, this.props.defaultSelected)) {
				this.defaultSelected = this.props.defaultSelected;
				let items = this.state.items;
				items = items.map((item) => {
					item.key = item.key.toString();
					item.status = this.defaultSelected.length && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
					return item;
				});
				this.setState({
					items: items,
					storedItems: items
				});
				this.handleSelect(this.defaultSelected);
			}
			if (!_.isEqual(this.sortBy, this.props.sortBy)) {
				this.sortBy = this.props.sortBy;
				this.handleSortSelect();
			}
		}, 300);
	}

	// stop streaming request and remove listener when component will unmount
	componentWillUnmount() {
		if(this.channelId) {
			manager.stopStream(this.channelId);
		}
		if(this.subChannelId) {
			manager.stopStream(this.subChannelId);
		}
		if(this.channelListener) {
			this.channelListener.remove();
		}
		if(this.subChannelListener) {
			this.subChannelListener.remove();
		}
	}

	// build query for this sensor only
	defaultQuery(record) {
		if(record) {
			let query = {
				bool: {
					must: generateRangeQuery(this.props.appbaseField)
				}
			};
			return query;
		}
		function generateRangeQuery(appbaseField) {
			return record.map((singleRecord, index) => {
				return {
					term: {
						[appbaseField[index]]: singleRecord
					}
				};
			});
		}
	}

	// set the query type and input data
	setQueryInfo() {
		var obj = {
				key: this.props.sensorId,
				value: {
					queryType: this.type,
					inputData: this.props.appbaseField[0],
					defaultQuery: this.defaultQuery
				}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	includeAggQuery() {
		this.nested.forEach((name) => {
			var obj = {
				key: name,
				value: this.sortObj
			};
			helper.selectedSensor.setSortInfo(obj);
		});
	}

	handleSortSelect() {
		this.sortObj = {
			aggSort: this.props.sortBy
		};
		this.nested.forEach((name) => {
			let obj = {
				key: name,
				value: this.sortObj
			};
			helper.selectedSensor.set(obj, true, 'sortChange');
		});
	}

	// Create a channel which passes the depends and receive results whenever depends changes
	createChannel() {
		// Set the depends - add self aggs query as well with depends
		let depends = this.props.depends ? this.props.depends : {};
		console.log(this.nested[0]);
		depends['aggs'] = {
			key: this.props.appbaseField[0],
			sort: this.props.sortBy,
			size: this.props.size,
			sortRef: this.nested[0]
		};
		depends[this.nested[0]] = {
			'operation': 'must'
		};
		this.includeAggQuery();

		// create a channel and listen the changes
		var channelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.channelId = channelObj.channelId;
		this.channelListener = channelObj.emitter.addListener(this.channelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.rawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			this.setState({
				rawData: rawData
			});
			this.setData(rawData, 0);
		}.bind(this));
	}

	// Create a channel for sub category
	createSubChannel() {
		this.setSubCategory();
		let depends = {
			'aggs': {
				key: this.props.appbaseField[1],
				sort: this.props.sortBy,
				size: this.props.size,
				sortRef: this.nested[1]
			},
			'subCategory': { operation: "must" },
			[this.nested[1]]: { operation: "must" }
		};
		// create a channel and listen the changes
		var subChannelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.subChannelId = subChannelObj.channelId;
		this.subChannelListener = subChannelObj.emitter.addListener(this.subChannelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.subRawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			if(this.state.selectedValues.length) {
				this.setState({
					subRawData: rawData
				});
				this.setData(rawData, 1);
			}
		}.bind(this));
		var obj = {
			key: 'subCategory',
			value: ''
		};
		helper.selectedSensor.set(obj, true);
	}

	// set the query type and input data
	setSubCategory() {
		var obj = {
				key: 'subCategory',
				value: {
					queryType: 'term',
					inputData: this.props.appbaseField[0]
				}
		};

		helper.selectedSensor.setSensorInfo(obj);
	}

	setData(data, level) {
		if(data.aggregations && data.aggregations[this.props.appbaseField[level]] && data.aggregations[this.props.appbaseField[level]].buckets) {
			this.addItemsToList(data.aggregations[this.props.appbaseField[level]].buckets, level);
		}
	}

	addItemsToList(newItems, level) {
		newItems = newItems.map((item) => {
			item.key = item.key.toString();
			item.status = this.defaultSelected && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
			return item
		});
		let itemVar = level === 0 ? 'items' : 'subItems';
		this.setState({
			[itemVar]: newItems,
			storedItems: newItems
		});
	}

	// set value
	setValue(value, isExecuteQuery=false) {
		var obj = {
			key: this.props.sensorId,
			value: value
		};
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	// filter
	filterBySearch(value) {
		if(value) {
			let items = this.state.storedItems.filter(function(item) {
				return item.key && item.key.toLowerCase().indexOf(value.toLowerCase()) > -1;
			});
			this.setState({
				items: items
			});
		} else {
			this.setState({
				items: this.state.storedItems
			});
		}
	}

	onItemSelect(key, level) {
		let selectedValues = this.state.selectedValues;
		let stateItems = {};
		if (selectedValues[level] == key && this.defaultSelected.length == 1) {
			delete selectedValues[level];
			stateItems = {
				selectedValues: selectedValues
			};
		} else {
			selectedValues[level] = key;
			stateItems = {
				selectedValues: selectedValues
			};
			if(level === 0) {
				selectedValues.splice(1, 1);
				if(key !== selectedValues[0]) {
					stateItems.subItems = [];
				}
				var obj = {
					key: 'subCategory',
					value: key
				};
				helper.selectedSensor.set(obj, true);
			}
		}
		this.setValue(selectedValues, true);
		this.setState(stateItems);
	}

	renderChevron(level) {
		return level === 0 ? () : '' ;
	}

	renderItems(items, level) {
		return items.map((item, index) => {
			let cx = classNames({
				'rbc-item-active': (item.key === this.state.selectedValues[level]),
				'rbc-item-inactive': !(item.key === this.state.selectedValues[level])
			});
			return (

					<a href="javascript:void(0);" className={`rbc-list-item ${cx}`} onClick={() => this.onItemSelect(item.key, level)}>
						 {item.key}
						 {item.doc_count}
						{this.renderChevron(level)}

					{this.renderList(item.key, level)}

			);
		});
	}

	renderList(key, level) {
		let list;
		if(key === this.state.selectedValues[level] && level === 0) {
			list = (

					{this.renderItems(this.state.subItems, 1)}

			)
		}
		return list;
	}

	render() {
		let listComponent,
			searchComponent = null,
			title = null;

		listComponent = (

				{this.renderItems(this.state.items, 0)}

		);

		// set static search
		if(this.props.showSearch) {
			searchComponent = <StaticSearch
				placeholder={this.props.searchPlaceholder}
				changeCallback={this.filterBySearch}
			/>
		}

		if(this.props.title) {
			title = (
{this.props.title}
);
		}

		let cx = classNames({
			'rbc-search-active': this.props.showSearch,
			'rbc-search-inactive': !this.props.showSearch,
			'rbc-title-active': this.props.title,
			'rbc-title-inactive': !this.props.title
		});

		return (
			<div className={`rbc rbc-nestedlist col s12 col-xs-12 card thumbnail ${cx}`}>
				{title}
				{searchComponent}
				{listComponent}

		);
	}
}

NestedList.propTypes = {
	appbaseField: React.PropTypes.array.isRequired,
	defaultQuery: React.PropTypes.func,
	size: React.PropTypes.number,
	showCount: React.PropTypes.bool,
	multipleSelect: React.PropTypes.bool,
	sortBy: React.PropTypes.string,
	includeSelectAll: React.PropTypes.bool
};

// Default props value
NestedList.defaultProps = {
	showCount: true,
	multipleSelect: false,
	sortBy: 'count',
	size: 100,
	showSearch: false,
	title: null,
	searchPlaceholder: 'Search',
	includeSelectAll: false
};

// context type
NestedList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired
};
<commit_msg>Remove unused props from nestedList<commit_after>import { default as React, Component } from 'react';
import { ItemCheckboxList } from './component/ItemCheckboxList.js';
import { NestedItem } from './component/NestedItem.js';
import classNames from 'classnames';
import { manager } from '../middleware/ChannelManager.js';
import { StaticSearch } from './component/StaticSearch.js';
var helper = require('../middleware/helper.js');
var _ = require('lodash');

export class NestedList extends Component {
	constructor(props, context) {
		super(props);
		this.state = {
			items: [],
			storedItems: [],
			rawData: {
				hits: {
					hits: []
				}
			},
			subItems: [],
			selectedValues: []
		};
		this.nested = [
			'nestedParentaggs',
			'nestedChildaggs'
		];
		this.sortObj = {
			aggSort: this.props.sortBy
		};
		this.channelId = null;
		this.channelListener = null;
		this.defaultSelected = this.props.defaultSelected;
		this.filterBySearch = this.filterBySearch.bind(this);
		this.onItemSelect = this.onItemSelect.bind(this);
		this.defaultQuery = this.defaultQuery.bind(this);
		this.handleSelect = this.handleSelect.bind(this);
		this.type = 'Term';
	}

	// Get the items from Appbase when component is mounted
	componentWillMount() {
		this.setQueryInfo();
		this.createChannel();
		this.createSubChannel();
	}

	componentDidMount() {
		if(this.props.defaultSelected) {
			this.setValue('', false);
			setTimeout(() => {
				this.handleSelect();
			}, 2000);
		}
	}

	handleSelect() {
		if(this.props.defaultSelected) {
			this.props.defaultSelected.forEach((value, index) => {
				this.onItemSelect(value, index);
			})
		}
	}

	componentWillUpdate() {
		setTimeout(() => {
			if (!_.isEqual(this.defaultSelected, this.props.defaultSelected)) {
				this.defaultSelected = this.props.defaultSelected;
				let items = this.state.items;
				items = items.map((item) => {
					item.key = item.key.toString();
					item.status = this.defaultSelected.length && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
					return item;
				});
				this.setState({
					items: items,
					storedItems: items
				});
				this.handleSelect(this.defaultSelected);
			}
			if (!_.isEqual(this.sortBy, this.props.sortBy)) {
				this.sortBy = this.props.sortBy;
				this.handleSortSelect();
			}
		}, 300);
	}

	// stop streaming request and remove listener when component will unmount
	componentWillUnmount() {
		if(this.channelId) {
			manager.stopStream(this.channelId);
		}
		if(this.subChannelId) {
			manager.stopStream(this.subChannelId);
		}
		if(this.channelListener) {
			this.channelListener.remove();
		}
		if(this.subChannelListener) {
			this.subChannelListener.remove();
		}
	}

	// build query for this sensor only
	defaultQuery(record) {
		if(record) {
			let query = {
				bool: {
					must: generateRangeQuery(this.props.appbaseField)
				}
			};
			return query;
		}
		function generateRangeQuery(appbaseField) {
			return record.map((singleRecord, index) => {
				return {
					term: {
						[appbaseField[index]]: singleRecord
					}
				};
			});
		}
	}

	// set the query type and input data
	setQueryInfo() {
		var obj = {
				key: this.props.sensorId,
				value: {
					queryType: this.type,
					inputData: this.props.appbaseField[0],
					defaultQuery: this.defaultQuery
				}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	includeAggQuery() {
		this.nested.forEach((name) => {
			var obj = {
				key: name,
				value: this.sortObj
			};
			helper.selectedSensor.setSortInfo(obj);
		});
	}

	handleSortSelect() {
		this.sortObj = {
			aggSort: this.props.sortBy
		};
		this.nested.forEach((name) => {
			let obj = {
				key: name,
				value: this.sortObj
			};
			helper.selectedSensor.set(obj, true, 'sortChange');
		});
	}

	// Create a channel which passes the depends and receive results whenever depends changes
	createChannel() {
		// Set the depends - add self aggs query as well with depends
		let depends = this.props.depends ? this.props.depends : {};
		console.log(this.nested[0]);
		depends['aggs'] = {
			key: this.props.appbaseField[0],
			sort: this.props.sortBy,
			size: this.props.size,
			sortRef: this.nested[0]
		};
		depends[this.nested[0]] = {
			'operation': 'must'
		};
		this.includeAggQuery();

		// create a channel and listen the changes
		var channelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.channelId = channelObj.channelId;
		this.channelListener = channelObj.emitter.addListener(this.channelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.rawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			this.setState({
				rawData: rawData
			});
			this.setData(rawData, 0);
		}.bind(this));
	}

	// Create a channel for sub category
	createSubChannel() {
		this.setSubCategory();
		let depends = {
			'aggs': {
				key: this.props.appbaseField[1],
				sort: this.props.sortBy,
				size: this.props.size,
				sortRef: this.nested[1]
			},
			'subCategory': { operation: "must" },
			[this.nested[1]]: { operation: "must" }
		};
		// create a channel and listen the changes
		var subChannelObj = manager.create(this.context.appbaseRef, this.context.type, depends);
		this.subChannelId = subChannelObj.channelId;
		this.subChannelListener = subChannelObj.emitter.addListener(this.subChannelId, function(res) {
			let data = res.data;
			let rawData;
			if(res.mode === 'streaming') {
				rawData = this.state.subRawData;
				rawData.hits.hits.push(res.data);
			} else if(res.mode === 'historic') {
				rawData = data;
			}
			if(this.state.selectedValues.length) {
				this.setState({
					subRawData: rawData
				});
				this.setData(rawData, 1);
			}
		}.bind(this));
		var obj = {
			key: 'subCategory',
			value: ''
		};
		helper.selectedSensor.set(obj, true);
	}

	// set the query type and input data
	setSubCategory() {
		var obj = {
				key: 'subCategory',
				value: {
					queryType: 'term',
					inputData: this.props.appbaseField[0]
				}
		};

		helper.selectedSensor.setSensorInfo(obj);
	}

	setData(data, level) {
		if(data.aggregations && data.aggregations[this.props.appbaseField[level]] && data.aggregations[this.props.appbaseField[level]].buckets) {
			this.addItemsToList(data.aggregations[this.props.appbaseField[level]].buckets, level);
		}
	}

	addItemsToList(newItems, level) {
		newItems = newItems.map((item) => {
			item.key = item.key.toString();
			item.status = this.defaultSelected && this.defaultSelected.indexOf(item.key) > -1 ? true : false;
			return item
		});
		let itemVar = level === 0 ? 'items' : 'subItems';
		this.setState({
			[itemVar]: newItems,
			storedItems: newItems
		});
	}

	// set value
	setValue(value, isExecuteQuery=false) {
		var obj = {
			key: this.props.sensorId,
			value: value
		};
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	// filter
	filterBySearch(value) {
		if(value) {
			let items = this.state.storedItems.filter(function(item) {
				return item.key && item.key.toLowerCase().indexOf(value.toLowerCase()) > -1;
			});
			this.setState({
				items: items
			});
		} else {
			this.setState({
				items: this.state.storedItems
			});
		}
	}

	onItemSelect(key, level) {
		let selectedValues = this.state.selectedValues;
		let stateItems = {};
		if (selectedValues[level] == key && this.defaultSelected.length == 1) {
			delete selectedValues[level];
			stateItems = {
				selectedValues: selectedValues
			};
		} else {
			selectedValues[level] = key;
			stateItems = {
				selectedValues: selectedValues
			};
			if(level === 0) {
				selectedValues.splice(1, 1);
				if(key !== selectedValues[0]) {
					stateItems.subItems = [];
				}
				var obj = {
					key: 'subCategory',
					value: key
				};
				helper.selectedSensor.set(obj, true);
			}
		}
		this.setValue(selectedValues, true);
		this.setState(stateItems);
	}

	renderChevron(level) {
		return level === 0 ? () : '' ;
	}

	renderItems(items, level) {
		return items.map((item, index) => {
			let cx = classNames({
				'rbc-item-active': (item.key === this.state.selectedValues[level]),
				'rbc-item-inactive': !(item.key === this.state.selectedValues[level])
			});
			return (

					<a href="javascript:void(0);" className={`rbc-list-item ${cx}`} onClick={() => this.onItemSelect(item.key, level)}>
						 {item.key}
						 {item.doc_count}
						{this.renderChevron(level)}

					{this.renderList(item.key, level)}

			);
		});
	}

	renderList(key, level) {
		let list;
		if(key === this.state.selectedValues[level] && level === 0) {
			list = (

					{this.renderItems(this.state.subItems, 1)}

			)
		}
		return list;
	}

	render() {
		let listComponent,
			searchComponent = null,
			title = null;

		listComponent = (

				{this.renderItems(this.state.items, 0)}

		);

		// set static search
		if(this.props.showSearch) {
			searchComponent = <StaticSearch
				placeholder={this.props.searchPlaceholder}
				changeCallback={this.filterBySearch}
			/>
		}

		if(this.props.title) {
			title = (
{this.props.title}
);
		}

		let cx = classNames({
			'rbc-search-active': this.props.showSearch,
			'rbc-search-inactive': !this.props.showSearch,
			'rbc-title-active': this.props.title,
			'rbc-title-inactive': !this.props.title
		});

		return (
			<div className={`rbc rbc-nestedlist col s12 col-xs-12 card thumbnail ${cx}`}>
				{title}
				{searchComponent}
				{listComponent}

		);
	}
}

NestedList.propTypes = {
	appbaseField: React.PropTypes.array.isRequired,
	size: React.PropTypes.number,
	showCount: React.PropTypes.bool,
	sortBy: React.PropTypes.string
};

// Default props value
NestedList.defaultProps = {
	showCount: true,
	sortBy: 'count',
	size: 100,
	showSearch: false,
	title: null,
	searchPlaceholder: 'Search'
};

// context type
NestedList.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired
};
<|endoftext|>


<commit_before>/**
 * Taking care of events
 *  - Simulating 'change' event on contentEditable element
 *  - Handling drag & drop logic
 *  - Catch paste events
 *  - Dispatch proprietary newword:composer event
 *  - Keyboard shortcuts
 */
(function(wysihtml5) {
  var dom       = wysihtml5.dom,
      browser   = wysihtml5.browser,
      /**
       * Map keyCodes to query commands
       */
      shortcuts = {
        "66": "bold",     // B
        "73": "italic",   // I
        "85": "underline" // U
      };

  var deleteAroundEditable = function(selection, uneditable, element) {
    // merge node with previous node from uneditable
    var prevNode = selection.getPreviousNode(uneditable, true),
        curNode = selection.getSelectedNode();

    if (curNode.nodeType !== 1 && curNode.parentNode !== element) { curNode = curNode.parentNode; }
    if (prevNode) {
      if (curNode.nodeType == 1) {
        var first = curNode.firstChild;

        if (prevNode.nodeType == 1) {
          while (curNode.firstChild) {
            prevNode.appendChild(curNode.firstChild);
          }
        } else {
          while (curNode.firstChild) {
            uneditable.parentNode.insertBefore(curNode.firstChild, uneditable);
          }
        }
        if (curNode.parentNode) {
          curNode.parentNode.removeChild(curNode);
        }
        selection.setBefore(first);
      } else {
        if (prevNode.nodeType == 1) {
          prevNode.appendChild(curNode);
        } else {
          uneditable.parentNode.insertBefore(curNode, uneditable);
        }
        selection.setBefore(curNode);
      }
    }
  };

  var handleDeleteKeyPress = function(event, selection, element, composer) {
    if (selection.isCollapsed()) {
      if (selection.caretIsInTheBeginnig('LI')) {
        event.preventDefault();
        composer.commands.exec('outdentList');
      } else if (selection.caretIsInTheBeginnig()) {
        event.preventDefault();
      } else {

        if (selection.caretIsFirstInSelection() &&
            selection.getPreviousNode() &&
            selection.getPreviousNode().nodeName &&
            (/^H\d$/gi).test(selection.getPreviousNode().nodeName)
        ) {
          var prevNode = selection.getPreviousNode();
          event.preventDefault();
          if ((/^\s*$/).test(prevNode.textContent || prevNode.innerText)) {
            // heading is empty
            prevNode.parentNode.removeChild(prevNode);
          } else {
            var range = prevNode.ownerDocument.createRange();
            range.selectNodeContents(prevNode);
            range.collapse(false);
            selection.setSelection(range);
          }
        }

        var beforeUneditable = selection.caretIsBeforeUneditable();
        // Do a special delete if caret would delete uneditable
        if (beforeUneditable) {
          event.preventDefault();
          deleteAroundEditable(selection, beforeUneditable, element);
        }
      }
    } else {
      if (selection.containsUneditable()) {
        event.preventDefault();
        selection.deleteContents();
      }
    }
  };

  var handleTabKeyDown = function(composer, element) {
    if (!composer.selection.isCollapsed()) {
      composer.selection.deleteContents();
    } else if (composer.selection.caretIsInTheBeginnig('LI')) {
      if (composer.commands.exec('indentList')) return;
    }

    // Is   close enough to tab. Could not find enough counter arguments for now.
    composer.commands.exec("insertHTML", " ");
  };

  wysihtml5.views.Composer.prototype.observe = function() {
    var that                = this,
        state               = this.getValue(false, false),
        container           = (this.sandbox.getIframe) ? this.sandbox.getIframe() : this.sandbox.getContentEditable(),
        element             = this.element,
        focusBlurElement    = (browser.supportsEventsInIframeCorrectly() || this.sandbox.getContentEditable) ? element : this.sandbox.getWindow(),
        pasteEvents         = ["drop", "paste", "beforepaste"],
        interactionEvents   = ["drop", "paste", "mouseup", "focus", "keyup"];

    // --------- destroy:composer event ---------
    dom.observe(container, "DOMNodeRemoved", function() {
      clearInterval(domNodeRemovedInterval);
      that.parent.fire("destroy:composer");
    });

    // DOMNodeRemoved event is not supported in IE 8
    if (!browser.supportsMutationEvents()) {
        var domNodeRemovedInterval = setInterval(function() {
          if (!dom.contains(document.documentElement, container)) {
            clearInterval(domNodeRemovedInterval);
            that.parent.fire("destroy:composer");
          }
        }, 250);
    }

    // --------- User interaction tracking --

    dom.observe(focusBlurElement, interactionEvents, function() {
      setTimeout(function() {
        that.parent.fire("interaction").fire("interaction:composer");
      }, 0);
    });

    if (this.config.handleTables) {
      if(!this.tableClickHandle && this.doc.execCommand && wysihtml5.browser.supportsCommand(this.doc, "enableObjectResizing") && wysihtml5.browser.supportsCommand(this.doc, "enableInlineTableEditing")) {
        if (this.sandbox.getIframe) {
          this.tableClickHandle = dom.observe(container , ["focus", "mouseup", "mouseover"], function() {
            that.doc.execCommand("enableObjectResizing", false, "false");
            that.doc.execCommand("enableInlineTableEditing", false, "false");
            that.tableClickHandle.stop();
          });
        } else {
          setTimeout(function() {
            that.doc.execCommand("enableObjectResizing", false, "false");
            that.doc.execCommand("enableInlineTableEditing", false, "false");
          }, 0);
        }
      }
      this.tableSelection = wysihtml5.quirks.tableCellsSelection(element, that.parent);
    }

    // --------- Focus & blur logic ---------
    dom.observe(focusBlurElement, "focus", function(event) {
      that.parent.fire("focus", event).fire("focus:composer", event);

      // Delay storing of state until all focus handler are fired
      // especially the one which resets the placeholder
      setTimeout(function() { state = that.getValue(false, false); }, 0);
    });

    dom.observe(focusBlurElement, "blur", function(event) {
      if (state !== that.getValue(false, false)) {
        //create change event if supported (all except IE8)
        var changeevent = event;
        if(typeof Object.create == 'function') {
          changeevent = Object.create(event, { type: { value: 'change' } });
        }
        that.parent.fire("change", changeevent).fire("change:composer", changeevent);
      }
      that.parent.fire("blur", event).fire("blur:composer", event);
    });

    // --------- Drag & Drop logic ---------
    dom.observe(element, "dragenter", function() {
      that.parent.fire("unset_placeholder");
    });

    dom.observe(element, pasteEvents, function(event) {
      that.parent.fire(event.type, event).fire(event.type + ":composer", event);
    });

    if (this.config.copyedFromMarking) {
      // If supported the copied source is based directly on selection
      // Very useful for webkit based browsers where copy will otherwise contain a lot of code and styles based on whatever and not actually in selection.
      dom.observe(element, "copy", function(event) {
        if (event.clipboardData) {
          event.clipboardData.setData("text/html", that.config.copyedFromMarking + that.selection.getHtml());
          event.preventDefault();
        }
        that.parent.fire(event.type, event).fire(event.type + ":composer", event);
      });
    }

    // --------- neword event ---------
    dom.observe(element, "keyup", function(event) {
      var keyCode = event.keyCode;
      if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) {
        that.parent.fire("newword:composer");
      }
    });

    this.parent.on("paste:composer", function() {
      setTimeout(function() { that.parent.fire("newword:composer"); }, 0);
    });

    // --------- Make sure that images are selected when clicking on them ---------
    if (!browser.canSelectImagesInContentEditable()) {
      dom.observe(element, "mousedown", function(event) {
        var target = event.target;
        var allImages = element.querySelectorAll('img'),
            notMyImages = element.querySelectorAll('.' + that.config.uneditableContainerClassname + ' img'),
            myImages = wysihtml5.lang.array(allImages).without(notMyImages);

        if (target.nodeName === "IMG" && wysihtml5.lang.array(myImages).contains(target)) {
          that.selection.selectNode(target);
        }
      });
    }

    if (!browser.canSelectImagesInContentEditable()) {
        dom.observe(element, "drop", function(event) {
            // TODO: if I knew how to get dropped elements list from event I could limit it to only IMG element case
            setTimeout(function() {
                that.selection.getSelection().removeAllRanges();
            }, 0);
        });
    }

    if (browser.hasHistoryIssue() && browser.supportsSelectionModify()) {
      dom.observe(element, "keydown", function(event) {
        if (!event.metaKey && !event.ctrlKey) {
          return;
        }

        var keyCode   = event.keyCode,
            win       = element.ownerDocument.defaultView,
            selection = win.getSelection();

        if (keyCode === 37 || keyCode === 39) {
          if (keyCode === 37) {
            selection.modify("extend", "left", "lineboundary");
            if (!event.shiftKey) {
              selection.collapseToStart();
            }
          }
          if (keyCode === 39) {
            selection.modify("extend", "right", "lineboundary");
            if (!event.shiftKey) {
              selection.collapseToEnd();
            }
          }
          event.preventDefault();
        }
      });
    }

    // --------- Shortcut logic ---------
    dom.observe(element, "keydown", function(event) {
      var keyCode  = event.keyCode,
          command  = shortcuts[keyCode];
      if ((event.ctrlKey || event.metaKey) && !event.altKey && command) {
        that.commands.exec(command);
        event.preventDefault();
      }
      if (keyCode === 8) {
        // delete key
        handleDeleteKeyPress(event, that.selection, element, that);
      } else if (that.config.handleTabKey && keyCode === 9) {
        event.preventDefault();
        handleTabKeyDown(that, element);
      }
    });

    // --------- Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor ---------
    dom.observe(element, "keydown", function(event) {
      var target  = that.selection.getSelectedNode(true),
          keyCode = event.keyCode,
          parent;
      if (target && target.nodeName === "IMG" && (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY)) { // 8 => backspace, 46 => delete
        parent = target.parentNode;
        // delete the <img>
        parent.removeChild(target);
        // and it's parent <a> too if it hasn't got any other child nodes
        if (parent.nodeName === "A" && !parent.firstChild) {
          parent.parentNode.removeChild(parent);
        }

        setTimeout(function() { wysihtml5.quirks.redraw(element); }, 0);
        event.preventDefault();
      }
    });

    // --------- IE 8+9 focus the editor when the iframe is clicked (without actually firing the 'focus' event on the <body>) ---------
    if (!this.config.contentEditableMode && browser.hasIframeFocusIssue()) {
      dom.observe(container, "focus", function() {
        setTimeout(function() {
          if (that.doc.querySelector(":focus") !== that.element) {
            that.focus();
          }
        }, 0);
      });

      dom.observe(this.element, "blur", function() {
        setTimeout(function() {
          that.selection.getSelection().removeAllRanges();
        }, 0);
      });
    }

    // --------- Show url in tooltip when hovering links or images ---------
    var titlePrefixes = {
      IMG: "Image: ",
      A:   "Link: "
    };

    dom.observe(element, "mouseover", function(event) {
      var target   = event.target,
          nodeName = target.nodeName,
          title;
      if (nodeName !== "A" && nodeName !== "IMG") {
        return;
      }
      var hasTitle = target.hasAttribute("title");
      if(!hasTitle){
        title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src"));
        target.setAttribute("title", title);
      }
    });
  };
})(wysihtml5);
<commit_msg>copy plain text<commit_after>/**
 * Taking care of events
 *  - Simulating 'change' event on contentEditable element
 *  - Handling drag & drop logic
 *  - Catch paste events
 *  - Dispatch proprietary newword:composer event
 *  - Keyboard shortcuts
 */
(function(wysihtml5) {
  var dom       = wysihtml5.dom,
      browser   = wysihtml5.browser,
      /**
       * Map keyCodes to query commands
       */
      shortcuts = {
        "66": "bold",     // B
        "73": "italic",   // I
        "85": "underline" // U
      };

  var deleteAroundEditable = function(selection, uneditable, element) {
    // merge node with previous node from uneditable
    var prevNode = selection.getPreviousNode(uneditable, true),
        curNode = selection.getSelectedNode();

    if (curNode.nodeType !== 1 && curNode.parentNode !== element) { curNode = curNode.parentNode; }
    if (prevNode) {
      if (curNode.nodeType == 1) {
        var first = curNode.firstChild;

        if (prevNode.nodeType == 1) {
          while (curNode.firstChild) {
            prevNode.appendChild(curNode.firstChild);
          }
        } else {
          while (curNode.firstChild) {
            uneditable.parentNode.insertBefore(curNode.firstChild, uneditable);
          }
        }
        if (curNode.parentNode) {
          curNode.parentNode.removeChild(curNode);
        }
        selection.setBefore(first);
      } else {
        if (prevNode.nodeType == 1) {
          prevNode.appendChild(curNode);
        } else {
          uneditable.parentNode.insertBefore(curNode, uneditable);
        }
        selection.setBefore(curNode);
      }
    }
  };

  var handleDeleteKeyPress = function(event, selection, element, composer) {
    if (selection.isCollapsed()) {
      if (selection.caretIsInTheBeginnig('LI')) {
        event.preventDefault();
        composer.commands.exec('outdentList');
      } else if (selection.caretIsInTheBeginnig()) {
        event.preventDefault();
      } else {

        if (selection.caretIsFirstInSelection() &&
            selection.getPreviousNode() &&
            selection.getPreviousNode().nodeName &&
            (/^H\d$/gi).test(selection.getPreviousNode().nodeName)
        ) {
          var prevNode = selection.getPreviousNode();
          event.preventDefault();
          if ((/^\s*$/).test(prevNode.textContent || prevNode.innerText)) {
            // heading is empty
            prevNode.parentNode.removeChild(prevNode);
          } else {
            var range = prevNode.ownerDocument.createRange();
            range.selectNodeContents(prevNode);
            range.collapse(false);
            selection.setSelection(range);
          }
        }

        var beforeUneditable = selection.caretIsBeforeUneditable();
        // Do a special delete if caret would delete uneditable
        if (beforeUneditable) {
          event.preventDefault();
          deleteAroundEditable(selection, beforeUneditable, element);
        }
      }
    } else {
      if (selection.containsUneditable()) {
        event.preventDefault();
        selection.deleteContents();
      }
    }
  };

  var handleTabKeyDown = function(composer, element) {
    if (!composer.selection.isCollapsed()) {
      composer.selection.deleteContents();
    } else if (composer.selection.caretIsInTheBeginnig('LI')) {
      if (composer.commands.exec('indentList')) return;
    }

    // Is   close enough to tab. Could not find enough counter arguments for now.
    composer.commands.exec("insertHTML", " ");
  };

  wysihtml5.views.Composer.prototype.observe = function() {
    var that                = this,
        state               = this.getValue(false, false),
        container           = (this.sandbox.getIframe) ? this.sandbox.getIframe() : this.sandbox.getContentEditable(),
        element             = this.element,
        focusBlurElement    = (browser.supportsEventsInIframeCorrectly() || this.sandbox.getContentEditable) ? element : this.sandbox.getWindow(),
        pasteEvents         = ["drop", "paste", "beforepaste"],
        interactionEvents   = ["drop", "paste", "mouseup", "focus", "keyup"];

    // --------- destroy:composer event ---------
    dom.observe(container, "DOMNodeRemoved", function() {
      clearInterval(domNodeRemovedInterval);
      that.parent.fire("destroy:composer");
    });

    // DOMNodeRemoved event is not supported in IE 8
    if (!browser.supportsMutationEvents()) {
        var domNodeRemovedInterval = setInterval(function() {
          if (!dom.contains(document.documentElement, container)) {
            clearInterval(domNodeRemovedInterval);
            that.parent.fire("destroy:composer");
          }
        }, 250);
    }

    // --------- User interaction tracking --

    dom.observe(focusBlurElement, interactionEvents, function() {
      setTimeout(function() {
        that.parent.fire("interaction").fire("interaction:composer");
      }, 0);
    });

    if (this.config.handleTables) {
      if(!this.tableClickHandle && this.doc.execCommand && wysihtml5.browser.supportsCommand(this.doc, "enableObjectResizing") && wysihtml5.browser.supportsCommand(this.doc, "enableInlineTableEditing")) {
        if (this.sandbox.getIframe) {
          this.tableClickHandle = dom.observe(container , ["focus", "mouseup", "mouseover"], function() {
            that.doc.execCommand("enableObjectResizing", false, "false");
            that.doc.execCommand("enableInlineTableEditing", false, "false");
            that.tableClickHandle.stop();
          });
        } else {
          setTimeout(function() {
            that.doc.execCommand("enableObjectResizing", false, "false");
            that.doc.execCommand("enableInlineTableEditing", false, "false");
          }, 0);
        }
      }
      this.tableSelection = wysihtml5.quirks.tableCellsSelection(element, that.parent);
    }

    // --------- Focus & blur logic ---------
    dom.observe(focusBlurElement, "focus", function(event) {
      that.parent.fire("focus", event).fire("focus:composer", event);

      // Delay storing of state until all focus handler are fired
      // especially the one which resets the placeholder
      setTimeout(function() { state = that.getValue(false, false); }, 0);
    });

    dom.observe(focusBlurElement, "blur", function(event) {
      if (state !== that.getValue(false, false)) {
        //create change event if supported (all except IE8)
        var changeevent = event;
        if(typeof Object.create == 'function') {
          changeevent = Object.create(event, { type: { value: 'change' } });
        }
        that.parent.fire("change", changeevent).fire("change:composer", changeevent);
      }
      that.parent.fire("blur", event).fire("blur:composer", event);
    });

    // --------- Drag & Drop logic ---------
    dom.observe(element, "dragenter", function() {
      that.parent.fire("unset_placeholder");
    });

    dom.observe(element, pasteEvents, function(event) {
      that.parent.fire(event.type, event).fire(event.type + ":composer", event);
    });

    if (this.config.copyedFromMarking) {
      // If supported the copied source is based directly on selection
      // Very useful for webkit based browsers where copy will otherwise contain a lot of code and styles based on whatever and not actually in selection.
      dom.observe(element, "copy", function(event) {
        if (event.clipboardData) {
          event.clipboardData.setData("text/html", that.config.copyedFromMarking + that.selection.getHtml());
          event.clipboardData.setData("text/plain", that.config.copyedFromMarking + that.selection.getText());
          event.preventDefault();
        }
        that.parent.fire(event.type, event).fire(event.type + ":composer", event);
      });
    }

    // --------- neword event ---------
    dom.observe(element, "keyup", function(event) {
      var keyCode = event.keyCode;
      if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) {
        that.parent.fire("newword:composer");
      }
    });

    this.parent.on("paste:composer", function() {
      setTimeout(function() { that.parent.fire("newword:composer"); }, 0);
    });

    // --------- Make sure that images are selected when clicking on them ---------
    if (!browser.canSelectImagesInContentEditable()) {
      dom.observe(element, "mousedown", function(event) {
        var target = event.target;
        var allImages = element.querySelectorAll('img'),
            notMyImages = element.querySelectorAll('.' + that.config.uneditableContainerClassname + ' img'),
            myImages = wysihtml5.lang.array(allImages).without(notMyImages);

        if (target.nodeName === "IMG" && wysihtml5.lang.array(myImages).contains(target)) {
          that.selection.selectNode(target);
        }
      });
    }

    if (!browser.canSelectImagesInContentEditable()) {
        dom.observe(element, "drop", function(event) {
            // TODO: if I knew how to get dropped elements list from event I could limit it to only IMG element case
            setTimeout(function() {
                that.selection.getSelection().removeAllRanges();
            }, 0);
        });
    }

    if (browser.hasHistoryIssue() && browser.supportsSelectionModify()) {
      dom.observe(element, "keydown", function(event) {
        if (!event.metaKey && !event.ctrlKey) {
          return;
        }

        var keyCode   = event.keyCode,
            win       = element.ownerDocument.defaultView,
            selection = win.getSelection();

        if (keyCode === 37 || keyCode === 39) {
          if (keyCode === 37) {
            selection.modify("extend", "left", "lineboundary");
            if (!event.shiftKey) {
              selection.collapseToStart();
            }
          }
          if (keyCode === 39) {
            selection.modify("extend", "right", "lineboundary");
            if (!event.shiftKey) {
              selection.collapseToEnd();
            }
          }
          event.preventDefault();
        }
      });
    }

    // --------- Shortcut logic ---------
    dom.observe(element, "keydown", function(event) {
      var keyCode  = event.keyCode,
          command  = shortcuts[keyCode];
      if ((event.ctrlKey || event.metaKey) && !event.altKey && command) {
        that.commands.exec(command);
        event.preventDefault();
      }
      if (keyCode === 8) {
        // delete key
        handleDeleteKeyPress(event, that.selection, element, that);
      } else if (that.config.handleTabKey && keyCode === 9) {
        event.preventDefault();
        handleTabKeyDown(that, element);
      }
    });

    // --------- Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor ---------
    dom.observe(element, "keydown", function(event) {
      var target  = that.selection.getSelectedNode(true),
          keyCode = event.keyCode,
          parent;
      if (target && target.nodeName === "IMG" && (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY)) { // 8 => backspace, 46 => delete
        parent = target.parentNode;
        // delete the <img>
        parent.removeChild(target);
        // and it's parent <a> too if it hasn't got any other child nodes
        if (parent.nodeName === "A" && !parent.firstChild) {
          parent.parentNode.removeChild(parent);
        }

        setTimeout(function() { wysihtml5.quirks.redraw(element); }, 0);
        event.preventDefault();
      }
    });

    // --------- IE 8+9 focus the editor when the iframe is clicked (without actually firing the 'focus' event on the <body>) ---------
    if (!this.config.contentEditableMode && browser.hasIframeFocusIssue()) {
      dom.observe(container, "focus", function() {
        setTimeout(function() {
          if (that.doc.querySelector(":focus") !== that.element) {
            that.focus();
          }
        }, 0);
      });

      dom.observe(this.element, "blur", function() {
        setTimeout(function() {
          that.selection.getSelection().removeAllRanges();
        }, 0);
      });
    }

    // --------- Show url in tooltip when hovering links or images ---------
    var titlePrefixes = {
      IMG: "Image: ",
      A:   "Link: "
    };

    dom.observe(element, "mouseover", function(event) {
      var target   = event.target,
          nodeName = target.nodeName,
          title;
      if (nodeName !== "A" && nodeName !== "IMG") {
        return;
      }
      var hasTitle = target.hasAttribute("title");
      if(!hasTitle){
        title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src"));
        target.setAttribute("title", title);
      }
    });
  };
})(wysihtml5);
<|endoftext|>


<commit_before>/**
 * Created by qiaodandan on 2016/11/8.
 */
//var stage = new createjs.Stage("gameView");
//
//var gameView = new createjs.Container();
//stage.addChild(gameView);
//
//var s = new createjs.Shape();
//s.graphics.beginFill("#FF0000");
//s.graphics.drawCircle(50,50,25);
//s.graphics.endFill();
//gameView.addChild(s);
//
//createjs.Ticker.setFPS(30);
//createjs.Ticker.addEventListener("tick",stage);

var stage = new createjs.Stage("gameView");
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener("tick",stage);

var gameView = new createjs.Container();
gameView.x = 30;
gameView.y = 30;
stage.addChild(gameView);

var circleArr = [[],[],[],[],[],[],[],[],[]];
var currentCat;
var stepNo = 0;

function randomNextStep(circle) {
  var randomNextStepX = -1, randomNextStepY = -1;
  do {
    randomNextStepX = circle.indexX + Math.floor(Math.random() * 2 - 1);
    randomNextStepY = circle.indexY + Math.floor(Math.random() * 2 - 1);
  } while ( randomNextStepX < 0 || randomNextStepY < 0
         || randomNextStepX > 8 || randomNextStepY > 8
         || (randomNextStepX == circle.indexX && randomNextStepY == circle.indexY)
         || ((circle.indexY % 2 == 0) && randomNextStepY != circle.indexY && randomNextStepX > circle.indexX)
         || ((circle.indexY % 2 != 0) && randomNextStepY != circle.indexY && randomNextStepX < circle.indexX)
         || (circleArr[randomNextStepX][randomNextStepY].getCircleType() == 2) );
  if ( randomNextStepX < 0 || randomNextStepY < 0) return null;
  stepNo = stepNo + 1;
  return circleArr[randomNextStepX][randomNextStepY];
}

function circleClicked(event){
  if (event.target.getCircleType() == 1){
    event.target.setCircleType(2);
  }

  var nextCircle = randomNextStep(currentCat);
  if (nextCircle) {
    nextCircle.setCircleType(3);
    currentCat.setCircleType(1);
    currentCat = nextCircle;
  } else {
    alert("你赢了!一共用了"+(stepNo+1)+"步!");
  }

  if (currentCat.indexX == 0 || currentCat.indexX == 8 || currentCat.indexY == 0 || currentCat.indexY ==8){
    alert("游戏结束,你输了!");
  }
}

function addCiecles(){

  for (var indexY = 0;indexY < 9;indexY ++){
    for (var indexX = 0;indexX < 9;indexX ++){
      var  c = new Circle();
      gameView.addChild(c);
      circleArr[indexX][indexY] = c;
      c.indexX = indexX;
      c.indexY = indexY;//忘记了这里
      c.x = indexY % 2 ? indexX * 55 + 25 : indexX * 55;
      c.y = indexY * 55;
      if (indexX == 4 && indexY == 4){
        c.setCircleType(3);//是猫
        currentCat = c;
      }
      c.addEventListener("click",circleClicked);
    }
  }
}

addCiecles();<commit_msg>二狗子删了女王大人的代码，为了对比清晰，女王大人又加上了<commit_after>/**
* Created by qiaodandan on 2016/11/8.
*/

////二超代码
//var stage = new createjs.Stage("gameView");
//createjs.Ticker.setFPS(30);
//createjs.Ticker.addEventListener("tick",stage);
//
//var gameView = new createjs.Container();
//gameView.x = 30;
//gameView.y = 30;
//stage.addChild(gameView);
//
//var circleArr = [[],[],[],[],[],[],[],[],[]];
//var currentCat;
//var stepNo = 0;
//
//function randomNextStep(circle) {
//  var randomNextStepX = -1, randomNextStepY = -1;
//  do {
//    randomNextStepX = circle.indexX + parseInt(Math.random() * 2 - 1);
//    randomNextStepY = circle.indexY + parseInt(Math.random() * 2 - 1);
//  } while ( randomNextStepX < 0 || randomNextStepY < 0
//         || randomNextStepX > 8 || randomNextStepY > 8
//         || (randomNextStepX == circle.indexX && randomNextStepY == circle.indexY)
//         || ((circle.indexY % 2 == 0) && randomNextStepY != circle.indexY && randomNextStepX > circle.indexX)
//         || ((circle.indexY % 2 != 0) && randomNextStepY != circle.indexY && randomNextStepX < circle.indexX)
//         || (circleArr[randomNextStepX][randomNextStepY].getCircleType() == 2) );
//  if ( randomNextStepX < 0 || randomNextStepY < 0) return null;
//  stepNo = stepNo + 1;
//  return circleArr[randomNextStepX][randomNextStepY];
//}
//
//function circleClicked(event){
//  if (event.target.getCircleType() == 1){
//    event.target.setCircleType(2);
//  }
//
//  var nextCircle = randomNextStep(currentCat);
//  if (nextCircle) {
//    nextCircle.setCircleType(3);
//    currentCat.setCircleType(1);
//    currentCat = nextCircle;
//  } else {
//    alert("你赢了!一共用了"+(stepNo+1)+"步!");
//  }
//
//  if (currentCat.indexX == 0 || currentCat.indexX == 8 || currentCat.indexY == 0 || currentCat.indexY ==8){
//    alert("游戏结束,你输了!");
//  }
//}
//
//function addCiecles(){
//
//  for (var indexY = 0;indexY < 9;indexY ++){
//    for (var indexX = 0;indexX < 9;indexX ++){
//      var  c = new Circle();
//      gameView.addChild(c);
//      circleArr[indexX][indexY] = c;
//      c.indexX = indexX;
//      c.indexY = indexY;//忘记了这里
//      c.x = indexY % 2 ? indexX * 55 + 25 : indexX * 55;
//      c.y = indexY * 55;
//      if (indexX == 4 && indexY == 4){
//        c.setCircleType(3);//是猫
//        currentCat = c;
//      }
//      c.addEventListener("click",circleClicked);
//    }
//  }
//}
//
//addCiecles();

//女王大人的的代码

var stage = new createjs.Stage("gameView");
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener("tick",stage);

var gameView = new createjs.Container();
gameView.x = 30;
gameView.y = 30;
stage.addChild(gameView);

var circleArr = [[],[],[],[],[],[],[],[],[]];
var currentCat;
var stepNo = 0;
function circleClicked(event){
  if (event.target.getCircleType() == 1){
    //不是猫并且不是已经走过的位置,能跳的位置
    event.target.setCircleType(2);
  }

  var leftCircle = circleArr[currentCat.indexX-1][currentCat.indexY];
  var rightCircle = circleArr[currentCat.indexX+1][currentCat.indexY];

  var leftBottomCircle = circleArr[currentCat.indexX][currentCat.indexY+1];
  var leftTopCircle = circleArr[currentCat.indexX][currentCat.indexY-1];

  var rightTopCircleOU = circleArr[currentCat.indexX-1][currentCat.indexY-1];
  var rightBobbtomCircleOU = circleArr[currentCat.indexX-1][currentCat.indexY+1]

  var rightTopCircleJS = circleArr[currentCat.indexX+1][currentCat.indexY-1];
  var rightBobbtomCircleJS = circleArr[currentCat.indexX+1][currentCat.indexY+1]

//alert(leftCircle.getCircleType());

  var tmpCircleArr = [];
  //alert(tmpCircleArr.count);
  if (leftCircle.getCircleType() == 1){
    tmpCircleArr.push(leftCircle);
  }
  if (rightCircle.getCircleType() == 1){
    tmpCircleArr.push(rightCircle);
  }
  if (leftTopCircle.getCircleType() == 1){
    tmpCircleArr.push(leftTopCircle);
  }
  if (leftBottomCircle.getCircleType() == 1){
    tmpCircleArr.push(leftBottomCircle);
  }
  if(currentCat.indexY%2==0){
    //偶数行
    if (rightTopCircleOU.getCircleType() == 1){
      tmpCircleArr.push(rightTopCircleOU);
    }
    if (rightBobbtomCircleOU.getCircleType() == 1){
      tmpCircleArr.push(rightBobbtomCircleOU);
    }
  }else {
    //奇数行
    if (rightTopCircleJS.getCircleType() == 1){
      tmpCircleArr.push(rightTopCircleJS);
    }
    if (rightBobbtomCircleJS.getCircleType() == 1){
      tmpCircleArr.push(rightBobbtomCircleJS);
    }
  }

  if (tmpCircleArr.length!=0){
    var tmpIndex = parseInt(tmpCircleArr.length*Math.random());
    var tmpCircle = tmpCircleArr[tmpIndex];
    tmpCircle.setCircleType(3);
    currentCat.setCircleType(1);
    currentCat = tmpCircleArr[tmpIndex];
    stepNo = stepNo + 1;
  }else {
    alert("你赢了!一共用了"+(stepNo+1)+"步!");
  }

  if (currentCat.indexX==0||currentCat.indexX==8||currentCat.indexY==0||currentCat.indexY==8){
    alert("游戏结束,你输了!");
  }
}

function addCiecles(){

  for (var indexY = 0;indexY < 9;indexY ++){
    for (var indexX = 0;indexX < 9;indexX ++){
      var  c = new Circle();
      gameView.addChild(c);
      circleArr[indexX][indexY] = c;
      c.indexX = indexX;
      c.indexY = indexY;//忘记了这里
      c.x = indexY % 2 ? indexX * 55 + 25 : indexX * 55;
      c.y = indexY * 55;
      if (indexX == 4 && indexY == 4){
        c.setCircleType(3);//是猫
        currentCat = c;
      }
      c.addEventListener("click",circleClicked);
    }
  }
}

addCiecles();
<|endoftext|>


<commit_before>//deps includes.js

// StateView is responsible for drawing a state and rendering animations.
// The StateView is not responsible for updating the state, just for handling state changes.
function StateView(state, attrs) {
  EventEmitter.call(this);

  this._state = state;
  this._chunkView = null;
  this._loader1 = attrs.loader1;
  this._loader2 = attrs.loader2;
  this._splashScreen = attrs.splashScreen;
  this._dataSource = attrs.dataSource;

  this._element = document.createElement('div');
  this._element.position = 'absolute';
  this._canvas = document.createElement('canvas');
  this._element.appendChild(this._splashScreen.element());
  this._splashScreen.setAnimate(false);

  this._yLabels = null;

  this._animate = false;
  this._animating = false;
  this._startYLabels = null;
  this._endYLabels = null;
}

StateView.prototype = Object.create(EventEmitter.prototype);

// element returns the element for the view.
StateView.prototype.element = function() {
  return this._element;
};

// totalWidth gets the width of the StateView based on the current state.
// This will also account for the current animation.
StateView.prototype.totalWidth = function() {
  // TODO: this.
  return 0;
};

// draw instructs the StateView to draw itself given the current state.
// This will also account for the current animation.
StateView.prototype.draw = function() {
  // TODO: draw the current state here.
};

// setAnimate enables/disables animations on the StateView.
StateView.prototype.setAnimate = function(flag) {
  if (flag === this._animate) {
    return;
  }
  this._animate = flag;
  if (this._showingContent()) {
    this._chunkView.setAnimate(flag);
  } else {
    this._splashScreen.setAnimate(flag);
  }
};

// dispose removes a StateView's references to the provider, data source, and ChunkView.
StateView.prototype.dispose = function() {
  this.setAnimate(false);
  // TODO: this.
};

// updateState indicates that the state changed for some reason other than a deletion, addition, or
// modification of a data point or from invalidation of the data set.
StateView.prototype.updateState = function(newState) {
  // TODO: update the chunkView here.
  this._state = newState;
};

// updateStateDeletion indicates that the state changed specifically due to a deletion.
StateView.prototype.updateStateDelete = function(newState, oldIndex, inVisibleChunk) {
  // TODO: this.
};

// updateStateAdd indicates that the state changed specifically due to an addition.
StateView.prototype.updateStateAdd = function(newState) {
  // TODO: this.
};

// updateStateModify indicates that the state changed specifically due to a modification.
StateView.prototype.updateStateModify = function(newState, index) {
  // TODO: this.
};

// updateStateInvalidate indicates that the state changed specifically due to a data invalidation.
StateView.prototype.updateStateInvalidate = function(newState) {
  // TODO: this.
};

StateView.prototype._showingContent = function() {
  return this._chunkView !== null && !this._state.normative.needsLeftmostChunk;
};
<commit_msg>copy relevant YLabelContentView code to StateView<commit_after>//deps includes.js

// StateView is responsible for drawing a state and rendering animations.
// The StateView is not responsible for updating the state, just for handling state changes.
function StateView(state, attrs) {
  EventEmitter.call(this);

  this._state = state;
  this._chunkView = null;
  this._loader1 = attrs.loader1;
  this._loader2 = attrs.loader2;
  this._splashScreen = attrs.splashScreen;
  this._dataSource = attrs.dataSource;

  this._element = document.createElement('div');
  this._element.position = 'absolute';
  this._canvas = document.createElement('canvas');
  this._element.appendChild(this._splashScreen.element());
  this._splashScreen.setAnimate(false);

  this._yLabels = null;

  this._animate = false;
  this._animating = false;
  this._startYLabels = null;
  this._endYLabels = null;

  this._pixelRatio = 0;
  this._crystalCallback = this._updatePixelRatio.bind(this);
}

StateView.prototype = Object.create(EventEmitter.prototype);

// element returns the element for the view.
StateView.prototype.element = function() {
  return this._element;
};

// totalWidth gets the width of the StateView based on the current state.
// This will also account for the current animation.
StateView.prototype.totalWidth = function() {
  if (this._showingContent()) {
    return this._chunkView.getInherentWidth() + this._chunkView.getRightOffset() +
      this._chunkView.getLeftOffset() + this._state.positive.leftmostYLabelsWidth;
  } else {
    return 0;
  }
};

// draw instructs the StateView to draw itself given the current state.
// This will also account for the current animation.
StateView.prototype.draw = function() {
  if (!this._showingContent()) {
    return;
  }

  this._drawCanvas();
  // TODO: position the inline loaders if necessary.
};

// setAnimate enables/disables animations on the StateView.
StateView.prototype.setAnimate = function(flag) {
  if (flag === this._animate) {
    return;
  }
  this._animate = flag;

  if (this._animate) {
    window.crystal.addListener(this._crystalCallback);
    this._updatePixelRatio();
  } else {
    window.crystal.removeListener(this._crystalCallback);
  }

  if (this._showingContent()) {
    this._chunkView.setAnimate(flag);
  } else {
    this._splashScreen.setAnimate(flag);
  }
};

// dispose removes a StateView's references to the provider, data source, and ChunkView.
StateView.prototype.dispose = function() {
  this.setAnimate(false);
};

// updateState indicates that the state changed for some reason other than a deletion, addition, or
// modification of a data point or from invalidation of the data set.
StateView.prototype.updateState = function(newState) {
  // TODO: update this._chunkView if necessary.
  // TODO: update the y-axis labels if necessary.
  // TODO: update other local state such as load timeouts if necessary.

  this._state = newState;

  this._splashScreen.layout(this._state.positive.viewportWidth,
    this._state.positive.viewportHeight);
  this._element.style.width = this._state.positive.viewportWidth.toFixed(2) + 'px';
  this._element.style.height = this._state.positive.viewportHeight.toFixed(2) + 'px';
};

// updateStateDeletion indicates that the state changed specifically due to a deletion.
StateView.prototype.updateStateDelete = function(newState, oldIndex, inVisibleChunk) {
  // TODO: this.
};

// updateStateAdd indicates that the state changed specifically due to an addition.
StateView.prototype.updateStateAdd = function(newState) {
  // TODO: this.
};

// updateStateModify indicates that the state changed specifically due to a modification.
StateView.prototype.updateStateModify = function(newState, index) {
  // TODO: this.
};

// updateStateInvalidate indicates that the state changed specifically due to a data invalidation.
StateView.prototype.updateStateInvalidate = function(newState) {
  // TODO: this.
};

StateView.prototype._drawCanvas = function() {
  // TODO: draw the ChunkView (possibly stretched) and the ziggity zaggity (edge of content) here.
  // TODO: also draw the y-axis labels and the horizontal lines.
};

StateView.prototype._updatePixelRatio = function() {
  var newRatio = Math.ceil(window.crystal.getRatio());
  if (this._pixelRatio === newRatio) {
    return;
  }
  this._pixelRatio = newRatio;
  this._canvas.width = this._state.positive.viewportWidth * newRatio;
  this._canvas.height = this._state.positive.viewportHeight * newRatio;
  if (this._showingContent()) {
    this._drawCanvas();
  }
};

StateView.prototype._showingContent = function() {
  return this._chunkView !== null && !this._state.normative.needsLeftmostChunk;
};
<|endoftext|>


<commit_before>ZBase.registerView((function() {
  var widget_list = null;
  var edit_view = null;

  // REMOVEME
  var goToURL = function(path) {
    var kPathPrefix = "/a/reports/";
    var report_id = path.substr(kPathPrefix.length);
    loadReport(report_id);
  }
  // REMOVEME END

  var loadReport = function(report_id) {
    if (widget_list) {
      widget_list.destroy();
      widget_list = null;
    }

    $.showLoader();
    $.httpGet("/api/v1/documents/" + report_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        if (doc.content.length == 0) {
          doc.content = null;
        } else {
          doc.content = JSON.parse(doc.content);
        }

        // load required widgets
        var required_widgets = findRequiredWidgets(doc);
        ReportWidgetFactory.loadWidgets(required_widgets, function() {
          render(doc);
          $.hideLoader();
        });
      } else {
        $.fatalError();
      }
    });
  };

  var destroy = function() {
    //if (docsync) {
    //  docsync.close();
    //}

    if (widget_list) {
      widget_list.destroy();
    }

    if (edit_view) {
      edit_view.destroy();
    }
  };

  var render = function(doc) {
    var readonly = !doc.is_writable;
    var page = $.getTemplate(
        "views/report",
        "zbase_report_main_tpl");

    $.handleLinks(page);
    $.replaceViewport(page);

    setReportName(doc.name);

    var description = "";
    if (doc.content != null && doc.content.hasOwnProperty("description")) {
      description = doc.content.description;
    }
    setReportDescription(description);

    var widgets = [];
    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      widgets = doc.content.widgets;
    }
    widget_list = WidgetList(widgets);
    widget_list.onWidgetEdit(function(widget_id) {
      showWidgetEditor(widget_id);
    });

    // handle display mode
    $(".zbase_report_pane z-dropdown.mode").addEventListener("change", function() {
      widget_list.setEditable(this.getValue() == "editing");
    }, false);

    if (readonly) {
      $(".readonly_hint").classList.remove("hidden");
    } else {
      initNameEditing();
      initDescriptionEditing();
      initShareDocModal(doc.uuid);
      initWidgetAdding();
      $.onClick($(".zbase_report_pane .link.edit_source"), showRawJSONEditor);
    }

    showReportView();

    //// setup docsync
    //docsync = DocSync(
    //    getDocument,
    //    "/api/v1/documents/" + doc_id,
    //    $(".zbase_report_infobar"));
  };

  var showReportView = function(doc) {
    //showLoader?
    if (edit_view) {
      edit_view.destroy();
    }
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";

    if (widget_list) {
      widget_list.render(viewport);
      widget_list.setEditable(true);
    } else {
      $.fatalError();
    }
  };

  var showWidgetEditor = function(widget_id) {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    var conf = widget_list.getWidgetConfig(widget_id);
    var editor = ReportWidgetFactory.getWidgetEditor(conf);

    editor.onSave(function(config) {
      widget_list.updateWidgetConfig(widget_id, config);
      showReportView();
    });

    editor.onCancel(function() {
      showReportView();
    });

    showEditView(editor);
  };

  var showRawJSONEditor = function() {
    var editor = ReportJSONEditor(getContentJSON());
    showEditView(editor);

    editor.onSave(function(json) {
      if (!widget_list) {
        $.fatalError();
        return;
      }
      var content = JSON.parse(json);
      widget_list.setJSON(content.widgets);
      setReportDescription(content.description);
      showReportView();
      save();
    });

    editor.onCancel(showReportView);
  };

  var showEditView = function(editor) {
    edit_view = editor;
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    edit_view.render(viewport);
  };

  //var setEditable = function(is_editable) {
  //  widget_list.setEditable(is_editable);

  //  if (is_editable) {
  //    $(".writable_report_actions").classList.remove("hidden");
  //    $(".zbase_report_pane .report_name").classList.add("editable");
  //    $(".zbase_report_pane .report_description").classList.add("editable");
  //  } else {
  //    $(".writable_report_actions").classList.add("hidden");
  //    $(".zbase_report_pane .report_name").classList.remove("editable");
  //    $(".zbase_report_pane .report_description").classList.remove("editable");
  //  }
  //};

  var initShareDocModal = function(doc_id) {
    var modal = ShareDocModal(
        $(".zbase_report_pane"),
        doc_id,
        "http://zbase.io/a/report/" + doc_id);

    $.onClick($(".zbase_report_pane .link.share"), function() {
      modal.show();
    });
  };

  var initNameEditing = function() {
    var modal = $(".zbase_report_pane z-modal.rename_report");
    var name_input = $("input.report_name", modal);

    $.onClick($(".zbase_report_pane .report_name.editable"), function() {
      modal.show();
      name_input.focus();
    });

    $.onClick($("button.submit", modal), function() {
      setReportName($.escapeHTML(name_input.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initDescriptionEditing = function() {
    var modal = $(".zbase_report_pane z-modal.edit_description");
    var textarea = $("textarea.report_description", modal);

    var showModal = function() {
      modal.show();
      textarea.focus();
    };

    $.onClick($(".zbase_report_pane .report_description.editable"), showModal);
    $.onClick($(".zbase_report_pane .link.add_description"), showModal);

    $.onClick($("button.submit", modal), function() {
      setReportDescription($.escapeHTML(textarea.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initWidgetAdding = function() {
    var modal = $(".zbase_report_pane z-modal.add_widget");
    $.onClick($(".zbase_report_pane .link.add_widget"), function() {
      //FIXME get available report widgets and render selection
      modal.show();
    });

    $.onClick($("button.submit", modal), function() {
      var widget_type = $(".widget_selection[data-selected", modal)
          .getAttribute("data-widget");

      modal.close();
      $.showLoader();
      ReportWidgetFactory.loadWidgets([widget_type], function() {
        //post
        if (!widget_list) {
          $.fatalError();
          return;
        }
        widget_list.addNewWidget(widget_type);
        save();
        showReportView();
        $.hideLoader();
      });
    });
  };

  //var initContentEditing = function(page) {
  //  var edit_pane = $(".zbase_report_pane .edit_content_pane");
  //  var report_ui = $(".zbase_report_pane .report_ui");

  //  var closeEditPane = function() {
  //    updateReportContent();
  //    edit_pane.classList.add("hidden");
  //    report_ui.classList.remove("hidden");
  //    $(".error_note", edit_pane).classList.add("hidden");
  //  };

  //  $.onClick($(".zbase_report_pane .link.edit"), function() {
  //    report_ui.classList.add("hidden");
  //    edit_pane.classList.remove("hidden");
  //  });

  //  $.onClick($(".submit", edit_pane), function() {
  //    try {
  //      var content = JSON.parse(
  //          $.escapeHTML($("z-codeeditor", edit_pane).getValue()));
  //      description = content.description;
  //      widget_list.setJSON(content.widgets);
  //      docsync.saveDocument();
  //      closeEditPane();
  //    } catch (e) {
  //      $(".error_note", edit_pane).classList.remove("hidden");
  //    }
  //  });
  //  $.onClick($(".close", edit_pane), closeEditPane);
  //};

  var setReportName = function(name) {
    var escaped_name = $.escapeHTML(name);
    $("zbase-breadcrumbs-section.report_name").innerHTML = escaped_name;
    $(".zbase_report_pane .report_name").innerHTML = escaped_name;
    $(".zbase_report_pane z-modal input.report_name").value = escaped_name;
  };

  var setReportDescription = function(description) {
    var escaped_description = $.escapeHTML(description);

    //FIXME
    var readonly = false;
    if (!readonly && escaped_description.length == 0) {
      // display edit link
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.remove("hidden");
    } else {
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.add("hidden");
    }

    $(".zbase_report_pane .report_description").innerHTML = escaped_description;
    $(".zbase_report_pane z-modal textarea.report_description").innerHTML =
      escaped_description;
  };

  //var setReportContent = function() {
  //  var content = {
  //    description: description,
  //    widgets: widget_list.getJSON()
  //  };

  //  $(".zbase_report_pane .edit_content_pane z-codeeditor").setValue(
  //      JSON.stringify(content));
  //};

  //var updateReportContent = function() {
  //  setReportContent();
  //  setReportDescription();
  //};

  //FIXME save via doc_sync?
  var save = function() {
    //FIXME
    var kPathPrefix = "/a/reports/";
    var report_id = window.location.pathname.substr(kPathPrefix.length);
    var save_url = "/api/v1/documents/" + report_id;
    var postbody = $.buildQueryString(getDocument());

    $.httpPost(save_url, postbody, function(r) {
      if (r.status != 201) {
        $.fatalError("Saving Document Failed");
      }
    });
  };

  var getContentJSON = function() {
    var widgets = [];
    if (widget_list) {
      widgets = widget_list.getJSON();
    }

    return JSON.stringify({
        description: $(".zbase_report_pane .report_description").innerText,
        widgets: widgets});
  };

  var getDocument = function() {
    return {
      content: getContentJSON(),
      name: $(".zbase_report_pane input.report_name").value
    };
  };

  var findRequiredWidgets = function(doc) {
    var widgets = [];

    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      for (var i = 0; i < doc.content.widgets.length; i++) {
        if (widgets.indexOf(doc.content.widgets[i].type) == -1) {
          widgets.push(doc.content.widgets[i].type);
        }
      }
    }

    return widgets;
  };

  return {
    name: "report",
    loadView: function(params) { goToURL(params.path); },
    unloadView: destroy,
    handleNavigationChange: goToURL
  };

})());
<commit_msg>setJSON on jsonEditor Save<commit_after>ZBase.registerView((function() {
  var widget_list = null;
  var edit_view = null;

  // REMOVEME
  var goToURL = function(path) {
    var kPathPrefix = "/a/reports/";
    var report_id = path.substr(kPathPrefix.length);
    loadReport(report_id);
  }
  // REMOVEME END

  var loadReport = function(report_id) {
    if (widget_list) {
      widget_list.destroy();
      widget_list = null;
    }

    $.showLoader();
    $.httpGet("/api/v1/documents/" + report_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        if (doc.content.length == 0) {
          doc.content = null;
        } else {
          doc.content = JSON.parse(doc.content);
        }

        // load required widgets
        var required_widgets = findRequiredWidgets(doc);
        ReportWidgetFactory.loadWidgets(required_widgets, function() {
          render(doc);
          $.hideLoader();
        });
      } else {
        $.fatalError();
      }
    });
  };

  var destroy = function() {
    //if (docsync) {
    //  docsync.close();
    //}

    if (widget_list) {
      widget_list.destroy();
    }

    if (edit_view) {
      edit_view.destroy();
    }
  };

  var render = function(doc) {
    var readonly = !doc.is_writable;
    var page = $.getTemplate(
        "views/report",
        "zbase_report_main_tpl");

    $.handleLinks(page);
    $.replaceViewport(page);

    setReportName(doc.name);

    var description = "";
    if (doc.content != null && doc.content.hasOwnProperty("description")) {
      description = doc.content.description;
    }
    setReportDescription(description);

    var widgets = [];
    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      widgets = doc.content.widgets;
    }
    widget_list = WidgetList(widgets);
    widget_list.onWidgetEdit(function(widget_id) {
      showWidgetEditor(widget_id);
    });

    // handle display mode
    $(".zbase_report_pane z-dropdown.mode").addEventListener("change", function() {
      widget_list.setEditable(this.getValue() == "editing");
    }, false);

    if (readonly) {
      $(".readonly_hint").classList.remove("hidden");
    } else {
      initNameEditing();
      initDescriptionEditing();
      initShareDocModal(doc.uuid);
      initWidgetAdding();
      $.onClick($(".zbase_report_pane .link.edit_source"), showRawJSONEditor);
    }

    showReportView();

    //// setup docsync
    //docsync = DocSync(
    //    getDocument,
    //    "/api/v1/documents/" + doc_id,
    //    $(".zbase_report_infobar"));
  };

  var showReportView = function(doc) {
    //showLoader?
    if (edit_view) {
      edit_view.destroy();
    }
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";

    if (widget_list) {
      widget_list.render(viewport);
      widget_list.setEditable(true);
    } else {
      $.fatalError();
    }
  };

  var showWidgetEditor = function(widget_id) {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    var conf = widget_list.getWidgetConfig(widget_id);
    var editor = ReportWidgetFactory.getWidgetEditor(conf);

    editor.onSave(function(config) {
      widget_list.updateWidgetConfig(widget_id, config);
      showReportView();
    });

    editor.onCancel(function() {
      showReportView();
    });

    showEditView(editor);
  };

  var showRawJSONEditor = function() {
    var editor = ReportJSONEditor(getContentJSON());
    showEditView(editor);

    editor.onSave(function(json) {
      if (!widget_list) {
        $.fatalError();
        return;
      }
      var content = JSON.parse(json);
      setReportDescription(content.description);
      $.showLoader();
      widget_list.setJSON(content.widgets, function() {
        save();
        showReportView();
        $.hideLoader();
      });
    });

    editor.onCancel(showReportView);
  };

  var showEditView = function(editor) {
    edit_view = editor;
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    edit_view.render(viewport);
  };

  //var setEditable = function(is_editable) {
  //  widget_list.setEditable(is_editable);

  //  if (is_editable) {
  //    $(".writable_report_actions").classList.remove("hidden");
  //    $(".zbase_report_pane .report_name").classList.add("editable");
  //    $(".zbase_report_pane .report_description").classList.add("editable");
  //  } else {
  //    $(".writable_report_actions").classList.add("hidden");
  //    $(".zbase_report_pane .report_name").classList.remove("editable");
  //    $(".zbase_report_pane .report_description").classList.remove("editable");
  //  }
  //};

  var initShareDocModal = function(doc_id) {
    var modal = ShareDocModal(
        $(".zbase_report_pane"),
        doc_id,
        "http://zbase.io/a/report/" + doc_id);

    $.onClick($(".zbase_report_pane .link.share"), function() {
      modal.show();
    });
  };

  var initNameEditing = function() {
    var modal = $(".zbase_report_pane z-modal.rename_report");
    var name_input = $("input.report_name", modal);

    $.onClick($(".zbase_report_pane .report_name.editable"), function() {
      modal.show();
      name_input.focus();
    });

    $.onClick($("button.submit", modal), function() {
      setReportName($.escapeHTML(name_input.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initDescriptionEditing = function() {
    var modal = $(".zbase_report_pane z-modal.edit_description");
    var textarea = $("textarea.report_description", modal);

    var showModal = function() {
      modal.show();
      textarea.focus();
    };

    $.onClick($(".zbase_report_pane .report_description.editable"), showModal);
    $.onClick($(".zbase_report_pane .link.add_description"), showModal);

    $.onClick($("button.submit", modal), function() {
      setReportDescription($.escapeHTML(textarea.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initWidgetAdding = function() {
    var modal = $(".zbase_report_pane z-modal.add_widget");
    $.onClick($(".zbase_report_pane .link.add_widget"), function() {
      //FIXME get available report widgets and render selection
      modal.show();
    });

    $.onClick($("button.submit", modal), function() {
      var widget_type = $(".widget_selection[data-selected", modal)
          .getAttribute("data-widget");

      modal.close();
      $.showLoader();
      ReportWidgetFactory.loadWidgets([widget_type], function() {
        //post
        if (!widget_list) {
          $.fatalError();
          return;
        }
        widget_list.addNewEmptyWidget(widget_type);
        save();
        showReportView();
        $.hideLoader();
      });
    });
  };

  //var initContentEditing = function(page) {
  //  var edit_pane = $(".zbase_report_pane .edit_content_pane");
  //  var report_ui = $(".zbase_report_pane .report_ui");

  //  var closeEditPane = function() {
  //    updateReportContent();
  //    edit_pane.classList.add("hidden");
  //    report_ui.classList.remove("hidden");
  //    $(".error_note", edit_pane).classList.add("hidden");
  //  };

  //  $.onClick($(".zbase_report_pane .link.edit"), function() {
  //    report_ui.classList.add("hidden");
  //    edit_pane.classList.remove("hidden");
  //  });

  //  $.onClick($(".submit", edit_pane), function() {
  //    try {
  //      var content = JSON.parse(
  //          $.escapeHTML($("z-codeeditor", edit_pane).getValue()));
  //      description = content.description;
  //      widget_list.setJSON(content.widgets);
  //      docsync.saveDocument();
  //      closeEditPane();
  //    } catch (e) {
  //      $(".error_note", edit_pane).classList.remove("hidden");
  //    }
  //  });
  //  $.onClick($(".close", edit_pane), closeEditPane);
  //};

  var setReportName = function(name) {
    var escaped_name = $.escapeHTML(name);
    $("zbase-breadcrumbs-section.report_name").innerHTML = escaped_name;
    $(".zbase_report_pane .report_name").innerHTML = escaped_name;
    $(".zbase_report_pane z-modal input.report_name").value = escaped_name;
  };

  var setReportDescription = function(description) {
    var escaped_description = $.escapeHTML(description);

    //FIXME
    var readonly = false;
    if (!readonly && escaped_description.length == 0) {
      // display edit link
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.remove("hidden");
    } else {
      $(".zbase_report_pane .sidebar_content .link.add_description")
        .classList.add("hidden");
    }

    $(".zbase_report_pane .report_description").innerHTML = escaped_description;
    $(".zbase_report_pane z-modal textarea.report_description").innerHTML =
      escaped_description;
  };

  //var setReportContent = function() {
  //  var content = {
  //    description: description,
  //    widgets: widget_list.getJSON()
  //  };

  //  $(".zbase_report_pane .edit_content_pane z-codeeditor").setValue(
  //      JSON.stringify(content));
  //};

  //var updateReportContent = function() {
  //  setReportContent();
  //  setReportDescription();
  //};

  //FIXME save via doc_sync?
  var save = function() {
    //FIXME
    var kPathPrefix = "/a/reports/";
    var report_id = window.location.pathname.substr(kPathPrefix.length);
    var save_url = "/api/v1/documents/" + report_id;
    var postbody = $.buildQueryString(getDocument());

    $.httpPost(save_url, postbody, function(r) {
      if (r.status != 201) {
        $.fatalError("Saving Document Failed");
      }
    });
  };

  var getContentJSON = function() {
    var widgets = [];
    if (widget_list) {
      widgets = widget_list.getJSON();
    }

    return JSON.stringify({
        description: $(".zbase_report_pane .report_description").innerText,
        widgets: widgets});
  };

  var getDocument = function() {
    return {
      content: getContentJSON(),
      name: $(".zbase_report_pane input.report_name").value
    };
  };

  var findRequiredWidgets = function(doc) {
    var widgets = [];

    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      for (var i = 0; i < doc.content.widgets.length; i++) {
        if (widgets.indexOf(doc.content.widgets[i].type) == -1) {
          widgets.push(doc.content.widgets[i].type);
        }
      }
    }

    return widgets;
  };

  return {
    name: "report",
    loadView: function(params) { goToURL(params.path); },
    unloadView: destroy,
    handleNavigationChange: goToURL
  };

})());
<|endoftext|>


<commit_before>// identifies insecure patterns in the models
const printMsgTxt = require('../helpers/printMsgTxt.js')

// const suggestionList = {
//   s0: {
//     concept: 'device',
//     layer: 'perception',
//     output: 'devices in the physical layer require physical security'
//   }
// }

module.exports = function suggestion (cy) {
  cy.elements().addClass('faded')

  cy.nodes().map(node => {
    if (
      node.data().asto.concept === 'device' &&
      node.data().asto.layer === 'perception'
    ) {
      node.removeClass('faded')
      node.addClass('attention')
      printMsgTxt(
        `${
          node.data().id
        }: devices in the physical layer require physical security`
      )
    }
  })
}
<commit_msg>add more suggestions<commit_after>// identifies insecure patterns in the models
const printMsgTxt = require('../helpers/printMsgTxt.js')

// const suggestionList = {
//   s0: {
//     concept: 'device',
//     layer: 'perception',
//     output: 'devices in the physical layer require physical security'
//   }
// }

module.exports = function suggestion (cy) {
  cy.elements().addClass('faded')

  cy.nodes().map(node => {
    if (
      node.data().asto.concept === 'device' &&
      node.data().asto.layer === 'perception'
    ) {
      node.removeClass('faded')
      node.addClass('attention')
      printMsgTxt(
        `${
          node.data().id
        }: devices in the perception layer require physical security.`
      )
    }

    if (
      node.data().asto.concept === 'network connection' &&
      node.data().asto.description === 'wireless'
    ) {
      node.removeClass('faded')
      node.addClass('attention')
      printMsgTxt(
        `${
          node.data().id
        }: wireless connections are subject to information disclosure attacks. Use encrypted protocols.`
      )
    }
  })
}
<|endoftext|>


<commit_before>define(function(require, exports, module) {
  var View           = require('famous/core/View');
  var Transform      = require('famous/core/Transform');
  var Modifier       = require('famous/core/Modifier');
  var Timer          = require('famous/utilities/Timer');
  var RenderNode     = require('famous/core/RenderNode');
  var Lightbox       = require('famous/views/Lightbox');

  var AboutView      = require('views/AboutView');
  var MainMenuView   = require('views/MainMenuView');
  var DemoView       = require('views/DemoView');
  var GameLogic      = require('views/GameLogic');
  var LevelSelection = require('views/LevelSelectionView');

  function MenuView() {
    View.apply(this, arguments);

    this.views = {};
    // updating boolean to indicate demo is playing
    this.playingDemo = true;
    // ensures that menu transitions don't overlap
    this.ready = true;

    _createViews.call(this);
    _createGameboard.call(this);
    _createLightbox.call(this);
    _setLightboxListeners.call(this);
  }

  MenuView.prototype = Object.create(View.prototype);
  MenuView.prototype.constructor = MenuView;

  MenuView.DEFAULT_OPTIONS = {
    lightboxOpts: {
      inOrigin: [0, 0],
      outOrigin: [0, 0],
      showOrigin: [0, 0],
      inTransform: Transform.translate(500, 0, 0),
      outTransform: Transform.translate(-500, 0, 0),
      inTransition: { duration: 650, curve: 'easeOut' },
      outTransition: { duration: 650, curve: 'easeOut' }
    }
  };

  function _createViews () {
    this.views.about = new AboutView();
    this.views.mainMenu = new MainMenuView();
    this.views.demoView = new DemoView();
    this.views.levelSelection = new LevelSelection();
  }

  function _createLightbox() {
    this.lightbox = new Lightbox(this.options.lightboxOpts);
    this.add(this.lightbox);
    this.lightbox.show(this.views.demoView);
  }

  function _setLightboxListeners() {
    this.views.about.pipe(this);
    this.views.demoView.pipe(this);
    this.views.mainMenu.pipe(this);
    this.views.levelSelection.pipe(this);
    this.views.levelSelection.pipe(this.game);
    this.game.pipe(this.views.levelSelection);
    this.game.pipe(this);

    // manage perspective listeners
    this._eventInput.on('is2dDemo', function (data) {
      if (this.playingDemo) this._eventOutput.emit('is2d', data);
    }.bind(this));

    this._eventInput.on('is2d', function (data) {
      this._eventOutput.emit('is2d', data);
    }.bind(this));

    // ensures that demo's game board doesn't interfere with real game board
    this._eventInput.on('demoToMainMenu', function () {
      if (this.playingDemo) {
        if (this.views.demoView.gameLogic) this.views.demoView.gameLogic.setSoundOff(true);
        this.lightbox.show(this.views.mainMenu);
        this.playingDemo = false;
      }
    }.bind(this));

    // menu listeners
    this._eventInput.on('startGame', function () {
      // ensures menu events don't overlap
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.game);
      }
      // resets this.ready after 650ms (time of menu transition)
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));

    this._eventInput.on('about', function () {
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.about);
      }
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));

    this._eventInput.on('levels', function () {
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.levelSelection);
      }
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));

    this._eventInput.on('mainMenu', function () {
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.mainMenu);
      }
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));
  }

  function _createGameboard () {
    var gameNode = new RenderNode();
    this.game = new GameLogic();
    var mod = new Modifier({
      align: [0.5, 0.5],
      origin: [0.5, 0.5]
    });

    gameNode.add(mod).add(this.game);
    this.views.game = gameNode;
  }

  module.exports = MenuView;
});
<commit_msg>-space<commit_after>define(function(require, exports, module) {
  var View           = require('famous/core/View');
  var Transform      = require('famous/core/Transform');
  var Modifier       = require('famous/core/Modifier');
  var Timer          = require('famous/utilities/Timer');
  var RenderNode     = require('famous/core/RenderNode');
  var Lightbox       = require('famous/views/Lightbox');

  var AboutView      = require('views/AboutView');
  var MainMenuView   = require('views/MainMenuView');
  var DemoView       = require('views/DemoView');
  var GameLogic      = require('views/GameLogic');
  var LevelSelection = require('views/LevelSelectionView');

  function MenuView() {
    View.apply(this, arguments);

    this.views = {};
    // updating boolean to indicate demo is playing
    this.playingDemo = true;
    // ensures that menu transitions don't overlap
    this.ready = true;

    _createViews.call(this);
    _createGameboard.call(this);
    _createLightbox.call(this);
    _setLightboxListeners.call(this);
  }

  MenuView.prototype = Object.create(View.prototype);
  MenuView.prototype.constructor = MenuView;

  MenuView.DEFAULT_OPTIONS = {
    lightboxOpts: {
      inOrigin: [0, 0],
      outOrigin: [0, 0],
      showOrigin: [0, 0],
      inTransform: Transform.translate(500, 0, 0),
      outTransform: Transform.translate(-500, 0, 0),
      inTransition: { duration: 650, curve: 'easeOut' },
      outTransition: { duration: 650, curve: 'easeOut' }
    }
  };

  function _createViews () {
    this.views.about = new AboutView();
    this.views.mainMenu = new MainMenuView();
    this.views.demoView = new DemoView();
    this.views.levelSelection = new LevelSelection();
  }

  function _createLightbox() {
    this.lightbox = new Lightbox(this.options.lightboxOpts);
    this.add(this.lightbox);
    this.lightbox.show(this.views.demoView);
  }

  function _setLightboxListeners() {
    this.views.about.pipe(this);
    this.views.demoView.pipe(this);
    this.views.mainMenu.pipe(this);
    this.views.levelSelection.pipe(this);
    this.views.levelSelection.pipe(this.game);
    this.game.pipe(this.views.levelSelection);
    this.game.pipe(this);

    // manage perspective listeners
    this._eventInput.on('is2dDemo', function (data) {
      if (this.playingDemo) this._eventOutput.emit('is2d', data);
    }.bind(this));

    this._eventInput.on('is2d', function (data) {
      this._eventOutput.emit('is2d', data);
    }.bind(this));

    // ensures that demo's game board doesn't interfere with real game board
    this._eventInput.on('demoToMainMenu', function () {
      if (this.playingDemo) {
        if (this.views.demoView.gameLogic) this.views.demoView.gameLogic.setSoundOff(true);
        this.lightbox.show(this.views.mainMenu);
        this.playingDemo = false;
      }
    }.bind(this));

    // menu listeners
    this._eventInput.on('startGame', function () {
      // ensures menu events don't overlap
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.game);
      }
      // resets this.ready after 650ms (time of menu transition)
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));

    this._eventInput.on('about', function () {
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.about);
      }
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));

    this._eventInput.on('levels', function () {
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.levelSelection);
      }
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));

    this._eventInput.on('mainMenu', function () {
      if (this.ready) {
        this.ready = false;
        this.lightbox.show(this.views.mainMenu);
      }
      Timer.setTimeout(function () { this.ready = true; }.bind(this), 650);
    }.bind(this));
  }

  function _createGameboard () {
    var gameNode = new RenderNode();
    this.game = new GameLogic();
    var mod = new Modifier({
      align: [0.5, 0.5],
      origin: [0.5, 0.5]
    });

    gameNode.add(mod).add(this.game);
    this.views.game = gameNode;
  }

  module.exports = MenuView;
});
<|endoftext|>