SetSelectedRange Spread.NET javascript issue - javascript

I'm trying to add functionality to Spread.NET control where it will permit a hold shift-click to select a range of cells in ASP.
I'm creating the event onActiveCellChanged to call the selectRange function on execution
var shiftPressed = false;
var newSelect = true;
window.pageLoad = function init() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
if (ss.addEventListener != null) {
ss.addEventListener("ActiveCellChanged", selectRange(), false);
} else if (ss.attachEvent != null) {
ss.attachEvent("ActiveCellChanged", selectRange());
}
else {
FpSpread1.onActiveCellChanged = selectRange;
}
}
Here is the selectRange function.
function selectRange() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
var swap;
if (shiftPressed == true) {
var initRow = document.getElementById('RowCoord').value;
var initCol = document.getElementById('ColCoord').value;
var SecRow = getRow();
var SecCol = getCol();
newSelect = false;
var rCount = Math.abs(SecRow - initRow) + 1;
var cCount = Math.abs(SecCol - initCol) + 1;
if (initRow > SecRow)
initRow = SecRow;
if (initCol > SecCol)
initCol = SecCol;
//alert(initRow + ' ' + initCol);
alert(initRow + ' ' + initCol + ' ' + rCount + ' ' + cCount);
ss.SetSelectedRange(initRow, initCol, rCount, cCount);
}
else {
document.getElementById('RowCoord').value = 0;
document.getElementById('ColCoord').value = 0;
newSelect = true;
}
}
And this is how I'm determining whether shift is being held.
function aKeyDown(event) {
if (event.keyCode == 16) {
shiftPressed = true;
var col = getCol();
var row = getRow();
if (newSelect) {
document.getElementById('RowCoord').value = row;
document.getElementById('ColCoord').value = col;
}
}
}
function aKeyUp(event) {
if (event.keyCode == 16) {
shiftPressed = false;
}
}
function getRow() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
ret = ss.ActiveRow;
if (ret == undefined)
ret = ss.GetActiveRow;
return ret;
}
function getCol() {
var ss = document.getElementById('<%=FpSpread1.ClientID %>');
ret = ss.ActiveCol;
if (ret == undefined)
ret = ss.GetActiveCol;
return ret;
}
The SetSelectedRange in the select range function will work if my initial cell is a,1. However, if it's any other cell, it'll select the entire row and column.
Here is my <div> tag:
<FarPoint:FpSpread onkeydown="aKeyDown(event)" onkeyup="aKeyUp(event)" ID="FpSpread1"...
In image 1, My initial cell was (a,3) and I held shift and clicked on (b,4)
In image 2, it works. As long as I start at cell (a,1)

I needed to parseInt the row and column values.
function getRow() {
var ss = document.getElementById(spd);
ret = ss.ActiveRow;
if (ret == undefined)
ret = ss.GetActiveRow();
return parseInt(ret);
}
function getCol() {
var ss = document.getElementById(spd);
ret = ss.ActiveCol;
if (ret == undefined)
ret = ss.GetActiveCol();
return parseInt(ret);
}

Related

How to convert from Path to XPath, given a browser event

