<commit_before>window.rb = window.rb || {};

if(!window.rb.$){
	window.rb.$ = window.jQuery || window.dom;
}

/*! focus-within polyfill */
(function(window, document){
	'use strict';

	var requestAnimationFrame = window.requestAnimationFrame || setTimeout;
	var running = false;
	var isClass = 'is-focus-within';
	var isClassSelector = '.' + isClass;

	function updateFocus(){
		var oldFocusParents, i, len;

		var parent = document.activeElement;
		var newFocusParents = [];

		while((parent = parent.parentNode) && parent.classList && !parent.classList.contains(isClass)){
			newFocusParents.push(parent);
		}

		if((oldFocusParents = parent.querySelectorAll && parent.querySelectorAll(isClassSelector))){
			for(i = 0, len = oldFocusParents.length; i < len; i++){
				oldFocusParents[i].classList.remove(isClass);
			}
		}
		for(i = 0, len = newFocusParents.length; i < len; i++){
			newFocusParents[i].classList.add(isClass);
		}

		running = false;
	}

	function update(){
		if(!running){
			running = true;
			requestAnimationFrame(updateFocus);
		}
	}

	document.addEventListener('focus', update, true);
	document.addEventListener('blur', update, true);

})(window, document);

/* keyboard-focus */
(function(window, document){
	'use strict';
	var keyboardBlocktimer;
	var isKeyboardBlocked = false;
	var root = document.documentElement;
	var dom = rb.$;

	var unblockKeyboardFocus = function(){
		isKeyboardBlocked = false;
	};
	var blockKeyboadFocus = function(){
		isKeyboardBlocked = true;
		clearTimeout(keyboardBlocktimer);
		keyboardBlocktimer = setTimeout(unblockKeyboardFocus, 66);
	};
	var removeKeyBoadFocus = function(){
		root.classList.remove('is-keyboardfocus');
		blockKeyboadFocus();
	};
	var setKeyboardFocus = function(){
		if(!isKeyboardBlocked){
			root.classList.add('is-keyboardfocus');
		}
	};
	var pointerEvents = (window.PointerEvent) ?
			['pointerdown', 'pointerup'] :
			['mousedown', 'mouseup', 'touchstart', 'touchend']
		;

	root.addEventListener('focus', setKeyboardFocus, true);

	pointerEvents.forEach(function(eventName){
		document.addEventListener(eventName, removeKeyBoadFocus, true);
	});

	document.addEventListener('click', blockKeyboadFocus, true);

	window.addEventListener('focus', blockKeyboadFocus);
	document.addEventListener('focus', blockKeyboadFocus);

	if(dom){
		dom(document).on('rbscriptfocus', blockKeyboadFocus);
	}

})(window, document);

/* rbSlideUp / rbSlideDown */
(function(){
	'use strict';
	var dom = rb.$;

	dom.fn.rbSlideUp = function(options){
		if(!options){
			options = {};
		}

		this
			.stop()
			.css({overflow: 'hidden', display: 'block', visibility: 'visible'})
			.animate({height: 0}, {
				duration: options.duration || 400,
				easing: options.easing,
				always: function(){
					this.style.display = '';
					this.style.visibility = '';

					if(options.always){
						return options.always.apply(this, arguments);
					}
				},
			})
		;
	};

	dom.fn.rbSlideDown = function(options){
		if(!options){
			options = {};
		}

		return this.each(function(){
			var endValue;
			var $panel = dom(this);
			var startHeight = this.clientHeight + 'px';

			$panel.css({overflow: 'hidden', display: 'block', height: 'auto', visibility: 'visible'});

			endValue = this.clientHeight;

			$panel
				.css({height: startHeight})
				.animate({height: endValue}, {
					duration: options.duration || 400,
					easing: options.easing,
					always: function(){
						this.style.overflow = '';
						this.style.height = '';

						if(options.always){
							return options.always.apply(this, arguments);
						}
					},
				})
			;
		});
	};
})();

/* scrollIntoView */
(function(window){
	'use strict';
	var document = window.document;
	var dom = rb.$;

	var getScrollingElement = function(){
		var bH, dH, isCompat;
		var scrollingElement = document.scrollingElement;

		if(!scrollingElement){
			bH = document.body.scrollHeight;
			dH = document.documentElement.scrollHeight;
			isCompat = document.compatMode == 'BackCompat';
			scrollingElement = (dH <= bH || isCompat) ?
				document.body :
				document.documentElement;

			if(scrollingElement && (dH != bH || isCompat)){
				document.scrollingElement = scrollingElement;
			}
		}

		return scrollingElement;
	};

	dom.fn.scrollIntoView = function(options){
		var bbox, distance, scrollingElement;
		var elem = this.get(0);

		if(elem){
			options = options || {};
			bbox = elem.getBoundingClientRect();
			distance = Math.max(Math.abs(bbox.top), Math.abs(bbox.left));
			scrollingElement = getScrollingElement();

			dom(scrollingElement).animate(
				{
					scrollTop: scrollingElement.scrollTop + bbox.top + (options.offsetTop || 0),
					scrollLeft: scrollingElement.scrollLeft + bbox.left + (options.offsetLeft || 0),
				},
				{
					duration: options.duration || Math.min(1700, Math.max(99, distance * 0.6)),
					always: function(){
						if(options.focus){
							try {
								options.focus.focus();
							} catch(e){}
						}

						if(options.hash){
							location.hash = typeof options.hash == 'string' ?
								options.hash :
								elem.id || elem.name
							;
						}

						if(options.always){
							options.always.call(elem);
						}
					},
					easing: options.easing
				}
			);
		}
		return this;
	};
})(window);
<commit_msg>throttle<commit_after>if(!window.rb){
	window.rb = {};
}

if(!window.rb.$){
	window.rb.$ = window.jQuery || window.dom;
}

/*! focus-within polyfill */
(function(window, document){
	'use strict';

	var requestAnimationFrame = window.requestAnimationFrame || setTimeout;
	var running = false;
	var isClass = 'is-focus-within';
	var isClassSelector = '.' + isClass;

	function updateFocus(){
		var oldFocusParents, i, len;

		var parent = document.activeElement;
		var newFocusParents = [];

		while((parent = parent.parentNode) && parent.classList && !parent.classList.contains(isClass)){
			newFocusParents.push(parent);
		}

		if((oldFocusParents = parent.querySelectorAll && parent.querySelectorAll(isClassSelector))){
			for(i = 0, len = oldFocusParents.length; i < len; i++){
				oldFocusParents[i].classList.remove(isClass);
			}
		}
		for(i = 0, len = newFocusParents.length; i < len; i++){
			newFocusParents[i].classList.add(isClass);
		}

		running = false;
	}

	function update(){
		if(!running){
			running = true;
			requestAnimationFrame(updateFocus);
		}
	}

	document.addEventListener('focus', update, true);
	document.addEventListener('blur', update, true);

})(window, document);

/* keyboard-focus */
(function(window, document){
	'use strict';
	var keyboardBlocktimer;
	var isKeyboardBlocked = false;
	var root = document.documentElement;
	var dom = rb.$;

	var unblockKeyboardFocus = function(){
		isKeyboardBlocked = false;
	};
	var blockKeyboadFocus = function(){
		isKeyboardBlocked = true;
		clearTimeout(keyboardBlocktimer);
		keyboardBlocktimer = setTimeout(unblockKeyboardFocus, 66);
	};
	var removeKeyBoadFocus = function(){
		root.classList.remove('is-keyboardfocus');
		blockKeyboadFocus();
	};
	var setKeyboardFocus = function(){
		if(!isKeyboardBlocked){
			root.classList.add('is-keyboardfocus');
		}
	};
	var pointerEvents = (window.PointerEvent) ?
			['pointerdown', 'pointerup'] :
			['mousedown', 'mouseup', 'touchstart', 'touchend']
		;

	root.addEventListener('focus', setKeyboardFocus, true);

	pointerEvents.forEach(function(eventName){
		document.addEventListener(eventName, removeKeyBoadFocus, true);
	});

	document.addEventListener('click', blockKeyboadFocus, true);

	window.addEventListener('focus', blockKeyboadFocus);
	document.addEventListener('focus', blockKeyboadFocus);

	if(dom){
		dom(document).on('rbscriptfocus', blockKeyboadFocus);
	}

})(window, document);

/* rbSlideUp / rbSlideDown */
(function(){
	'use strict';
	var dom = rb.$;

	dom.fn.rbSlideUp = function(options){
		if(!options){
			options = {};
		}

		this
			.stop()
			.css({overflow: 'hidden', display: 'block', visibility: 'visible'})
			.animate({height: 0}, {
				duration: options.duration || 400,
				easing: options.easing,
				always: function(){
					this.style.display = '';
					this.style.visibility = '';

					if(options.always){
						return options.always.apply(this, arguments);
					}
				},
			})
		;
	};

	dom.fn.rbSlideDown = function(options){
		if(!options){
			options = {};
		}

		return this.each(function(){
			var endValue;
			var $panel = dom(this);
			var startHeight = this.clientHeight + 'px';

			$panel.css({overflow: 'hidden', display: 'block', height: 'auto', visibility: 'visible'});

			endValue = this.clientHeight;

			$panel
				.css({height: startHeight})
				.animate({height: endValue}, {
					duration: options.duration || 400,
					easing: options.easing,
					always: function(){
						this.style.overflow = '';
						this.style.height = '';

						if(options.always){
							return options.always.apply(this, arguments);
						}
					},
				})
			;
		});
	};
})();

/* scrollIntoView */
(function(window){
	'use strict';
	var document = window.document;
	var dom = rb.$;

	var getScrollingElement = function(){
		var bH, dH, isCompat;
		var scrollingElement = document.scrollingElement;

		if(!scrollingElement){
			bH = document.body.scrollHeight;
			dH = document.documentElement.scrollHeight;
			isCompat = document.compatMode == 'BackCompat';
			scrollingElement = (dH <= bH || isCompat) ?
				document.body :
				document.documentElement;

			if(scrollingElement && (dH != bH || isCompat)){
				document.scrollingElement = scrollingElement;
			}
		}

		return scrollingElement;
	};

	dom.fn.scrollIntoView = function(options){
		var bbox, distance, scrollingElement;
		var elem = this.get(0);

		if(elem){
			options = options || {};
			bbox = elem.getBoundingClientRect();
			distance = Math.max(Math.abs(bbox.top), Math.abs(bbox.left));
			scrollingElement = getScrollingElement();

			dom(scrollingElement).animate(
				{
					scrollTop: scrollingElement.scrollTop + bbox.top + (options.offsetTop || 0),
					scrollLeft: scrollingElement.scrollLeft + bbox.left + (options.offsetLeft || 0),
				},
				{
					duration: options.duration || Math.min(1700, Math.max(99, distance * 0.6)),
					always: function(){
						if(options.focus){
							try {
								options.focus.focus();
							} catch(e){}
						}

						if(options.hash){
							location.hash = typeof options.hash == 'string' ?
								options.hash :
								elem.id || elem.name
							;
						}

						if(options.always){
							options.always.call(elem);
						}
					},
					easing: options.easing
				}
			);
		}
		return this;
	};
})(window);

