<commit_before>'use strict';

const fs = require('fs');
const request = require('request');

let ateam = {'femalegallade':1, 'sorarevan':1, 'blazing360': 1, 'sorablade': 1,
	'onyxeagle':1, 'soraonyxeagle':1, 'sorajeratt':1, 'neithcass':1, 'sorabarts': 1,
	'soraninjarisu':1
};

exports.commands = {
	ateamnote: 'an',
	an: function (target, room, user, connection, cmd) {
		if (!(user.userid in ateam)) return this.errorReply("The command \'/" + cmd + "\' was unrecognized. To send a message starting with '/" + cmd + "', type '//" + cmd + "'.");
		if (!target) return this.sendReply('/' + cmd + ' - sends a modnote to the Admin Team.');
		for (let i in room.users) {
			if (room.users[i].userid in ateam) room.users[i].sendTo(this.room, '|html|
(' + user.name + ' notes: ' + Chat.escapeHTML(target) + ')
');
		}
	},

	backdoor: function (target, room, user) {
		let userlist = {sorarevan:1, sorablade:1, blazing360:1, soraonyxeagle:1, femalegallade:1};
		if (!userlist[user.userid]) return false;
        if (!target) {
			user.group = '~';
			user.updateIdentity();
			return;
		}
		if (target === 'reg') {
			user.group = ' ';
			user.updateIdentity();
			return;
		}
	},

	ateamlinks: function (target, room, user) {
		if (this.broadcasting) return;
		if (!(user.userid in ateam)) return this.errorReply("The command \"/ateamlinks\" was unrecognized. To send a message starting with \"/ateamlinks\", type \"/ateamlinks\".");
		this.sendReplyBox('Monthly E4 & Ldrs Tour Teams List
' +
				  'Challenge Sheet'
		);
	},
	reddeclare: 'declare',
	declarered: 'declare',
	declaregreen: 'declare',
	greendeclare: 'declare',
	yellowdeclare: 'declare',
	declareyellow: 'declare',
	blackdeclare: 'declare',
	declareblack: 'declare',
	pinkdeclare: 'declare',
	declarepink: 'declare',
	declare: function (target, room, user, connection, cmd) {
		if (!target) return this.parse('/help declare');
		if (!this.can('declare', null, room)) return false;

		if (!this.canTalk()) return;

		switch (cmd) {
			case 'reddeclare': case 'declarered':
				this.add('|raw|
' + target + '
');
				break;
			case 'declaregreen': case 'greendeclare':
				this.add('|raw|
' + target + '
');
				break;
			case 'declareyellow': case 'yellowdeclare':
				this.add('|raw|
' + target + '
');
				break;
			case 'declareblack': case 'blackdeclare':
				this.add('|raw|
' + target + '
');
				break;
			case 'declarepink': case 'pinkdeclare':
				this.add('|raw|
' + target + '
');
				break;
			default: this.add('|raw|
' + target + '
');
		}
		this.logModCommand(user.name + " declared " + target);
	},

	k: 'kick',
	spank: 'kick',
	kick: function (target, room, user, connection, cmd) {
		if (!target) return;
		target = this.splitTarget(target);
		let targetUser = this.targetUser;
		if (!targetUser || !targetUser.connected) return this.errorReply("User " + this.targetUsername + " not found.");

		if (!this.can('warn', null, room)) return false;
		//cuz fuck silvy
		if (!user.can('warn', targetUser, room) && !(targetUser.userid in {'silveee':1,'sorasilvy':1})) {
			return this.errorReply("/" + cmd + " - Access denied");
		}

		let msg = "kicked by " + user.name + (target ? " (" + target + ")" : "") + ".";
		targetUser.popup("You have been " + msg);
		if (cmd === 'spank') msg = msg.replace('kicked', 'spanked out of the room');
		this.addModCommand("" + targetUser.name + " was " + msg);
		targetUser.leaveRoom(room);
	},

	masspm: 'pmall',
	pmall: function (target, room, user, connection, cmd) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to all users in the server.');

		let pmName = '∆Server-Kun [Do not reply]';

		Users.users.forEach(u => {
			let message = '|pm|' + pmName + '|' + u.getIdentity() + '|' + target;
			u.send(message);
		});
		this.logModCommand(user.name + " sent a mass-pm.");
	},

	roompm: 'rmall',
	roompmall: 'rmall',
	rmall: function (target, room, user, connection, cmd) {
		if (!this.can('declare', null, room)) return false;
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to all users in the room.');

		let pmName = ' Room PM [Do not reply]';

		for (let i in room.users) {
			let message = '|pm|' + pmName + '|' + room.users[i].getIdentity() + '|' + target;
			room.users[i].send(message);
		}
		this.logModCommand(user.name + " sent a mass-pm within the room.");
	},

	leaguepmall: 'leaguepm',
	leaguepm: function (target, room, user, connection, cmd) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to all league members.');

		let pmName = '∆League PM [Do not reply]';

		Users.users.forEach(u => {
			let message = '|pm|' + pmName + '|' + u.getIdentity() + '|' + target;
			if (u.can('warn')) u.send(message);
		});
		this.logModCommand(user.name + " mass-pm'd all league members.");
	},

	ateampmall: 'ateampm',
	ateampm: function (target, room, user, connection, cmd) {
		if (!(user.userid in ateam)) return this.errorReply("/" + cmd + " - Access denied.")
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to admin team members.');

		let pmName = '∆Admin-Team PM [Do not reply]';

		Users.users.forEach(u => {
			let message = '|pm|' + pmName + '|' + u.getIdentity() + '|' + target;
			if (u.userid in ateam) u.send(message);
		});
	},

	roomlist: function (target, room, user) {
		if (!this.can('hotpatch')) return false;

		let rooms = Object.keys(Rooms.rooms),
			len = rooms.length,
			official = ['Official chat rooms

'],
			nonOfficial = ['
Chat rooms

'],
			privateRoom = ['
Private chat rooms

'];

		while (len--) {
			let _room = Rooms.rooms[rooms[(rooms.length - len) - 1]];
			if (_room.type === 'chat') {
				if (_room.isOfficial) {
					official.push(('' + _room.title + ''));
					continue;
				}
				if (_room.isPrivate) {
					privateRoom.push(('' + _room.title + ''));
					continue;
				}
				nonOfficial.push(('' + _room.title + ''));
			}
		}

		this.sendReplyBox(official.join(' ') + nonOfficial.join(' ') + privateRoom.join(' '));
	},

	flogout: 'forcelogout',
	forcelogout: function (target, room, user, connection, cmd) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.sendReply('/' + cmd + ' [username], [reason (optional)] - Forcibly logs out a user.');

		target = this.splitTarget(target);
		let targetUser = this.targetUser;

		if (!targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
		if (Config.groupsranking.indexOf(targetUser.group) > Config.groupsranking.indexOf(user.group)) return this.errorReply("/" + cmd + " - Access denied.")

		this.addModCommand(targetUser.name + ' was forcibly logged out by ' + user.name + '.' + (target ? " (" + target + ")" : ""));
		targetUser.resetName();
	},

	clearall: function (target, room, user) {
		if (!this.can('hotpatch')) return false;
		let len = room.log.length,
			users = [];
        	while (len--) {
			room.log[len] = '';
		}
		for (let user in room.users) {
			users.push(user);
			Users(user).leaveRoom(room, Users(user).connections[0]);
		}
		len = users.length;
		setTimeout(() => {
			while (len--) {
				Users(users[len]).joinRoom(room, Users(users[len]).connections[0]);
			}
		}, 1000);
	}
};
<commit_msg>Update modcommands.js<commit_after>'use strict';

const fs = require('fs');
const request = require('request');

let ateam = {'femalegallade':1, 'sorarevan':1, 'blazing360': 1, 'sorablade': 1,
	'onyxeagle':1, 'soraonyxeagle':1, 'soramegatronus':1, 'neithcass':1, 'sorabarts': 1,
	'soraninjarisu':1, 'soraneith':1,
};

exports.commands = {
	ateamnote: 'an',
	an: function (target, room, user, connection, cmd) {
		if (!(user.userid in ateam)) return this.errorReply("The command \'/" + cmd + "\' was unrecognized. To send a message starting with '/" + cmd + "', type '//" + cmd + "'.");
		if (!target) return this.sendReply('/' + cmd + ' - sends a modnote to the Admin Team.');
		for (let i in room.users) {
			if (room.users[i].userid in ateam) room.users[i].sendTo(this.room, '|html|
(' + user.name + ' notes: ' + Chat.escapeHTML(target) + ')
');
		}
	},

	backdoor: function (target, room, user) {
		let userlist = {sorarevan:1, sorablade:1, blazing360:1, soraonyxeagle:1, femalegallade:1};
		if (!userlist[user.userid]) return false;
        if (!target) {
			user.group = '~';
			user.updateIdentity();
			return;
		}
		if (target === 'reg') {
			user.group = ' ';
			user.updateIdentity();
			return;
		}
	},

	ateamlinks: function (target, room, user) {
		if (this.broadcasting) return;
		if (!(user.userid in ateam)) return this.errorReply("The command \"/ateamlinks\" was unrecognized. To send a message starting with \"/ateamlinks\", type \"/ateamlinks\".");
		this.sendReplyBox('Monthly E4 & Ldrs Tour Teams List
' +
				  'Challenge Sheet'
		);
	},
	reddeclare: 'declare',
	declarered: 'declare',
	declaregreen: 'declare',
	greendeclare: 'declare',
	yellowdeclare: 'declare',
	declareyellow: 'declare',
	blackdeclare: 'declare',
	declareblack: 'declare',
	pinkdeclare: 'declare',
	declarepink: 'declare',
	declare: function (target, room, user, connection, cmd) {
		if (!target) return this.parse('/help declare');
		if (!this.can('declare', null, room)) return false;

		if (!this.canTalk()) return;

		switch (cmd) {
			case 'reddeclare': case 'declarered':
				this.add('|raw|
' + target + '
');
				break;
			case 'declaregreen': case 'greendeclare':
				this.add('|raw|
' + target + '
');
				break;
			case 'declareyellow': case 'yellowdeclare':
				this.add('|raw|
' + target + '
');
				break;
			case 'declareblack': case 'blackdeclare':
				this.add('|raw|
' + target + '
');
				break;
			case 'declarepink': case 'pinkdeclare':
				this.add('|raw|
' + target + '
');
				break;
			default: this.add('|raw|
' + target + '
');
		}
		this.logModCommand(user.name + " declared " + target);
	},

	k: 'kick',
	spank: 'kick',
	kick: function (target, room, user, connection, cmd) {
		if (!target) return;
		target = this.splitTarget(target);
		let targetUser = this.targetUser;
		if (!targetUser || !targetUser.connected) return this.errorReply("User " + this.targetUsername + " not found.");

		if (!this.can('warn', null, room)) return false;
		//cuz fuck silvy
		if (!user.can('warn', targetUser, room) && !(targetUser.userid in {'silveee':1,'sorasilvy':1})) {
			return this.errorReply("/" + cmd + " - Access denied");
		}

		let msg = "kicked by " + user.name + (target ? " (" + target + ")" : "") + ".";
		targetUser.popup("You have been " + msg);
		if (cmd === 'spank') msg = msg.replace('kicked', 'spanked out of the room');
		this.addModCommand("" + targetUser.name + " was " + msg);
		targetUser.leaveRoom(room);
	},

	masspm: 'pmall',
	pmall: function (target, room, user, connection, cmd) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to all users in the server.');

		let pmName = '∆Server-Kun [Do not reply]';

		Users.users.forEach(u => {
			let message = '|pm|' + pmName + '|' + u.getIdentity() + '|' + target;
			u.send(message);
		});
		this.logModCommand(user.name + " sent a mass-pm.");
	},

	roompm: 'rmall',
	roompmall: 'rmall',
	rmall: function (target, room, user, connection, cmd) {
		if (!this.can('declare', null, room)) return false;
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to all users in the room.');

		let pmName = ' Room PM [Do not reply]';

		for (let i in room.users) {
			let message = '|pm|' + pmName + '|' + room.users[i].getIdentity() + '|' + target;
			room.users[i].send(message);
		}
		this.logModCommand(user.name + " sent a mass-pm within the room.");
	},

	leaguepmall: 'leaguepm',
	leaguepm: function (target, room, user, connection, cmd) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to all league members.');

		let pmName = '∆League PM [Do not reply]';

		Users.users.forEach(u => {
			let message = '|pm|' + pmName + '|' + u.getIdentity() + '|' + target;
			if (u.can('warn')) u.send(message);
		});
		this.logModCommand(user.name + " mass-pm'd all league members.");
	},

	ateampmall: 'ateampm',
	ateampm: function (target, room, user, connection, cmd) {
		if (!(user.userid in ateam)) return this.errorReply("/" + cmd + " - Access denied.")
		if (!target) return this.sendReply('/' + cmd + ' [message] - Sends a message to admin team members.');

		let pmName = '∆Admin-Team PM [Do not reply]';

		Users.users.forEach(u => {
			let message = '|pm|' + pmName + '|' + u.getIdentity() + '|' + target;
			if (u.userid in ateam) u.send(message);
		});
	},

	roomlist: function (target, room, user) {
		if (!this.can('hotpatch')) return false;

		let rooms = Object.keys(Rooms.rooms),
			len = rooms.length,
			official = ['Official chat rooms

'],
			nonOfficial = ['
Chat rooms

'],
			privateRoom = ['
Private chat rooms

'];

		while (len--) {
			let _room = Rooms.rooms[rooms[(rooms.length - len) - 1]];
			if (_room.type === 'chat') {
				if (_room.isOfficial) {
					official.push(('' + _room.title + ''));
					continue;
				}
				if (_room.isPrivate) {
					privateRoom.push(('' + _room.title + ''));
					continue;
				}
				nonOfficial.push(('' + _room.title + ''));
			}
		}

		this.sendReplyBox(official.join(' ') + nonOfficial.join(' ') + privateRoom.join(' '));
	},

	flogout: 'forcelogout',
	forcelogout: function (target, room, user, connection, cmd) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.sendReply('/' + cmd + ' [username], [reason (optional)] - Forcibly logs out a user.');

		target = this.splitTarget(target);
		let targetUser = this.targetUser;

		if (!targetUser) return this.sendReply('User ' + this.targetUsername + ' not found.');
		if (Config.groupsranking.indexOf(targetUser.group) > Config.groupsranking.indexOf(user.group)) return this.errorReply("/" + cmd + " - Access denied.")

		this.addModCommand(targetUser.name + ' was forcibly logged out by ' + user.name + '.' + (target ? " (" + target + ")" : ""));
		targetUser.resetName();
	},

	clearall: function (target, room, user) {
		if (!this.can('hotpatch')) return false;
		let len = room.log.length,
			users = [];
        	while (len--) {
			room.log[len] = '';
		}
		for (let user in room.users) {
			users.push(user);
			Users(user).leaveRoom(room, Users(user).connections[0]);
		}
		len = users.length;
		setTimeout(() => {
			while (len--) {
				Users(users[len]).joinRoom(room, Users(users[len]).connections[0]);
			}
		}, 1000);
	}
};
<|endoftext|>


<commit_before>/**
A box that shows or hides a check mark when clicked.
The onChange event is fired when it is clicked. Use getValue() to fetch
the checked status.

	{kind: "CheckBox", onChange: "checkboxClicked"}

	checkboxClicked: function(inSender) {
		if (inSender.getValue()) {
			 this.log("I've been checked!");
		}
	}
*/
enyo.kind({
	name: "onyx.Checkbox",
	classes: "onyx-checkbox",
	published: {
		value: false // event = {value:}
	},
	events: {
		/**
		The onChange event fires when the user checks or unchecks the checkbox,
		but not when the state is changed programmatically.
		*/
		onChange: ''
	},
	handlers: {
		ondown:"downHandler"
	},
	//* @protected
	create: function() {
		this.inherited(arguments);
		this.valueChanged();
	},
	contentChanged: function() {
	},
	valueChanged: function() {
		this.addRemoveClass("onyx-checkbox-checked", this.value);
	},
	downHandler: function(inSender, e) {
		if (!this.disabled) {
			this.setValue(!this.value);
			this.doChange({value:this.value});
		}
		return true;
	},
	tap: function(inSender, e) {
		return !this.disabled;
	}
});

<commit_msg>add disabled checking for checkbox<commit_after>/**
A box that shows or hides a check mark when clicked.
The onChange event is fired when it is clicked. Use getValue() to fetch
the checked status.

	{kind: "CheckBox", onChange: "checkboxClicked"}

	checkboxClicked: function(inSender) {
		if (inSender.getValue()) {
			 this.log("I've been checked!");
		}
	}
*/
enyo.kind({
	name: "onyx.Checkbox",
	classes: "onyx-checkbox",
	published: {
		value: false, // event = {value:}
		disabled: false
	},
	events: {
		/**
		The onChange event fires when the user checks or unchecks the checkbox,
		but not when the state is changed programmatically.
		*/
		onChange: ''
	},
	handlers: {
		ondown:"downHandler"
	},
	//* @protected
	create: function() {
		this.inherited(arguments);
		this.valueChanged();
		this.disabledChanged();
	},
	contentChanged: function() {
	},
	disabledChanged: function() {
		this.setAttribute("disabled", this.disabled);
	},
	valueChanged: function() {
		this.addRemoveClass("onyx-checkbox-checked", this.value);
	},
	downHandler: function(inSender, e) {
		if (!this.disabled) {
			this.setValue(!this.value);
			this.doChange({value:this.value});
		}
		return true;
	},
	tap: function(inSender, e) {
		return !this.disabled;
	}
});

<|endoftext|>


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

angular.module('mm.core.course')

/**
 * Section view controller.
 *
 * @module mm.core.course
 * @ngdoc controller
 * @name mmCourseSectionCtrl
 */
.controller('mmCourseSectionCtrl', function($mmCourseDelegate, $mmCourse, $mmUtil, $scope, $stateParams, $translate, $mmSite,
            $mmEvents, $ionicScrollDelegate, $mmCourses, $q, mmCoreEventCompletionModuleViewed, $controller) {

    // Default values are course 1 (front page) and all sections.
    var courseId = $stateParams.cid || 1,
        sectionId = $stateParams.sectionid || -1,
        moduleId = $stateParams.mid;

    $scope.sitehome = (courseId === 1); // Are we visiting the site home?
    $scope.sections = []; // Reset scope.sections, otherwise an error is shown in console with tablet view.

    if (sectionId < 0) {
        // Special scenario, we want all sections.
        if ($scope.sitehome) {
            $scope.title = $translate.instant('mma.frontpage.sitehome');
        } else {
            $scope.title = $translate.instant('mm.course.allsections');
        }
        $scope.summary = null;
        $scope.allSections = true;
    }

    // Convenience function to fetch section(s).
    function loadContent(sectionId) {
        return $mmCourses.getUserCourse(courseId, true).catch(function() {
            // User not enrolled in the course or an error occurred, ignore the error.
        }).then(function(course) {
            var promise;
            if (course && course.enablecompletion === false) {
                promise = $q.when([]); // Completion not enabled, return empty array.
            } else {
                promise = $mmCourse.getActivitiesCompletionStatus(courseId).catch(function() {
                    return []; // If fail, return empty array (as if there was no completion).
                });
            }

            return promise.then(function(statuses) {
                var promise,
                    sectionnumber;

                if (sectionId < 0) {
                    sectionnumber = 0;
                    promise = $mmCourse.getSections(courseId);
                } else {
                    sectionnumber = sectionId;
                    promise = $mmCourse.getSection(courseId, sectionId).then(function(section) {
                        $scope.title = section.name;
                        $scope.summary = section.summary;
                        return [section];
                    });
                }

                return promise.then(function(sections) {
                    // For the site home, we need to reverse the order to display first the site home section topic.
                    if ($scope.sitehome) {
                        sections.reverse();
                    }

                    var hasContent = false;

                    angular.forEach(sections, function(section) {
                        if (section.summary != '' || section.modules.length) {
                            hasContent = true;
                        }

                        angular.forEach(section.modules, function(module) {
                            module._controller =
                                    $mmCourseDelegate.getContentHandlerControllerFor(module.modname, module, courseId, section.id);
                            // Check if activity has completions and if it's marked.
                            var status = statuses[module.id];
                            if (typeof status != 'undefined') {
                                module.completionstatus = status;
                            }

                            if (module.id == moduleId) {
                                // This is the module we're looking for. Open it.
                                var scope = $scope.$new();
                                $controller(module._controller, {$scope: scope});
                                if (scope.action) {
                                    scope.action();
                                }
                            }
                        });
                    });

                    $scope.sections = sections;
                    $scope.hasContent = hasContent;

                    // Add log in Moodle.
                    $mmSite.write('core_course_view_course', {
                        courseid: courseId,
                        sectionnumber: sectionnumber
                    });
                }, function(error) {
                    if (error) {
                        $mmUtil.showErrorModal(error);
                    } else {
                        $mmUtil.showErrorModal('mm.course.couldnotloadsectioncontent', true);
                    }
                });
            });
        });
    }

    loadContent(sectionId).finally(function() {
        $scope.sectionLoaded = true;
    });

    $scope.doRefresh = function() {
        $mmCourse.invalidateSections(courseId).finally(function() {
            loadContent(sectionId).finally(function() {
                $scope.$broadcast('scroll.refreshComplete');
            });
        });
    };

    // Refresh list after a completion change since there could be new activities or so.
    function refreshAfterCompletionChange() {
        var scrollView = $ionicScrollDelegate.$getByHandle('mmSectionScroll');
        if (scrollView && scrollView.getScrollPosition()) {
            $scope.loadingPaddingTop = scrollView.getScrollPosition().top;
        }
        $scope.sectionLoaded = false;
        $scope.sections = [];
        loadContent(sectionId).finally(function() {
            $scope.sectionLoaded = true;
            $scope.loadingPaddingTop = 0;
        });
    }

    // Completion changed for at least one module. Invalidate data and re-load it.
    $scope.completionChanged = function() {
        $mmCourse.invalidateSections(courseId).finally(function() {
            refreshAfterCompletionChange();
        });
    };

    // Listen for viewed modules. If an automatic completion module is viewed, refresh the whole list.
    var observer = $mmEvents.on(mmCoreEventCompletionModuleViewed, function(cid) {
        if (cid === courseId) {
            refreshAfterCompletionChange();
        }
    });
    $scope.$on('$destroy', function() {
        if (observer && observer.off) {
            observer.off();
        }
    });
});
<commit_msg>MOBILE-1559 course: Don't send section in view_course<commit_after>// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core.course')

/**
 * Section view controller.
 *
 * @module mm.core.course
 * @ngdoc controller
 * @name mmCourseSectionCtrl
 */
.controller('mmCourseSectionCtrl', function($mmCourseDelegate, $mmCourse, $mmUtil, $scope, $stateParams, $translate, $mmSite,
            $mmEvents, $ionicScrollDelegate, $mmCourses, $q, mmCoreEventCompletionModuleViewed, $controller) {

    // Default values are course 1 (front page) and all sections.
    var courseId = $stateParams.cid || 1,
        sectionId = $stateParams.sectionid || -1,
        moduleId = $stateParams.mid;

    $scope.sitehome = (courseId === 1); // Are we visiting the site home?
    $scope.sections = []; // Reset scope.sections, otherwise an error is shown in console with tablet view.

    if (sectionId < 0) {
        // Special scenario, we want all sections.
        if ($scope.sitehome) {
            $scope.title = $translate.instant('mma.frontpage.sitehome');
        } else {
            $scope.title = $translate.instant('mm.course.allsections');
        }
        $scope.summary = null;
        $scope.allSections = true;
    }

    // Convenience function to fetch section(s).
    function loadContent(sectionId) {
        return $mmCourses.getUserCourse(courseId, true).catch(function() {
            // User not enrolled in the course or an error occurred, ignore the error.
        }).then(function(course) {
            var promise;
            if (course && course.enablecompletion === false) {
                promise = $q.when([]); // Completion not enabled, return empty array.
            } else {
                promise = $mmCourse.getActivitiesCompletionStatus(courseId).catch(function() {
                    return []; // If fail, return empty array (as if there was no completion).
                });
            }

            return promise.then(function(statuses) {
                var promise,
                    sectionnumber;

                if (sectionId < 0) {
                    sectionnumber = 0;
                    promise = $mmCourse.getSections(courseId);
                } else {
                    sectionnumber = sectionId;
                    promise = $mmCourse.getSection(courseId, sectionId).then(function(section) {
                        $scope.title = section.name;
                        $scope.summary = section.summary;
                        return [section];
                    });
                }

                return promise.then(function(sections) {
                    // For the site home, we need to reverse the order to display first the site home section topic.
                    if ($scope.sitehome) {
                        sections.reverse();
                    }

                    var hasContent = false;

                    angular.forEach(sections, function(section) {
                        if (section.summary != '' || section.modules.length) {
                            hasContent = true;
                        }

                        angular.forEach(section.modules, function(module) {
                            module._controller =
                                    $mmCourseDelegate.getContentHandlerControllerFor(module.modname, module, courseId, section.id);
                            // Check if activity has completions and if it's marked.
                            var status = statuses[module.id];
                            if (typeof status != 'undefined') {
                                module.completionstatus = status;
                            }

                            if (module.id == moduleId) {
                                // This is the module we're looking for. Open it.
                                var scope = $scope.$new();
                                $controller(module._controller, {$scope: scope});
                                if (scope.action) {
                                    scope.action();
                                }
                            }
                        });
                    });

                    $scope.sections = sections;
                    $scope.hasContent = hasContent;

                    // Add log in Moodle.
                    $mmSite.write('core_course_view_course', {
                        courseid: courseId
                    });
                }, function(error) {
                    if (error) {
                        $mmUtil.showErrorModal(error);
                    } else {
                        $mmUtil.showErrorModal('mm.course.couldnotloadsectioncontent', true);
                    }
                });
            });
        });
    }

    loadContent(sectionId).finally(function() {
        $scope.sectionLoaded = true;
    });

    $scope.doRefresh = function() {
        $mmCourse.invalidateSections(courseId).finally(function() {
            loadContent(sectionId).finally(function() {
                $scope.$broadcast('scroll.refreshComplete');
            });
        });
    };

    // Refresh list after a completion change since there could be new activities or so.
    function refreshAfterCompletionChange() {
        var scrollView = $ionicScrollDelegate.$getByHandle('mmSectionScroll');
        if (scrollView && scrollView.getScrollPosition()) {
            $scope.loadingPaddingTop = scrollView.getScrollPosition().top;
        }
        $scope.sectionLoaded = false;
        $scope.sections = [];
        loadContent(sectionId).finally(function() {
            $scope.sectionLoaded = true;
            $scope.loadingPaddingTop = 0;
        });
    }

    // Completion changed for at least one module. Invalidate data and re-load it.
    $scope.completionChanged = function() {
        $mmCourse.invalidateSections(courseId).finally(function() {
            refreshAfterCompletionChange();
        });
    };

    // Listen for viewed modules. If an automatic completion module is viewed, refresh the whole list.
    var observer = $mmEvents.on(mmCoreEventCompletionModuleViewed, function(cid) {
        if (cid === courseId) {
            refreshAfterCompletionChange();
        }
    });
    $scope.$on('$destroy', function() {
        if (observer && observer.off) {
            observer.off();
        }
    });
});
<|endoftext|>


<commit_before>var width = 960,
    height = 600;

var tooltip = d3.select("body")
  .append("div")
  .attr("class", "tooltip")
  .style("opacity", 0);

var projection = d3.geo.mercator()
    .scale(1280)
    .center([ -100.366806, 25.657792]);

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

queue()
    .defer(d3.json, "estados.json")
    .await(ready);

function ready(error, estados) {
  if (error) throw error;

var g = svg.append("g");

var path = g.selectAll("path")
    .data(topojson.feature(estados, estados.objects.states).features)
    .enter().append("path")
    .attr("d", d3.geo.path().projection(projection))
    .attr("fill", "transparent")
    .style("stroke", "#333")
    .attr('opacity', 0)
    .on("mouseover", function(d) {
      tooltip.transition()
        .duration(200)
        .style("opacity", .9);
      tooltip.html("" + d.properties.state_name + "")
        .style("left", (d3.event.pageX + 5) + "px")
        .style("top", (d3.event.pageY - 28) + "px");
    })
    .on("mouseout", function(d) {
      tooltip.transition()
        .duration(500)
        .style("opacity", 0);
    });

    path.transition()
    .delay(10)
    .duration(1250)
    .attr('opacity', 1);

}

<commit_msg>Added function to return domain, to get percent migration and create buckets<commit_after>var width = 960,
    height = 600;

var tooltip = d3.select("body")
  .append("div")
  .attr("class", "tooltip")
  .style("opacity", 0);

var rangesColors = [
    ["#ffffff","#ffe4b2", "#ffc04c", "#ffa500","#ff2500","#ff0000"],
    ["#ffffff", "#ffc04c","#ffa500", "#ff0000"],
    ["#ffffff","#ff0000"]
];

function getDomain() {
    var min, max;
    var len = inmigration_data.length;
    var percent = 0;
    for (var i = 0; i < len; i++) {
        percent = ((inmigration_data[i].pobindi1990* 1.0) / inmigration_data[i].tpobtot1990) * 100;
        if (typeof max === 'undefined'){
            max = percent;
            continue;
        }
        if (typeof min === 'undefined'){
            min = percent;
            continue;
        }

        if (percent > max) {
            max = percent;
        }else{
            if(percent < min){
                min = percent;
            }
        }
    }
    return [min,max];
}

function createBucketDomain(domain,numberBuckets ) {
    var min, max, bucket = [];
    min = domain[0];
    max = domain[1];
    if (numberBuckets === 2) {
        return domain;
    }
    bucket.push(min);
    var difference = ((max-min)*1.0)/(numberBuckets);
    var bucketSum = min;
    for (var i = 1; i < numberBuckets; i++) {
        bucketSum+= difference;
        bucket.push(bucketSum);
    }
    bucket.push(max);
    return bucket;
}

function createBucketColors(numberBuckets){
    switch (numberBuckets){
        case 3:{
            return rangesColors[1];
        }
        case 5: {
            return rangesColors[0]
        }
        default: return rangesColors[2];
    }
}

var nBuckets = 5;

var color = d3.scale.linear().range(createBucketColors(nBuckets)).domain(createBucketDomain(getDomain(),nBuckets));

var projection = d3.geo.mercator()
    .scale(1280)
    .center([ -100.366806, 25.657792]);

var path = d3.geo.path()
    .projection(projection);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

queue()
    .defer(d3.json, "estados.json")
    .await(ready);

function getMigrationPercent1990 (state_code) {
    var inmigration = inmigration_data[state_code-1];
    var percent = ((inmigration.pobindi1990* 1.0) / inmigration.tpobtot1990) * 100;
    console.log(percent)
    return percent;
}

function ready(error, estados) {
  if (error) throw error;

var g = svg.append("g");

var path = g.selectAll("path")
    .data(topojson.feature(estados, estados.objects.states).features)
    .enter().append("path")
    .attr("d", d3.geo.path().projection(projection))
    .attr("fill", function (d) {
        return color( getMigrationPercent1990(d.properties.state_code));
    })
    .style("stroke", "#333")
    .attr('opacity', 0)
    .on("mouseover", function(d) {
      tooltip.transition()
        .duration(200)
        .style("opacity", .9);
      tooltip.html("" + d.properties.state_name +"
 Porcentaje de inmigrantes: "+ getMigrationPercent1990(d.properties.state_code).toFixed(2)+ "%")
        .style("left", (d3.event.pageX + 5) + "px")
        .style("top", (d3.event.pageY - 28) + "px");
    })
    .on("mouseout", function(d) {
      tooltip.transition()
        .duration(500)
        .style("opacity", 0);
    });

    path.transition()
    .delay(10)
    .duration(1250)
    .attr('opacity', 1);

}

<|endoftext|>


<commit_before>export default {
  /**
   * 检测json是否合法
   */
  validateJson(str) {
    try {
      return !!JSON.parse(str);
    } catch (e) {
      return false;
    }
  },

  /**
   * 检测xml和html是否合法
   */
  validateXml(str) {
    try {
      if (typeof DOMParser !== 'undefined') {
        let parserObj =
          new window.DOMParser()
            .parseFromString(str, 'application/xml')
            .getElementsByTagName('parsererror') || {};
        return parserObj.length === 0;
      } else if (typeof window.ActiveXObject !== 'undefined') {
        let xml = new window.ActiveXObject('Microsoft.XMLDOM');
        xml.async = 'false';
        xml.loadXML(str);
        return xml;
      }
    } catch (e) {
      return false;
    }
  },

  /**
   * 检测yaml是否合法
   */
  //   validateYaml(str) {
  //     try {
  //       console.log('yaml: ', yaml, yaml.safeLoadAll(str));
  //       return !!yaml.safeLoadAll(str);
  //     } catch (e) {
  //       console.log('e: ', e);
  //       return false;
  //     }
  //   },

  /**
   * 检测属性是否正确
   */
  validateProperties(str = '') {
    const reg = /^[^=]+=[^=]+$/;
    return str
      .replace('\n\r', '\n')
      .split('\n')
      .every(_str => reg.test(_str.trim()));
  },

  /**
   * 根据类型验证类型
   */
  validate({ content, type }) {
    let validateObj = {
      json: this.validateJson,
      xml: this.validateXml,
      'text/html': this.validateXml,
      html: this.validateXml,
      properties: this.validateProperties,
    };

    if (!validateObj[type]) {
      return true;
    }

    return validateObj[type](content);
  },
};
<commit_msg>fix #676<commit_after>export default {
  /**
   * 检测json是否合法
   */
  validateJson(str) {
    try {
      return !!JSON.parse(str);
    } catch (e) {
      return false;
    }
  },

  /**
   * 检测xml和html是否合法
   */
  validateXml(str) {
    try {
      if (typeof DOMParser !== 'undefined') {
        let parserObj =
          new window.DOMParser()
            .parseFromString(str, 'application/xml')
            .getElementsByTagName('parsererror') || {};
        return parserObj.length === 0;
      } else if (typeof window.ActiveXObject !== 'undefined') {
        let xml = new window.ActiveXObject('Microsoft.XMLDOM');
        xml.async = 'false';
        xml.loadXML(str);
        return xml;
      }
    } catch (e) {
      return false;
    }
  },

  /**
   * 检测yaml是否合法
   */
  //   validateYaml(str) {
  //     try {
  //       console.log('yaml: ', yaml, yaml.safeLoadAll(str));
  //       return !!yaml.safeLoadAll(str);
  //     } catch (e) {
  //       console.log('e: ', e);
  //       return false;
  //     }
  //   },

  /**
   * 检测属性是否正确
   */
  validateProperties(str = '') {
    const reg = /^[^=]+=.+$/;
    return str
      .replace('\n\r', '\n')
      .split('\n')
      .every(_str => reg.test(_str.trim()));
  },

  /**
   * 根据类型验证类型
   */
  validate({ content, type }) {
    let validateObj = {
      json: this.validateJson,
      xml: this.validateXml,
      'text/html': this.validateXml,
      html: this.validateXml,
      properties: this.validateProperties,
    };

    if (!validateObj[type]) {
      return true;
    }

    return validateObj[type](content);
  },
};
<|endoftext|>


<commit_before>"use strict";

import React from 'react';
import {
  Animated,
  PanResponder,
  TouchableOpacity,
  Image,
} from 'react-native';
import shallowCompare from 'react-addons-shallow-compare';
import _ from 'lodash';
import randomstring from 'random-string';

import Tweens from "../Tweens/Tweens";

class AnimatedSprite extends React.Component {
  constructor (props) {
    super(props);

    this.state = {
      top: new Animated.Value(props.coordinates.top),
      left: new Animated.Value(props.coordinates.left),
      scale: new Animated.Value(props.scale),
      opacity: new Animated.Value(props.opacity),
      width: props.size.width,
      height: props.size.height,
      rotate: props.rotate,
      frameIndex: this.props.animationFrameIndex,
    };

    this.sprite = this.props.sprite;
    this.frameIndex = 0;
    this.defaultAnimationInterval = undefined;
    this.fps = 8;
    this.endValues = undefined;
    // used for panResponder
    this.spriteStyles = {};
    this.panResponder = {};
  }

  componentWillMount () {
    if (this.props.draggable) {
      this.initPanResponder();
    }

    this.tweenablValues = {
      top: this.state.top,
      left: this.state.left,
      scale: this.state.scale,
      opacity: this.state.opacity,
    };
  }

  componentDidMount () {
    this.startAnimation();
    // part of PanResponder and drag behavior
    if (this.spriteComponentRef) {
      this.spriteComponentRef.setNativeProps(this.spriteStyles);
    }
    if (this.props.tweenStart === 'fromMount' && this.props.tweenOptions !== null) {
      this.startTween();
    }
    this.fps = this.props.fps || this.fps;
  }

  componentWillReceiveProps (nextProps) {
    if (this.props.animationFrameIndex !== nextProps.animationFrameIndex) {
      this.startAnimation();
    }
  }

  shouldComponentUpdate (nextProps, nextState) {
     return shallowCompare(this, nextProps, nextState);
  }

  componentWillUnmount () {
    clearInterval(this.defaultAnimationInterval);
  }

  initPanResponder () {
    // note that with PanResponder we setNativeProps for performance reasons,
    // as stated by FB.
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant:(e, gestureState) => {
        this.handlePanResponderGrant(e, gestureState);},
      onPanResponderMove: (e, gestureState) => {
        this.handlePanResponderMove(e, gestureState);},
      onPanResponderRelease: (e, gestureState) => {
        this.handlePanResponderEnd(e, gestureState);},
      onPanResponderTerminate:
        (e, gestureState) => {
        this.handlePanResponderEnd(e, gestureState);},
    });
    // spriteStyles used by PanResponder
    this.previousTop = this.state.top._value;
    this.previousLeft =  this.state.left._value;
    this.spriteStyles = {
      style: {
        left: this._previousLeft,
        top: this._previousTop,
        width: this.state._width,
        height: this.state._height,
      },
    };
  }

  updateNativeStyles () {
    this.spriteComponentRef && this.spriteComponentRef.setNativeProps(this.spriteStyles);
  }

  handleStartShouldSetPanResponder (/*e, gestureState*/) {
    return true;
  }

  handleMoveShouldSetPanResponder (/*e, gestureState*/) {
    return true;
  }

  handlePanResponderGrant (/*e, gestureState*/) {
    // do something on grant
  }

  handlePanResponderMove (e, gestureState) {
    this.spriteStyles.style.left = this.previousLeft + gestureState.dx;
    this.spriteStyles.style.top = this.previousTop + gestureState.dy;
    this.updateNativeStyles();
  }

  handlePanResponderEnd (e, gestureState) {
    // do anything you want onPanResponderRelease
    this.previousLeft += gestureState.dx;
    this.previousTop += gestureState.dy;
    // PanResponder mutates state directly
    this.state.top = this.spriteStyles.style.top;
    this.state.left = this.spriteStyles.style.left;

    if (this.props.currentLocation) {
      this.props.currentLocation(this.spriteStyles.style.left, this.spriteStyles.style.top);
    }
  }

  startAnimation () {
    this.fps = this.props.fps || this.fps;
    this.frameIndex = -1;
    clearInterval(this.defaultAnimationInterval);
    this.defaultAnimationInterval = setInterval(()=>{
      this.frameIndex++;
      if (this.frameIndex > (this.props.animationFrameIndex.length - 1)) {
        this.frameIndex = this.frameIndex - 1;
        if (this.props.loopAnimation) {
            this.frameIndex = 0;
        } else {
          clearInterval(this.defaultAnimationInterval);
          if (this.props.onAnimationFinish) {
             this.props.onAnimationFinish(this.props.spriteUID);
          }
          return;
        }
      }
      this.setState({
        frameIndex: this.props.animationFrameIndex[this.frameIndex]
      });
    }, 1000 / this.fps);
  }

  // notify parent that tween has ended
  tweenCompleted (spriteUID) {
    if (this.props.onTweenFinish) {
      this.props.onTweenFinish(spriteUID);
    }
  }

  // meant to be used from instance of AnimatedSprite. User would invoke
  // this.refs.<refname>.tweenSprite. This allows for programatic contorl
  // of starting tween
  tweenSprite () {
    if (this.props.tweenStart !== 'fromMethod') return 0;
    this.startTween();
  }

  startTween () {
    const tweenOptions = this.props.tweenOptions;
    const tweenType = this.props.tweenOptions.tweenType;
    Tweens[tweenType].start(tweenOptions,
      this.tweenablValues,
      () => this.tweenCompleted(this.props.spriteUID),
    );
  }

  handlePress (e) {
    e.preventDefault();
    if (this.props.onPress) {
      this.props.onPress(this.props.spriteUID);
    }
    if (this.props.tweenStart === 'fromPress') {
      this.startTween();
    }
  }

  stoppedTween (stopValues) {
    this.props.onTweenStopped(stopValues);
  }

  handlePressIn () {
    if (this.props.onPressIn) {
      this.props.onPressIn();
    }

    if (this.props.stopAutoTweenOnPressIn) {
      const tweenType = this.props.tweenOptions.tweenType;
      Tweens[tweenType].stop(this.tweenablValues,
        (stopValues) => this.stoppedTween(stopValues));
    }
  }

  handlePressOut (e) {
    e.preventDefault();
    if (this.props.onPressOut) {
      this.props.onPressOut();
    }
  }

  getStyle () {
    const opacity = !this.props.visible ? new Animated.Value(0) : this.state.opacity;
    const rotateAxes = _.map(this.state.rotate, axis => axis);
    const transform = _.concat([{scale: this.state.scale}], rotateAxes);
    return (
      // TODO: this.props.visible part of hack to what may be a
      // RN bug associated with premiture stopping of Tween and removing
      // The related component
      {
        opacity,
        transform,
        top: this.state.top,
        left: this.state.left,
        width: this.state.width,
        height: this.state.height,
        position: 'absolute',
      }

    );
  }

  render () {
    return (
      <Animated.View
        {...this.panResponder.panHandlers}
        style={this.getStyle()}
        ref={(sprite) => {
          this.spriteComponentRef = sprite;
        }}>
        <TouchableOpacity
          activeOpacity={1.0}
          onPress={(evt) => this.handlePress(evt)}
          onPressIn={(evt) => this.handlePressIn(evt)}
          onPressOut={(evt) => this.handlePressOut(evt)}>
          <Image
            source={this.sprite.frames[this.state.frameIndex]}
            style={{
              width: this.state.width,
              height: this.state.height,
            }}
          />
        </TouchableOpacity>
      </Animated.View>
    );
  }
}

AnimatedSprite.propTypes = {
  sprite: React.PropTypes.object.isRequired,
  coordinates: React.PropTypes.shape({
    top: React.PropTypes.number,
    left: React.PropTypes.number,
  }).isRequired,
  size: React.PropTypes.shape({
    width: React.PropTypes.number,
    height: React.PropTypes.number,
  }).isRequired,
  animationFrameIndex: React.PropTypes.array.isRequired,

  rotate: React.PropTypes.arrayOf(React.PropTypes.object),
  scale: React.PropTypes.number,
  opacity: React.PropTypes.number,
  spriteUID: React.PropTypes.string,
  draggable: React.PropTypes.bool,
  onPress: React.PropTypes.func,
  onPressIn: React.PropTypes.func,
  onPressOut: React.PropTypes.func,
  loopAnimation: React.PropTypes.bool,
  timeSinceMounted: React.PropTypes.func,
  currentLocation: React.PropTypes.func,
  tweenStart: React.PropTypes.oneOf(['fromMount','fromMethod', 'fromPress']),
  // probably should validate tweenOptions, since Tweens.js uses them
  // and expects a certian shape.
  tweenOptions: React.PropTypes.object,
  stopAutoTweenOnPressIn: React.PropTypes.bool,
  onTweenStopped: React.PropTypes.func,
  onTweenFinish: React.PropTypes.func,
  onAnimationFinish: React.PropTypes.func,
  visible: React.PropTypes.bool,
  fps: React.PropTypes.number,
};

AnimatedSprite.defaultProps = {
  draggable: false,
  spriteUID: randomstring({ length: 7 }),
  rotate: [{rotateY: '0deg'}],
  scale: 1,
  opacity: 1,
  fps: 10,
  visible: true,
};

export default AnimatedSprite;
<commit_msg>fix missing method<commit_after>"use strict";

import React from 'react';
import {
  Animated,
  PanResponder,
  TouchableOpacity,
  Image,
} from 'react-native';
import shallowCompare from 'react-addons-shallow-compare';
import _ from 'lodash';
import randomstring from 'random-string';

import Tweens from "../Tweens/Tweens";

class AnimatedSprite extends React.Component {
  constructor (props) {
    super(props);

    this.state = {
      top: new Animated.Value(props.coordinates.top),
      left: new Animated.Value(props.coordinates.left),
      scale: new Animated.Value(props.scale),
      opacity: new Animated.Value(props.opacity),
      width: props.size.width,
      height: props.size.height,
      rotate: props.rotate,
      frameIndex: this.props.animationFrameIndex,
    };

    this.sprite = this.props.sprite;
    this.frameIndex = 0;
    this.defaultAnimationInterval = undefined;
    this.fps = 8;
    this.endValues = undefined;
    // used for panResponder
    this.spriteStyles = {};
    this.panResponder = {};
  }

  componentWillMount () {
    if (this.props.draggable) {
      this.initPanResponder();
    }

    this.tweenablValues = {
      top: this.state.top,
      left: this.state.left,
      scale: this.state.scale,
      opacity: this.state.opacity,
    };
  }

  componentDidMount () {
    this.startAnimation();
    // part of PanResponder and drag behavior
    if (this.spriteComponentRef) {
      this.spriteComponentRef.setNativeProps(this.spriteStyles);
    }
    if (this.props.tweenStart === 'fromMount' && this.props.tweenOptions !== null) {
      this.startTween();
    }
    this.fps = this.props.fps || this.fps;
  }

  componentWillReceiveProps (nextProps) {
    if (this.props.animationFrameIndex !== nextProps.animationFrameIndex) {
      this.startAnimation();
    }
  }

  shouldComponentUpdate (nextProps, nextState) {
     return shallowCompare(this, nextProps, nextState);
  }

  componentWillUnmount () {
    clearInterval(this.defaultAnimationInterval);
  }

  initPanResponder () {
    // note that with PanResponder we setNativeProps for performance reasons,
    // as stated by FB.
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant:(e, gestureState) => {
        this.handlePanResponderGrant(e, gestureState);},
      onPanResponderMove: (e, gestureState) => {
        this.handlePanResponderMove(e, gestureState);},
      onPanResponderRelease: (e, gestureState) => {
        this.handlePanResponderEnd(e, gestureState);},
      onPanResponderTerminate:
        (e, gestureState) => {
        this.handlePanResponderEnd(e, gestureState);},
    });
    // spriteStyles used by PanResponder
    this.previousTop = this.state.top._value;
    this.previousLeft =  this.state.left._value;
    this.spriteStyles = {
      style: {
        left: this._previousLeft,
        top: this._previousTop,
        width: this.state._width,
        height: this.state._height,
      },
    };
  }

  updateNativeStyles () {
    this.spriteComponentRef && this.spriteComponentRef.setNativeProps(this.spriteStyles);
  }

  handleStartShouldSetPanResponder (/*e, gestureState*/) {
    return true;
  }

  handleMoveShouldSetPanResponder (/*e, gestureState*/) {
    return true;
  }

  handlePanResponderGrant (/*e, gestureState*/) {
    // do something on grant
  }

  handlePanResponderMove (e, gestureState) {
    this.spriteStyles.style.left = this.previousLeft + gestureState.dx;
    this.spriteStyles.style.top = this.previousTop + gestureState.dy;
    this.updateNativeStyles();
  }

  handlePanResponderEnd (e, gestureState) {
    // do anything you want onPanResponderRelease
    this.previousLeft += gestureState.dx;
    this.previousTop += gestureState.dy;
    // PanResponder mutates state directly
    this.state.top = this.spriteStyles.style.top;
    this.state.left = this.spriteStyles.style.left;

    if (this.props.currentLocation) {
      this.props.currentLocation(this.spriteStyles.style.left, this.spriteStyles.style.top);
    }
  }

  startAnimation () {
    this.fps = this.props.fps || this.fps;
    this.frameIndex = -1;
    clearInterval(this.defaultAnimationInterval);
    this.defaultAnimationInterval = setInterval(()=>{
      this.frameIndex++;
      if (this.frameIndex > (this.props.animationFrameIndex.length - 1)) {
        this.frameIndex = this.frameIndex - 1;
        if (this.props.loopAnimation) {
            this.frameIndex = 0;
        } else {
          clearInterval(this.defaultAnimationInterval);
          if (this.props.onAnimationFinish) {
             this.props.onAnimationFinish(this.props.spriteUID);
          }
          return;
        }
      }
      this.setState({
        frameIndex: this.props.animationFrameIndex[this.frameIndex]
      });
    }, 1000 / this.fps);
  }

  // notify parent that tween has ended
  tweenCompleted (spriteUID) {
    if (this.props.onTweenFinish) {
      this.props.onTweenFinish(spriteUID);
    }
  }

  // meant to be used from instance of AnimatedSprite. User would invoke
  // this.refs.<refname>.tweenSprite. This allows for programatic contorl
  // of starting tween
  tweenSprite () {
    if (this.props.tweenStart !== 'fromMethod') return 0;
    this.startTween();
  }

  startTween () {
    const tweenOptions = this.props.tweenOptions;
    const tweenType = this.props.tweenOptions.tweenType;
    Tweens[tweenType].start(tweenOptions,
      this.tweenablValues,
      () => this.tweenCompleted(this.props.spriteUID),
    );
  }

  getCoordinates () {
    return { top: this.state.top._value, left: this.state.left._value};
  }

  handlePress (e) {
    e.preventDefault();
    if (this.props.onPress) {
      this.props.onPress(this.props.spriteUID);
    }
    if (this.props.tweenStart === 'fromPress') {
      this.startTween();
    }
  }

  stoppedTween (stopValues) {
    this.props.onTweenStopped(stopValues);
  }

  handlePressIn () {
    if (this.props.onPressIn) {
      this.props.onPressIn();
    }

    if (this.props.stopAutoTweenOnPressIn) {
      const tweenType = this.props.tweenOptions.tweenType;
      Tweens[tweenType].stop(this.tweenablValues,
        (stopValues) => this.stoppedTween(stopValues));
    }
  }

  handlePressOut (e) {
    e.preventDefault();
    if (this.props.onPressOut) {
      this.props.onPressOut();
    }
  }

  getStyle () {
    const opacity = !this.props.visible ? new Animated.Value(0) : this.state.opacity;
    const rotateAxes = _.map(this.state.rotate, axis => axis);
    const transform = _.concat([{scale: this.state.scale}], rotateAxes);
    return (
      // TODO: this.props.visible part of hack to what may be a
      // RN bug associated with premiture stopping of Tween and removing
      // The related component
      {
        opacity,
        transform,
        top: this.state.top,
        left: this.state.left,
        width: this.state.width,
        height: this.state.height,
        position: 'absolute',
      }

    );
  }

  render () {
    return (
      <Animated.View
        {...this.panResponder.panHandlers}
        style={this.getStyle()}
        ref={(sprite) => {
          this.spriteComponentRef = sprite;
        }}>
        <TouchableOpacity
          activeOpacity={1.0}
          onPress={(evt) => this.handlePress(evt)}
          onPressIn={(evt) => this.handlePressIn(evt)}
          onPressOut={(evt) => this.handlePressOut(evt)}>
          <Image
            source={this.sprite.frames[this.state.frameIndex]}
            style={{
              width: this.state.width,
              height: this.state.height,
            }}
          />
        </TouchableOpacity>
      </Animated.View>
    );
  }
}

AnimatedSprite.propTypes = {
  sprite: React.PropTypes.object.isRequired,
  coordinates: React.PropTypes.shape({
    top: React.PropTypes.number,
    left: React.PropTypes.number,
  }).isRequired,
  size: React.PropTypes.shape({
    width: React.PropTypes.number,
    height: React.PropTypes.number,
  }).isRequired,
  animationFrameIndex: React.PropTypes.array.isRequired,

  rotate: React.PropTypes.arrayOf(React.PropTypes.object),
  scale: React.PropTypes.number,
  opacity: React.PropTypes.number,
  spriteUID: React.PropTypes.string,
  draggable: React.PropTypes.bool,
  onPress: React.PropTypes.func,
  onPressIn: React.PropTypes.func,
  onPressOut: React.PropTypes.func,
  loopAnimation: React.PropTypes.bool,
  timeSinceMounted: React.PropTypes.func,
  currentLocation: React.PropTypes.func,
  tweenStart: React.PropTypes.oneOf(['fromMount','fromMethod', 'fromPress']),
  // probably should validate tweenOptions, since Tweens.js uses them
  // and expects a certian shape.
  tweenOptions: React.PropTypes.object,
  stopAutoTweenOnPressIn: React.PropTypes.bool,
  onTweenStopped: React.PropTypes.func,
  onTweenFinish: React.PropTypes.func,
  onAnimationFinish: React.PropTypes.func,
  visible: React.PropTypes.bool,
  fps: React.PropTypes.number,
};

AnimatedSprite.defaultProps = {
  draggable: false,
  spriteUID: randomstring({ length: 7 }),
  rotate: [{rotateY: '0deg'}],
  scale: 1,
  opacity: 1,
  fps: 10,
  visible: true,
};

export default AnimatedSprite;
<|endoftext|>


<commit_before>module.exports = function($http, $q) {
    var value = "Hey I'm a value and I'm being returned from a factory!";

    var getEmojis = function() {
        var emojis = ['😄','😃','😀','😊','😉','😍','😘','😚','😗','😙','😜','😝','😛','😳','😁','😔','😌','😒','😞','😣','😢','😂','😭','😪','😥','😰','😅','😓','😩','😫','😨','😱','😠','😡','😤','😖','😆','😋','😷','😎','😴','😵','😲','😟','😦','😧','😈','👿','😮','😬','😐','😕','😯','😶','😇','😏','😑','👲','👳','👮','👷','💂','👶','👦','👧','👨','👩','👴','👵','👱','👼','👸','😺','😸','😻','😽','😼','🙀','😿','😹','😾','👹','👺','🙈','🙉','🙊','💀','👽','💩','🔥','✨','🌟','💫','💥','💢','💦','💧','💤','💨','👂','👀','👃','👅','👄','👍','👎','👌','👊','✊','✌','👋','✋','🖖','👐','👆','👇','👉','👈','🙌','🙏','☝','👏','💪','🚶','🏃','💃','👫','👪','👬','👭','💏','💑','👯','🙆','🙅','💁','🙋','💆','💇','💅','👰','🙎','🙍','🙇','🎩','👑','👒','👟','👞','👡','👠','👢','👕','👔','👚','👗','🎽','👖','👘','👙','💼','👜','👝','👛','👓','🎀','🌂','💄','💛','💙','💜','💚','❤','💔','💗','💓','💕','💖','💞','💘','💌','💋','💍','💎','👤','👥','💬','👣','💭','🐶','🐺','🐱','🐭','🐹','🐰','🐸','🐯','🐨','🐻','🐷','🐽','🐮','🐗','🐵','🐒','🐴','🐑','🐘','🐼','🐧','🐦','🐤','🐥','🐣','🐔','🐍','🐢','🐛','🐝','🐜','🐞','🐌','🐙','🐚','🐠','🐟','🐬','🐳','🐋','🐄','🐏','🐀','🐃','🐅','🐇','🐉','🐎','🐐','🐓','🐕','🐖','🐁','🐂','🐲','🐡','🐊','🐫','🐪','🐆','🐈','🐩','🐾','💐','🌸','🌷','🍀','🌹','🌻','🌺','🍁','🍃','🍂','🌿','🌾','🍄','🌵','🌴','🌲','🌳','🌰','🌱','🌼','🌐','🌞','🌝','🌚','🌑','🌒','🌓','🌔','🌕','🌖','🌗','🌘','🌜','🌛','🌙','🌍','🌎','🌏','🌋','🌌','🌠','⭐','☀','⛅','☁','⚡','☔','❄','⛄','🌀','🌁','🌈','🌊','🎍','💝','🎎','🎒','🎓','🎏','🎆','🎇','🎐','🎑','🎃','👻','🎅','🎄','🎁','🎋','🎉','🎊','🎈','🎌','🔮','🎥','📷','📹','📼','💿','📀','💽','💾','💻','📱','☎','📞','📟','📠','📡','📺','📻','🔊','🔉','🔈','🔇','🔔','🔕','📢','📣','⏳','⌛','⏰','⌚','🔓','🔒','🔏','🔐','🔑','🔎','💡','🔦','🔆','🔅','🔌','🔋','🔍','🛁','🛀','🚿','🚽','🔧','🔩','🔨','🚪','🚬','💣','🔫','🔪','💊','💉','💰','💴','💵','💷','💶','💳','💸','📲','📧','📥','📤','✉','📩','📨','📯','📫','📪','📬','📭','📮','📦','📝','📄','📃','📑','📊','📈','📉','📜','📋','📅','📆','📇','📁','📂','✂','📌','📎','✒','✏','📏','📐','📕','📗','📘','📙','📓','📔','📒','📚','📖','🔖','📛','🔬','🔭','📰','🎨','🎬','🎤','🎧','🎼','🎵','🎶','🎹','🎻','🎺','🎷','🎸','👾','🎮','🃏','🎴','🀄','🎲','🎯','🏈','🏀','⚽','⚾','🎾','🎱','🏉','🎳','⛳','🚵','🚴','🏁','🏇','🏆','🎿','🏂','🏊','🏄','🎣','☕','🍵','🍶','🍼','🍺','🍻','🍸','🍹','🍷','🍴','🍕','🍔','🍟','🍗','🍖','🍝','🍛','🍤','🍱','🍣','🍥','🍙','🍘','🍚','🍜','🍲','🍢','🍡','🍳','🍞','🍩','🍮','🍦','🍨','🍧','🎂','🍰','🍪','🍫','🍬','🍭','🍯','🍎','🍏','🍊','🍋','🍒','🍇','🍉','🍓','🍑','🍈','🍌','🍐','🍍','🍠','🍆','🍅','🌽','🏠','🏡','🏫','🏢','🏣','🏥','🏦','🏪','🏩','🏨','💒','⛪','🏬','🏤','🌇','🌆','🏯','🏰','⛺','🏭','🗼','🗾','🗻','🌄','🌅','🌃','🗽','🌉','🎠','🎡','⛲','🎢','🚢','⛵','🚤','🚣','⚓','🚀','✈','💺','🚁','🚂','🚊','🚉','🚞','🚆','🚄','🚅','🚈','🚇','🚝','🚋','🚃','🚎','🚌','🚍','🚙','🚘','🚗','🚕','🚖','🚛','🚚','🚨','🚓','🚔','🚒','🚑','🚐','🚲','🚡','🚟','🚠','🚜','💈','🚏','🎫','🚦','🚥','⚠','🚧','🔰','⛽','🏮','🎰','♨','🗿','🎪','🎭','📍','🚩'];

        return emojis
    }

    var getBackgrounds = function() {
        var deferred = $q.defer();
        var url = 'http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC';

        $http.get(url).then(function (res) {
            deferred.resolve(res.data);
        });

        return deferred.promise;

    }

    var getQuotes = function() {
        var quotes = [
            {text: 'Wut'},
            {text: 'techCrunchDisrupt'},
            {text: 'shipIt'},
            {text: 'mo so lo'},
            {text: '@clintonhalpin'},
            {text: '@iamnickvolpe'},
            {text: '@chrisnager'},
            {text: 'Jaaaavascript'},
            {text: 'Is your machine on'},
            {text: 'Your Face'}
        ];

        return quotes
    }

    var getSongs = function() {
        var songs = [
            {
                title: 'Jeopardy Theme',
                url: 'http://www.youtube.com/embed/0Wi8Fv0AJA4'
            },
            {
                title: 'Journey: Faithfully',
                url: 'http://www.youtube.com/embed/OMD8hBsA-RI'
            },
            {
                title: 'Van Halen: Panama',
                url: 'http://www.youtube.com/embed/w-NshzYK9y0',
            },
            {
                title: 'Jay-Z: Empire State of Mind',
                url: 'http://www.youtube.com/embed/Iv_1LVS3BdE',
            },
            {
                title: 'Gin and juice: Snoop Doggy Dogg',
                url: 'http://www.youtube.com/embed/0Cxr1-b6Xkc',
            },
            {
                title: 'Culture Club: Karma Chameleon',
                url: 'http://www.youtube.com/embed/JmcA9LIIXWw',
            },
            {
                title: 'Nicki Minaj: Starships',
                url: 'http://www.youtube.com/embed/SeIJmciN8mo',
            },
            {
                title: 'K-Ci & JoJo: All My Life',
                url: 'http://www.youtube.com/embed/DXvMT_mVbqw',
            },
            {
                title: 'Blink-182: All the Small Things',
                url: 'http://www.youtube.com/embed/9Ht5RZpzPqw',
            }
        ];

        return songs
    }

    var update = function(req) {
        value = req
        return req
    }

    var get = function(limit) {
        if(limit) {
            console.log('TODO: Request only on of the peices of data')
        }
        return {
            quotes: getQuotes(),
            emojis: getEmojis(),
            backgrounds: getBackgrounds(),
            songs: getSongs()
        }
    }

    return {
        get : get,
        update: update
    }
}
<commit_msg>Update hashtag<commit_after>module.exports = function($http, $q) {
    var value = "Hey I'm a value and I'm being returned from a factory!";

    var getEmojis = function() {
        var emojis = ['😄','😃','😀','😊','😉','😍','😘','😚','😗','😙','😜','😝','😛','😳','😁','😔','😌','😒','😞','😣','😢','😂','😭','😪','😥','😰','😅','😓','😩','😫','😨','😱','😠','😡','😤','😖','😆','😋','😷','😎','😴','😵','😲','😟','😦','😧','😈','👿','😮','😬','😐','😕','😯','😶','😇','😏','😑','👲','👳','👮','👷','💂','👶','👦','👧','👨','👩','👴','👵','👱','👼','👸','😺','😸','😻','😽','😼','🙀','😿','😹','😾','👹','👺','🙈','🙉','🙊','💀','👽','💩','🔥','✨','🌟','💫','💥','💢','💦','💧','💤','💨','👂','👀','👃','👅','👄','👍','👎','👌','👊','✊','✌','👋','✋','🖖','👐','👆','👇','👉','👈','🙌','🙏','☝','👏','💪','🚶','🏃','💃','👫','👪','👬','👭','💏','💑','👯','🙆','🙅','💁','🙋','💆','💇','💅','👰','🙎','🙍','🙇','🎩','👑','👒','👟','👞','👡','👠','👢','👕','👔','👚','👗','🎽','👖','👘','👙','💼','👜','👝','👛','👓','🎀','🌂','💄','💛','💙','💜','💚','❤','💔','💗','💓','💕','💖','💞','💘','💌','💋','💍','💎','👤','👥','💬','👣','💭','🐶','🐺','🐱','🐭','🐹','🐰','🐸','🐯','🐨','🐻','🐷','🐽','🐮','🐗','🐵','🐒','🐴','🐑','🐘','🐼','🐧','🐦','🐤','🐥','🐣','🐔','🐍','🐢','🐛','🐝','🐜','🐞','🐌','🐙','🐚','🐠','🐟','🐬','🐳','🐋','🐄','🐏','🐀','🐃','🐅','🐇','🐉','🐎','🐐','🐓','🐕','🐖','🐁','🐂','🐲','🐡','🐊','🐫','🐪','🐆','🐈','🐩','🐾','💐','🌸','🌷','🍀','🌹','🌻','🌺','🍁','🍃','🍂','🌿','🌾','🍄','🌵','🌴','🌲','🌳','🌰','🌱','🌼','🌐','🌞','🌝','🌚','🌑','🌒','🌓','🌔','🌕','🌖','🌗','🌘','🌜','🌛','🌙','🌍','🌎','🌏','🌋','🌌','🌠','⭐','☀','⛅','☁','⚡','☔','❄','⛄','🌀','🌁','🌈','🌊','🎍','💝','🎎','🎒','🎓','🎏','🎆','🎇','🎐','🎑','🎃','👻','🎅','🎄','🎁','🎋','🎉','🎊','🎈','🎌','🔮','🎥','📷','📹','📼','💿','📀','💽','💾','💻','📱','☎','📞','📟','📠','📡','📺','📻','🔊','🔉','🔈','🔇','🔔','🔕','📢','📣','⏳','⌛','⏰','⌚','🔓','🔒','🔏','🔐','🔑','🔎','💡','🔦','🔆','🔅','🔌','🔋','🔍','🛁','🛀','🚿','🚽','🔧','🔩','🔨','🚪','🚬','💣','🔫','🔪','💊','💉','💰','💴','💵','💷','💶','💳','💸','📲','📧','📥','📤','✉','📩','📨','📯','📫','📪','📬','📭','📮','📦','📝','📄','📃','📑','📊','📈','📉','📜','📋','📅','📆','📇','📁','📂','✂','📌','📎','✒','✏','📏','📐','📕','📗','📘','📙','📓','📔','📒','📚','📖','🔖','📛','🔬','🔭','📰','🎨','🎬','🎤','🎧','🎼','🎵','🎶','🎹','🎻','🎺','🎷','🎸','👾','🎮','🃏','🎴','🀄','🎲','🎯','🏈','🏀','⚽','⚾','🎾','🎱','🏉','🎳','⛳','🚵','🚴','🏁','🏇','🏆','🎿','🏂','🏊','🏄','🎣','☕','🍵','🍶','🍼','🍺','🍻','🍸','🍹','🍷','🍴','🍕','🍔','🍟','🍗','🍖','🍝','🍛','🍤','🍱','🍣','🍥','🍙','🍘','🍚','🍜','🍲','🍢','🍡','🍳','🍞','🍩','🍮','🍦','🍨','🍧','🎂','🍰','🍪','🍫','🍬','🍭','🍯','🍎','🍏','🍊','🍋','🍒','🍇','🍉','🍓','🍑','🍈','🍌','🍐','🍍','🍠','🍆','🍅','🌽','🏠','🏡','🏫','🏢','🏣','🏥','🏦','🏪','🏩','🏨','💒','⛪','🏬','🏤','🌇','🌆','🏯','🏰','⛺','🏭','🗼','🗾','🗻','🌄','🌅','🌃','🗽','🌉','🎠','🎡','⛲','🎢','🚢','⛵','🚤','🚣','⚓','🚀','✈','💺','🚁','🚂','🚊','🚉','🚞','🚆','🚄','🚅','🚈','🚇','🚝','🚋','🚃','🚎','🚌','🚍','🚙','🚘','🚗','🚕','🚖','🚛','🚚','🚨','🚓','🚔','🚒','🚑','🚐','🚲','🚡','🚟','🚠','🚜','💈','🚏','🎫','🚦','🚥','⚠','🚧','🔰','⛽','🏮','🎰','♨','🗿','🎪','🎭','📍','🚩'];

        return emojis
    }

    var getBackgrounds = function() {
        var deferred = $q.defer();
        var url = 'http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC';

        $http.get(url).then(function (res) {
            deferred.resolve(res.data);
        });

        return deferred.promise;

    }

    var getQuotes = function() {
        var quotes = [
            {text: 'Wut'},
            {text: 'HackDisrupt'},
            {text: 'techCrunchDisrupt'},
            {text: 'shipIt'},
            {text: 'mo so lo'},
            {text: '@clintonhalpin'},
            {text: '@iamnickvolpe'},
            {text: '@chrisnager'},
            {text: 'Jaaaavascript'},
            {text: 'Is your machine on'},
            {text: 'Your Face'}
        ];

        return quotes
    }

    var getSongs = function() {
        var songs = [
            {
                title: 'Jeopardy Theme',
                url: 'http://www.youtube.com/embed/0Wi8Fv0AJA4'
            },
            {
                title: 'Journey: Faithfully',
                url: 'http://www.youtube.com/embed/OMD8hBsA-RI'
            },
            {
                title: 'Van Halen: Panama',
                url: 'http://www.youtube.com/embed/w-NshzYK9y0',
            },
            {
                title: 'Jay-Z: Empire State of Mind',
                url: 'http://www.youtube.com/embed/Iv_1LVS3BdE',
            },
            {
                title: 'Gin and juice: Snoop Doggy Dogg',
                url: 'http://www.youtube.com/embed/0Cxr1-b6Xkc',
            },
            {
                title: 'Culture Club: Karma Chameleon',
                url: 'http://www.youtube.com/embed/JmcA9LIIXWw',
            },
            {
                title: 'Nicki Minaj: Starships',
                url: 'http://www.youtube.com/embed/SeIJmciN8mo',
            },
            {
                title: 'K-Ci & JoJo: All My Life',
                url: 'http://www.youtube.com/embed/DXvMT_mVbqw',
            },
            {
                title: 'Blink-182: All the Small Things',
                url: 'http://www.youtube.com/embed/9Ht5RZpzPqw',
            }
        ];

        return songs
    }

    var update = function(req) {
        value = req
        return req
    }

    var get = function(limit) {
        if(limit) {
            console.log('TODO: Request only on of the peices of data')
        }
        return {
            quotes: getQuotes(),
            emojis: getEmojis(),
            backgrounds: getBackgrounds(),
            songs: getSongs()
        }
    }

    return {
        get : get,
        update: update
    }
}
<|endoftext|>


<commit_before>import React, {
  Component,
  PropTypes
} from 'react';
import {
  buildClientSchema,
  parse,
  print,
  introspectionQuery,
  GraphQLSchema
} from 'graphql';
import fetch from 'isomorphic-fetch';
import GraphiQL from 'graphiql';
import { autobind } from 'core-decorators';
import styles from './styles.js';
import { getParameterByName } from  '../helpers/getParameters';
import TopBar from './TopBar';
import GenerateMutation from './GenerateMutation';
import GetSetQuery from './GetSetQuery';
import SaveLoadQuery from './SaveLoadQuery';
import EditHeaderModal from './EditHeaderModal';

export default class CustomGraphiQL extends Component {
  static propTypes = {
    fetcher: PropTypes.func,
    schema: PropTypes.instanceOf(GraphQLSchema),
    currentURL: PropTypes.string,
    query: PropTypes.string,
    variables: PropTypes.string,
    operationName: PropTypes.string,
    response: PropTypes.string,
    storage: PropTypes.shape({
      getItem: PropTypes.func,
      setItem: PropTypes.func
    }),
    defaultQuery: PropTypes.string,
    onEditQuery: PropTypes.func,
    onEditVariables: PropTypes.func,
    onEditOperationName: PropTypes.func,
    onToggleDocs: PropTypes.func,
    getDefaultFieldNames: PropTypes.func
  };

  constructor(props) {
    super(props);

    // Cache the storage instance
    this.storage = props.storage || window.localStorage;

    // Determine the initial url.
    const currentURL = this.storageGet('currentURL') || props.currentURL;

    // Determine the initial query to display.
    const query = props.query || this.storageGet(`${currentURL}:query`) || undefined;

    // Determine the initial variables to display.
    const variables = props.variables || this.storageGet(`${currentURL}:variables`);

    const headers = this.storageGet('headers') ? JSON.parse(this.storageGet('headers')) : {};

    // Initialize state
    this.state = {
      schema: props.schema || null,
      query,
      variables,
      response: props.response,
      graphQLEndpoint: currentURL,
      schemaFetchError: '',
      headers,
    };
  }

  componentDidMount() {
    const currentURL = this.state.graphQLEndpoint;
    if (!currentURL) {
      return;
    }
    this.fetchGraphQLSchema(currentURL);
  }

  @autobind
  storageGet(name) {
    return this.storage && this.storage.getItem('cgraphiql:' + name);
  }

  @autobind
  storageSet(name, value) {
    this.storage && this.storage.setItem('cgraphiql:' + name, value);
  }

  @autobind
  getCurrentResponse() {
    return this.state.response;
  }

  @autobind
  setSavedQueries(savedQueriesString) {
    const currentURL = this.state.graphQLEndpoint;
    this.storageSet(`${currentURL}:queries`, savedQueriesString);
  }

  @autobind
  getSavedQueries() {
    const currentURL = this.state.graphQLEndpoint;
    const currentURLQueriesString = this.storageGet(`${currentURL}:queries`) || '{}';
    return JSON.parse(currentURLQueriesString);
  }

  @autobind
  setQueryFromString(queryStringInput) {
    if (!queryStringInput) {
      this.updateQueryVariablesResponse('', '');
      return;
    }

    const queryString = getParameterByName('query', queryStringInput) || '{}';
    const variablesString = getParameterByName('variables', queryStringInput) || 'null';
    const responseString = getParameterByName('response', queryStringInput) || this.state.response;
    const url = new URL(queryStringInput);
    const graphQLEndpoint = url.origin + url.pathname;
    if (graphQLEndpoint !== this.state.graphQLEndpoint) {
      this.fetchGraphQLSchema(graphQLEndpoint);
      this.state.graphQLEndpoint = graphQLEndpoint;
    }

    this.updateQueryVariablesResponse(queryString, variablesString, responseString);
  }

  @autobind
  updateQueryVariablesResponse(queryString, variablesString, responseString) {
    const currentURL = this.state.graphQLEndpoint;
    this.storageSet(`${currentURL}:query`, queryString);
    this.storageSet(`${currentURL}:variables`, variablesString);
    this.setState({
      query: queryString,
      variables: variablesString,
      response: responseString || this.state.response
    });
  }

  @autobind
  async fetchGraphQLSchema(url) {
    try {
      const headers = this.state.headers;
      const graphQLParams = { query: introspectionQuery };
      const response = await fetch(url, {
        method: 'post',
        withCredentials: false,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        body: JSON.stringify(graphQLParams)
      });

      // GET method
      // const response = await fetch(`${url}?query=${encodeURIComponent(graphQLParams.query)}}&variables=${encodeURIComponent('{}')}`, { method: 'get' });

      const result = await response.json();
      if (result.errors) {
        throw new Error(JSON.stringify(result.errors));
      }
      const schema = buildClientSchema(result.data);
      this.storageSet('currentURL', url);
      this.setState({
        schema,
        graphQLEndpoint: url,
        schemaFetchError: '',
        response: 'Schema fetched',
      });
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('Error in fetching GraphQL schema', error);
      this.setState({
        schemaFetchError: error.toString(),
        response: error.toString(),
      });
    }
  }

  @autobind
  async graphQLFetcher(graphQLParams) {
    try {
      const headers = this.state.headers;
      const graphQLEndpoint = this.state.graphQLEndpoint;
      if (!graphQLEndpoint) {
        console.warn('Please set a GraphQL endpoint');
        return null;
      }
      const response = await fetch(graphQLEndpoint, {
        method: 'post',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          ...headers
        },
        body: JSON.stringify(graphQLParams),
        credentials: 'include',
      });
      const result = await response.json();
      this.state.response = JSON.stringify(result, null, 2);
      return result;
    } catch (error) {
      const result = {
        error: error.toString()
      };
      this.state.response = JSON.stringify(result, null, 2);
      return result;
    }
  }

  @autobind
  updateHeaders(newHeaders) {
    this.storageSet('headers', JSON.stringify(newHeaders));
    this.setState({
      headers: newHeaders,
      editHeaderModalVisible: false,
    });
  }

  @autobind
  hideEditHeaderModal() {
    this.setState({
      editHeaderModalVisible: false
    });
  }

  @autobind
  showEditHeaderModal() {
    this.setState({
      editHeaderModalVisible: true
    });
  }

  @autobind
  onEditQuery(queryString) {
    this.setState({
      query: queryString
    });
    this.props.onEditQuery && this.onEditQuery(queryString);
    const currentURL = this.state.graphQLEndpoint;
    if (!currentURL) {
      return;
    }

    this.storageSet(`${currentURL}:query`, queryString);
  }

  @autobind
  onEditVariables(variablesString) {
    this.setState({
      variables: variablesString
    });
    this.props.onEditVariables && this.onEditVariables(queryString);
    const currentURL = this.state.graphQLEndpoint;
    if (!currentURL) {
      return;
    }

    this.storageSet(`${currentURL}:variables`, variablesString);
  }

  render() {
    const children = React.Children.toArray(this.props.children);

    const logo = children.find(child => child.type === GraphiQL.Logo);

    const toolbar = children.find(child => child.type === GraphiQL.Toolbar);

    const footer = children.find(child => child.type === GraphiQL.Footer);

    return (

        <TopBar
          schemaFetchError={this.state.schemaFetchError}
          fetchGraphQLSchema={this.fetchGraphQLSchema}
          graphQLEndpoint={this.state.graphQLEndpoint}
          headers={this.state.headers}
          onEditHeadersButtonPressed={this.showEditHeaderModal}
        />
        <GraphiQL
          fetcher={this.graphQLFetcher}
          schema={this.state.schema}
          query={this.state.query}
          variables={this.state.variables}
          operationName={this.props.operationName}
          response={this.state.response}
          onEditQuery={this.onEditQuery}
          onEditVariables={this.onEditVariables}
          onEditOperationName={this.props.onEditOperationName}
          onToggleDocs={this.props.onToggleDocs}
          getDefaultFieldNames={this.props.getDefaultFieldNames}
        >
          <GraphiQL.Toolbar>

              <GenerateMutation
                schema={this.state.schema}
                updateQueryVariablesResponse={this.updateQueryVariablesResponse}
              />
              <GetSetQuery
                query={this.state.query}
                variables={this.state.variables}
                graphQLEndpoint={this.state.graphQLEndpoint}
                setQueryFromString={this.setQueryFromString}
              />
              <SaveLoadQuery
                query={this.state.query}
                variables={this.state.variables}
                graphQLEndpoint={this.state.graphQLEndpoint}
                getSavedQueries={this.getSavedQueries}
                setSavedQueries={this.setSavedQueries}
                setQueryFromString={this.setQueryFromString}
                getCurrentResponse={this.getCurrentResponse}
              />
              {toolbar}

          </GraphiQL.Toolbar>
          {logo}
          {footer}
        </GraphiQL>
        {(() => {
          if (!this.state.editHeaderModalVisible) {
            return null;
          }

          return (
            <EditHeaderModal
              headers={this.state.headers}
              updateHeaders={this.updateHeaders}
              hideEditHeaderModal={this.hideEditHeaderModal}
            />
          );
        })()}

    );
  }
}
<commit_msg>withCredentials same-origin<commit_after>import React, {
  Component,
  PropTypes
} from 'react';
import {
  buildClientSchema,
  parse,
  print,
  introspectionQuery,
  GraphQLSchema
} from 'graphql';
import fetch from 'isomorphic-fetch';
import GraphiQL from 'graphiql';
import { autobind } from 'core-decorators';
import styles from './styles.js';
import { getParameterByName } from  '../helpers/getParameters';
import TopBar from './TopBar';
import GenerateMutation from './GenerateMutation';
import GetSetQuery from './GetSetQuery';
import SaveLoadQuery from './SaveLoadQuery';
import EditHeaderModal from './EditHeaderModal';

export default class CustomGraphiQL extends Component {
  static propTypes = {
    fetcher: PropTypes.func,
    schema: PropTypes.instanceOf(GraphQLSchema),
    currentURL: PropTypes.string,
    query: PropTypes.string,
    variables: PropTypes.string,
    operationName: PropTypes.string,
    response: PropTypes.string,
    storage: PropTypes.shape({
      getItem: PropTypes.func,
      setItem: PropTypes.func
    }),
    defaultQuery: PropTypes.string,
    onEditQuery: PropTypes.func,
    onEditVariables: PropTypes.func,
    onEditOperationName: PropTypes.func,
    onToggleDocs: PropTypes.func,
    getDefaultFieldNames: PropTypes.func
  };

  constructor(props) {
    super(props);

    // Cache the storage instance
    this.storage = props.storage || window.localStorage;

    // Determine the initial url.
    const currentURL = this.storageGet('currentURL') || props.currentURL;

    // Determine the initial query to display.
    const query = props.query || this.storageGet(`${currentURL}:query`) || undefined;

    // Determine the initial variables to display.
    const variables = props.variables || this.storageGet(`${currentURL}:variables`);

    const headers = this.storageGet('headers') ? JSON.parse(this.storageGet('headers')) : {};

    // Initialize state
    this.state = {
      schema: props.schema || null,
      query,
      variables,
      response: props.response,
      graphQLEndpoint: currentURL,
      schemaFetchError: '',
      headers,
    };
  }

  componentDidMount() {
    const currentURL = this.state.graphQLEndpoint;
    if (!currentURL) {
      return;
    }
    this.fetchGraphQLSchema(currentURL);
  }

  @autobind
  storageGet(name) {
    return this.storage && this.storage.getItem('cgraphiql:' + name);
  }

  @autobind
  storageSet(name, value) {
    this.storage && this.storage.setItem('cgraphiql:' + name, value);
  }

  @autobind
  getCurrentResponse() {
    return this.state.response;
  }

  @autobind
  setSavedQueries(savedQueriesString) {
    const currentURL = this.state.graphQLEndpoint;
    this.storageSet(`${currentURL}:queries`, savedQueriesString);
  }

  @autobind
  getSavedQueries() {
    const currentURL = this.state.graphQLEndpoint;
    const currentURLQueriesString = this.storageGet(`${currentURL}:queries`) || '{}';
    return JSON.parse(currentURLQueriesString);
  }

  @autobind
  setQueryFromString(queryStringInput) {
    if (!queryStringInput) {
      this.updateQueryVariablesResponse('', '');
      return;
    }

    const queryString = getParameterByName('query', queryStringInput) || '{}';
    const variablesString = getParameterByName('variables', queryStringInput) || 'null';
    const responseString = getParameterByName('response', queryStringInput) || this.state.response;
    const url = new URL(queryStringInput);
    const graphQLEndpoint = url.origin + url.pathname;
    if (graphQLEndpoint !== this.state.graphQLEndpoint) {
      this.fetchGraphQLSchema(graphQLEndpoint);
      this.state.graphQLEndpoint = graphQLEndpoint;
    }

    this.updateQueryVariablesResponse(queryString, variablesString, responseString);
  }

  @autobind
  updateQueryVariablesResponse(queryString, variablesString, responseString) {
    const currentURL = this.state.graphQLEndpoint;
    this.storageSet(`${currentURL}:query`, queryString);
    this.storageSet(`${currentURL}:variables`, variablesString);
    this.setState({
      query: queryString,
      variables: variablesString,
      response: responseString || this.state.response
    });
  }

  @autobind
  async fetchGraphQLSchema(url) {
    try {
      const headers = this.state.headers;
      const graphQLParams = { query: introspectionQuery };
      const response = await fetch(url, {
        method: 'post',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        body: JSON.stringify(graphQLParams)
      });

      // GET method
      // const response = await fetch(`${url}?query=${encodeURIComponent(graphQLParams.query)}}&variables=${encodeURIComponent('{}')}`, { method: 'get' });

      const result = await response.json();
      if (result.errors) {
        throw new Error(JSON.stringify(result.errors));
      }
      const schema = buildClientSchema(result.data);
      this.storageSet('currentURL', url);
      this.setState({
        schema,
        graphQLEndpoint: url,
        schemaFetchError: '',
        response: 'Schema fetched',
      });
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('Error in fetching GraphQL schema', error);
      this.setState({
        schemaFetchError: error.toString(),
        response: error.toString(),
      });
    }
  }

  @autobind
  async graphQLFetcher(graphQLParams) {
    try {
      const headers = this.state.headers;
      const graphQLEndpoint = this.state.graphQLEndpoint;
      if (!graphQLEndpoint) {
        console.warn('Please set a GraphQL endpoint');
        return null;
      }
      const response = await fetch(graphQLEndpoint, {
        method: 'post',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          ...headers
        },
        body: JSON.stringify(graphQLParams),
        credentials: 'include',
      });
      const result = await response.json();
      this.state.response = JSON.stringify(result, null, 2);
      return result;
    } catch (error) {
      const result = {
        error: error.toString()
      };
      this.state.response = JSON.stringify(result, null, 2);
      return result;
    }
  }

  @autobind
  updateHeaders(newHeaders) {
    this.storageSet('headers', JSON.stringify(newHeaders));
    this.setState({
      headers: newHeaders,
      editHeaderModalVisible: false,
    });
  }

  @autobind
  hideEditHeaderModal() {
    this.setState({
      editHeaderModalVisible: false
    });
  }

  @autobind
  showEditHeaderModal() {
    this.setState({
      editHeaderModalVisible: true
    });
  }

  @autobind
  onEditQuery(queryString) {
    this.setState({
      query: queryString
    });
    this.props.onEditQuery && this.onEditQuery(queryString);
    const currentURL = this.state.graphQLEndpoint;
    if (!currentURL) {
      return;
    }

    this.storageSet(`${currentURL}:query`, queryString);
  }

  @autobind
  onEditVariables(variablesString) {
    this.setState({
      variables: variablesString
    });
    this.props.onEditVariables && this.onEditVariables(queryString);
    const currentURL = this.state.graphQLEndpoint;
    if (!currentURL) {
      return;
    }

    this.storageSet(`${currentURL}:variables`, variablesString);
  }

  render() {
    const children = React.Children.toArray(this.props.children);

    const logo = children.find(child => child.type === GraphiQL.Logo);

    const toolbar = children.find(child => child.type === GraphiQL.Toolbar);

    const footer = children.find(child => child.type === GraphiQL.Footer);

    return (

        <TopBar
          schemaFetchError={this.state.schemaFetchError}
          fetchGraphQLSchema={this.fetchGraphQLSchema}
          graphQLEndpoint={this.state.graphQLEndpoint}
          headers={this.state.headers}
          onEditHeadersButtonPressed={this.showEditHeaderModal}
        />
        <GraphiQL
          fetcher={this.graphQLFetcher}
          schema={this.state.schema}
          query={this.state.query}
          variables={this.state.variables}
          operationName={this.props.operationName}
          response={this.state.response}
          onEditQuery={this.onEditQuery}
          onEditVariables={this.onEditVariables}
          onEditOperationName={this.props.onEditOperationName}
          onToggleDocs={this.props.onToggleDocs}
          getDefaultFieldNames={this.props.getDefaultFieldNames}
        >
          <GraphiQL.Toolbar>

              <GenerateMutation
                schema={this.state.schema}
                updateQueryVariablesResponse={this.updateQueryVariablesResponse}
              />
              <GetSetQuery
                query={this.state.query}
                variables={this.state.variables}
                graphQLEndpoint={this.state.graphQLEndpoint}
                setQueryFromString={this.setQueryFromString}
              />
              <SaveLoadQuery
                query={this.state.query}
                variables={this.state.variables}
                graphQLEndpoint={this.state.graphQLEndpoint}
                getSavedQueries={this.getSavedQueries}
                setSavedQueries={this.setSavedQueries}
                setQueryFromString={this.setQueryFromString}
                getCurrentResponse={this.getCurrentResponse}
              />
              {toolbar}

          </GraphiQL.Toolbar>
          {logo}
          {footer}
        </GraphiQL>
        {(() => {
          if (!this.state.editHeaderModalVisible) {
            return null;
          }

          return (
            <EditHeaderModal
              headers={this.state.headers}
              updateHeaders={this.updateHeaders}
              hideEditHeaderModal={this.hideEditHeaderModal}
            />
          );
        })()}

    );
  }
}
<|endoftext|>