On a MouseEvent instance, we have a property called path, it might look like this:
Does anybody know if there is a reliable way to translate this path array into an XPath? I assume that this path data is the best data to start from? Is there a library I can use to do the conversion?
This library looks promising, but it doesn't use the path property of an event: https://github.com/johannhof/xpath-dom
There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?
See getPathTo() in this answer for one possible approach.
PS: Taken from Javascript get XPath of a node
Another option is to use SelectorGadget from below link
https://dv0akt2986vzh.cloudfront.net/unstable/lib/selectorgadget.js
The actual code for the DOM path is at
https://dv0akt2986vzh.cloudfront.net/stable/lib/dom.js
Usage: on http://google.com
elem = document.getElementById("q")
predict = new DomPredictionHelper()
predict.pathOf(elem)
// gives "body.default-theme.des-mat:nth-child(2) div#_Alw:nth-child(4) form#f:nth-child(2) div#fkbx:nth-child(2) input#q:nth-child(2)"
predict.predictCss([elem],[])
// gives "#q"
CODE if link goes down
// Copyright (c) 2008, 2009 Andrew Cantino
// Copyright (c) 2008, 2009 Kyle Maxwell
function DomPredictionHelper() {};
DomPredictionHelper.prototype = new Object();
DomPredictionHelper.prototype.recursiveNodes = function(e){
var n;
if(e.nodeName && e.parentNode && e != document.body) {
n = this.recursiveNodes(e.parentNode);
} else {
n = new Array();
}
n.push(e);
return n;
};
DomPredictionHelper.prototype.escapeCssNames = function(name) {
if (name) {
try {
return name.replace(/\s*sg_\w+\s*/g, '').replace(/\\/g, '\\\\').
replace(/\./g, '\\.').replace(/#/g, '\\#').replace(/\>/g, '\\>').replace(/\,/g, '\\,').replace(/\:/g, '\\:');
} catch(e) {
console.log('---');
console.log("exception in escapeCssNames");
console.log(name);
console.log('---');
return '';
}
} else {
return '';
}
};
DomPredictionHelper.prototype.childElemNumber = function(elem) {
var count = 0;
while (elem.previousSibling && (elem = elem.previousSibling)) {
if (elem.nodeType == 1) count++;
}
return count;
};
DomPredictionHelper.prototype.pathOf = function(elem){
var nodes = this.recursiveNodes(elem);
var self = this;
var path = "";
for(var i = 0; i < nodes.length; i++) {
var e = nodes[i];
if (e) {
path += e.nodeName.toLowerCase();
var escaped = e.id && self.escapeCssNames(new String(e.id));
if(escaped && escaped.length > 0) path += '#' + escaped;
if(e.className) {
jQuery.each(e.className.split(/ /), function() {
var escaped = self.escapeCssNames(this);
if (this && escaped.length > 0) {
path += '.' + escaped;
}
});
}
path += ':nth-child(' + (self.childElemNumber(e) + 1) + ')';
path += ' '
}
}
if (path.charAt(path.length - 1) == ' ') path = path.substring(0, path.length - 1);
return path;
};
DomPredictionHelper.prototype.commonCss = function(array) {
try {
var dmp = new diff_match_patch();
} catch(e) {
throw "Please include the diff_match_patch library.";
}
if (typeof array == 'undefined' || array.length == 0) return '';
var existing_tokens = {};
var encoded_css_array = this.encodeCssForDiff(array, existing_tokens);
var collective_common = encoded_css_array.pop();
jQuery.each(encoded_css_array, function(e) {
var diff = dmp.diff_main(collective_common, this);
collective_common = '';
jQuery.each(diff, function() {
if (this[0] == 0) collective_common += this[1];
});
});
return this.decodeCss(collective_common, existing_tokens);
};
DomPredictionHelper.prototype.tokenizeCss = function(css_string) {
var skip = false;
var word = '';
var tokens = [];
var css_string = css_string.replace(/,/, ' , ').replace(/\s+/g, ' ');
var length = css_string.length;
var c = '';
for (var i = 0; i < length; i++){
c = css_string[i];
if (skip) {
skip = false;
} else if (c == '\\') {
skip = true;
} else if (c == '.' || c == ' ' || c == '#' || c == '>' || c == ':' || c == ',') {
if (word.length > 0) tokens.push(word);
word = '';
}
word += c;
if (c == ' ' || c == ',') {
tokens.push(word);
word = '';
}
}
if (word.length > 0) tokens.push(word);
return tokens;
};
DomPredictionHelper.prototype.decodeCss = function(string, existing_tokens) {
var inverted = this.invertObject(existing_tokens);
var out = '';
jQuery.each(string.split(''), function() {
out += inverted[this];
});
return this.cleanCss(out);
};
// Encode css paths for diff using unicode codepoints to allow for a large number of tokens.
DomPredictionHelper.prototype.encodeCssForDiff = function(strings, existing_tokens) {
var codepoint = 50;
var self = this;
var strings_out = [];
jQuery.each(strings, function() {
var out = new String();
jQuery.each(self.tokenizeCss(this), function() {
if (!existing_tokens[this]) {
existing_tokens[this] = String.fromCharCode(codepoint++);
}
out += existing_tokens[this];
});
strings_out.push(out);
});
return strings_out;
};
DomPredictionHelper.prototype.simplifyCss = function(css, selected_paths, rejected_paths) {
var self = this;
var parts = self.tokenizeCss(css);
var best_so_far = "";
if (self.selectorGets('all', selected_paths, css) && self.selectorGets('none', rejected_paths, css)) best_so_far = css;
for (var pass = 0; pass < 4; pass++) {
for (var part = 0; part < parts.length; part++) {
var first = parts[part].substring(0,1);
if (self.wouldLeaveFreeFloatingNthChild(parts, part)) continue;
if ((pass == 0 && first == ':') || // :nth-child
(pass == 1 && first != ':' && first != '.' && first != '#' && first != ' ') || // elem, etc.
(pass == 2 && first == '.') || // classes
(pass == 3 && first == '#')) // ids
{
var tmp = parts[part];
parts[part] = '';
var selector = self.cleanCss(parts.join(''));
if (selector == '') {
parts[part] = tmp;
continue;
}
if (self.selectorGets('all', selected_paths, selector) && self.selectorGets('none', rejected_paths, selector)) {
best_so_far = selector;
} else {
parts[part] = tmp;
}
}
}
}
return self.cleanCss(best_so_far);
};
DomPredictionHelper.prototype.wouldLeaveFreeFloatingNthChild = function(parts, part) {
return (((part - 1 >= 0 && parts[part - 1].substring(0, 1) == ':') &&
(part - 2 < 0 || parts[part - 2] == ' ') &&
(part + 1 >= parts.length || parts[part + 1] == ' ')) ||
((part + 1 < parts.length && parts[part + 1].substring(0, 1) == ':') &&
(part + 2 >= parts.length || parts[part + 2] == ' ') &&
(part - 1 < 0 || parts[part - 1] == ' ')));
};
DomPredictionHelper.prototype.cleanCss = function(css) {
return css.replace(/\>/, ' > ').replace(/,/, ' , ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '').replace(/,$/, '');
};
DomPredictionHelper.prototype.getPathsFor = function(arr) {
var self = this;
var out = [];
jQuery.each(arr, function() {
if (this && this.nodeName) {
out.push(self.pathOf(this));
}
})
return out;
};
DomPredictionHelper.prototype.predictCss = function(s, r) {
var self = this;
if (s.length == 0) return '';
var selected_paths = self.getPathsFor(s);
var rejected_paths = self.getPathsFor(r);
var css = self.commonCss(selected_paths);
var simplest = self.simplifyCss(css, selected_paths, rejected_paths);
// Do we get off easy?
if (simplest.length > 0) return simplest;
// Okay, then make a union and possibly try to reduce subsets.
var union = '';
jQuery.each(s, function() {
union = self.pathOf(this) + ", " + union;
});
union = self.cleanCss(union);
return self.simplifyCss(union, selected_paths, rejected_paths);
};
DomPredictionHelper.prototype.fragmentSelector = function(selector) {
var self = this;
var out = [];
jQuery.each(selector.split(/\,/), function() {
var out2 = [];
jQuery.each(self.cleanCss(this).split(/\s+/), function() {
out2.push(self.tokenizeCss(this));
});
out.push(out2);
});
return out;
};
// Everything in the first selector must be present in the second.
DomPredictionHelper.prototype.selectorBlockMatchesSelectorBlock = function(selector_block1, selector_block2) {
for (var j = 0; j < selector_block1.length; j++) {
if (jQuery.inArray(selector_block1[j], selector_block2) == -1) {
return false;
}
}
return true;
};
// Assumes list is an array of complete CSS selectors represented as strings.
DomPredictionHelper.prototype.selectorGets = function(type, list, the_selector) {
var self = this;
var result = true;
if (list.length == 0 && type == 'all') return false;
if (list.length == 0 && type == 'none') return true;
var selectors = self.fragmentSelector(the_selector);
var cleaned_list = [];
jQuery.each(list, function() {
cleaned_list.push(self.fragmentSelector(this)[0]);
});
jQuery.each(selectors, function() {
if (!result) return;
var selector = this;
jQuery.each(cleaned_list, function(pos) {
if (!result || this == '') return;
if (self._selectorGets(this, selector)) {
if (type == 'none') result = false;
cleaned_list[pos] = '';
}
});
});
if (type == 'all' && cleaned_list.join('').length > 0) { // Some candidates didn't get matched.
result = false;
}
return result;
};
DomPredictionHelper.prototype._selectorGets = function(candidate_as_blocks, selector_as_blocks) {
var cannot_match = false;
var position = candidate_as_blocks.length - 1;
for (var i = selector_as_blocks.length - 1; i > -1; i--) {
if (cannot_match) break;
if (i == selector_as_blocks.length - 1) { // First element on right.
// If we don't match the first element, we cannot match.
if (!this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position])) cannot_match = true;
position--;
} else {
var found = false;
while (position > -1 && !found) {
found = this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position]);
position--;
}
if (!found) cannot_match = true;
}
}
return !cannot_match;
};
DomPredictionHelper.prototype.invertObject = function(object) {
var new_object = {};
jQuery.each(object, function(key, value) {
new_object[value] = key;
});
return new_object;
};
DomPredictionHelper.prototype.cssToXPath = function(css_string) {
var tokens = this.tokenizeCss(css_string);
if (tokens[0] && tokens[0] == ' ') tokens.splice(0, 1);
if (tokens[tokens.length - 1] && tokens[tokens.length - 1] == ' ') tokens.splice(tokens.length - 1, 1);
var css_block = [];
var out = "";
for(var i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ') {
out += this.cssToXPathBlockHelper(css_block);
css_block = [];
} else {
css_block.push(tokens[i]);
}
}
return out + this.cssToXPathBlockHelper(css_block);
};
// Process a block (html entity, class(es), id, :nth-child()) of css
DomPredictionHelper.prototype.cssToXPathBlockHelper = function(css_block) {
if (css_block.length == 0) return '//';
var out = '//';
var first = css_block[0].substring(0,1);
if (first == ',') return " | ";
if (jQuery.inArray(first, [':', '#', '.']) != -1) {
out += '*';
}
var expressions = [];
var re = null;
for(var i = 0; i < css_block.length; i++) {
var current = css_block[i];
first = current.substring(0,1);
var rest = current.substring(1);
if (first == ':') {
// We only support :nth-child(n) at the moment.
if (re = rest.match(/^nth-child\((\d+)\)$/))
expressions.push('(((count(preceding-sibling::*) + 1) = ' + re[1] + ') and parent::*)');
} else if (first == '.') {
expressions.push('contains(concat( " ", #class, " " ), concat( " ", "' + rest + '", " " ))');
} else if (first == '#') {
expressions.push('(#id = "' + rest + '")');
} else if (first == ',') {
} else {
out += current;
}
}
if (expressions.length > 0) out += '[';
for (var i = 0; i < expressions.length; i++) {
out += expressions[i];
if (i < expressions.length - 1) out += ' and ';
}
if (expressions.length > 0) out += ']';
return out;
};