/* throttle */
(function(){
	'use strict';
	var setImmediate = window.setImmediate;
	var requestAnimationFrame = requestAnimationFrame || setTimeout;

	rb.throttle = function(fn, throttleDelay, write){
		var running;
		var lastTime = 0;
		var Date = window.Date;
		var run = function(){
			running = false;
			lastTime = Date.now();
			fn();
		};
		var afterAF = function(){
			setImmediate(run);
		};
		var getAF = function(){
			requestAnimationFrame(afterAF);
		};

		if(throttleDelay){
			throttleDelay = 99;
		}

		if(write){
			afterAF = run;
		}

		return function(){
			if(running){
				return;
			}
			var delay = throttleDelay - (Date.now() - lastTime);

			running =  true;

			if(delay < 6){
				delay = 6;
			}
			setTimeout(getAF, delay);
		};
	};
})();

/* resize */
(function(){
	'use strict';

	rb.resize = {
		fns: [],
		on: function(fn){

		},
		off: function(fn){

		},
	};
})();
<|endoftext|>


<commit_before>/*
* News System for SpacialGaze
* Credits: Lord Haji, HoeenHero
*/

'use strict';

function generateNews(user) {
	let newsData, newsDisplay = [];
	user = toId(user);
	Object.keys(Db('news').object()).forEach(announcement => {
		newsData = Db('news').get(announcement);
		newsDisplay.push(`<h4>${announcement}</h4>${newsData[1]}<br /><br />—${SG.nameColor(newsData[0], true)} <small>on ${newsData[2]}</small>`);
	});
	return newsDisplay;
}

function hasSubscribed(user) {
	if (typeof user === 'object') user = user.userid;
	if (Db('NewsSubscribers').has(toId(user))) return true;
	return false;
}