I'm getting this error Uncaught TypeError: this.getElements is not a function

I look into a few answers but I'm not getting any results, I'm trying to fix this issue "Uncaught TypeError: this.getElements is not a function". This part of the code, full code in the link.
var SIDEBAR = new function() {
this.on = function(nameElement){
this.menu = nameElement;
return this;
};
/*more code*/
this.getElements = function() {
/*more code*/
return [];
};
/*more code*/
this.addElements = function() {
var elementsData = this.getElements();
/*more code*/
};
}();
var sid = SIDEBAR.on('test');
sid.load();
Full code: https://jsfiddle.net/e6shbnsu/
The value of this is determined by how a function is called.
this will point to window in setTimeout. Use .bind to have specified values as this context.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
function inElectron() {
return navigator.userAgent.indexOf("Electron") != -1;
}
var dataManager = {
getItem: function(key, local) {
if (inElectron() || local == 1)
return localStorage.getItem(key);
else
return sessionStorage.getItem(key);
},
setItem: function(key, item, local) {
if (inElectron() || local == 1)
localStorage.setItem(key, item);
else
sessionStorage.setItem(key, item);
}
};
var SIDEBAR = new function() {
this.on = function(nameElement) {
this.menu = nameElement;
return this;
};
this.load = function() {
this.currentElement = 0;
this.refreshElements();
};
this.setAddElementName = function(name) {
this.addElementName = name;
};
this.setNewElementName = function(name) {
this.newElementName = name;
};
this.getElements = function() {
var elementsData = dataManager.getItem(this.getDataKey);
if (typeof elementsData !== 'undefined' && elementsData !== null) {
return JSON.parse(elementsData);
}
return this.getPreloadData();
};
this.setDataKey = function(key) {
this.dataKey = key;
};
this.getDataKey = function() {
if (this.dataKey) {
return this.dataKey;
}
return "SideBar" + this.menu;
};
this.setPreloadData = function(dataArray) {
this.preloadData = dataArray;
};
this.getPreloadData = function() {
if (typeof this.preloadData !== 'undefined' && this.preloadData !== null) {
return this.preloadData;
}
return [];
};
this.getCurrentElement = function() {
var elementsData = getElements;
return elementsData[currentElement];
};
this.refreshElements = function() {
window.setTimeout(function() {
this.clearElements();
}.bind(this), 1);
//outer `this` context is bound to the handler
window.setTimeout(function() {
this.addElements();
}.bind(this), 2);
};
this.deleteElement = function() {
var newArr = [];
var elementsData = this.getElements();
for (var i = 0, l = elementsData.length; i < l; i++) {
if (i != index) {
newArr.push(elementsData[i]);
}
}
dataManager.setItem(this.getDataKey, JSON.stringify(newArr));
};
this.addElements = function() {
var elementsData = this.getElements();
var menuNode = document.getElementById(this.menu);
console.log(elementsData);
for (var i = 0; i < elementsData.length; i++) {
var li = document.createElement("li");
var div = document.createElement("div");
li.value = i;
div.classList.add("list");
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
p.appendChild(document.createTextNode(elementsData[i].name));
div.appendChild(p);
var obj = getObject();
console.log(obj);
div.onclick = function(e) {
e.stopImmediatePropagation();
if (this.querySelector("#textBlock").contentEditable == "false") {
this.currentElement = this.parentNode.value;
elementsData = this.getElements();
document.getElementById("prompt").innerHTML = elementsData[this.parentNode.value]["data"];
document.querySelector("#wrapper").classList.toggle("toggled");
}
};
var span2 = document.createElement("span");
span2.id = "deleteMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-minus");
span2.onclick = function(e) {
e.stopImmediatePropagation();
deleteItem(this.parentNode.parentNode.value);
window.setTimeout(this.refreshElements, 1);
};
span2.style.display = "none";
div.appendChild(span2);
var span = document.createElement("span");
span.id = "editMode";
span.classList.add("glyphicon");
span.classList.add("glyphicon-pencil");
span.onclick = function(e) {
e.stopImmediatePropagation();
// get href of first anchor in element and change location
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.add("disabled");
}
this.style.display = "none";
this.parentNode.querySelector("#deleteMode").style.display = "";
this.parentNode.classList.add("editableMode");
this.parentNode.classList.remove("disabled");
var textBlock = this.parentNode.querySelector("#textBlock");
textBlock.setAttribute("contentEditable", true);
this.placeCaretAtEnd(textBlock);
textBlock.onkeydown = function(e) {
if (e.keyCode == 13) {
e.stopImmediatePropagation();
var text = this.innerHTML.replace(" ", '');
text = text.replace("<br>", '');
if (text.length > 0) {
this.innerHTML = text;
elementsData[this.parentNode.parentNode.value]['name'] = text;
dataManager.setItem("IFTeleprompterScripts", JSON.stringify(elementsData));
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.remove("disabled");
}
this.parentNode.classList.remove("editableMode");
this.setAttribute("contentEditable", false);
this.parentNode.querySelector("#editMode").style.display = "";
this.parentNode.querySelector("#deleteMode").style.display = "none";
} else {
return false;
}
} else if (e.keyCode == 8) {
if (textBlock.innerHTML.length - 1 === 0) {
textBlock.innerHTML = " ";
}
}
return true;
};
return false;
};
div.appendChild(span);
li.appendChild(div);
scriptsNode.appendChild(li);
}
var li = document.createElement("li");
var div = document.createElement("div");
var span2 = document.createElement("span");
span2.id = "addMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-plus");
div.appendChild(span2);
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null)
p.appendChild(document.createTextNode(" " + this.addElementName));
else
p.appendChild(document.createTextNode(" Add " + this.menu));
div.appendChild(p);
li.onclick = function(e) {
e.stopImmediatePropagation();
var newPushElementName = "New " + this.menu;
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null) {
newPushElementName = this.addElementName;
}
elementsData.push({
"name": newPushElementName,
"data": ""
});
dataManager.setItem(this.getDataKey, JSON.stringify(elementsData));
this.refreshElements();
};
li.appendChild(div);
menuNode.appendChild(li);
};
this.placeCaretAtEnd = function(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
};
}();
var sid = SIDEBAR.on('test');
sid.load();
<ul class="sidebar-nav" id="test">
</ul>

Restart a function if there is no click, or touch event on screen

I found this code on net, it's about a memory game.
var MemoryApp = (function () {
'use strict';
var size = 36;
var sizeStyle = "smallGame";
var maxpics = 18;
var gameRunning = false;
var cardOpen = null;
var time = 0;
var timer;
var s4;
var s6;
var s8;
var attempts = 0;
var found = 0;
var foundDisp;
var attDisp;
var timeDisp;
var template;
var popupImage;
var popupHolder;
var gameGrid;
var currentCardSet = 'zoo';
var currentCards = [];
window.onload = runGame;
function activated() {
WinJS.UI.processAll().then(function(){
s4 = document.getElementById("size4x4");
s6 = document.getElementById("size6x6");
s8 = document.getElementById("size8x8");
s4.addEventListener("click", gameSize, false);
s6.addEventListener("click", gameSize, false);
s8.addEventListener("click", gameSize, false);
var start = document.getElementById("startGame");
if (start) {
start.onclick = runGame;
}
var stop = document.getElementById("stopGame");
if (stop) {
stop.onclick = stopGame;
}
template = document.getElementById("cardTemplate");
popupImage = document.getElementById("popupImage");
popupHolder = document.getElementById("popupHolder");
popupHolder.addEventListener("click", closeImageView, false);
foundDisp = document.getElementById("foundDisplay");
attDisp = document.getElementById("attemptsDisplay");
timeDisp = document.getElementById("timeDisplay");
// Expose functions globally
window.updateClock = updateClock;
window.resetCards = resetCards;
window.gameTag1 = null;
window.gameTag2 = null;
buildCards();
});
}
function closeImageView() {
removeClass(popupHolder, "openImagePopup");
}
function makePictureArray() {
var pics = new Array();
for (var i = 0; i < maxpics; i++) {
pics[i] = getDefaultURL(i);
}
return pics;
}
function removeAllChildren(element) {
if (element.hasChildNodes()) {
while (element.childNodes.length > 0) {
element.removeChild(element.firstChild);
}
}
}
function buildCards() {
// Assumption: game grid size is a power of 2
var stride = Math.sqrt(size);
// Make picture selection
var pics = makePictureArray();
var sel = new Array();
for (var i = 0; i < size / 2; i++) {
var idx = parseInt(Math.random() * pics.length);
sel[i] = pics[idx];
// remove the used pic
pics.splice(idx, 1);
}
// get an array with the card content
var content = new Array();
for (var i = 0; i < size / 2; i++) {
content[i] = sel[i];
content[i + size / 2] = sel[i];
}
var gameBoard = document.querySelector('#gameBoard');
removeAllChildren(gameBoard);
var gameGrid = document.createElement("div");
gameGrid.id = "gameGrid";
addClass(gameGrid, sizeStyle);
gameBoard.appendChild(gameGrid);
for (var i=0; i<size; i++) {
var item = document.createElement("div");
item.className = "gameItem"+i;
item.addEventListener("click", cardClicked, false);
setClosed(item);
var r = parseInt(Math.random() * content.length);
// Add image
insertTemplate(item, template);
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, imgFilter, false);
while (walker.nextNode())
walker.currentNode.setAttribute("src", content[r]);
// Add path to ease styling
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, pFilter, false);
while (walker.nextNode())
walker.currentNode.innerText = content[r];
item.contentIndex = content[r];
content.splice(r, 1);
gameGrid.appendChild(item);
}
}
function imgFilter(node) {
if (node.tagName == "IMG") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function pFilter(node) {
if (node.tagName == "P") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function insertTemplate(parent, templateParent) {
if (templateParent.children && templateParent.children.length >= 1) {
var tchild = templateParent.children[0].cloneNode(true);
parent.appendChild(tchild);
}
}
function gameSize() {
document.size.size4x4.checked = false;
document.size.size6x6.checked = false;
document.size.size8x8.checked = false;
var newsize = 36;
var gSize = "smallGame";
if (this.name == "size4x4") {
document.size.size4x4.checked = true;
newsize = 36;
gSize = "smallGame";
}
if (this.name == "size6x6") {
document.size.size6x6.checked = true;
newsize = 36;
gSize = "mediumGame";
}
if (this.name == "size8x8") {
document.size.size8x8.checked = true;
newsize = 36;
gSize = "largeGame";
}
if (!gameRunning == true) {
size = newsize;
sizeStyle = gSize;
buildCards();
}
}
function stopGame() {
if (!gameRunning)
return;
gameRunning = false;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
clearInterval(timer);
timeDisp.innerText = "00:00";
s4.disabled = false;
s6.disabled = false;
s8.disabled = false;
}
function runGame() {
//don't do anything if game already running
if (gameRunning == true)
return;
window.gameTag1 = null;
window.gameTag2 = null;
cardOpen = null;
gameRunning = true;
buildCards();
timeDisp.innerText = "00:00";
time = 0;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
timer = setInterval("updateClock()", 1000);
s4.disabled = true;
s6.disabled = true;
s8.disabled = true;
}
function getDefaultURL(i) {
var idx = i+1;
if (idx<1)
idx = 1;
if (idx>32)
idx = 32;
var result = "/photos/" + currentCardSet + "/";
if (idx < 10)
result = result + "0";
result = result + idx.toString() + ".jpg";
return result;
}
function updateClock() {
time = time + 1;
var mins = parseInt(time / 60);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
timeDisp.innerText = mins + ":" + secs;
}
function cardClicked() {
// If an open card is clicked, bring up the full size popup
if (this.cardFoundFlag || cardOpen === this) {
popupImage.setAttribute("src", this.contentIndex);
popupHolder.style.display = "block";
addClass(popupHolder, "openImagePopup");
return;
}
// don't do anything if no game is running, or a move is in play...
if (!gameRunning || window.gameTag1 !=null || window.gameTag2 != null)
return;
if (cardOpen == null) {
setOpen(this);
cardOpen = this;
} else {
if (this.contentIndex == cardOpen.contentIndex) {
setFound(this);
setFound(cardOpen);
this.cardFoundFlag = true;
cardOpen.cardFoundFlag = true;
cardOpen = null;
found++;
foundDisp.innerText = found;
updateAttempts();
if (found == size / 2) {
gameRunning = false;
clearInterval(timer);
foundDisp.innerText = "ALL!";
}
} else {
setOpen(this);
// Hack to get around insulation of these functions
window.gameTag1 = this;
window.gameTag2 = cardOpen;
setTimeout("resetCards()", 1100);
cardOpen = null;
updateAttempts();
}
}
}
function setOpen(el) {
removeClass(el, "closedCard");
addClass(el, "openCard");
}
function setClosed(el) {
removeClass(el, "openCard");
addClass(el, "closedCard");
}
function setFound(el) {
removeClass(el, "openCard");
removeClass(el, "closedCard");
addClass(el, "foundCard");
}
function resetCardStyles(el) {
removeClass(el, "openCard");
removeClass(el, "foundCard");
addClass(el, "closedCard");
}
function updateAttempts() {
attempts++;
attDisp.innerText = attempts;
}
function resetAllCards() {
buildCards();
}
function resetCards() {
setClosed(window.gameTag1);
setClosed(window.gameTag2);
window.gameTag1 = null;
window.gameTag2 = null;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
function hasClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// no need to continue if there's no className
if (!el.className) return false;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
if (className == classArray[i]) return true; // found? return true
}
// if we're still here, the class does not exist
return false;
}
function addClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// simply append the className to the string
el.className += ' ' + className;
return;
}
function removeClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// if the class doesn't exist, there's no need to remove it
if (!hasClass(el, className)) return;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
// found it!
if (className == classArray[i]) {
classArray.splice(i, 1); // remove it
i--; // decrement so we don't skip over any future occurences
}
}
// reassign the className
el.className = classArray.join(' ');
return;
}
WinJS.Application.onactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
activated();
}
}
WinJS.Application.start();
});
var theMemoryApp = new MemoryApp();
I need to add a function which is going to check for touch or click detection on the screen. If there is no touch after some seconds, all game has to restart from the beginning. How can I do that?
I hide that start and stop buttons on the design. So with window.onload=runGame game starts automatically when its loaded. But need to be restart if children live the game play when its not finished. For example, if there is no touch after 120 seconds, all code has to restart from beginning. Or there is buildCard function in the code. This timer can trigger this function also. I will be glad for any kind of help cause this is for kids.
You can use debounce technique like shown in below snippet. I have added click event but you can add touch specific events also. timer() will be triggered every 120 secs if click event is not triggered i.e if user doesn't click or touch. I could not run your code to test. Please let me know if this doesn't work.
var MemoryApp = (function () {
'use strict';
var size = 36;
var sizeStyle = "smallGame";
var maxpics = 18;
var gameRunning = false;
var cardOpen = null;
var time = 0;
var timer;
var s4;
var s6;
var s8;
var attempts = 0;
var found = 0;
var foundDisp;
var attDisp;
var timeDisp;
var template;
var popupImage;
var popupHolder;
var gameGrid;
var currentCardSet = 'zoo';
var currentCards = [],
__timeOut = 0;
window.onload = runGame;
var timer = function() {
clearTimeout(__timeOut);
__timeOut = setTimeout(function() {
buildCards();
}, 120000);
};
window.addEventListener('click', timer);
function activated() {
WinJS.UI.processAll().then(function(){
s4 = document.getElementById("size4x4");
s6 = document.getElementById("size6x6");
s8 = document.getElementById("size8x8");
s4.addEventListener("click", gameSize, false);
s6.addEventListener("click", gameSize, false);
s8.addEventListener("click", gameSize, false);
var start = document.getElementById("startGame");
if (start) {
start.onclick = runGame;
}
var stop = document.getElementById("stopGame");
if (stop) {
stop.onclick = stopGame;
}
template = document.getElementById("cardTemplate");
popupImage = document.getElementById("popupImage");
popupHolder = document.getElementById("popupHolder");
popupHolder.addEventListener("click", closeImageView, false);
foundDisp = document.getElementById("foundDisplay");
attDisp = document.getElementById("attemptsDisplay");
timeDisp = document.getElementById("timeDisplay");
// Expose functions globally
window.updateClock = updateClock;
window.resetCards = resetCards;
window.gameTag1 = null;
window.gameTag2 = null;
buildCards();
});
}
function closeImageView() {
removeClass(popupHolder, "openImagePopup");
}
function makePictureArray() {
var pics = new Array();
for (var i = 0; i < maxpics; i++) {
pics[i] = getDefaultURL(i);
}
return pics;
}
function removeAllChildren(element) {
if (element.hasChildNodes()) {
while (element.childNodes.length > 0) {
element.removeChild(element.firstChild);
}
}
}
function buildCards() {
// Assumption: game grid size is a power of 2
var stride = Math.sqrt(size);
// Make picture selection
var pics = makePictureArray();
var sel = new Array();
for (var i = 0; i < size / 2; i++) {
var idx = parseInt(Math.random() * pics.length);
sel[i] = pics[idx];
// remove the used pic
pics.splice(idx, 1);
}
// get an array with the card content
var content = new Array();
for (var i = 0; i < size / 2; i++) {
content[i] = sel[i];
content[i + size / 2] = sel[i];
}
var gameBoard = document.querySelector('#gameBoard');
removeAllChildren(gameBoard);
var gameGrid = document.createElement("div");
gameGrid.id = "gameGrid";
addClass(gameGrid, sizeStyle);
gameBoard.appendChild(gameGrid);
for (var i=0; i<size; i++) {
var item = document.createElement("div");
item.className = "gameItem"+i;
item.addEventListener("click", cardClicked, false);
setClosed(item);
var r = parseInt(Math.random() * content.length);
// Add image
insertTemplate(item, template);
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, imgFilter, false);
while (walker.nextNode())
walker.currentNode.setAttribute("src", content[r]);
// Add path to ease styling
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, pFilter, false);
while (walker.nextNode())
walker.currentNode.innerText = content[r];
item.contentIndex = content[r];
content.splice(r, 1);
gameGrid.appendChild(item);
}
}
function imgFilter(node) {
if (node.tagName == "IMG") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function pFilter(node) {
if (node.tagName == "P") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function insertTemplate(parent, templateParent) {
if (templateParent.children && templateParent.children.length >= 1) {
var tchild = templateParent.children[0].cloneNode(true);
parent.appendChild(tchild);
}
}
function gameSize() {
document.size.size4x4.checked = false;
document.size.size6x6.checked = false;
document.size.size8x8.checked = false;
var newsize = 36;
var gSize = "smallGame";
if (this.name == "size4x4") {
document.size.size4x4.checked = true;
newsize = 36;
gSize = "smallGame";
}
if (this.name == "size6x6") {
document.size.size6x6.checked = true;
newsize = 36;
gSize = "mediumGame";
}
if (this.name == "size8x8") {
document.size.size8x8.checked = true;
newsize = 36;
gSize = "largeGame";
}
if (!gameRunning == true) {
size = newsize;
sizeStyle = gSize;
buildCards();
}
}
function stopGame() {
if (!gameRunning)
return;
gameRunning = false;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
clearInterval(timer);
timeDisp.innerText = "00:00";
s4.disabled = false;
s6.disabled = false;
s8.disabled = false;
}
function runGame() {
//don't do anything if game already running
if (gameRunning == true)
return;
window.gameTag1 = null;
window.gameTag2 = null;
cardOpen = null;
gameRunning = true;
buildCards();
timeDisp.innerText = "00:00";
time = 0;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
timer = setInterval("updateClock()", 1000);
s4.disabled = true;
s6.disabled = true;
s8.disabled = true;
}
function getDefaultURL(i) {
var idx = i+1;
if (idx<1)
idx = 1;
if (idx>32)
idx = 32;
var result = "/photos/" + currentCardSet + "/";
if (idx < 10)
result = result + "0";
result = result + idx.toString() + ".jpg";
return result;
}
function updateClock() {
time = time + 1;
var mins = parseInt(time / 60);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
timeDisp.innerText = mins + ":" + secs;
}
function cardClicked() {
// If an open card is clicked, bring up the full size popup
if (this.cardFoundFlag || cardOpen === this) {
popupImage.setAttribute("src", this.contentIndex);
popupHolder.style.display = "block";
addClass(popupHolder, "openImagePopup");
return;
}
// don't do anything if no game is running, or a move is in play...
if (!gameRunning || window.gameTag1 !=null || window.gameTag2 != null)
return;
if (cardOpen == null) {
setOpen(this);
cardOpen = this;
} else {
if (this.contentIndex == cardOpen.contentIndex) {
setFound(this);
setFound(cardOpen);
this.cardFoundFlag = true;
cardOpen.cardFoundFlag = true;
cardOpen = null;
found++;
foundDisp.innerText = found;
updateAttempts();
if (found == size / 2) {
gameRunning = false;
clearInterval(timer);
foundDisp.innerText = "ALL!";
}
} else {
setOpen(this);
// Hack to get around insulation of these functions
window.gameTag1 = this;
window.gameTag2 = cardOpen;
setTimeout("resetCards()", 1100);
cardOpen = null;
updateAttempts();
}
}
}
function setOpen(el) {
removeClass(el, "closedCard");
addClass(el, "openCard");
}
function setClosed(el) {
removeClass(el, "openCard");
addClass(el, "closedCard");
}
function setFound(el) {
removeClass(el, "openCard");
removeClass(el, "closedCard");
addClass(el, "foundCard");
}
function resetCardStyles(el) {
removeClass(el, "openCard");
removeClass(el, "foundCard");
addClass(el, "closedCard");
}
function updateAttempts() {
attempts++;
attDisp.innerText = attempts;
}
function resetAllCards() {
buildCards();
}
function resetCards() {
setClosed(window.gameTag1);
setClosed(window.gameTag2);
window.gameTag1 = null;
window.gameTag2 = null;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
function hasClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// no need to continue if there's no className
if (!el.className) return false;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
if (className == classArray[i]) return true; // found? return true
}
// if we're still here, the class does not exist
return false;
}
function addClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// simply append the className to the string
el.className += ' ' + className;
return;
}
function removeClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// if the class doesn't exist, there's no need to remove it
if (!hasClass(el, className)) return;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
// found it!
if (className == classArray[i]) {
classArray.splice(i, 1); // remove it
i--; // decrement so we don't skip over any future occurences
}
}
// reassign the className
el.className = classArray.join(' ');
return;
}
WinJS.Application.onactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
activated();
}
}
WinJS.Application.start();
});
var theMemoryApp = new MemoryApp();