function showSubButton(user) {
	user = toId(user);
	let output;
	output = "
<button class = \"button\" name=\"send\" value=\"/news " + (hasSubscribed(user) ? "unsubscribe" : "subscribe") + "\">" + (hasSubscribed(user) ? "Unsubscribe from the news" : "Subscribe to the news") + "</button>";
	return output;
}
SG.showNews = function (userid, user) {
	if (!user || !userid) return false;
	userid = toId(userid);
	let newsDisplay = generateNews(user);
	if (!hasSubscribed(userid)) return false;
	if (newsDisplay.length > 0) {
		newsDisplay = newsDisplay.join('
');
		newsDisplay += showSubButton(userid);
		return user.send(`|pm| SG Server|${user.getIdentity()}|/raw ${newsDisplay}`);
	}
};

exports.commands = {
	news: 'serverannouncements',
	announcements: 'serverannouncements',
	serverannouncements: {
		'': 'view',
		display: 'view',
		view: function (target, room, user) {
			if (!this.runBroadcast()) return;
			let output = "SpacialGaze News:";
			output += generateNews().join('
') + showSubButton(user.userid);
			if (this.broadcasting) return this.sendReplyBox("<div class =\"infobox-limited\"" + output + "
");
			return user.send('|popup||wide||html|' + output);
		},
		remove: 'delete',
		delete: function (target, room, user) {
			if (!this.can('ban')) return false;
			if (!target) return this.parse('/help serverannouncements');
			if (!Db('news').has(target)) return this.errorReply("News with this title doesn't exist.");
			Db('news').delete(target);
			this.privateModCommand(`(${user.name} deleted server announcement titled: ${target}.)`);
		},
		add: function (target, room, user) {
			if (!this.can('ban')) return false;
			if (!target) return this.parse('/help serverannouncements');
			let parts = target.split(',');
			if (parts.length !== 2) return this.errorReply("Usage: /news add [title], [desc]");
			let title = parts[0], desc = parts[1], postedBy = user.name;
			let d = new Date();
			const MonthNames = ["Jan", "Feb", "Mar", "Apr", "May", "June",
				"July", "Aug", "Sep", "Oct", "Nov", "Dec",
			];
			let postTime = (MonthNames[d.getUTCMonth()] + ' ' + d.getUTCDate() + ", " + d.getUTCFullYear());
			Db('news').set(title, [postedBy, desc, postTime]);
			this.privateModCommand(`(${user.name} added server announcement: ${parts[0]})`);
		},
		subscribe: function (target, room, user) {
			if (!user.named) return this.errorReply('You must choose a name before subscribing');
			if (hasSubscribed(user.userid)) return this.errorReply("You are alreading subscribing SpacialGaze News.");
			Db('NewsSubscribers').set(user.userid, true);
			this.sendReply("You have subscribed SpacialGaze News.");
			this.popupReply("|wide||html|You will receive SpacialGaze News automatically once you connect to the SpacialGaze next time.

<button class='button' name = 'send' value = '/news'>Go Back</button>");
		},
		unsubscribe: function (target, room, user) {
			if (!user.named) return this.errorReply('You must choose a name before unsubscribing');
			if (!hasSubscribed(user.userid)) return this.errorReply("You have not subscribed SpacialGaze News.");
			Db('NewsSubscribers').delete(user.userid);
			this.sendReply("You have unsubscribed SpacialGaze News.");
			this.popupReply("|wide||html|You will no longer automatically receive SpacialGaze News.

<button class='button' name='send' value='/news'>Go Back</button>");
		},
	},
	serverannouncementshelp: ["/news view - Views current SpacialGaze news.",
		"/news delete [news title] - Deletes announcement with the [title]. Requires @, &, ~",
		"/news add [news title], [news desc] - Adds news [news]. Requires @, &, ~",
		"/news subscribe - Subscribes to SpacialGaze News.",
		"/news unsubscribe - Unsubscribes to SpacialGaze News.",
	],
};
<commit_msg>Handle commas in the news desc<commit_after>/*
* News System for SpacialGaze
* Credits: Lord Haji, HoeenHero
*/

'use strict';

function generateNews(user) {
	let newsData, newsDisplay = [];
	user = toId(user);
	Object.keys(Db('news').object()).forEach(announcement => {
		newsData = Db('news').get(announcement);
		newsDisplay.push(`<h4>${announcement}</h4>${newsData[1]}<br /><br />—${SG.nameColor(newsData[0], true)} <small>on ${newsData[2]}</small>`);
	});
	return newsDisplay;
}

function hasSubscribed(user) {
	if (typeof user === 'object') user = user.userid;
	if (Db('NewsSubscribers').has(toId(user))) return true;
	return false;
}

function showSubButton(user) {
	user = toId(user);
	let output;
	output = "
<button class = \"button\" name=\"send\" value=\"/news " + (hasSubscribed(user) ? "unsubscribe" : "subscribe") + "\">" + (hasSubscribed(user) ? "Unsubscribe from the news" : "Subscribe to the news") + "</button>";
	return output;
}
SG.showNews = function (userid, user) {
	if (!user || !userid) return false;
	userid = toId(userid);
	let newsDisplay = generateNews(user);
	if (!hasSubscribed(userid)) return false;
	if (newsDisplay.length > 0) {
		newsDisplay = newsDisplay.join('
');
		newsDisplay += showSubButton(userid);
		return user.send(`|pm| SG Server|${user.getIdentity()}|/raw ${newsDisplay}`);
	}
};

exports.commands = {
	news: 'serverannouncements',
	announcements: 'serverannouncements',
	serverannouncements: {
		'': 'view',
		display: 'view',
		view: function (target, room, user) {
			if (!this.runBroadcast()) return;
			let output = "SpacialGaze News:";
			output += generateNews().join('
') + showSubButton(user.userid);
			if (this.broadcasting) return this.sendReplyBox("<div class =\"infobox-limited\"" + output + "
");
			return user.send('|popup||wide||html|' + output);
		},
		remove: 'delete',
		delete: function (target, room, user) {
			if (!this.can('ban')) return false;
			if (!target) return this.parse('/help serverannouncements');
			if (!Db('news').has(target)) return this.errorReply("News with this title doesn't exist.");
			Db('news').delete(target);
			this.privateModCommand(`(${user.name} deleted server announcement titled: ${target}.)`);
		},
		add: function (target, room, user) {
			if (!this.can('ban')) return false;
			if (!target) return this.parse('/help serverannouncements');
			let parts = target.split(',');
			if (parts.length < 2) return this.errorReply("Usage: /news add [title], [desc]");
			let descArray = [];
			if (parts.length - 2 > 0) {
				for (let j = 0; j < parts.length; j++) {
					if (j < 1) continue;
					descArray.push(parts[j]);
				}
				parts[1] = descArray.join();
			}
			let title = parts[0], desc = parts[1], postedBy = user.name;
			let d = new Date();
			const MonthNames = ["Jan", "Feb", "Mar", "Apr", "May", "June",
				"July", "Aug", "Sep", "Oct", "Nov", "Dec",
			];
			let postTime = (MonthNames[d.getUTCMonth()] + ' ' + d.getUTCDate() + ", " + d.getUTCFullYear());
			Db('news').set(title, [postedBy, desc, postTime]);
			this.privateModCommand(`(${user.name} added server announcement: ${parts[0]})`);
		},
		subscribe: function (target, room, user) {
			if (!user.named) return this.errorReply('You must choose a name before subscribing');
			if (hasSubscribed(user.userid)) return this.errorReply("You are alreading subscribing SpacialGaze News.");
			Db('NewsSubscribers').set(user.userid, true);
			this.sendReply("You have subscribed SpacialGaze News.");
			this.popupReply("|wide||html|You will receive SpacialGaze News automatically once you connect to the SpacialGaze next time.

<button class='button' name = 'send' value = '/news'>Go Back</button>");
		},
		unsubscribe: function (target, room, user) {
			if (!user.named) return this.errorReply('You must choose a name before unsubscribing');
			if (!hasSubscribed(user.userid)) return this.errorReply("You have not subscribed SpacialGaze News.");
			Db('NewsSubscribers').delete(user.userid);
			this.sendReply("You have unsubscribed SpacialGaze News.");
			this.popupReply("|wide||html|You will no longer automatically receive SpacialGaze News.

<button class='button' name='send' value='/news'>Go Back</button>");
		},
	},
	serverannouncementshelp: ["/news view - Views current SpacialGaze news.",
		"/news delete [news title] - Deletes announcement with the [title]. Requires @, &, ~",
		"/news add [news title], [news desc] - Adds news [news]. Requires @, &, ~",
		"/news subscribe - Subscribes to SpacialGaze News.",
		"/news unsubscribe - Unsubscribes to SpacialGaze News.",
	],
};
<|endoftext|>


<commit_before>/*
    Copyright (C) 2014 Härnösands kommun

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

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

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @class OpenEMap.view.SavedMapConfigs
 */
Ext.define('OpenEMap.view.SavedMapConfigs' ,{
    extend: 'Ext.grid.Panel',
    requires: ['OpenEMap.data.SavedMapConfigs'],
    autoScroll: true,
    hideHeaders: true,

    id: 'savedMapConfigsGrid',

    constructor: function() {
        /*this.selModel = Ext.create('Ext.selection.CheckboxModel', {
		    mode: 'SINGLE',
            checkOnly: true,
		    listeners: {
			    select: function( t, record, index, eOpts ) {
			        this.client.destroy();
			        this.client.configure(record.raw, this.client.initialOptions);
				    //var configId = record.get('configId');
				    //init(OpenEMap.wsUrls.basePath + OpenEMap.wsUrls.configs + '/' + configId);
			    },
			    scope: this
		    }
	    });*/

	    this.store = Ext.create('OpenEMap.data.SavedMapConfigs');
        this.columns = [
            {
            	header: 'Name',
            	dataIndex: 'name',
            	flex: 1
            },
            {
                xtype: 'actioncolumn',
                width: 40,
                iconCls: 'action-load',
                tooltip: 'Ladda',
                handler: function(grid, rowIndex, cellIndex, column, e, record, tr) {
                    this.client.destroy();
			        this.client.configure(record.raw, this.client.initialOptions);
                    e.stopEvent();
                    return false;
                }.bind(this)
            },
            {
                xtype: 'actioncolumn',
                width: 40,
                getClass: function(value, meta) {
			    	return meta.record.get('isPublic') ? 'action-none' : 'action-remove';
	    		},
                tooltip: 'Ta bort',
                handler: function(grid, rowIndex, cellIndex, column, e, record, tr) {
                    //TODO! change to proper rest store delete
                    if (record.get('isPublic')) {
                    	return false;
                    };

                    Ext.MessageBox.confirm('Ta bort', 'Vill du verkligen ta bort konfigurationen?', function(btn) {
                        if(btn === 'yes') {
                            var store = grid.getStore();
                            grid.panel.dataHandler.deleteConfiguration(record.get('configId'),{ configId: record.get('configId') });
                            store.removeAt(rowIndex);
                        }
                    });
                    e.stopEvent();
                    return false;
                }
            }
        ];

    	this.callParent(arguments);
    }
});
<commit_msg>Making map name clickable. A click on the name loads the map. Removed action column for loading the map.<commit_after>/*
    Copyright (C) 2014 Härnösands kommun

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

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

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @class OpenEMap.view.SavedMapConfigs
 */
Ext.define('OpenEMap.view.SavedMapConfigs' ,{
    extend: 'Ext.grid.Panel',
    requires: ['OpenEMap.data.SavedMapConfigs'],
    autoScroll: true,
    hideHeaders: true,

    id: 'savedMapConfigsGrid',

    constructor: function() {
        /*this.selModel = Ext.create('Ext.selection.CheckboxModel', {
		    mode: 'SINGLE',
            checkOnly: true,
		    listeners: {
			    select: function( t, record, index, eOpts ) {
			        this.client.destroy();
			        this.client.configure(record.raw, this.client.initialOptions);
				    //var configId = record.get('configId');
				    //init(OpenEMap.wsUrls.basePath + OpenEMap.wsUrls.configs + '/' + configId);
			    },
			    scope: this
		    }
	    });*/

	    this.store = Ext.create('OpenEMap.data.SavedMapConfigs');
        this.columns = [
            {
            	header: 'Name',
            	dataIndex: 'name',
            	flex: 1,
                tooltip: 'Ladda',
                renderer: function(value, metadata, record) {
                	metadata.tdAttr = 'data-qtip="Ladda karta"';
                	return value;
                },
			    listeners: {
		            click: function(grid, rowIndex, cellIndex, column, e, record, tr) {
	                    this.client.destroy();
				        this.client.configure(record.raw, this.client.initialOptions);
	                    e.stopEvent();
	                    return false;
	               }.bind(this)
			    }
            },
            {
                xtype: 'actioncolumn',
                width: 40,
                getClass: function(value, meta) {
			    	return meta.record.get('isPublic') ? 'action-none' : 'action-remove';
	    		},
                tooltip: 'Ta bort',
                handler: function(grid, rowIndex, cellIndex, column, e, record, tr) {
                    //TODO! change to proper rest store delete
                    if (record.get('isPublic')) {
                    	return false;
                    };

                    Ext.MessageBox.confirm('Ta bort', 'Vill du verkligen ta bort konfigurationen?', function(btn) {
                        if(btn === 'yes') {
                            var store = grid.getStore();
                            grid.panel.dataHandler.deleteConfiguration(record.get('configId'),{ configId: record.get('configId') });
                            store.removeAt(rowIndex);
                        }
                    });
                    e.stopEvent();
                    return false;
                }
            }
        ];

    	this.callParent(arguments);
    }
});
<|endoftext|>


<commit_before>'use strict';
/*global Packages, require, server, exports*/

/*
 wph 20150103 - temporarily commenting out - textcolors was removed.
 var textcolors = require('textcolors');
*/
var sb;
if (__plugin.canary){
  var Canary = Packages.net.canarymod.Canary;
  sb = Canary.scoreboards().getScoreboard();
} else {
  console.warn('Scoreboard not yet supported in CraftBukkit');
  return;
}
function execCommand( command ){
  server.executeVanillaCommand(server, command);
}
function getTeamByName( teamName ){
  var allTeams = sb.getTeams().toArray();
  for (var i = 0;i < allTeams.length; i++){
    if (allTeams[i].displayName == teamName){
      return allTeams[i];
    }
  }
  return null;
}
function createScoreboard( objectiveName, displayName ){
  execCommand('scoreboard objectives add ' + objectiveName + ' dummy ' + displayName);
  execCommand('scoreboard objectives setdisplay sidebar ' + objectiveName);
}
function addTeamToScoreboard( teamName, color){
  execCommand('scoreboard teams add ' + teamName);
  var team = getTeamByName( teamName );
  /*
   wph 20150103 - temporarily commenting out - textcolors was removed.
   team.prefix = textcolors.colorize(color, '');
   */
  //execCommand('scoreboard teams option ' + teamName + ' color ' + color);
}
function removeScoreboard( name ){
  //execCommand('scoreboard objectives remove ' + name );
  sb['removeScoreObjective(String)'](name);
}
function addPlayerToTeam( objectiveName, teamName, playerName ){
  execCommand('scoreboard teams join ' + teamName + ' ' + playerName);
  execCommand('scoreboard players set ' + playerName + ' ' + objectiveName + ' -1');
  updatePlayerScore( objectiveName, playerName, 0);
}

function updatePlayerScore( objectiveName, playerName, score ){
  /*
   wph 20150801 - this fails with CanaryMod 1.8.2 so use command instead - messy for ops but non-ops won't see messages

   var sc = sb['getScore(String, ScoreObjective)']( playerName, sb.getScoreObjective( objectiveName) );
   sc.score = score;
   */
  execCommand('scoreboard players set ' + playerName + ' ' + objectiveName + score);
}

function removeTeamFromScoreboard( teamName ){
  execCommand('scoreboard teams remove ' + teamName);
  //sb['removeTeam(String)'](teamName);
}
exports.create = createScoreboard;
exports.addTeam = addTeamToScoreboard;
exports.removeTeam = removeTeamFromScoreboard;
exports.addPlayerToTeam = addPlayerToTeam;
exports.updateScore = updatePlayerScore;
exports.remove = removeScoreboard;
<commit_msg>Fixed updatePlayerScore correctly update the score<commit_after>'use strict';
/*global Packages, require, server, exports*/

/*
 wph 20150103 - temporarily commenting out - textcolors was removed.
 var textcolors = require('textcolors');
*/
var sb;
if (__plugin.canary){
  var Canary = Packages.net.canarymod.Canary;
  sb = Canary.scoreboards().getScoreboard();
} else {
  console.warn('Scoreboard not yet supported in CraftBukkit');
  return;
}
function execCommand( command ){
  server.executeVanillaCommand(server, command);
}
function getTeamByName( teamName ){
  var allTeams = sb.getTeams().toArray();
  for (var i = 0;i < allTeams.length; i++){
    if (allTeams[i].displayName == teamName){
      return allTeams[i];
    }
  }
  return null;
}
function createScoreboard( objectiveName, displayName ){
  execCommand('scoreboard objectives add ' + objectiveName + ' dummy ' + displayName);
  execCommand('scoreboard objectives setdisplay sidebar ' + objectiveName);
}
function addTeamToScoreboard( teamName, color){
  execCommand('scoreboard teams add ' + teamName);
  var team = getTeamByName( teamName );
  /*
   wph 20150103 - temporarily commenting out - textcolors was removed.
   team.prefix = textcolors.colorize(color, '');
   */
  //execCommand('scoreboard teams option ' + teamName + ' color ' + color);
}
function removeScoreboard( name ){
  //execCommand('scoreboard objectives remove ' + name );
  sb['removeScoreObjective(String)'](name);
}
function addPlayerToTeam( objectiveName, teamName, playerName ){
  execCommand('scoreboard teams join ' + teamName + ' ' + playerName);
  execCommand('scoreboard players set ' + playerName + ' ' + objectiveName + ' -1');
  updatePlayerScore( objectiveName, playerName, 0);
}

function updatePlayerScore( objectiveName, playerName, score ){
  /*
   wph 20150801 - this fails with CanaryMod 1.8.2 so use command instead - messy for ops but non-ops won't see messages

   var sc = sb['getScore(String, ScoreObjective)']( playerName, sb.getScoreObjective( objectiveName) );
   sc.score = score;
   */
  execCommand('scoreboard players set ' + playerName + ' ' + objectiveName + ' ' + score);
}

function removeTeamFromScoreboard( teamName ){
  execCommand('scoreboard teams remove ' + teamName);
  //sb['removeTeam(String)'](teamName);
}
exports.create = createScoreboard;
exports.addTeam = addTeamToScoreboard;
exports.removeTeam = removeTeamFromScoreboard;
exports.addPlayerToTeam = addPlayerToTeam;
exports.updateScore = updatePlayerScore;
exports.remove = removeScoreboard;
<|endoftext|>


<commit_before>/*
 * to-asciidoc - an HTML to Asciidoc converter
 *
 * Copyright 2015, asciidocfx
 * Licenced under the MIT licence
 *
 */

var nbspRegex = new RegExp(String.fromCharCode(160), "g");

var toAsciidoc = function (string) {

    string = string.replace(nbspRegex, " ");

    var all = document.createElement("div");
    all.innerHTML = string;

    // fix for apple converted space
    var spans = all.querySelectorAll("span.Apple-converted-space");
    for (var i = 0; i < spans.length; i++) {
        var parentNode = spans[i].parentNode || "";
        if (parentNode)
            parentNode.replaceChild(document.createTextNode(" "), spans[i]);
    }

    // crayon-syntax higlighter fix
    $(all).find("div[class*='crayon-syntax']").each(function () {
        var elem = $(this);
        elem.find(".crayon-line").append("\n");
        elem.find(".crayon-num").remove();
        var code = $("");
        code.append(elem.text());
        elem.replaceWith(code);
    });

    // google syntax higlighter fix
    $(all).find("div.syntaxhighlighter").each(function () {
        var elem = $(this);
        elem.find(".line").append("\n");
        elem.find(".number,.toolbar,.gutter").remove();
        console.log(elem.text());
        var code = $("");
        code.append(elem.text());
        elem.replaceWith(code);
    });

    // table converter
    var tables = all.querySelectorAll("table");
    for (var i = 0; i < tables.length; i++) {
        var tableBoundary = "|====\n";
        var tableText = "";
        var table = tables[i];
        var trs = table.querySelectorAll("tr");
        var caption = table.querySelector("caption");

        tableText += "\n\n";
        if (caption)
            tableText += "." + caption.innerText.replace(/Table \d+\. /, "") + "\n";
        tableText += tableBoundary;

        for (var j = 0; j < trs.length; j++) {
            var tr = trs[j];
            var columns = tr.querySelectorAll("td");
            if (columns.length == 0)
                columns = tr.querySelectorAll("th");
            var row = [].slice.call(columns).map(function (e) {
                return "|" + (e.innerHTML ? traverse(e.innerHTML) : "");
            }).join(" ");
            tableText += row + "\n";
        }

        tableText += tableBoundary;

        if (table.parentNode)
            table.parentNode.replaceChild(document.createTextNode(tableText), table);
    }

    // fix pre > code block
    var codes = all.querySelectorAll("pre,code,pre>code");
    for (var i = 0; i < codes.length; i++) {
        var code = codes[i];
        if (code.innerHTML.split(/\n|\r|
|<\/br>/).length > 1) {
            if (code.parentNode)
                code.parentNode.replaceChild(document.createTextNode("\n[source,java]\n----\n" + code.innerText + "\n----\n"), code);
        }
    }

    // remove anchor surrounding an img
    var images = all.querySelectorAll("img");
    for (var i = 0; i < images.length; i++) {
        var parentNode = images[i].parentNode || "";
        if (parentNode.parentNode)
            if (parentNode.constructor == HTMLAnchorElement)
                parentNode.parentNode.replaceChild(images[i], parentNode);
    }
    string = traverse(all.innerHTML);

    function traverse(string) {
        var ELEMENTS = [
            {
                patterns: ["script", "iframe", "meta","embed"],
                replacement: function (str, attrs, innerHTML) {
                    return "";
                }
            },
            {
                patterns: ["div", "span", "body", "i", "section", "html","article","header","label"],
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? innerHTML : '';
                }
            },
            {
                patterns: 'p',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? "\n" + innerHTML + "\n" : '';
                }
            },
            {
                patterns: 'br',
                type: 'void',
                replacement: '  \n'
            },
            {
                patterns: 'h([1-6])',
                replacement: function (str, hLevel, attrs, innerHTML) {
                    var hPrefix = '';
                    for (var i = 0; i < hLevel; i++) {
                        hPrefix += '=';
                    }
                    return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
                }
            },
            {
                patterns: 'hr',
                type: 'void',
                replacement: "\n\n'''\n"
            },
            {
                patterns: 'a',
                replacement: function (str, attrs, innerHTML) {
                    var href = attrs.match(attrRegExp('href')),
                        title = attrs.match(attrRegExp('title'));

                    return href ? href[1] + '[' + innerHTML + ']' : '';
                    //return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
                }
            },
            {
                patterns: ['b', 'strong'],
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '**' + innerHTML + '**' : '';
                }
            },
            {
                patterns: ['i', 'em'],
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '__' + innerHTML + '__' : '';
                }
            },
            {
                patterns: 'sub',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '~' + innerHTML + '~' : '';
                }
            },
            {
                patterns: 'sup',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '^' + innerHTML + '^' : '';
                }
            },
            {
                patterns: 'u',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '[underline]#' + innerHTML + '#' : '';
                }
            },
            {
                patterns: 'del',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '[line-through]#' + innerHTML + '#' : '';
                }
            },
            {
                patterns: 'code',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '``' + innerHTML + '``' : '';
                }
            },
            {
                patterns: 'pre',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '\n\n----\n' + innerHTML + '\n----\n' : '';
                }
            },
            {
                patterns: 'img',
                type: 'void',
                replacement: function (str, attrs, innerHTML) {
                    var src = attrs.match(attrRegExp('src')),
                        alt = attrs.match(attrRegExp('alt')),
                        title = attrs.match(attrRegExp('title'));
                    return src ? '\nimage::' + src[1] + '[' + (alt && alt[1] ? alt[1] : '') + ']\n' : '';
                    //return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
                }
            }
        ];

        for (var i = 0, len = ELEMENTS.length; i < len; i++) {
            if (typeof ELEMENTS[i].patterns === 'string') {
                string = replaceEls(string, {
                    tag: ELEMENTS[i].patterns,
                    replacement: ELEMENTS[i].replacement,
                    type: ELEMENTS[i].type
                });
            }
            else {
                for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
                    string = replaceEls(string, {
                        tag: ELEMENTS[i].patterns[j],
                        replacement: ELEMENTS[i].replacement,
                        type: ELEMENTS[i].type
                    });
                }
            }
        }

        function replaceEls(html, elProperties) {
            var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
                regex = new RegExp(pattern, 'gi'),
                asciidoc = '';
            if (typeof elProperties.replacement === 'string') {
                asciidoc = html.replace(regex, elProperties.replacement);
            }
            else {
                asciidoc = html.replace(regex, function (str, p1, p2, p3) {
                    return elProperties.replacement.call(this, str, p1, p2, p3);
                });
            }
            return asciidoc;
        }

        return string;
    }

    function strip(html) {
        html = html.replace(/<[\/]?(meta)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(span)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(div)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(section)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(i)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(html)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(body)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(article)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(header)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(address)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(abbr)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(small)[^><]*>/ig, "");
        html = html.replace(/(>)/ig, ">");
        html = html.replace(/(<)/ig, "<");
        html = html.replace(/(&)/ig, "&");
        html = html.replace(/(\u2014)/ig, "--");
        html = html.replace(/(\u2009)/ig, " ");
        return html;
    }

    function attrRegExp(attr) {
        return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
    }

    // Pre code blocks

    string = string.replace(/
]*>`([\s\S]*?)`<\/pre>/gi, function (str, innerHTML) {
        var text = innerHTML;
        text = text.replace(/^\t+/g, '  '); // convert tabs to spaces (you know it makes sense)
        text = text.replace(/\n/g, '\n    ');
        return '\n\n    ' + text + '\n';
    });

    // Lists

    // Escape numbers that could trigger an ol
    // If there are more than three spaces before the code, it would be in a pre tag
    // Make sure we are escaping the period not matching any character
    string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');

    // Converts lists that have no child lists (of same type) first, then works its way up
    var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
    while (string.match(noChildrenRegex)) {
        string = string.replace(noChildrenRegex, function (str) {
            return replaceLists(str);
        });
    }

    function replaceLists(html) {

        html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function (str, listType, innerHTML) {
            var lis = innerHTML.split('
');
            lis.splice(lis.length - 1, 1);

            for (i = 0, len = lis.length; i < len; i++) {
                if (lis[i]) {
                    var prefix = (listType === 'ol') ? (i + 1) + ".  " : "*   ";
                    lis[i] = lis[i].replace(/\s*
]*>([\s\S]*)/i, function (str, innerHTML) {

                        innerHTML = innerHTML.replace(/^\s+/, '');
                        innerHTML = innerHTML.replace(/\n\n/g, '\n\n    ');
                        // indent nested lists
                        innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1    $2 ');
                        return prefix + innerHTML;
                    });
                }
                lis[i] = lis[i].replace(/(.) +$/m, '$1');
            }
            return lis.join('\n');
        });

        return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
    }

    // Blockquotes
    var deepest = /
]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
    while (string.match(deepest)) {
        string = string.replace(deepest, function (str) {
            return replaceBlockquotes(str);
        });
    }

    function replaceBlockquotes(html) {
        html = html.replace(/
]*>([\s\S]*?)<\/blockquote>/gi, function (str, inner) {
            inner = inner.replace(/^\s+|\s+$/g, '');
            inner = cleanUp(inner);
            inner = inner.replace(/^/gm, '> ');
            inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
            return inner;
        });
        return html;
    }

    function cleanUp(string) {
        string = strip(string);
        string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
        string = string.replace(/\n\s+\n/g, '\n\n');
        string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
        string = strip(string);
        return string;
    }

    return cleanUp(string);
};
<commit_msg>Add textarea to strip list<commit_after>/*
 * to-asciidoc - an HTML to Asciidoc converter
 *
 * Copyright 2015, asciidocfx
 * Licenced under the MIT licence
 *
 */