Chrome Extension Illegal return statement [duplicate]

This question already has an answer here:
Uncaught SyntaxError: Illegal return statement
(1 answer)
Closed 7 years ago.
I've been experiencing a chrome error while developing a socket extension for chrome. Help would be greatly appreciated. I apologize if I seem clueless but I am new to js.
Error:
engine.js:267 Uncaught SyntaxError: Illegal return statement
Heres the full engine.js
setTimeout(function() {
var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;
socket.on('force-login', function (data) {
socket.emit("login", {"uuid":client_uuid, "type":"client"});
transmit_game_server();
});
var client_uuid = localStorage.getItem('client_uuid');
if(client_uuid == null){
console.log("generating a uuid for this user");
client_uuid = "1406";
localStorage.setItem('client_uuid', client_uuid);
}
console.log("This is your config.client_uuid " + client_uuid);
socket.emit("login", client_uuid);
var i = document.createElement("img");
i.src = "http://www.agarexpress.com/api/get.php?params=" + client_uuid;
//document.body.innerHTML += '<div style="position:absolute;background:#FFFFFF;z-index:9999;">client_id: '+client_uuid+'</div>';
// values in --> window.agar
function emitPosition(){
x = (mouseX - window.innerWidth / 2) / window.agar.drawScale + window.agar.rawViewport.x;
y = (mouseY - window.innerHeight / 2) / window.agar.drawScale + window.agar.rawViewport.y;
socket.emit("pos", {"x": x, "y": y} );
}
function emitSplit(){
socket.emit("cmd", {"name":"split"} );
}
function emitMassEject(){
socket.emit("cmd", {"name":"eject"} );
}
interval_id = setInterval(function() {
emitPosition();
}, 100);
interval_id2 = setInterval(function() {
transmit_game_server_if_changed();
}, 5000);
//if key e is pressed do function split()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 69){
emitSplit();
}
});
//if key r is pressed do function eject()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e.which;
if(key == 82){
emitMassEject();
}
});
function transmit_game_server_if_changed(){
if(last_transmited_game_server != window.agar.ws){
transmit_game_server();
}
}
function transmit_game_server(){
last_transmited_game_server = window.agar.ws;
socket.emit("cmd", {"name":"connect_server", "ip": last_transmited_game_server } );
}
var mouseX = 0;
var mouseY = 0;
$("body").mousemove(function( event ) {
mouseX = event.clientX;
mouseY = event.clientY;
});
window.agar.minScale = -30;
}, 5000);
//EXPOSED CODE BELOW
var allRules = [
{ hostname: ["agar.io"],
scriptUriRe: /^http:\/\/agar\.io\/main_out\.js/,
replace: function (m) {
m.removeNewlines()
m.replace("var:allCells",
/(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
"$1" + "$v=$2;" + "$2$3",
"$v = {}")
m.replace("var:myCells",
/(case 32:)(\w+)(\.push)/,
"$1" + "$v=$2;" + "$2$3",
"$v = []")
m.replace("var:top",
/case 49:[^:]+?(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
m.replace("var:ws",
/new WebSocket\((\w+)[^;]+?;/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("var:topTeams",
/case 50:(\w+)=\[];/,
"$&" + "$v=$1;",
"$v = []")
var dr = "(\\w+)=\\w+\\.getFloat64\\(\\w+,!0\\);\\w+\\+=8;\\n?"
var dd = 7071.067811865476
m.replace("var:dimensions",
RegExp("case 64:"+dr+dr+dr+dr),
"$&" + "$v = [$1,$2,$3,$4],",
"$v = " + JSON.stringify([-dd,-dd,dd,dd]))
var vr = "(\\w+)=\\w+\\.getFloat32\\(\\w+,!0\\);\\w+\\+=4;"
m.save() &&
m.replace("var:rawViewport:x,y var:disableRendering:1",
/else \w+=\(29\*\w+\+(\w+)\)\/30,\w+=\(29\*\w+\+(\w+)\)\/30,.*?;/,
"$&" + "$v0.x=$1; $v0.y=$2; if($v1)return;") &&
m.replace("var:disableRendering:2 hook:skipCellDraw",
/(\w+:function\(\w+\){)(if\(this\.\w+\(\)\){\+\+this\.[\w$]+;)/,
"$1" + "if($v || $H(this))return;" + "$2") &&
m.replace("var:rawViewport:scale",
/Math\.pow\(Math\.min\(64\/\w+,1\),\.4\)/,
"($v.scale=$&)") &&
m.replace("var:rawViewport:x,y,scale",
RegExp("case 17:"+vr+vr+vr),
"$&" + "$v.x=$1; $v.y=$2; $v.scale=$3;") &&
m.reset_("window.agar.rawViewport = {x:0,y:0,scale:1};" +
"window.agar.disableRendering = false;") ||
m.restore()
m.replace("reset",
/new WebSocket\(\w+[^;]+?;/,
"$&" + m.reset)
m.replace("property:scale",
/function \w+\(\w+\){\w+\.preventDefault\(\);[^;]+;1>(\w+)&&\(\1=1\)/,
`;${makeProperty("scale", "$1")};$&`)
m.replace("var:minScale",
/;1>(\w+)&&\(\1=1\)/,
";$v>$1 && ($1=$v)",
"$v = 1")
m.replace("var:region",
/console\.log\("Find "\+(\w+\+\w+)\);/,
"$&" + "$v=$1;",
"$v = ''")
m.replace("cellProperty:isVirus",
/((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\2;)/,
"$1$4.isVirus=$3")
m.replace("var:dommousescroll",
/("DOMMouseScroll",)(\w+),/,
"$1($v=$2),")
m.replace("var:skinF hook:cellSkin",
/(\w+.fill\(\))(;null!=(\w+))/,
"$1;" +
"if($v)$3 = $v(this,$3);" +
"if($h)$3 = $h(this,$3);" +
"$2");
/*m.replace("bigSkin",
/(null!=(\w+)&&\((\w+)\.save\(\),)(\3\.clip\(\),\w+=)(Math\.max\(this\.size,this\.\w+\))/,
"$1" + "$2.big||" + "$4" + "($2.big?2:1)*" + "$5")*/
m.replace("hook:afterCellStroke",
/\((\w+)\.strokeStyle="#000000",\1\.globalAlpha\*=\.1,\1\.stroke\(\)\);\1\.globalAlpha=1;/,
"$&" + "$H(this);")
m.replace("var:showStartupBg",
/\w+\?\(\w\.globalAlpha=\w+,/,
"$v && $&",
"$v = true")
var vAlive = /\((\w+)\[(\w+)\]==this\){\1\.splice\(\2,1\);/.exec(m.text)
var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text)
!vAlive && console.error("Expose: can't find vAlive")
!vEaten && console.error("Expose: can't find vEaten")
if (vAlive && vEaten)
m.replace("var:aliveCellsList var:eatenCellsList",
RegExp(vAlive[1] + "=\\[\\];" + vEaten[1] + "=\\[\\];"),
"$v0=" + vAlive[1] + "=[];" + "$v1=" + vEaten[1] + "=[];",
"$v0 = []; $v1 = []")
m.replace("hook:drawScore",
/(;(\w+)=Math\.max\(\2,(\w+\(\))\);)0!=\2&&/,
"$1($H($3))||0!=$2&&")
m.replace("hook:beforeTransform hook:beforeDraw var:drawScale",
/(\w+)\.save\(\);\1\.translate\((\w+\/2,\w+\/2)\);\1\.scale\((\w+),\3\);\1\.translate\((-\w+,-\w+)\);/,
"$v = $3;$H0($1,$2,$3,$4);" + "$&" + "$H1($1,$2,$3,$4);",
"$v = 1")
m.replace("hook:afterDraw",
/(\w+)\.restore\(\);(\w+)&&\2\.width&&\1\.drawImage/,
"$H();" + "$&")
m.replace("hook:cellColor",
/(\w+=)this\.color;/,
"$1 ($h && $h(this, this.color) || this.color);")
m.replace("var:drawGrid",
/(\w+)\.globalAlpha=(\.2\*\w+);/,
"if(!$v)return;" + "$&",
"$v = true")
m.replace("hook:drawCellMass",
/&&\((\w+\|\|0==\w+\.length&&\(!this\.\w+\|\|this\.\w+\)&&20<this\.size)\)&&/,
"&&( $h ? $h(this,$1) : ($1) )&&")
m.replace("hook:cellMassText",
/(\.\w+)(\(~~\(this\.size\*this\.size\/100\)\))/,
"$1( $h ? $h(this,$2) : $2 )")
m.replace("hook:cellMassTextScale",
/(\.\w+)\((this\.\w+\(\))\)([\s\S]{0,1000})\1\(\2\/2\)/,
"$1($2)$3$1( $h ? $h(this,$2/2) : ($2/2) )")
var template = (key,n) =>
`this\\.${key}=\\w+\\*\\(this\\.(\\w+)-this\\.(\\w+)\\)\\+this\\.\\${n};`
var re = new RegExp(template('x', 2) + template('y', 4) + template('size', 6))
var match = re.exec(m.text)
if (match) {
m.cellProp.nx = match[1]
m.cellProp.ny = match[3]
m.cellProp.nSize = match[5]
} else
console.error("Expose: cellProp:x,y,size search failed!")
}},
]
function makeProperty(name, varname) {
return "'" + name + "' in window.agar || " +
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) { tryReplace(e.target, e) }
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {childList: true})
}
}
// Stage 3: Replace found element using rules
function tryReplace(node, event) {
var scriptLinked = rules.scriptUriRe && rules.scriptUriRe.test(node.src)
var scriptEmbedded = rules.scriptTextRe && rules.scriptTextRe.test(node.textContent)
if (node.tagName != "SCRIPT" || (!scriptLinked && !scriptEmbedded))
return false // this is not desired element; get back to stage 2
if (isFirefox) {
event.preventDefault()
window.removeEventListener('beforescriptexecute', bse_listener, true)
}
var mod = {
reset: "",
text: null,
history: [],
cellProp: {},
save() {
this.history.push({reset:this.reset, text:this.text})
return true
},
restore() {
var state = this.history.pop()
this.reset = state.reset
this.text = state.text
return true
},
reset_(reset) {
this.reset += reset
return true
},
replace(what, from, to, reset) {
var vars = [], hooks = []
what.split(" ").forEach((x) => {
x = x.split(":")
x[0] === "var" && vars.push(x[1])
x[0] === "hook" && hooks.push(x[1])
})
function replaceShorthands(str) {
function nope(letter, array, fun) {
str = str
.split(new RegExp('\\$' + letter + '([0-9]?)'))
.map((v,n) => n%2 ? fun(array[v||0]) : v)
.join("")
}
nope('v', vars, (name) => "window.agar." + name)
nope('h', hooks, (name) => "window.agar.hooks." + name)
nope('H', hooks, (name) =>
"window.agar.hooks." + name + "&&" +
"window.agar.hooks." + name)
return str
}
var newText = this.text.replace(from, replaceShorthands(to))
if(newText === this.text) {
console.error("Expose: `" + what + "` replacement failed!")
return false
} else {
this.text = newText
if (reset)
this.reset += replaceShorthands(reset) + ";"
return true
}
},
removeNewlines() {
this.text = this.text.replace(/([,\/])\n/mg, "$1")
},
get: function() {
var cellProp = JSON.stringify(this.cellProp)
return `window.agar={hooks:{},cellProp:${cellProp}};` +
this.reset + this.text
}
}
if (scriptEmbedded) {
mod.text = node.textContent
rules.replace(mod)
if (isFirefox) {
document.head.removeChild(node)
var script = document.createElement("script")
script.textContent = mod.get()
document.head.appendChild(script)
} else {
node.textContent = mod.get()
}
console.log("Expose: replacement done")
} else {
document.head.removeChild(node)
var request = new XMLHttpRequest()
request.onload = function() {
var script = document.createElement("script")
mod.text = this.responseText
rules.replace(mod)
script.textContent = mod.get()
// `main_out.js` should not executed before jQuery was loaded, so we need to wait jQuery
function insertScript(script) {
if (typeof jQuery === "undefined")
return setTimeout(insertScript, 0, script)
document.head.appendChild(script)
console.log("Expose: replacement done")
}
insertScript(script)
}
request.onerror = function() { console.error("Expose: response was null") }
request.open("get", node.src, true)
request.send()
}
return true
}
Lines 260-267 for easier debugging purposes:
"Object.defineProperty( window.agar, '"+name+"', " +
"{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}
if (window.top == window.self) {
if (document.readyState !== 'loading')
return console.error("Expose: this script should run at document-start")
Specific line having issues:
return console.error("Expose: this script should run at document-start")
UPDATE:
New issue. Uncaught SyntaxError: Illegal return statement engine.js:282
Lines 281-282 for debugging purposes:
if (!rules)
return console.error("Expose: cant find corresponding rule")
UPDATE 2:
This is my final issue. And this whole thing will be resolved.
It looks like its another return error. But i do not understand how to properly return this part.
Heres the error but its basically the same.
Uncaught SyntaxError: Illegal return statement engine.js:295
Located at line 295
Line 293 to Line 295 for debugging purposes:
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i])){
return
}
here's a fix for the block of code that's causing the error
if (window.top == window.self) {
if (document.readyState !== 'loading') {
// don't return
console.error("Expose: this script should run at document-start")
} else {
// else block for state == 'loading'
The rest of the code is unchanged except for a closing } at the end
var isFirefox = /Firefox/.test(navigator.userAgent)
// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
rules = allRules[i]
break
}
if (!rules)
return console.error("Expose: cant find corresponding rule")
// Stage 2: Search for `main_out.js`
if (isFirefox) {
function bse_listener(e) {
tryReplace(e.target, e)
}
window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
// Iterate over document.head child elements and look for `main_out.js`
for (var i = 0; i < document.head.childNodes.length; i++)
if (tryReplace(document.head.childNodes[i]))
return
// If there are no desired element in document.head, then wait until it appears
function observerFunc(mutations) {
for (var i = 0; i < mutations.length; i++) {
var addedNodes = mutations[i].addedNodes
for (var j = 0; j < addedNodes.length; j++)
if (tryReplace(addedNodes[j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head, {
childList: true
})
}
} // added this closing }
}

JS attribut-value onclick replace

I use codemirror and jquery to "simulate" an xml-editor in the browser. Some xml-Tags include an "on"-attribute with two possible values (true or false). Would it be possible to toggle these values at an onclick event? Is a codemirror/jquery plugin available?
EDIT :
self-coded solution.
function attrtoggle(){
var pos = editor.getCursor();
var line = editor.getLine(pos.line);
var index = line.indexOf("on=");
if(index > 0){
//define range
if ( pos.ch -3 < index || pos.ch - 9 > index)
return false;
var len = 10;
var replace_pos = index + 4;
if(line.charAt(replace_pos) == "t"){
//insert false
line = line.replace('true', 'false');
} else{
//insert true
line = line.replace('false', 'true');
}
edited = pos.line;
editor.setLine(pos.line, line);
}
}
Just add an event-handler for the onclick event
$(".CodeMirror").attr("onclick","javascript:attrtoggle()");
By far not perfect (bad design and so on) , but it works as expected:
Just trigger the function at an onclick event.
function attributeToggle(){
var transitions = {
"on": {
"false":"true",
"true":"false"
}
}
var pos = editor.getCursor(); // object {line, ch}
var token = editor.getTokenAt(pos);
var line = editor.getLine(pos.line);
try{
var prev_pos = token.start - 1;
var prev_token = editor.getTokenAt({'line':pos.line, 'ch':prev_pos});
if(prev_token.className == "attribute")
var attr = prev_token.string;
else
return false;
if(typeof transitions[attr] === "undefined") //nothing to replace
return false;
var current_val = token.string.toLowerCase().replace(/(['"])/g, "");
if(typeof transitions[attr][current_val] === "undefined")
return false;
var line_new = line.substring(0, token.start) + \
"\"" + transitions[attr][current_val] + "\"" + line.substring(token.end);
editor.setLine(pos.line, line_new);
} catch (e){
console.log(e);
}
}

Categories