var nbspRegex = new RegExp(String.fromCharCode(160), "g");

var toAsciidoc = function (string) {

    string = string.replace(nbspRegex, " ");

    var all = document.createElement("div");
    all.innerHTML = string;

    // fix for apple converted space
    var spans = all.querySelectorAll("span.Apple-converted-space");
    for (var i = 0; i < spans.length; i++) {
        var parentNode = spans[i].parentNode || "";
        if (parentNode)
            parentNode.replaceChild(document.createTextNode(" "), spans[i]);
    }

    // crayon-syntax higlighter fix
    $(all).find("div[class*='crayon-syntax']").each(function () {
        var elem = $(this);
        elem.find(".crayon-line").append("\n");
        elem.find(".crayon-num").remove();
        var code = $("");
        code.append(elem.text());
        elem.replaceWith(code);
    });

    // google syntax higlighter fix
    $(all).find("div.syntaxhighlighter").each(function () {
        var elem = $(this);
        elem.find(".line").append("\n");
        elem.find(".number,.toolbar,.gutter").remove();
        console.log(elem.text());
        var code = $("");
        code.append(elem.text());
        elem.replaceWith(code);
    });

    // table converter
    var tables = all.querySelectorAll("table");
    for (var i = 0; i < tables.length; i++) {
        var tableBoundary = "|====\n";
        var tableText = "";
        var table = tables[i];
        var trs = table.querySelectorAll("tr");
        var caption = table.querySelector("caption");

        tableText += "\n\n";
        if (caption)
            tableText += "." + caption.innerText.replace(/Table \d+\. /, "") + "\n";
        tableText += tableBoundary;

        for (var j = 0; j < trs.length; j++) {
            var tr = trs[j];
            var columns = tr.querySelectorAll("td");
            if (columns.length == 0)
                columns = tr.querySelectorAll("th");
            var row = [].slice.call(columns).map(function (e) {
                return "|" + (e.innerHTML ? traverse(e.innerHTML) : "");
            }).join(" ");
            tableText += row + "\n";
        }

        tableText += tableBoundary;

        if (table.parentNode)
            table.parentNode.replaceChild(document.createTextNode(tableText), table);
    }

    // fix pre > code block
    var codes = all.querySelectorAll("pre,code,pre>code");
    for (var i = 0; i < codes.length; i++) {
        var code = codes[i];
        if (code.innerHTML.split(/\n|\r|
|<\/br>/).length > 1) {
            if (code.parentNode)
                code.parentNode.replaceChild(document.createTextNode("\n[source,java]\n----\n" + code.innerText + "\n----\n"), code);
        }
    }

    // remove anchor surrounding an img
    var images = all.querySelectorAll("img");
    for (var i = 0; i < images.length; i++) {
        var parentNode = images[i].parentNode || "";
        if (parentNode.parentNode)
            if (parentNode.constructor == HTMLAnchorElement)
                parentNode.parentNode.replaceChild(images[i], parentNode);
    }
    string = traverse(all.innerHTML);

    function traverse(string) {
        var ELEMENTS = [
            {
                patterns: ["script", "iframe", "meta","embed"],
                replacement: function (str, attrs, innerHTML) {
                    return "";
                }
            },
            {
                patterns: ["div", "span", "body", "i", "section", "html","article","header","label","textarea"],
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? innerHTML : '';
                }
            },
            {
                patterns: 'p',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? "\n" + innerHTML + "\n" : '';
                }
            },
            {
                patterns: 'br',
                type: 'void',
                replacement: '  \n'
            },
            {
                patterns: 'h([1-6])',
                replacement: function (str, hLevel, attrs, innerHTML) {
                    var hPrefix = '';
                    for (var i = 0; i < hLevel; i++) {
                        hPrefix += '=';
                    }
                    return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
                }
            },
            {
                patterns: 'hr',
                type: 'void',
                replacement: "\n\n'''\n"
            },
            {
                patterns: 'a',
                replacement: function (str, attrs, innerHTML) {
                    var href = attrs.match(attrRegExp('href')),
                        title = attrs.match(attrRegExp('title'));

                    return href ? href[1] + '[' + innerHTML + ']' : '';
                    //return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
                }
            },
            {
                patterns: ['b', 'strong'],
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '**' + innerHTML + '**' : '';
                }
            },
            {
                patterns: ['i', 'em'],
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '__' + innerHTML + '__' : '';
                }
            },
            {
                patterns: 'sub',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '~' + innerHTML + '~' : '';
                }
            },
            {
                patterns: 'sup',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '^' + innerHTML + '^' : '';
                }
            },
            {
                patterns: 'u',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '[underline]#' + innerHTML + '#' : '';
                }
            },
            {
                patterns: 'del',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '[line-through]#' + innerHTML + '#' : '';
                }
            },
            {
                patterns: 'code',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '``' + innerHTML + '``' : '';
                }
            },
            {
                patterns: 'pre',
                replacement: function (str, attrs, innerHTML) {
                    return innerHTML ? '\n\n----\n' + innerHTML + '\n----\n' : '';
                }
            },
            {
                patterns: 'img',
                type: 'void',
                replacement: function (str, attrs, innerHTML) {
                    var src = attrs.match(attrRegExp('src')),
                        alt = attrs.match(attrRegExp('alt')),
                        title = attrs.match(attrRegExp('title'));
                    return src ? '\nimage::' + src[1] + '[' + (alt && alt[1] ? alt[1] : '') + ']\n' : '';
                    //return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
                }
            }
        ];

        for (var i = 0, len = ELEMENTS.length; i < len; i++) {
            if (typeof ELEMENTS[i].patterns === 'string') {
                string = replaceEls(string, {
                    tag: ELEMENTS[i].patterns,
                    replacement: ELEMENTS[i].replacement,
                    type: ELEMENTS[i].type
                });
            }
            else {
                for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
                    string = replaceEls(string, {
                        tag: ELEMENTS[i].patterns[j],
                        replacement: ELEMENTS[i].replacement,
                        type: ELEMENTS[i].type
                    });
                }
            }
        }

        function replaceEls(html, elProperties) {
            var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
                regex = new RegExp(pattern, 'gi'),
                asciidoc = '';
            if (typeof elProperties.replacement === 'string') {
                asciidoc = html.replace(regex, elProperties.replacement);
            }
            else {
                asciidoc = html.replace(regex, function (str, p1, p2, p3) {
                    return elProperties.replacement.call(this, str, p1, p2, p3);
                });
            }
            return asciidoc;
        }

        return string;
    }

    function strip(html) {
        html = html.replace(/<[\/]?(meta)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(span)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(div)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(section)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(i)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(html)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(body)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(article)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(header)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(address)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(abbr)[^><]*>/ig, "");
        html = html.replace(/<[\/]?(small)[^><]*>/ig, "");
        html = html.replace(/(>)/ig, ">");
        html = html.replace(/(<)/ig, "<");
        html = html.replace(/(&)/ig, "&");
        html = html.replace(/(\u2014)/ig, "--");
        html = html.replace(/(\u2009)/ig, " ");
        return html;
    }

    function attrRegExp(attr) {
        return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
    }

    // Pre code blocks

    string = string.replace(/
]*>`([\s\S]*?)`<\/pre>/gi, function (str, innerHTML) {
        var text = innerHTML;
        text = text.replace(/^\t+/g, '  '); // convert tabs to spaces (you know it makes sense)
        text = text.replace(/\n/g, '\n    ');
        return '\n\n    ' + text + '\n';
    });

    // Lists

    // Escape numbers that could trigger an ol
    // If there are more than three spaces before the code, it would be in a pre tag
    // Make sure we are escaping the period not matching any character
    string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');

    // Converts lists that have no child lists (of same type) first, then works its way up
    var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
    while (string.match(noChildrenRegex)) {
        string = string.replace(noChildrenRegex, function (str) {
            return replaceLists(str);
        });
    }

    function replaceLists(html) {

        html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function (str, listType, innerHTML) {
            var lis = innerHTML.split('
');
            lis.splice(lis.length - 1, 1);

            for (i = 0, len = lis.length; i < len; i++) {
                if (lis[i]) {
                    var prefix = (listType === 'ol') ? (i + 1) + ".  " : "*   ";
                    lis[i] = lis[i].replace(/\s*
]*>([\s\S]*)/i, function (str, innerHTML) {

                        innerHTML = innerHTML.replace(/^\s+/, '');
                        innerHTML = innerHTML.replace(/\n\n/g, '\n\n    ');
                        // indent nested lists
                        innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1    $2 ');
                        return prefix + innerHTML;
                    });
                }
                lis[i] = lis[i].replace(/(.) +$/m, '$1');
            }
            return lis.join('\n');
        });

        return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
    }

    // Blockquotes
    var deepest = /
]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
    while (string.match(deepest)) {
        string = string.replace(deepest, function (str) {
            return replaceBlockquotes(str);
        });
    }

    function replaceBlockquotes(html) {
        html = html.replace(/
]*>([\s\S]*?)<\/blockquote>/gi, function (str, inner) {
            inner = inner.replace(/^\s+|\s+$/g, '');
            inner = cleanUp(inner);
            inner = inner.replace(/^/gm, '> ');
            inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
            return inner;
        });
        return html;
    }

    function cleanUp(string) {
        string = strip(string);
        string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
        string = string.replace(/\n\s+\n/g, '\n\n');
        string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
        string = strip(string);
        return string;
    }

    return cleanUp(string);
};
<|endoftext|>


<commit_before>//open command bar
Mousetrap.bindGlobal(['shift+up'], function(e) {
  document.getElementById('light').style.display='block';
  return false;
});

//close command bar
Mousetrap.bindGlobal(['shift+down', 'esc'], function(e) {
  document.getElementById('light').style.display='none';
  return false;
});

//open command bar and trigger voice search
Mousetrap.bindGlobal(['ctrl+shift+.'], function(e) {
  document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'
  return false;
});

jQuery( "iframe" ).each( function( i, iframe )
{
  Mousetrap.bindEventsTo( iframe.contentDocument );
} );
<commit_msg>Clean imput box with shortcut keys<commit_after>//open command bar
Mousetrap.bindGlobal(['shift+up'], function(e) {
  document.getElementById('light').style.display='block';
  return false;
});

//close command bar
Mousetrap.bindGlobal(['shift+down', 'esc'], function(e) {
	document.getElementById('lightboxInput').value="";
	document.getElementById('light').style.display='none';

  return false;
});

//open command bar and trigger voice search
Mousetrap.bindGlobal(['ctrl+shift+.'], function(e) {
  document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'
  return false;
});

jQuery( "iframe" ).each( function( i, iframe )
{
  Mousetrap.bindEventsTo( iframe.contentDocument );
} );
<|endoftext|>


<commit_before>/*
 * @file To set up the interact.js library to allow the user to move the chess pieces on the board
 * @author Adrian McLaughlin
 */

/*global interact*/
/*global console*/

/*
 * Creates an InteractActions object
 * To be used by Interact.js
 * @class
 * @access private
 * @param {stompConnection} stompClient - STOMP Connection to server
 * @param {string} gameUID - String represention of the Game unique number
 */
var InteractActions = function (stompClient, gameUID) {
    "use strict";
    this.stompClient = stompClient;
    this.gameUID = gameUID;
    this.ACTION_CLASSES = {
        DROP_ACTIVE: 'drop-active',
        DROP_TARGET: 'drop-target',
        CAN_DROP: 'can-drop'
    };
    this.startOfMove = true;
    this.sourceId = "";
    this.destId = "";
};

InteractActions.prototype = {
    onMove : function (event) {
        "use strict";
        var target = event.target,
            // keep the dragged position in the data-x/data-y attributes
            x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
            y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy,
            correctY = target.transform.baseVal[0].matrix.f,
            correctX = target.transform.baseVal[0].matrix.e;
        // translate the element
        target.style.webkitTransform =
            target.style.transform =
            'translate(' + (x + correctX) + 'px, ' + (y + correctY) + 'px)';

        // update the posiion attributes
        target.setAttribute('data-x', x);
        target.setAttribute('data-y', y);
    },

    onDragEnter : function (event) {
        "use strict";
        console.log("Drop dragEnter");
        var draggableElement = event.relatedTarget,
            dropzoneElement = event.target;

            // feedback the possibility of a drop
        dropzoneElement.classList.add(this.ACTION_CLASSES.DROP_TARGET);
        draggableElement.classList.add(this.ACTION_CLASSES.CAN_DROP);
    },

    onDropActivate : function (event) {
        "use strict";
        console.log("Drop onDropActivate");
        // add active dropzone feedback
        event.target.classList.add(this.ACTION_CLASSES.DROP_ACTIVE);
    },

    onDragLeave : function (event) {
        "use strict";
        console.log("Drop onDragLeave");
        event.target.classList.remove(this.ACTION_CLASSES.DROP_TARGET);
        event.relatedTarget.classList.remove(this.ACTION_CLASSES.CAN_DROP);
        if (this.startOfMove) {
            this.sourceId = event.target.id;
            this.startOfMove = false;
        }
    },

    onDrop : function (event) {
        "use strict";
        console.log("Drop onDrop");
        this.destId = event.target.id;
        this.startOfMove = true;
        var move = this.sourceId + "-" + this.destId;
        this.stompClient.send("/app/move/" + this.gameUID, {priority: 9}, move);
    },

    onDropDeactivate : function (event) {
        "use strict";
        console.log("Drop deactivate");
        // remove active dropzone feedback
        event.target.classList.remove(this.ACTION_CLASSES.DROP_ACTIVE);
        event.target.classList.remove(this.ACTION_CLASSES.DROP_TARGET);
    }
};

/*
 *
 */
function chessGameInteract(stompClient, gameUID) {
    "use strict";

    var DRAGGABLE_CLASS = '.draggable',
        DROPZONE_CLASS = '.dropzone',
        DROPZONE_ACCEPT_CLASS = '.chesspiece',
        RESTRICTION_ELEMENT = '#layer',
        actions = new InteractActions(stompClient, gameUID);

    interact(DRAGGABLE_CLASS).draggable({
        // enable inertial throwing
        inertia: false,
        // keep the element within the area of it's parent
        restrict: {
            restriction: RESTRICTION_ELEMENT,
            endOnly: true,
            elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
        },

        // call this function on every dragmove event
        onmove: function (event) {
            actions.onMove.call(actions, event);
        }
    });

    interact(DROPZONE_CLASS).dropzone({
        accept: DROPZONE_ACCEPT_CLASS,
        overlap: 0.1,
        ondropactivate: function (event) {
            actions.onDropActivate.call(actions, event);
        },
        ondragenter: function (event) {
            actions.onDragEnter.call(actions, event);
        },
        ondragleave: function (event) {
            actions.onDragLeave.call(actions, event);
        },
        ondrop: function (event) {
            actions.onDrop.call(actions, event);
        },
        ondropdeactivate: function (event) {
            actions.onDropDeactivate.call(actions, event);
        }
    });
}

<commit_msg>CG-41 fix Dragging chess piece doesn't generate a move in FireFox<commit_after>/*
 * @file To set up the interact.js library to allow the user to move the chess pieces on the board
 * @author Adrian McLaughlin
 */

/*global interact*/
/*global console*/

/*
 * Creates an InteractActions object
 * To be used by Interact.js
 * @class
 * @access private
 * @param {stompConnection} stompClient - STOMP Connection to server
 * @param {string} gameUID - String represention of the Game unique number
 */
var InteractActions = function (stompClient, gameUID) {
    "use strict";
    this.stompClient = stompClient;
    this.gameUID = gameUID;
    this.ACTION_CLASSES = {
        DROP_ACTIVE: 'drop-active',
        DROP_TARGET: 'drop-target',
        CAN_DROP: 'can-drop'
    };
    this.startOfMove = true;
    this.sourceId = "";
    this.destId = "";
};

InteractActions.prototype = {
    onMove : function (event) {
        "use strict";
        var target = event.target,
            // keep the dragged position in the data-x/data-y attributes
            x = event.dx,
            y = event.dy,
            correctY = target.transform.baseVal[0].matrix.f,
            correctX = target.transform.baseVal[0].matrix.e;
        // translate the element
        target.setAttribute('transform', 'translate(' + (x + correctX) + ', ' + (y + correctY) + ')');
    },

    onDragEnter : function (event) {
        "use strict";
        console.log("Drop dragEnter");
        var draggableElement = event.relatedTarget,
            dropzoneElement = event.target;

            // feedback the possibility of a drop
        dropzoneElement.classList.add(this.ACTION_CLASSES.DROP_TARGET);
        draggableElement.classList.add(this.ACTION_CLASSES.CAN_DROP);
    },

    onDropActivate : function (event) {
        "use strict";
        console.log("Drop onDropActivate");
        // add active dropzone feedback
        event.target.classList.add(this.ACTION_CLASSES.DROP_ACTIVE);
    },

    onDragLeave : function (event) {
        "use strict";
        console.log("Drop onDragLeave");
        event.target.classList.remove(this.ACTION_CLASSES.DROP_TARGET);
        event.relatedTarget.classList.remove(this.ACTION_CLASSES.CAN_DROP);
        if (this.startOfMove) {
            this.sourceId = event.target.id;
            this.startOfMove = false;
        }
    },

    onDrop : function (event) {
        "use strict";
        console.log("Drop onDrop");
        this.destId = event.target.id;
        this.startOfMove = true;
        var move = this.sourceId + "-" + this.destId;
        this.stompClient.send("/app/move/" + this.gameUID, {priority: 9}, move);
    },

    onDropDeactivate : function (event) {
        "use strict";
        console.log("Drop deactivate");
        // remove active dropzone feedback
        event.target.classList.remove(this.ACTION_CLASSES.DROP_ACTIVE);
        event.target.classList.remove(this.ACTION_CLASSES.DROP_TARGET);
    }
};

/*
 *
 */
function chessGameInteract(stompClient, gameUID) {
    "use strict";

    var DRAGGABLE_CLASS = '.draggable',
        DROPZONE_CLASS = '.dropzone',
        DROPZONE_ACCEPT_CLASS = '.chesspiece',
        RESTRICTION_ELEMENT = '#layer',
        actions = new InteractActions(stompClient, gameUID);

    interact(DRAGGABLE_CLASS).draggable({
        // enable inertial throwing
        inertia: false,
        // keep the element within the area of it's parent
        restrict: {
            restriction: RESTRICTION_ELEMENT,
            endOnly: true,
            elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
        },

        // call this function on every dragmove event
        onmove: function (event) {
            actions.onMove.call(actions, event);
        }
    });

    interact(DROPZONE_CLASS).dropzone({
        accept: DROPZONE_ACCEPT_CLASS,
        overlap: 0.1,
        ondropactivate: function (event) {
            actions.onDropActivate.call(actions, event);
        },
        ondragenter: function (event) {
            actions.onDragEnter.call(actions, event);
        },
        ondragleave: function (event) {
            actions.onDragLeave.call(actions, event);
        },
        ondrop: function (event) {
            actions.onDrop.call(actions, event);
        },
        ondropdeactivate: function (event) {
            actions.onDropDeactivate.call(actions, event);
        }
    });
}

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import style from './style';

export default class CommentList extends Component {
  constructor(props, ...args) {
    super(props, ...args);
    this.usersMap = {};
    this.updateUsersMap();
  }

  updateUsersMap() {
    this.usersMap = this.props.users.reduce((map, user) => {
       map[user.id] = user;
       return map;
    }, {});
  }

  componentDidMount() {
    const wrapper = this.refs.wrapper;
    wrapper.scrollTop = wrapper.scrollHeight;
  }

  componentDidUpdate(prev) {
    this.updateUsersMap();
    if (this.props.comments.length !== prev.comments.length) {
      const wrapper = this.refs.wrapper;
      wrapper.scrollTop = wrapper.scrollHeight;
    }
  }

  formatTime(ts) {
    return new Date(ts).toLocaleString();
  }

  renderComment(comment, key) {
    let user = this.usersMap[comment.userId];
    if (!user) {
      return null;
    }
    let commentStyle = style.commentItem;
    if (comment.loading) {
      commentStyle = style.commentItemloading;
    }
    return (

            {user.name}
            {this.formatTime(comment.time)}

          {comment.text}

    );
  }

  render() {
    return (

        {this.props.comments.map((c, idx) => this.renderComment(c, idx))}

    );
  }
}
<commit_msg>change date format on comment section<commit_after>import React, { Component } from 'react';
import moment from 'moment';
import style from './style';

export default class CommentList extends Component {
  constructor(props, ...args) {
    super(props, ...args);
    this.usersMap = {};
    this.updateUsersMap();
  }

  updateUsersMap() {
    this.usersMap = this.props.users.reduce((map, user) => {
       map[user.id] = user;
       return map;
    }, {});
  }

  componentDidMount() {
    const wrapper = this.refs.wrapper;
    wrapper.scrollTop = wrapper.scrollHeight;
  }

  componentDidUpdate(prev) {
    this.updateUsersMap();
    if (this.props.comments.length !== prev.comments.length) {
      const wrapper = this.refs.wrapper;
      wrapper.scrollTop = wrapper.scrollHeight;
    }
  }

  formatTime(ts) {
    return moment(new Date(ts), "YYYYMMDD").fromNow();
  }

  renderComment(comment, key) {
    let user = this.usersMap[comment.userId];
    if (!user) {
      return null;
    }
    let commentStyle = style.commentItem;
    if (comment.loading) {
      commentStyle = style.commentItemloading;
    }
    return (

            {user.name}
            {this.formatTime(comment.time)}

          {comment.text}

    );
  }

  render() {
    return (

        {this.props.comments.map((c, idx) => this.renderComment(c, idx))}

    );
  }
}
<|endoftext|>


<commit_before>/*
*     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
*     S.A.Unipersonal (Telefonica I+D)
*
*     This file is part of Morfeo EzWeb Platform.
*
*     Morfeo EzWeb Platform is free software: you can redistribute it and/or modify
*     it under the terms of the GNU Affero General Public License as published by
*     the Free Software Foundation, either version 3 of the License, or
*     (at your option) any later version.
*
*     Morfeo EzWeb Platform is distributed in the hope that it will be useful,
*     but WITHOUT ANY WARRANTY; without even the implied warranty of
*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*     GNU Affero General Public License for more details.
*
*     You should have received a copy of the GNU Affero General Public License
*     along with Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
*
*     Info about members and contributors of the MORFEO project
*     is available at
*
*     http://morfeo-project.org
 */

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// VARIABLE (Parent Class)  <<PLATFORM>>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function Variable (id, iGadget, name, varManager) {
	// True when a the value of the variable has changed and the callback has not been invoked!
	this.annotated = false;
	this.varManager = null;
	this.id = null;
	this.iGadget = null;
	this.name = null;
	this.label = null;
	this.action_label = null;
	this.aspect = null;
	this.value = null;
	this.tab = null;
	this.shared = null; //null means no sharing at all (true or false means that could be shared)
}

//////////////////////////////////////////////
// PARENT CONTRUCTOR (Super class emulation)
//////////////////////////////////////////////

Variable.prototype.Variable = function (id, iGadget_, name_, aspect_, varManager_,  value_, label_, action_label_, tab_, shared_) {
	this.varManager = varManager_;
	this.id = id;
	this.iGadget = iGadget_;
	this.name = name_;
	this.label = label_;
	this.action_label = action_label_;
	this.aspect = aspect_;
	this.value = value_;
	this.tab = tab_;
	this.shared = shared_;
}

//////////////////////////////////////////////
// PUBLIC METHODS TO BE INHERITANCED
//////////////////////////////////////////////

Variable.prototype.get = function () {
	return this.value;
}

Variable.prototype.setHandler = function () { }

Variable.prototype.set = function (value) { }

Variable.prototype.setSharedState = function (shared_) {
	this.shared = shared_;
}

Variable.prototype.annotate = function (value) {
	this.annotated = true;
	this.value = value;
}

Variable.prototype.assignConnectable = function (connectable) {
	this.connectable = connectable;
}

Variable.prototype.getConnectable = function () {
	return this.connectable;
}

Variable.prototype.getWorkspace = function () {
	return this.varManager.getWorkspace();
}

//////////////////////////////////////////////
// PUBLIC CONSTANTS
//////////////////////////////////////////////

Variable.prototype.EVENT = "EVEN"
Variable.prototype.SLOT = "SLOT"
Variable.prototype.USER_PREF = "PREF"
Variable.prototype.PROPERTY = "PROP"
Variable.prototype.EXTERNAL_CONTEXT = "ECTX"
Variable.prototype.GADGET_CONTEXT = "GCTX"

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RVARIABLE (Derivated class) <<PLATFORM>>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function RVariable(id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_) {
	Variable.prototype.Variable.call(this, id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_);

	this.handler = null;
}

//////////////////////////////////////////////
// DEFINING INHERITANCE
//////////////////////////////////////////////

RVariable.prototype = new Variable;

//////////////////////////////////////////////
// PUBLIC METHODS TO BE INHERITANCED
//////////////////////////////////////////////

//////////////////////////////////////////////
// OVERWRITTEN METHODS
//////////////////////////////////////////////

RVariable.prototype.setHandler = function (handler_) {
	this.handler = handler_;
}

RVariable.prototype.set = function (newValue) {
	if (this.annotated) {
		// If annotated, the value must be managed!

		var varInfo = [{id: this.id, value: newValue, aspect: this.aspect}];

		if (this.shared != null){ //its a possible shared variable
			varInfo[0]["shared"] = this.shared;
		}

		switch (this.aspect) {
			case Variable.prototype.SLOT:

				// On-demand loading of tabs!
				// Only wiring variables are involved!
				if (! this.tab.is_painted() ) {
					this.varManager.addPendingVariable(this.iGadget, this.name, newValue);
					this.tab.paint();
					return;
				}
				var opManager = OpManagerFactory.getInstance();
				var iGadget = opManager.activeWorkSpace.getIgadget(this.iGadget);
				if (!iGadget.loaded) { //the tab is being painted due to another variable in the same tab and this gadget isn't fully loaded
					this.varManager.addPendingVariable(this.iGadget, this.name, newValue);
					return;
				}
				iGadget.notifyEvent();

			case Variable.prototype.USER_PREF:
			case Variable.prototype.EXTERNAL_CONTEXT:
			case Variable.prototype.GADGET_CONTEXT:
                if (this.aspect === this.USER_PREF) {
                    // Only gadget preferences are persisted
                    this.varManager.markVariablesAsModified(varInfo);
                }

				this.value = newValue;

				if (this.handler) {
					try {
						this.handler(newValue);
					} catch (e) {
						var transObj = {iGadgetId: this.iGadget, varName: this.name, exceptionMsg: e};
						var msg = interpolate(gettext("Error in the handler of the \"%(varName)s\" RVariable in iGadget %(iGadgetId)s: %(exceptionMsg)s."), transObj, true);
						OpManagerFactory.getInstance().logIGadgetError(this.iGadget, msg, Constants.Logging.ERROR_MSG);
					}
				} else {
					var opManager = OpManagerFactory.getInstance();
					var iGadget = opManager.activeWorkSpace.getIgadget(this.iGadget);
					if (iGadget.loaded) {
						var transObj = {iGadgetId: this.iGadget, varName: this.name};
						var msg = interpolate(gettext("IGadget %(iGadgetId)s does not provide a handler for the \"%(varName)s\" RVariable."), transObj, true);
						opManager.logIGadgetError(this.iGadget, msg, Constants.Logging.WARN_MSG);
					}
				}

				break;
			default:
				break;
		}
		if (this.shared==true) {
			this.varManager.forceCommit();
		}
		// And it must be changed to NOT annotated!
		this.annotated = false;
	}
}

RVariable.prototype.refresh = function() {
	switch (this.aspect) {
		case Variable.prototype.USER_PREF:
		case Variable.prototype.EXTERNAL_CONTEXT:
		case Variable.prototype.GADGET_CONTEXT:
		case Variable.prototype.SLOT:
			if (this.handler) {
				try {
					this.handler(this.value);
				} catch (e) {
					var transObj = {iGadgetId: this.iGadget, varName: this.name, exceptionMsg: e};
					var msg = interpolate(gettext("Error in the handler of the \"%(varName)s\" RVariable in iGadget %(iGadgetId)s: %(exceptionMsg)s."), transObj, true);
					OpManagerFactory.getInstance().logIGadgetError(this.iGadget, msg, Constants.Logging.ERROR_MSG);
				}
			} else {
				var opManager = OpManagerFactory.getInstance();
				var iGadget = opManager.activeWorkSpace.getIgadget(this.iGadget);
				if (iGadget.loaded) {
					var transObj = {iGadgetId: this.iGadget, varName: this.name};
					var msg = interpolate(gettext("IGadget %(iGadgetId)s does not provide a handler for the \"%(varName)s\" RVariable."), transObj, true);
					opManager.logIGadgetError(this.iGadget, msg, Constants.Logging.WARN_MSG);
				}
			}
			break;
		default:
			break;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RWVARIABLE (Derivated class)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function RWVariable(id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_) {
	Variable.prototype.Variable.call(this, id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_);
}

//////////////////////////////////////////////
// DEFINING INHERITANCE
//////////////////////////////////////////////

RWVariable.prototype = new Variable;

//////////////////////////////////////////////
// PUBLIC METHODS TO BE INHERITANCED
//////////////////////////////////////////////

RWVariable.prototype.set = function (value_, options_) {
	if (this.aspect == Variable.prototype.PROPERTY && this.shared==true) {
		//it is a shared property. Gadgets cannot set its value
		throw new Error("Shared properties cannot be changed by gadgets");
	}
	this.varManager.incNestingLevel();

	this.value = value_;

	if (this.aspect === this.PROPERTY && this.value != value_) {
		this.varManager.markVariablesAsModified([this]);

		if (this.shared == true) {
			this.varManager.forceCommit();
		}
	}

	// Propagate changes to wiring module
	// Only when variable is an Event, the connectable must start propagating
	// When variable is INOUT, is the connectable who propagates
	switch (this.aspect) {
		case Variable.prototype.EVENT:
			if (this.connectable != null) {
				this.connectable.propagate(this.value, options_);
				break;
			}
		default:
			break;
	}

	// This will save all modified vars if we are the root event
	this.varManager.decNestingLevel();
}

RWVariable.prototype.getFinalSlots = function () {
	if (this.connectable == null) {
		return;
	}

	switch (this.aspect) {
		case Variable.prototype.EVENT:
			return this.connectable.getFinalSlots();
		default:
			return [];
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

<commit_msg>Fix properties not being saved<commit_after>/*
*     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
*     S.A.Unipersonal (Telefonica I+D)
*
*     This file is part of Morfeo EzWeb Platform.
*
*     Morfeo EzWeb Platform is free software: you can redistribute it and/or modify
*     it under the terms of the GNU Affero General Public License as published by
*     the Free Software Foundation, either version 3 of the License, or
*     (at your option) any later version.
*
*     Morfeo EzWeb Platform is distributed in the hope that it will be useful,
*     but WITHOUT ANY WARRANTY; without even the implied warranty of
*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*     GNU Affero General Public License for more details.
*
*     You should have received a copy of the GNU Affero General Public License
*     along with Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
*
*     Info about members and contributors of the MORFEO project
*     is available at
*
*     http://morfeo-project.org
 */

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// VARIABLE (Parent Class)  <<PLATFORM>>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function Variable (id, iGadget, name, varManager) {
	// True when a the value of the variable has changed and the callback has not been invoked!
	this.annotated = false;
	this.varManager = null;
	this.id = null;
	this.iGadget = null;
	this.name = null;
	this.label = null;
	this.action_label = null;
	this.aspect = null;
	this.value = null;
	this.tab = null;
	this.shared = null; //null means no sharing at all (true or false means that could be shared)
}

//////////////////////////////////////////////
// PARENT CONTRUCTOR (Super class emulation)
//////////////////////////////////////////////

Variable.prototype.Variable = function (id, iGadget_, name_, aspect_, varManager_,  value_, label_, action_label_, tab_, shared_) {
	this.varManager = varManager_;
	this.id = id;
	this.iGadget = iGadget_;
	this.name = name_;
	this.label = label_;
	this.action_label = action_label_;
	this.aspect = aspect_;
	this.value = value_;
	this.tab = tab_;
	this.shared = shared_;
}

//////////////////////////////////////////////
// PUBLIC METHODS TO BE INHERITANCED
//////////////////////////////////////////////

Variable.prototype.get = function () {
	return this.value;
}

Variable.prototype.setHandler = function () { }

Variable.prototype.set = function (value) { }

Variable.prototype.setSharedState = function (shared_) {
	this.shared = shared_;
}

Variable.prototype.annotate = function (value) {
	this.annotated = true;
	this.value = value;
}

Variable.prototype.assignConnectable = function (connectable) {
	this.connectable = connectable;
}

Variable.prototype.getConnectable = function () {
	return this.connectable;
}

Variable.prototype.getWorkspace = function () {
	return this.varManager.getWorkspace();
}

//////////////////////////////////////////////
// PUBLIC CONSTANTS
//////////////////////////////////////////////

Variable.prototype.EVENT = "EVEN"
Variable.prototype.SLOT = "SLOT"
Variable.prototype.USER_PREF = "PREF"
Variable.prototype.PROPERTY = "PROP"
Variable.prototype.EXTERNAL_CONTEXT = "ECTX"
Variable.prototype.GADGET_CONTEXT = "GCTX"

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RVARIABLE (Derivated class) <<PLATFORM>>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function RVariable(id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_) {
	Variable.prototype.Variable.call(this, id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_);

	this.handler = null;
}

//////////////////////////////////////////////
// DEFINING INHERITANCE
//////////////////////////////////////////////

RVariable.prototype = new Variable;

//////////////////////////////////////////////
// PUBLIC METHODS TO BE INHERITANCED
//////////////////////////////////////////////

//////////////////////////////////////////////
// OVERWRITTEN METHODS
//////////////////////////////////////////////

RVariable.prototype.setHandler = function (handler_) {
	this.handler = handler_;
}

RVariable.prototype.set = function (newValue) {
	if (this.annotated) {
		// If annotated, the value must be managed!

		var varInfo = [{id: this.id, value: newValue, aspect: this.aspect}];

		if (this.shared != null){ //its a possible shared variable
			varInfo[0]["shared"] = this.shared;
		}

		switch (this.aspect) {
			case Variable.prototype.SLOT:

				// On-demand loading of tabs!
				// Only wiring variables are involved!
				if (! this.tab.is_painted() ) {
					this.varManager.addPendingVariable(this.iGadget, this.name, newValue);
					this.tab.paint();
					return;
				}
				var opManager = OpManagerFactory.getInstance();
				var iGadget = opManager.activeWorkSpace.getIgadget(this.iGadget);
				if (!iGadget.loaded) { //the tab is being painted due to another variable in the same tab and this gadget isn't fully loaded
					this.varManager.addPendingVariable(this.iGadget, this.name, newValue);
					return;
				}
				iGadget.notifyEvent();

			case Variable.prototype.USER_PREF:
			case Variable.prototype.EXTERNAL_CONTEXT:
			case Variable.prototype.GADGET_CONTEXT:
                if (this.aspect === this.USER_PREF) {
                    // Only gadget preferences are persisted
                    this.varManager.markVariablesAsModified(varInfo);
                }

				this.value = newValue;

				if (this.handler) {
					try {
						this.handler(newValue);
					} catch (e) {
						var transObj = {iGadgetId: this.iGadget, varName: this.name, exceptionMsg: e};
						var msg = interpolate(gettext("Error in the handler of the \"%(varName)s\" RVariable in iGadget %(iGadgetId)s: %(exceptionMsg)s."), transObj, true);
						OpManagerFactory.getInstance().logIGadgetError(this.iGadget, msg, Constants.Logging.ERROR_MSG);
					}
				} else {
					var opManager = OpManagerFactory.getInstance();
					var iGadget = opManager.activeWorkSpace.getIgadget(this.iGadget);
					if (iGadget.loaded) {
						var transObj = {iGadgetId: this.iGadget, varName: this.name};
						var msg = interpolate(gettext("IGadget %(iGadgetId)s does not provide a handler for the \"%(varName)s\" RVariable."), transObj, true);
						opManager.logIGadgetError(this.iGadget, msg, Constants.Logging.WARN_MSG);
					}
				}

				break;
			default:
				break;
		}
		if (this.shared==true) {
			this.varManager.forceCommit();
		}
		// And it must be changed to NOT annotated!
		this.annotated = false;
	}
}

RVariable.prototype.refresh = function() {
	switch (this.aspect) {
		case Variable.prototype.USER_PREF:
		case Variable.prototype.EXTERNAL_CONTEXT:
		case Variable.prototype.GADGET_CONTEXT:
		case Variable.prototype.SLOT:
			if (this.handler) {
				try {
					this.handler(this.value);
				} catch (e) {
					var transObj = {iGadgetId: this.iGadget, varName: this.name, exceptionMsg: e};
					var msg = interpolate(gettext("Error in the handler of the \"%(varName)s\" RVariable in iGadget %(iGadgetId)s: %(exceptionMsg)s."), transObj, true);
					OpManagerFactory.getInstance().logIGadgetError(this.iGadget, msg, Constants.Logging.ERROR_MSG);
				}
			} else {
				var opManager = OpManagerFactory.getInstance();
				var iGadget = opManager.activeWorkSpace.getIgadget(this.iGadget);
				if (iGadget.loaded) {
					var transObj = {iGadgetId: this.iGadget, varName: this.name};
					var msg = interpolate(gettext("IGadget %(iGadgetId)s does not provide a handler for the \"%(varName)s\" RVariable."), transObj, true);
					opManager.logIGadgetError(this.iGadget, msg, Constants.Logging.WARN_MSG);
				}
			}
			break;
		default:
			break;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RWVARIABLE (Derivated class)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function RWVariable(id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_) {
	Variable.prototype.Variable.call(this, id, iGadget_, name_, aspect_, varManager_, value_, label_, action_label_, tab_, shared_);
}

//////////////////////////////////////////////
// DEFINING INHERITANCE
//////////////////////////////////////////////

RWVariable.prototype = new Variable;

//////////////////////////////////////////////
// PUBLIC METHODS TO BE INHERITANCED
//////////////////////////////////////////////

RWVariable.prototype.set = function (value_, options_) {
    var oldvalue;

	if (this.aspect == Variable.prototype.PROPERTY && this.shared==true) {
		//it is a shared property. Gadgets cannot set its value
		throw new Error("Shared properties cannot be changed by gadgets");
	}
	this.varManager.incNestingLevel();

    oldvalue = this.value;
	this.value = value_;

	if (this.aspect === this.PROPERTY && oldvalue != value_) {
		this.varManager.markVariablesAsModified([this]);

		if (this.shared == true) {
			this.varManager.forceCommit();
		}
	}

	// Propagate changes to wiring module
	// Only when variable is an Event, the connectable must start propagating
	// When variable is INOUT, is the connectable who propagates
	switch (this.aspect) {
		case Variable.prototype.EVENT:
			if (this.connectable != null) {
				this.connectable.propagate(this.value, options_);
				break;
			}
		default:
			break;
	}

	// This will save all modified vars if we are the root event
	this.varManager.decNestingLevel();
}

RWVariable.prototype.getFinalSlots = function () {
	if (this.connectable == null) {
		return;
	}

	switch (this.aspect) {
		case Variable.prototype.EVENT:
			return this.connectable.getFinalSlots();
		default:
			return [];
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>'use strict';

const DiscordHook = require('../../../../bot/modules/DiscordHook');

const regex = {
    li: /(\d+) Legendary Insights Earned/,
    clear: /cleared everything.*⭐/
};

class HookExperienced extends DiscordHook {
    constructor(bot) {
        super(bot, 'experienced');
        this._hooks = {
            message: this.onMessage.bind(this)
        };
        this._localizerNamespaces = 'module.guildwars2';
    }

    async onMessage(message) {
        const bot = this.getBot();
        const config = this.getConfig();
        const l = bot.getLocalizer();

        const gw2botId = config.get('gw2bot-id');
        const expRoleId = config.get('experienced-role-id');
        const liReq = config.get('li');
        const clearReq = config.get('full-clear');

        if (!expRoleId || liReq === false || !clearReq) {
            // Nothing configured
            return;
        }

        if (message.author.id !== gw2botId) {
            // Only listen to GW2Bot messages
            return;
        }

        if (!message.mentions.members) {
            // No mentions
            return;
        }
        const member = message.mentions.members.first();
        if (member && member.roles.has(expRoleId)) {
            // No mentions or already has the role assigned
            return;
        }

        let passed = false;
        let text = message.context;
        if (message.embeds.length > 0) {
            const embed = message.embeds[0];
            text = `${embed.title}\n${embed.description}\n`;
            for (const field of embed.fields) {
                text += `${field.name}\n${field.value}\n`;
            }
        }
        if (!text) {
            return;
        }

        let match;
        if (liReq !== false && (match = text.match(regex.li))) {
            // LI
            if (parseInt(match[1], 10) >= liReq) {
                passed = true;
            }
        } else if (clearReq && text.match(regex.clear)) {
            passed = true;
        }

        if (passed) {
            return Promise.all([
                message.channel.send(l.t('module.guildwars2:experienced.response-passed-experienced-check', { user: member.toString() })),
                member.addRole(expRoleId, 'Automatically verified by LI and/or full raid clear requirement')
            ]);
        }
    }
}

module.exports = HookExperienced;
<commit_msg>Fix full clears not being detected<commit_after>'use strict';

const DiscordHook = require('../../../../bot/modules/DiscordHook');

const regex = {
    li: /(\d+) Legendary Insights Earned/,
    clear: /cleared everything.*(⭐|:star:)/
};

class HookExperienced extends DiscordHook {
    constructor(bot) {
        super(bot, 'experienced');
        this._hooks = {
            message: this.onMessage.bind(this)
        };
        this._localizerNamespaces = 'module.guildwars2';
    }

    async onMessage(message) {
        const bot = this.getBot();
        const config = this.getConfig();
        const l = bot.getLocalizer();

        const gw2botId = config.get('gw2bot-id');
        const expRoleId = config.get('experienced-role-id');
        const liReq = config.get('li');
        const clearReq = config.get('full-clear');

        if (!expRoleId || liReq === false || !clearReq) {
            // Nothing configured
            return;
        }

        if (message.author.id !== gw2botId) {
            // Only listen to GW2Bot messages
            return;
        }

        if (!message.mentions.members) {
            // No mentions
            return;
        }
        const member = message.mentions.members.first();
        if (member && member.roles.has(expRoleId)) {
            // No mentions or already has the role assigned
            return;
        }

        let passed = false;
        let text = message.content;
        if (message.embeds.length > 0) {
            const embed = message.embeds[0];
            text = `${embed.title}\n${embed.description}\n`;
            for (const field of embed.fields) {
                text += `${field.name}\n${field.value}\n`;
            }
        }
        if (!text) {
            return;
        }

        let match;
        if (liReq !== false && (match = text.match(regex.li))) {
            // LI
            if (parseInt(match[1], 10) >= liReq) {
                passed = true;
            }
        } else if (clearReq && text.match(regex.clear)) {
            // Full clear
            passed = true;
        }

        if (passed) {
            return Promise.all([
                message.channel.send(l.t('module.guildwars2:experienced.response-passed-experienced-check', { user: member.toString() })),
                member.addRole(expRoleId, 'Automatically verified by LI and/or full raid clear requirement')
            ]);
        }
    }
}

module.exports = HookExperienced;
<|endoftext|>


<commit_before>var Collision = function()
{
	this.collided = true
}

Collision.prototype.update = function(x1, y1, w1, h1, x2, y2, w2, h2)
{
	if ( 	y2 + h2 < y1 ||
			x2 + w2 < x1 ||
			x2 > x1 + w1 ||
			y2 > y1 + h1)
			{
				this.collided = false
			}
}<commit_msg>+ Collision<commit_after>var Collision = function()
{
	this.collided = false
}

Collision.prototype.update = function(x1, y1, w1, h1, x2, y2, w2, h2)
{
	if ( 	y2 + h2 < y1 ||
			x2 + w2 < x1 ||
			x2 > x1 + w1 ||
			y2 > y1 + h1)
			{
				this.collided = true
			}
}<|endoftext|>