<commit_before>document.addEventListener("DOMContentLoaded", function(event) {
	let gameData = {
		level: 1,
		stats: {
			clicks: {
				id: "clicks",
				value: 0
			},
			moves: {
				id: "moves",
				value: 0
			},
			score: {
				id: "score",
				value: 0
			},
			level: {
				id: "level",
				value: 1
			}
		},
		active: "",
		matches: [],
		clickQ: [],
		squares: []
	}

	let utils = {
		draw: {
			pickRandomColor: function(obj, num) {
				//obj = colors object, num = number of colors to pick from
				var colors = Object.keys(obj)
				return obj[colors[(num * Math.random()) << 0]]
			},
			fillSquares: function(num) {
				//num defines how many colored squares to get
				for (var i = 1; i <= num; i++) {
					var randomId = Math.floor(Math.random() * 49 + 1)
					var squareToFill = document.getElementById("sq" + randomId)
					squareToFill.style.backgroundColor = utils.draw.pickRandomColor(
						utils.colors,
						3
					)
				}
			},
			fillEmptySquares: function(num) {
				for (var i = 1; i <= num; i++) {
					var rowId = Math.floor(Math.random() * 7)
					var colId = Math.floor(Math.random() * 7)
					var squareToFill = document.getElementById(`sq${rowId}${colId}`)
					if (squareToFill.style.backgroundColor) {
						console.log("picked a full square!")
						i--
					} else {
						squareToFill.style.backgroundColor = utils.draw.pickRandomColor(
							utils.colors,
							3
						)
					}
				}
			}
		},
		init: {
			drawBoard: function() {
				var board = document.getElementById("boardcontainer")
				var width = 6

				for (var r = 0; r <= width; r++) {
					var row = document.createElement("div")
					row.setAttribute("id", "row" + r)
					row.setAttribute("class", "row")
					board.appendChild(row)

					gameData.squares.push([])

					var rowElem = document.getElementById(`row${r}`)

					for (var c = 0; c <= width; c++) {
						var sq = document.createElement("div")
						sq.setAttribute("id", `sq${r}${c}`)
						sq.setAttribute("class", "square")
						sq.dataset.x = r
						sq.dataset.y = c
						rowElem.appendChild(sq)
						gameData.squares[r].push(sq)
					}
				}
			}
		},

		makeActive: function(id) {
			let current = document.getElementById(id)
			current.classList.add("active")
		},

		makeInactive: function(id) {
			let current = document.getElementById(id)
			current.classList.remove("active")
		},

		moveSquare: function(from, to) {
			let fromSquare = document.getElementById(from)
			let toSquare = document.getElementById(to)

			toSquare.style.backgroundColor = fromSquare.style.backgroundColor
			fromSquare.removeAttribute("style")
			fromSquare.classList.remove("active")
			gameData.active = ""
			gameData.stats.moves.value += 1

			utils.draw.fillEmptySquares(1)
		},

		updateNumbers: function() {
			for (stat in gameData.stats) {
				gameData.stats[stat]
				let elem = document.getElementById(gameData.stats[stat].id)
				let value = gameData.stats[stat].value
				elem.innerHTML = value
			}
		},

		onClick: function(e) {
			gameData.stats.clicks.value += 1
			let targetID = e.target.id

			// keep queue short
			if (gameData.clickQ.length > 5) {
				gameData.clickQ.pop()
			}

			gameData.clickQ.unshift(targetID)

			if (!gameData.active) {
				// set active id
				gameData.active = targetID
				// make active visually
				utils.makeActive(gameData.active)
				// if the clicked element is the active element
			} else if (gameData.active === targetID) {
				// then deselect
				utils.makeInactive(gameData.active)
				gameData.active = null
			} else {
				// move square
				let from = gameData.clickQ[1]
				let to = gameData.clickQ[0]
				let toElem = document.getElementById(to)

				// only move if we click on an empty square
				if (!toElem.style.backgroundColor) {
					utils.moveSquare(from, to)
				}
			}

			utils.updateNumbers()

			console.log(gameData.matches)
		},

		colors: {
			blue: "#2882ff",
			red: "#ff141d",
			green: "#00f40d",
			orange: "#ff9300",
			purple: "#ff00bd",
			cyan: "#14fcff"
		}
	}

	function Game() {
		//main game is here
		// window.addEventListener("DOMContentLoaded", this.init)

		window.requestAnimationFrame =
			window.requestAnimationFrame ||
			window.mozRequestAnimationFrame ||
			window.webkitRequestAnimationFrame ||
			window.oRequestAnimationFrame

		window.requestAnimationFrame(this.draw.bind(this))
	}

	Game.prototype.draw = function() {
		this.update()

		requestAnimationFrame(this.draw.bind(this))
	}

	Game.prototype.update = function() {
		this.checkNeighborsLoop()
	}

	Game.prototype.checkDR = function(x, y, matched) {
		if (
			y < 6 &&
			x < 6 &&
			gameData.squares[x + 1][y + 1].style.backgroundColor ===
			gameData.squares[x][y].style.backgroundColor
		) {
			matched.push(gameData.squares[x + 1][y + 1])
			this.checkDR(x + 1, y + 1, matched)
		} else {
			if (matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkUR = function(x, y, matched) {
		if (
			y < 6 &&
			x > 0 &&
			gameData.squares[x - 1][y + 1].style.backgroundColor ===
			gameData.squares[x][y].style.backgroundColor
		) {
			matched.push(gameData.squares[x - 1][y + 1])
			this.checkUR(x - 1, y + 1, matched)
		} else {
			if (matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkRight = function(x, y, matched) {
		if (
			y < 6 &&
			gameData.squares[x][y + 1].style.backgroundColor ===
			gameData.squares[x][y].style.backgroundColor
		) {
			matched.push(gameData.squares[x][y + 1])
			this.checkRight(x, y + 1, matched)
		} else {
			if (matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkDown = function(x, y, matched) {
		if(
			x < 6 &&
			gameData.squares[x + 1][y].style.backgroundColor ===
			gameData.squares[x][y].style.backgroundColor
		) {
			//
			matched.push(gameData.squares[x + 1][y])
			this.checkDown(x + 1, y, matched)
		}
		else {
			if(matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkNeighbors = function(x, y) {
		let matched = [gameData.squares[x][y]]
		// check down if x < 6

		this.checkDown(x, y, matched)
		this.checkRight(x, y, matched)
		this.checkDR(x, y, matched)
		this.checkUR(x, y, matched)

			// if next square is a match, add to matches
			// if not, skip
	}

	Game.prototype.checkNeighborsLoop = function() {
		for (let x = 0; x <= 6; x++) {
			for (let y = 0; y <= 6; y++) {
				// if no color, skip
				if (gameData.squares[x][y].style.backgroundColor) {
					// initiate checking functions
					this.checkNeighbors(x, y)
					this.removeMatches()
				}
			}
		}
	}

	Game.prototype.removeMatches = function() {
		if (gameData.matches.length > 0) {
			gameData.matches.forEach((match, m) => {
				match.forEach((sq, i, arr) => {
					sq.removeAttribute("style")
					gameData.stats.score.value += 1
					arr.splice(i, 1)
				})
				// match.splice(m, 1)
			})
		}
	}

	Game.prototype.init = function() {
		console.log("init fired")

		utils.init.drawBoard()

		var squareListeners = document.getElementsByClassName("square")
		// setup onclick handlers
		for (var i = 0; i < squareListeners.length; i++) {
			squareListeners[i].addEventListener("click", utils.onClick, false)
		}

		utils.draw.fillEmptySquares(3)
	}

	//init the game here and stuff
	var game = new Game()
	game.init()
})
<commit_msg>add score multiplier<commit_after>document.addEventListener("DOMContentLoaded", function(event) {
	let gameData = {
		level: 1,
		stats: {
			clicks: {
				id: "clicks",
				value: 0
			},
			moves: {
				id: "moves",
				value: 0
			},
			score: {
				id: "score",
				value: 0
			},
			level: {
				id: "level",
				value: 1
			}
		},
		squaresToFill: level.value + 1,
		active: "",
		matches: [],
		clickQ: [],
		squares: []
	}

	let utils = {
		draw: {
			pickRandomColor: function(obj, num) {
				//obj = colors object, num = number of colors to pick from
				var colors = Object.keys(obj)
				return obj[colors[(num * Math.random()) << 0]]
			},
			fillSquares: function(num) {
				//num defines how many colored squares to get
				for (var i = 1; i <= num; i++) {
					var randomId = Math.floor(Math.random() * 49 + 1)
					var squareToFill = document.getElementById("sq" + randomId)
					squareToFill.style.backgroundColor = utils.draw.pickRandomColor(
						utils.colors,
						3
					)
				}
			},
			fillEmptySquares: function(num) {
				for (var i = 1; i <= num; i++) {
					var rowId = Math.floor(Math.random() * 7)
					var colId = Math.floor(Math.random() * 7)
					var squareToFill = document.getElementById(`sq${rowId}${colId}`)
					if (squareToFill.style.backgroundColor) {
						console.log("picked a full square!")
						i--
					} else {
						squareToFill.style.backgroundColor = utils.draw.pickRandomColor(
							utils.colors,
							3
						)
					}
				}
			}
		},
		init: {
			drawBoard: function() {
				var board = document.getElementById("boardcontainer")
				var width = 6

				for (var r = 0; r <= width; r++) {
					var row = document.createElement("div")
					row.setAttribute("id", "row" + r)
					row.setAttribute("class", "row")
					board.appendChild(row)

					gameData.squares.push([])

					var rowElem = document.getElementById(`row${r}`)

					for (var c = 0; c <= width; c++) {
						var sq = document.createElement("div")
						sq.setAttribute("id", `sq${r}${c}`)
						sq.setAttribute("class", "square")
						sq.dataset.x = r
						sq.dataset.y = c
						rowElem.appendChild(sq)
						gameData.squares[r].push(sq)
					}
				}
			}
		},

		makeActive: function(id) {
			let current = document.getElementById(id)
			current.classList.add("active")
		},

		makeInactive: function(id) {
			let current = document.getElementById(id)
			current.classList.remove("active")
		},

		moveSquare: function(from, to) {
			let fromSquare = document.getElementById(from)
			let toSquare = document.getElementById(to)

			toSquare.style.backgroundColor = fromSquare.style.backgroundColor
			fromSquare.removeAttribute("style")
			fromSquare.classList.remove("active")
			gameData.active = ""
			gameData.stats.moves.value += 1

			utils.draw.fillEmptySquares(1)
		},

		updateNumbers: function() {
			for (stat in gameData.stats) {
				gameData.stats[stat]
				let elem = document.getElementById(gameData.stats[stat].id)
				let value = gameData.stats[stat].value
				console.log(stat, value)
				elem.innerHTML = value
			}
		},

		onClick: function(e) {
			gameData.stats.clicks.value += 1
			let targetID = e.target.id

			// keep queue short
			if (gameData.clickQ.length > 5) {
				gameData.clickQ.pop()
			}

			gameData.clickQ.unshift(targetID)

			if (!gameData.active) {
				// set active id
				gameData.active = targetID
				// make active visually
				utils.makeActive(gameData.active)
				// if the clicked element is the active element
			} else if (gameData.active === targetID) {
				// then deselect
				utils.makeInactive(gameData.active)
				gameData.active = null
			} else {
				// move square
				let from = gameData.clickQ[1]
				let to = gameData.clickQ[0]
				let toElem = document.getElementById(to)

				// only move if we click on an empty square
				if (!toElem.style.backgroundColor) {
					utils.moveSquare(from, to)
				}
			}

			utils.updateNumbers()

			console.log(gameData.matches)
		},

		colors: {
			blue: "#2882ff",
			red: "#ff141d",
			green: "#00f40d",
			orange: "#ff9300",
			purple: "#ff00bd",
			cyan: "#14fcff"
		}
	}

	function Game() {
		//main game is here
		// window.addEventListener("DOMContentLoaded", this.init)

		window.requestAnimationFrame =
			window.requestAnimationFrame ||
			window.mozRequestAnimationFrame ||
			window.webkitRequestAnimationFrame ||
			window.oRequestAnimationFrame

		window.requestAnimationFrame(this.draw.bind(this))
	}

	Game.prototype.draw = function() {
		this.update()

		requestAnimationFrame(this.draw.bind(this))
	}

	Game.prototype.update = function() {
		this.checkNeighborsLoop()
	}

	Game.prototype.checkDR = function(x, y, matched) {
		if (
			y < 6 &&
			x < 6 &&
			gameData.squares[x + 1][y + 1].style.backgroundColor ===
				gameData.squares[x][y].style.backgroundColor
		) {
			matched.push(gameData.squares[x + 1][y + 1])
			this.checkDR(x + 1, y + 1, matched)
		} else {
			if (matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkUR = function(x, y, matched) {
		if (
			y < 6 &&
			x > 0 &&
			gameData.squares[x - 1][y + 1].style.backgroundColor ===
				gameData.squares[x][y].style.backgroundColor
		) {
			matched.push(gameData.squares[x - 1][y + 1])
			this.checkUR(x - 1, y + 1, matched)
		} else {
			if (matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkRight = function(x, y, matched) {
		if (
			y < 6 &&
			gameData.squares[x][y + 1].style.backgroundColor ===
				gameData.squares[x][y].style.backgroundColor
		) {
			matched.push(gameData.squares[x][y + 1])
			this.checkRight(x, y + 1, matched)
		} else {
			if (matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkDown = function(x, y, matched) {
		if (
			x < 6 &&
			gameData.squares[x + 1][y].style.backgroundColor ===
				gameData.squares[x][y].style.backgroundColor
		) {
			//
			matched.push(gameData.squares[x + 1][y])
			this.checkDown(x + 1, y, matched)
		} else {
			if (matched.length >= 4) {
				gameData.matches[x] = matched
			}
		}
	}

	Game.prototype.checkNeighbors = function(x, y) {
		let matched = [gameData.squares[x][y]]
		// check down if x < 6

		this.checkDown(x, y, matched)
		this.checkRight(x, y, matched)
		this.checkDR(x, y, matched)
		this.checkUR(x, y, matched)
	}

	Game.prototype.checkNeighborsLoop = function() {
		for (let x = 0; x <= 6; x++) {
			for (let y = 0; y <= 6; y++) {
				// if no color, skip
				if (gameData.squares[x][y].style.backgroundColor) {
					// initiate checking functions
					this.checkNeighbors(x, y)
					this.removeMatches()
				}
			}
		}
	}

	Game.prototype.calcScore = function(length) {
		let mult

		switch (length) {
			case 4:
				mult = 10
				break
			case 5:
				mult = 12.5
				break
			case 6:
				mult = 17.5
				break
			case 7:
				mult = 25
				break
			default:
				mult = 40
				break
		}

		let filler = Array(length).fill(1 * mult, 0)

		let score = filler.reduce((acc, curr) => {
			return acc += curr
		})

		gameData.stats.score.value += score
	}

	Game.prototype.removeMatches = function() {
		let self = this
		if (gameData.matches.length > 0) {
			gameData.matches.forEach((match, m, gdArr) => {
				self.calcScore(match.length)

				match.forEach(sq => {
					sq.removeAttribute("style")
				})
				gdArr.splice(m, 1)
			})
		}
	}

	Game.prototype.init = function() {
		console.log("init fired")

		utils.init.drawBoard()

		var squareListeners = document.getElementsByClassName("square")
		// setup onclick handlers
		for (var i = 0; i < squareListeners.length; i++) {
			squareListeners[i].addEventListener("click", utils.onClick, false)
		}

		utils.draw.fillEmptySquares(3)
	}

	//init the game here and stuff
	var game = new Game()
	game.init()
})
<|endoftext|>


<commit_before>//Eric Wan
//A script I wrote to add this page to your favorites
//no idea why anyone would but whatever
var url
if ('sidebar' in window  && 'addPanel' in window.sidebar) {//mozilla
  window.sidebar.addPanel(location.href, document.title, "");
} else if( /*@cc_on!@*/false) {//IE why would you willingly use IE
  window.external.AddFavorite(location.href, document.title);
} else {//safari or chrome
  alert('Press " + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D to boomark this page.');
}
<commit_msg>friggin smart that's what i am<commit_after>//Eric Wan
//A script I wrote to add this page to your favorites
//no idea why anyone would but whatever
if ('sidebar' in window  && 'addPanel' in window.sidebar) {//mozilla
  window.sidebar.addPanel(location.href, document.title, "");
} else if( /*@cc_on!@*/false) {//IE why would you willingly use IE
  window.external.AddFavorite(location.href, document.title);
} else {//safari or chrome
  alert('Press " + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D to boomark this page.');
}
<|endoftext|>


<commit_before>/*
 *  shot.js
 *  2015/10/09
 *  @auther minimo
 *  This Program is MIT license.
 */

pbr.checkLayers = [LAYER_OBJECT_UPPER, LAYER_OBJECT, LAYER_OBJECT_LOWER];

phina.define("pbr.Shot", {
    superClass: "phina.display.Sprite",

    _member: {
        layer: LAYER_SHOT,
        parentScene: null,
        player: null,

        speed: 15,
        power: 1,
        defaultSpeed: 15,
        defaultPower: 1,
    },

    init: function(rotation, power, type) {
        if (type == 0) {
            this.superInit("shot1", 16, 16);
            this.setScale(2);
        } else {
            this.superInit("shot2", 16, 32);
            this.scaleX = 1.5;
        }
        this.$extend(this._member);

        this.rotation = rotation || 0;
        this.speed = this.defaultSpeed;
        this.power = power || this.defaultPower;

        this.alpha = 0.8;
        this.blendMode = "lighter";

        rotation-=90;
        this.vx = Math.cos(rotation*toRad) * this.speed;
        this.vy = Math.sin(rotation*toRad) * this.speed;

        //当り判定設定
        this.boundingType = "circle";
        if (type == 0) {
            this.radius = 6;
        } else {
            this.radius = 12;
        }

        this.beforeX = this.x;
        this.beforeY = this.y;
    },
    update: function() {
        this.x += this.vx;
        this.y += this.vy;

        if (this.x<-20 || this.x>SC_W+20 || this.y<-20 || this.y>SC_H+20) {
            this.remove();
        }

        //敵との当り判定チェック
        for (var i = 0; i < 3; i++) {
            var layer = this.parentScene.layers[pbr.checkLayers[i]];
            layer.children.each(function(a) {
                if (a === app.player) return;
                if (this.parent && a.isCollision && a.isHitElement(this)) {
                    a.damage(this.power);
                    this.vanish();
                    this.remove();
                    return;
                }
            }.bind(this));
        }
    },

    vanish: function() {
    },
});
<commit_msg>add shot impact<commit_after>/*
 *  shot.js
 *  2015/10/09
 *  @auther minimo
 *  This Program is MIT license.
 */

pbr.checkLayers = [LAYER_OBJECT_UPPER, LAYER_OBJECT, LAYER_OBJECT_LOWER];

phina.define("pbr.Shot", {
    superClass: "phina.display.Sprite",

    _member: {
        layer: LAYER_SHOT,
        parentScene: null,
        player: null,

        speed: 15,
        power: 1,
        defaultSpeed: 15,
        defaultPower: 1,
    },

    init: function(rotation, power, type) {
        if (type == 0) {
            this.superInit("shot1", 16, 16);
            this.setScale(2);
        } else {
            this.superInit("shot2", 16, 32);
            this.scaleX = 1.5;
        }
        this.$extend(this._member);

        this.rotation = rotation || 0;
        this.speed = this.defaultSpeed;
        this.power = power || this.defaultPower;

        this.alpha = 0.8;
        this.blendMode = "lighter";

        rotation-=90;
        this.vx = Math.cos(rotation*toRad) * this.speed;
        this.vy = Math.sin(rotation*toRad) * this.speed;

        //当り判定設定
        this.boundingType = "circle";
        if (type == 0) {
            this.radius = 6;
        } else {
            this.radius = 12;
        }

        this.beforeX = this.x;
        this.beforeY = this.y;
    },
    update: function() {
        this.x += this.vx;
        this.y += this.vy;

        if (this.x<-20 || this.x>SC_W+20 || this.y<-20 || this.y>SC_H+20) {
            this.remove();
        }

        //敵との当り判定チェック
        for (var i = 0; i < 3; i++) {
            var layer = this.parentScene.layers[pbr.checkLayers[i]];
            layer.children.each(function(a) {
                if (a === app.player) return;
                if (this.parent && a.isCollision && a.isHitElement(this)) {
                    a.damage(this.power);
                    this.vanish();
                    this.remove();
                    return;
                }
            }.bind(this));
        }
    },

    vanish: function() {
        pbr.Effect.ShotImpact().addChildTo(this.parentScene).setPosition(this.x, this.y);
        pbr.Effect.enterDebrisSmall(this.parentScene, this.x, this.y, 1);
    },
});
<|endoftext|>


<commit_before>/*! Promiscuous ©2013 Ruben Verborgh @license MIT https://github.com/RubenVerborgh/promiscuous*/
(function (exports,tick) {
	var func = 'function';
	// Creates a deferred: an object with a promise and corresponding resolve/reject methods
	function Deferred() {
		// The `handler` variable points to the function that will
		// 1) handle a .then(onFulfilled, onRejected) call
		// 2) handle a .resolve or .reject call (if not fulfilled)
		// Before 2), `handler` holds a queue of callbacks.
		// After 2), `handler` is a simple .then handler.
		// We use only one function to save memory and complexity.
		var handler = function (onFulfilled, onRejected, value) {
			// Case 1) handle a .then(onFulfilled, onRejected) call
			var createdDeffered;
			if (onFulfilled !== handler) {
				createdDeffered = createDeferred();
				handler.queue.push({ deferred: createdDeffered, resolve: onFulfilled, reject: onRejected });
				return createdDeffered.promise;
			}

			// Case 2) handle a .resolve or .reject call
			// (`onFulfilled` acts as a sentinel)
			// The actual function signature is
			// .re[ject|solve](sentinel, success, value)
			var action = onRejected ? 'resolve' : 'reject',queue,deferred,callback;
			for (var i = 0, l = handler.queue.length; i < l; i++) {
				queue = handler.queue[i];
				deferred = queue.deferred;
				callback = queue[action];
				if (typeof callback !== func) {
					deferred[action](value);
				} else {
					execute(callback, value, deferred);
				}
			}
			// Replace this handler with a simple resolved or rejected handler
			handler = createHandler(promise, value, onRejected);
		};
		function Promise(){
			this.then=function (onFulfilled, onRejected) {
				return handler(onFulfilled, onRejected);
			};
		}
		var promise = new Promise();
		this.promise = promise;
		// The queue of deferreds
		handler.queue = [];

		this.resolve = function (value)	{
			handler.queue && handler(handler, true, value);
		};

		this.reject = function (reason) {
			handler.queue && handler(handler, false, reason);
		};
	}

	function createDeferred(){
		return new Deferred();
	}

	// Creates a fulfilled or rejected .then function
	function createHandler(promise, value, success) {
		return function (onFulfilled, onRejected) {
			var callback = success ? onFulfilled : onRejected, result;
			if (typeof callback !== func) {
				return promise;
			}
			execute(callback, value, result = createDeferred());
			return result.promise;
		};
	}

	// Executes the callback with the specified value,
	// resolving or rejecting the deferred
	function execute(callback, value, deferred) {
		tick(function () {
			var result;
			try {
				result = callback(value);
				if (result && typeof result.then === func) {
					result.then(deferred.resolve, deferred.reject);
				} else {
					deferred.resolve(result);
				}
			}
			catch (error) {
				deferred.reject(error);
			}
		});
	}

	// Returns a resolved promise
	exports.resolve= function (value) {
		var promise = {};
		promise.then = createHandler(promise, value, true);
		return promise;
	};
	// Returns a rejected promise
	exports.reject= function (reason) {
		var promise = {};
		promise.then = createHandler(promise, reason, false);
		return promise;
	};
	// Returns a deferred
	exports.deferred= createDeferred;
	exports.all=function(array){
		var promise = exports.deferred();
		var len = array.length;
		var resolved=0;
		var out = [];
		var onSuccess=function(n){
			return function(v){
				out[n]=v;
				resolved++;
				if(resolved===len){
					promise.resolve(out);
				}
			};
		};
		array.forEach(function(v,i){
			v.then(onSuccess(i),function(a){
				promise.reject(a);
			});
		});
		return promise.promise;
	};
})(catiline,catiline.setImmediate);
<commit_msg>rm it<commit_after><|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

var React = require('react');
var jsxToString = require('jsx-to-string');
var Link = require('react-router').Link;
var DocsArticle = require('../../DocsArticle');
var Footer = require('grommet/components/Footer');
var Menu = require('grommet/components/Menu');
var Button = require('grommet/components/Button');
var A11y = require('../../utils/a11y');

Footer.displayName = 'Footer';
Menu.displayName = 'Menu';
Button.displayName = 'Button';

var FooterDoc = React.createClass({

  contextTypes: {
    routePrefix: React.PropTypes.string.isRequired
  },

  componentDidMount: function () {
    A11y.updatePageTitle('Footer');
  },

  _onClick: function () {
    // no-op
  },

  _renderFooterCode(heading, footerJSX) {
    return (

{heading}

          {footerJSX}

          {jsxToString(footerJSX)}

    );
  },

  render: function() {
    var basicFooter = (

        <Menu direction="row">
          <Button label="OK" primary={true} onClick={this._onClick} />
          <Button label="Cancel" onClick={this._onClick} />
        </Menu>

    );

    var rightFooter = (

        <Menu direction="row" justify="end">
          <Button label="Cancel" onClick={this._onClick} />
          <Button label="OK" primary={true} onClick={this._onClick} />
        </Menu>

    );

    return (
      <DocsArticle title="Footer" colorIndex="neutral-3">

Put things at the bottom.

          {"\n  ...\n"}

Options

size        small|medium|large

The size of the Header. Defaults to medium.

primary     true|false

Whether it should be treated as main footer or not.
              Used for Accessibility.

Options for <Link to={this.context.routePrefix + "box"}>Box</Link> are
          also available.

Examples

          {this._renderFooterCode("Form Footer", basicFooter)}
          {this._renderFooterCode("Form Footer, right", rightFooter)}

      </DocsArticle>
    );
  }
});

module.exports = FooterDoc;
<commit_msg>Updated footer documentation<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

var React = require('react');
var jsxToString = require('jsx-to-string');
var Link = require('react-router').Link;
var DocsArticle = require('../../DocsArticle');
var Footer = require('grommet/components/Footer');
var Menu = require('grommet/components/Menu');
var Button = require('grommet/components/Button');
var A11y = require('../../utils/a11y');

Footer.displayName = 'Footer';
Menu.displayName = 'Menu';
Button.displayName = 'Button';

var FooterDoc = React.createClass({

  contextTypes: {
    routePrefix: React.PropTypes.string.isRequired
  },

  componentDidMount: function () {
    A11y.updatePageTitle('Footer');
  },

  _onClick: function () {
    // no-op
  },

  _renderFooterCode(heading, footerJSX) {
    return (

{heading}

          {footerJSX}

          {jsxToString(footerJSX)}

    );
  },

  render: function() {
    var basicFooter = (

        <Menu direction="row">
          <Button label="OK" primary={true} onClick={this._onClick} />
          <Button label="Cancel" onClick={this._onClick} />
        </Menu>

    );

    var rightFooter = (

        <Menu direction="row" justify="end">
          <Button label="Cancel" onClick={this._onClick} />
          <Button label="OK" primary={true} onClick={this._onClick} />
        </Menu>

    );

    return (
      <DocsArticle title="Footer" colorIndex="neutral-3">

Put things at the bottom.

          {"\n  ...\n"}

Options

size        small|medium|large

The size of the Footer. Defaults to medium.

primary     true|false

Whether it should be treated as main footer or not.
              Used for Accessibility.

fixed       true|false

Whether the footer is fixed on the page, typically
              so content above it will scroll under it.

float       true|false

Whether the footer floats above content underneath it.

Options for <Link to={this.context.routePrefix + "box"}>Box</Link> are
          also available.

Examples

          {this._renderFooterCode("Form Footer", basicFooter)}
          {this._renderFooterCode("Form Footer, right", rightFooter)}

      </DocsArticle>
    );
  }
});

module.exports = FooterDoc;
<|endoftext|>


<commit_before>/**
 * @file
 * Js functionality for the social links.
 */

(function ($) {

  Drupal.behaviors.culturefeedSocialLinks = {
    attach: function (context, settings) {

      $(context).find('a.do-link').once('no-double-click').bind('click', function (e) {
        console.log('click');
        var $link = $(e.target);
        if (!$link.data('no-click')) {

          $link.data('no-click', 1);

          setTimeout(function(){
            $link.data('no-click', 0);
          }, 5000);
        }
        else {
          console.log('nope');
          e.preventDefault();
        }
      });
    }
  };

})(jQuery);
<commit_msg>WKS-330: Remove debug logs<commit_after>/**
 * @file
 * Js functionality for the social links.
 */

(function ($) {

  Drupal.behaviors.culturefeedSocialLinks = {
    attach: function (context, settings) {

      $(context).find('a.do-link').once('no-double-click').bind('click', function (e) {

        var $link = $(e.target);
        if (!$link.data('no-click')) {

          $link.data('no-click', 1);

          setTimeout(function(){
            $link.data('no-click', 0);
          }, 5000);
        }
        else {
          e.preventDefault();
        }
      });
    }
  };

})(jQuery);
<|endoftext|>


<commit_before>const request = require('request');

var ScrapedProduct = require('../../../models/Scrapedprodcut');
var random = require('mongoose-random');

exports.CommonFixer = class CommonFixer {
    constructor() {
    }

    fixProductsInScrapedProductsDB(){
        return setInterval(function() {
                // ScrapedProduct.findOne({'product_url' : {$regex : ".*657622412782*"}}).skip(0).exec(function (err, productToScrape) {
                ScrapedProduct.findOne({ barcode_id: { $exists: true } , $where: "this.barcode_id.length < 13"}).exec(function (err, productToFix) {
                    try {
                        if (productToFix) {
                            productToFix.barcode_id = fixBarcode(productToFix);
                            ScrapedProduct.update({_id: productToFix.id}, {
                                barcode_id: productToFix.barcode_id
                            }, function(err, affected, resp) {
                                console.log('SAVED ' + productToFix.barcode_id);
                            })
                        } else {
                            console.log('no products');
                        }
                    }catch (err){
                        console.log('Error ' + err);
                    }
                });
        }, 2000);
    }
};

fixBarcode = function(product){
    let newBarcode = '';
    if(product.barcode_id) {
        newBarcode = product.barcode_id;
        while (newBarcode.length < 13){
            newBarcode = '0'+newBarcode;
        }
    }
    return newBarcode;
};<commit_msg>Adding db fixer<commit_after>const request = require('request');

var ScrapedProduct = require('../../../models/Scrapedprodcut');
var random = require('mongoose-random');

exports.CommonFixer = class CommonFixer {
    constructor() {
    }

    fixProductsInScrapedProductsDB(){
        return setInterval(function() {
                // ScrapedProduct.findOne({'product_url' : {$regex : ".*657622412782*"}}).skip(0).exec(function (err, productToScrape) {
                ScrapedProduct.findOne({ barcode_id: { $exists: true } , $where: "this.barcode_id.length < 13"}).exec(function (err, productToFix) {
                    try {
                        if (productToFix && productToFix.barcode_id) {
                            productToFix.barcode_id = fixBarcode(productToFix);
                            ScrapedProduct.update({_id: productToFix.id}, {
                                barcode_id: productToFix.barcode_id
                            }, function(err, affected, resp) {
                                console.log('SAVED ' + productToFix.barcode_id);
                            })
                        } else {
                            console.log('no products');
                        }
                    }catch (err){
                        console.log('Error ' + err);
                    }
                });
        }, 2000);
    }
};

fixBarcode = function(product){
    let newBarcode = '';
    if(product.barcode_id) {
        newBarcode = product.barcode_id;
        while (newBarcode.length < 13){
            newBarcode = '0'+newBarcode;
        }
    }
    return newBarcode;
};<|endoftext|>


<commit_before>(function () {
  var _ = {};

  _.toArray = function (collection) {
    return [].slice.call(collection);
  };

  _.$ = function (selector, context) {
      return _.toArray((context ? context : document).querySelectorAll(selector));
  };

  _.load = function (callback) {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", callback);
    } else {
      callback.call(document);
    }
  };

  _.replaceTag = function (container, tag) {
    var parent = container.parentElement;
    var newContainer = _.createElement(tag);
    _.toArray(container.classList).forEach(function (name) {
      newContainer.classList.add(name);
    });
    while (container.firstChild) {
      newContainer.appendChild(container.firstChild);
    }
    parent.replaceChild(newContainer, container);

    return newContainer;
  };

  _.request = function (url, method, callback) {
    var request = new XMLHttpRequest();
    request.open(method, url, true);

    request.onreadystatechange = function () {
      if (request.readyState === 4) {
        callback(request.responseText);
      }
    }

    request.send();
  };

  _.createElement = function (type, options) {
    var elem = document.createElement(type);
    if (options) {
      if (options.content) elem.innerHTML = options.content;
      if (options.classes) {
        options.classes.forEach(function (name) {
          elem.classList.add(name);
        });
      }
      if (options.attributes) {
        for (var attr in options.attributes) {
          elem.setAttribute(attr, options.attributes[attr]);
        }
      }
    }

    return elem;
  };

  _.dispatch = function (event, target) {
    var event = new Event("change");
    target.dispatchEvent(event);
  }

  _.naturalWords = function (key) {
    return key.replace(/_/g, " ").replace(/^\S/, function (char) { return char.toUpperCase() });
  };

  _.lowerFirst = function (string) {
    return string.charAt(0).toLowerCase() + string.substr(1, string.length);
  }

  _.clone = function (object) {
    return JSON.parse(JSON.stringify(object));
  };

  _.isTitleLink = function (link) {
    return link.parentElement.classList.contains("title") && !link.getAttribute("href").match(/^\/x\S+/) && !link.classList.contains("hnspecial-infinite-pause");
  }

  _.isCommentLink = function (link) {
    if (!link.getAttribute("href").match(/^reply\?id/)) {
      var parent = link.parentElement;
      while (parent.tagName.toLowerCase() !== "td") {
        if (parent.tagName.toLowerCase() === "span" && parent.classList.contains("comment")) return true;
        parent = parent.parentElement;
      }
    }
    return false;
  }

  _.isCommentPage = function () {
    var title = document.getElementsByClassName("title")[0];
    return title && title.childElementCount && title.children[0].nodeName.toLowerCase() === "a" && !title.children[0].getAttribute("href").match(/^\/x\?.+/);
  }

  _.isListingPage = function () {
    var title = document.getElementsByClassName("title")[0];
    return title && !title.childElementCount && title.parentElement.childElementCount === 3;
  }

  this._ = _;
}).call(this);
<commit_msg>dispatch the event from the argument rather than a hardcoded one<commit_after>(function () {
  var _ = {};

  _.toArray = function (collection) {
    return [].slice.call(collection);
  };

  _.$ = function (selector, context) {
      return _.toArray((context ? context : document).querySelectorAll(selector));
  };

  _.load = function (callback) {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", callback);
    } else {
      callback.call(document);
    }
  };

  _.replaceTag = function (container, tag) {
    var parent = container.parentElement;
    var newContainer = _.createElement(tag);
    _.toArray(container.classList).forEach(function (name) {
      newContainer.classList.add(name);
    });
    while (container.firstChild) {
      newContainer.appendChild(container.firstChild);
    }
    parent.replaceChild(newContainer, container);

    return newContainer;
  };

  _.request = function (url, method, callback) {
    var request = new XMLHttpRequest();
    request.open(method, url, true);

    request.onreadystatechange = function () {
      if (request.readyState === 4) {
        callback(request.responseText);
      }
    }

    request.send();
  };

  _.createElement = function (type, options) {
    var elem = document.createElement(type);
    if (options) {
      if (options.content) elem.innerHTML = options.content;
      if (options.classes) {
        options.classes.forEach(function (name) {
          elem.classList.add(name);
        });
      }
      if (options.attributes) {
        for (var attr in options.attributes) {
          elem.setAttribute(attr, options.attributes[attr]);
        }
      }
    }

    return elem;
  };

  _.dispatch = function (event, target) {
    var event = new Event(event);
    target.dispatchEvent(event);
  }

  _.naturalWords = function (key) {
    return key.replace(/_/g, " ").replace(/^\S/, function (char) { return char.toUpperCase() });
  };

  _.lowerFirst = function (string) {
    return string.charAt(0).toLowerCase() + string.substr(1, string.length);
  }

  _.clone = function (object) {
    return JSON.parse(JSON.stringify(object));
  };

  _.isTitleLink = function (link) {
    return link.parentElement.classList.contains("title") && !link.getAttribute("href").match(/^\/x\S+/) && !link.classList.contains("hnspecial-infinite-pause");
  }

  _.isCommentLink = function (link) {
    if (!link.getAttribute("href").match(/^reply\?id/)) {
      var parent = link.parentElement;
      while (parent.tagName.toLowerCase() !== "td") {
        if (parent.tagName.toLowerCase() === "span" && parent.classList.contains("comment")) return true;
        parent = parent.parentElement;
      }
    }
    return false;
  }

  _.isCommentPage = function () {
    var title = document.getElementsByClassName("title")[0];
    return title && title.childElementCount && title.children[0].nodeName.toLowerCase() === "a" && !title.children[0].getAttribute("href").match(/^\/x\?.+/);
  }

  _.isListingPage = function () {
    var title = document.getElementsByClassName("title")[0];
    return title && !title.childElementCount && title.parentElement.childElementCount === 3;
  }

  this._ = _;
}).call(this);
<|endoftext|>


<commit_before>'use strict';

const { resolve } = require('path');
const define = require('./define');

module.exports.generateConfig = (script, template, chunksList) => {
    if (!template) {
        template = 'app';
    }

    const config = {
        hash: false,
        cache: define.rs_production,
        inject: 'body',
        filetype: 'pug',
        // prefetch: '*.js',
        // preload: '*.*',
        prefetch: false,
        preload: '*.*',
        template: [template, 'pug'].join('.'),
        filename: resolve(define.rs_dist, [script, 'html'].join('.')),
        minify: define.rs_development ? {} : {
            keepClosingSlash: false,
            removeEmptyElements: false,
            removeComments: define.rs_production,
            conservativeCollapse: define.rs_production,
            collapseWhitespace: define.rs_production,
            removeAttributeQuotes: define.rs_production,
            removeEmptyAttributes: define.rs_production,
            removeRedundantAttributes: define.rs_production,
            removeScriptTypeAttributes: define.rs_production,
            removeStyleLinkTypeAttributes: define.rs_production,
            removeTagWhitespace: define.rs_production, // TEST MODE
            useShortDoctype: define.rs_production,
            minifyJS: define.rs_production,
            minifyCSS: define.rs_production,
            minifyURLs: define.rs_production
        }
    }

    if (chunksList !== undefined) {
        config.chunks = chunksList;
    }

    return config;
}<commit_msg>remove comment<commit_after>'use strict';

const { resolve } = require('path');
const define = require('./define');

module.exports.generateConfig = (script, template, chunksList) => {
    if (!template) {
        template = 'app';
    }

    const config = {
        hash: false,
        cache: define.rs_production,
        inject: 'body',
        filetype: 'pug',
        prefetch: false, // '*.js'
        preload: '*.*',
        template: [template, 'pug'].join('.'),
        filename: resolve(define.rs_dist, [script, 'html'].join('.')),
        minify: define.rs_development ? {} : {
            keepClosingSlash: false,
            removeEmptyElements: false,
            removeComments: define.rs_production,
            conservativeCollapse: define.rs_production,
            collapseWhitespace: define.rs_production,
            removeAttributeQuotes: define.rs_production,
            removeEmptyAttributes: define.rs_production,
            removeRedundantAttributes: define.rs_production,
            removeScriptTypeAttributes: define.rs_production,
            removeStyleLinkTypeAttributes: define.rs_production,
            removeTagWhitespace: define.rs_production, // TEST MODE
            useShortDoctype: define.rs_production,
            minifyJS: define.rs_production,
            minifyCSS: define.rs_production,
            minifyURLs: define.rs_production
        }
    }

    if (chunksList !== undefined) {
        config.chunks = chunksList;
    }

    return config;
}<|endoftext|>


<commit_before>'use strict';

describe('Controller: <%= classedName %>Controller', function() {
    var controller;

    // load the controller's module
    beforeEach(module('<%= scriptAppName %>'));

    // Initialize the controller and a mock scope if it is needed
    beforeEach(inject(function($controller) {
        controller = $controller('<%= classedName %>Controller', {});
    }));

    describe('Admin controller', function() {
        it('should be created successfully', function() {
            expect(controller).to.be.defined;
        });

        describe('after activate', function() {
            it('should have exPublicVariable of exampleVar', function() {
                expect(controller.exPublicVariable).to.equal('exampleVar');
            });
        });
    });
});
<commit_msg>injection update<commit_after>'use strict';

describe('Controller: <%= classedName %>Controller', function() {
    var controller;

    // load the controller's module
    beforeEach(module('<%= scriptAppName %>'));

    // Initialize the controller and a mock scope if it is needed
    beforeEach(function() {
        bard.inject('$controller');
        controller = $controller('<%= classedName %>Controller', {});
    });

    describe('Admin controller', function() {
        it('should be created successfully', function() {
            expect(controller).to.be.defined;
        });

        describe('after activate', function() {
            it('should have exPublicVariable of exampleVar', function() {
                expect(controller.exPublicVariable).to.equal('exampleVar');
            });
        });
    });
});
<|endoftext|>


<commit_before>(function () {
    'use strict';

    let API = {
        nodes (args) {
            const p = '/api/v1/nodes';
            if (!args) {
                return p;
            }
            if (typeof args === 'string' || args instanceof String) {
                return `${p}/${args}`;
            }
            return `${p}?${args.toString()}`;
        },

        cache (args) {
            const p = '/api/v1/cache';
            if (!args) {
                return p;
            }
            if (typeof args === 'string' || args instanceof String) {
                return `${p}/${args}`;
            }
            return `${p}?${args.toString()}`;
        },

        log () {
            return '/api/v1/log';
        },
    };

    function main () {
        return Promise.all([
            setupSearch(),
            setupDownload(),
            setupTrash(),
            setupDoCache(),
            setupSync(),
            setupCompare(),
            setupLogWatcher(),
        ]).then(_ => 0);
    }

    function setupSearch () {
        let input = document.querySelector('#search-input');
        let button = document.querySelector('#search-button');
        let result = document.querySelector('#search-result');

        input.addEventListener('keypress', (event) => {
            if (event.keyCode !== 10 && event.keyCode !== 13) {
                return;
            }
            onSubmitSearch(input.value, result);
        });
        button.addEventListener('click', (event) => {
            onSubmitSearch(input.value, result);
        });

        return Promise.resolve();
    }

    function onSubmitSearch (pattern, searchResultArea) {
        return search(pattern).then((data) => {
            return appendSearchResult(searchResultArea, data);
        });
    }

    function search (pattern) {
        let args = new URLSearchParams();
        args.set('pattern', pattern);
        let headers = new Headers();
        headers.set('Cache-Control', 'no-store');
        return fetch(API.nodes(args), {
          method: 'GET',
          headers: headers,
        }).then((response) => {
            return response.json();
        });
    }

    function appendSearchResult (searchResultArea, data) {
        data = createSearchResultList(data);
        searchResultArea.insertBefore(data, searchResultArea.firstElementChild);
    }

    function createSearchResultList (data) {
        let wrapper = document.createElement('div');
        wrapper.classList.add('search-group');

        wrapper.addEventListener('contextmenu', (event) => {
            event.preventDefault();
            let entries = wrapper.querySelectorAll('.search-entry');
            for (let entry of entries) {
                entry.classList.toggle('selected');
            }
        });

        if (data.length <= 0) {
            wrapper.classList.add('empty');
        } else {
            for (let result of data) {
                result = createSearchResult(result);
                wrapper.appendChild(result);
            }
        }

        return wrapper;
    }

    function createSearchResult (resultData) {
        let wrapper = document.createElement('div');
        wrapper.dataset.id = resultData.id;
        wrapper.classList.add('search-entry');

        let nameLabel = document.createElement('span');
        nameLabel.textContent = resultData.name;
        wrapper.appendChild(nameLabel);

        wrapper.addEventListener('click', (event) => {
            wrapper.classList.toggle('selected');
        });

        return wrapper;
    }

    function setupDownload () {
        let button = document.querySelector('#download-button');

        button.addEventListener('click', (event) => {
            let idList = getSelectedIDList();
            download(idList);
        });

        return Promise.resolve();
    }

    function download (idList) {
        let requests = idList.map((v) => {
            return fetch(API.cache(v), {
                method: 'PUT',
            });
        });
        return Promise.all(requests);
    }

    function setupTrash () {
        let button = document.querySelector('#trash-button');

        button.addEventListener('click', async (event) => {
            let rv = confirm('trash?');
            if (!rv) {
                return;
            }
            // HACK trash is slow, dont do too much at the sametime
            let idList = getSelectedIDList();
            for (let subList of chunk(idList, 8)) {
                await trash(idList);
            }
        });

        return Promise.resolve();
    }

    function trash (idList) {
        let requests = idList.map((v) => {
            return fetch(API.nodes(v), {
                method: 'DELETE',
            });
        });
        return Promise.all(requests);
    }

    function setupDoCache () {
        let button = document.querySelector('#do-cache-button');

        button.addEventListener('click', (event) => {
            doCache();
        });

        return Promise.resolve();
    }

    function doCache () {
        let args = new URLSearchParams();
        args.append('paths[]', '/tmp');

        return fetch(API.cache(), {
            method: 'POST',
            body: args,
        }).then((response) => {
            return response.text();
        });
    }

    function setupSync () {
        let button = document.querySelector('#sync-button');

        button.addEventListener('click', (event) => {
            doSync();
        });

        return Promise.resolve();
    }

    function doSync () {
        return fetch(API.cache(), {
            method: 'POST',
        });
    }

    function setupCompare () {
        let button = document.querySelector('#compare-button');

        button.addEventListener('click', (event) => {
            let idList = getSelectedIDList();
            compare(idList);
        });

        return Promise.resolve();
    }

    async function compare (idList) {
        let args = new URLSearchParams();
        for (let id of idList) {
            args.append('nodes[]', id);
        }
        let rv = await fetch(API.cache(args), {
            method: 'GET',
        });
        rv = await rv.json();
        updateCompareResult(rv);
    }

    function updateCompareResult (result) {
        let block = document.querySelector('#compare-result');
        while (block.firstChild) {
            block.firstChild.remove();
        }
        if (!result) {
            block.textContent = 'OK';
            return;
        }
        for (let [size, path] of result) {
            let pre = document.createElement('pre');
            pre.textContent = `${size}: ${path}`;
            block.appendChild(pre);
        }
    }

    function getSelectedIDList () {
        let list = document.querySelectorAll('#search-result .selected');
        let idList = Array.prototype.map.call(list, (v) => {
            return v.dataset.id;
        });
        list.forEach((v) => {
            v.classList.remove('selected');
        });
        return idList;
    }

    function setupLogWatcher () {
      let result = document.querySelector('#log-watcher');

      setupLogSocket(result);

      let headers = new Headers();
      headers.set('Cache-Control', 'no-store');
      return fetch(API.log(), {
          method: 'GET',
          headers: headers,
      }).then((response) => {
          return response.json();
      }).then((logs) => {
          let msgs = logs.map(formatRecord);
          msgs.reverse();
          msgs.forEach((record) => {
              result.appendChild(record);
          });
      });
    }

    function setupLogSocket (resultBlock) {
        let ws = new WebSocket(`ws://${location.host}/api/v1/socket`);
        ws.addEventListener('message', (event) => {
            let record = formatRecord(JSON.parse(event.data));
            resultBlock.insertBefore(record, resultBlock.firstElementChild);
        });
        ws.addEventListener('close', (event) => {
            console.info('close', event);
            setupLogSocket(resultBlock);
        });
        ws.addEventListener('error', (event) => {
            console.info('error', event);
            setTimeout(() => {
                setupLogSocket(resultBlock);
            }, 5 * 1000);
        });
    }

    function formatRecord (record) {
        let a = document.createElement('pre');
        a.textContent = record.message;
        return a;
    }

    function * chunk (array, size) {
        for (let i = 0; i < array.length; i += size) {
            yield array.slice(i, i + size);
        }
    }

    return main();

})();
<commit_msg>no need for chunk<commit_after>(function () {
    'use strict';

    let API = {
        nodes (args) {
            const p = '/api/v1/nodes';
            if (!args) {
                return p;
            }
            if (typeof args === 'string' || args instanceof String) {
                return `${p}/${args}`;
            }
            return `${p}?${args.toString()}`;
        },

        cache (args) {
            const p = '/api/v1/cache';
            if (!args) {
                return p;
            }
            if (typeof args === 'string' || args instanceof String) {
                return `${p}/${args}`;
            }
            return `${p}?${args.toString()}`;
        },

        log () {
            return '/api/v1/log';
        },
    };

    function main () {
        return Promise.all([
            setupSearch(),
            setupDownload(),
            setupTrash(),
            setupDoCache(),
            setupSync(),
            setupCompare(),
            setupLogWatcher(),
        ]).then(_ => 0);
    }

    function setupSearch () {
        let input = document.querySelector('#search-input');
        let button = document.querySelector('#search-button');
        let result = document.querySelector('#search-result');

        input.addEventListener('keypress', (event) => {
            if (event.keyCode !== 10 && event.keyCode !== 13) {
                return;
            }
            onSubmitSearch(input.value, result);
        });
        button.addEventListener('click', (event) => {
            onSubmitSearch(input.value, result);
        });

        return Promise.resolve();
    }

    function onSubmitSearch (pattern, searchResultArea) {
        return search(pattern).then((data) => {
            return appendSearchResult(searchResultArea, data);
        });
    }

    function search (pattern) {
        let args = new URLSearchParams();
        args.set('pattern', pattern);
        let headers = new Headers();
        headers.set('Cache-Control', 'no-store');
        return fetch(API.nodes(args), {
          method: 'GET',
          headers: headers,
        }).then((response) => {
            return response.json();
        });
    }

    function appendSearchResult (searchResultArea, data) {
        data = createSearchResultList(data);
        searchResultArea.insertBefore(data, searchResultArea.firstElementChild);
    }

    function createSearchResultList (data) {
        let wrapper = document.createElement('div');
        wrapper.classList.add('search-group');

        wrapper.addEventListener('contextmenu', (event) => {
            event.preventDefault();
            let entries = wrapper.querySelectorAll('.search-entry');
            for (let entry of entries) {
                entry.classList.toggle('selected');
            }
        });

        if (data.length <= 0) {
            wrapper.classList.add('empty');
        } else {
            for (let result of data) {
                result = createSearchResult(result);
                wrapper.appendChild(result);
            }
        }

        return wrapper;
    }

    function createSearchResult (resultData) {
        let wrapper = document.createElement('div');
        wrapper.dataset.id = resultData.id;
        wrapper.classList.add('search-entry');

        let nameLabel = document.createElement('span');
        nameLabel.textContent = resultData.name;
        wrapper.appendChild(nameLabel);

        wrapper.addEventListener('click', (event) => {
            wrapper.classList.toggle('selected');
        });

        return wrapper;
    }

    function setupDownload () {
        let button = document.querySelector('#download-button');

        button.addEventListener('click', (event) => {
            let idList = getSelectedIDList();
            download(idList);
        });

        return Promise.resolve();
    }

    function download (idList) {
        let requests = idList.map((v) => {
            return fetch(API.cache(v), {
                method: 'PUT',
            });
        });
        return Promise.all(requests);
    }

    function setupTrash () {
        let button = document.querySelector('#trash-button');

        button.addEventListener('click', async (event) => {
            let rv = confirm('trash?');
            if (!rv) {
                return;
            }
            // HACK trash is slow, dont do too much at the sametime
            let idList = getSelectedIDList();
            trash(idList);
        });

        return Promise.resolve();
    }

    function trash (idList) {
        let requests = idList.map((v) => {
            return fetch(API.nodes(v), {
                method: 'DELETE',
            });
        });
        return Promise.all(requests);
    }

    function setupDoCache () {
        let button = document.querySelector('#do-cache-button');

        button.addEventListener('click', (event) => {
            doCache();
        });

        return Promise.resolve();
    }

    function doCache () {
        let args = new URLSearchParams();
        args.append('paths[]', '/tmp');

        return fetch(API.cache(), {
            method: 'POST',
            body: args,
        }).then((response) => {
            return response.text();
        });
    }

    function setupSync () {
        let button = document.querySelector('#sync-button');

        button.addEventListener('click', (event) => {
            doSync();
        });

        return Promise.resolve();
    }

    function doSync () {
        return fetch(API.cache(), {
            method: 'POST',
        });
    }

    function setupCompare () {
        let button = document.querySelector('#compare-button');

        button.addEventListener('click', (event) => {
            let idList = getSelectedIDList();
            compare(idList);
        });

        return Promise.resolve();
    }

    async function compare (idList) {
        let args = new URLSearchParams();
        for (let id of idList) {
            args.append('nodes[]', id);
        }
        let rv = await fetch(API.cache(args), {
            method: 'GET',
        });
        rv = await rv.json();
        updateCompareResult(rv);
    }

    function updateCompareResult (result) {
        let block = document.querySelector('#compare-result');
        while (block.firstChild) {
            block.firstChild.remove();
        }
        if (!result) {
            block.textContent = 'OK';
            return;
        }
        for (let [size, path] of result) {
            let pre = document.createElement('pre');
            pre.textContent = `${size}: ${path}`;
            block.appendChild(pre);
        }
    }

    function getSelectedIDList () {
        let list = document.querySelectorAll('#search-result .selected');
        let idList = Array.prototype.map.call(list, (v) => {
            return v.dataset.id;
        });
        list.forEach((v) => {
            v.classList.remove('selected');
        });
        return idList;
    }

    function setupLogWatcher () {
      let result = document.querySelector('#log-watcher');

      setupLogSocket(result);

      let headers = new Headers();
      headers.set('Cache-Control', 'no-store');
      return fetch(API.log(), {
          method: 'GET',
          headers: headers,
      }).then((response) => {
          return response.json();
      }).then((logs) => {
          let msgs = logs.map(formatRecord);
          msgs.reverse();
          msgs.forEach((record) => {
              result.appendChild(record);
          });
      });
    }

    function setupLogSocket (resultBlock) {
        let ws = new WebSocket(`ws://${location.host}/api/v1/socket`);
        ws.addEventListener('message', (event) => {
            let record = formatRecord(JSON.parse(event.data));
            resultBlock.insertBefore(record, resultBlock.firstElementChild);
        });
        ws.addEventListener('close', (event) => {
            console.info('close', event);
            setupLogSocket(resultBlock);
        });
        ws.addEventListener('error', (event) => {
            console.info('error', event);
            setTimeout(() => {
                setupLogSocket(resultBlock);
            }, 5 * 1000);
        });
    }

    function formatRecord (record) {
        let a = document.createElement('pre');
        a.textContent = record.message;
        return a;
    }

    return main();

})();
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Thorsten Lorenz.
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 */

(function (exports) {
  'use strict';
  //@ sourceMappingURL=spans.js.map
  var classes = {
        String                   :  's'
      , Number                   :  'f'

      , Keyword                  :  'k'
      , 'Keyword.Constant'       :  'kc'
      , 'Keyword.Declaration'    :  'kd'
      , 'Keyword.Namespace'      :  'kn'
      , 'Keyword.Pseudo'         :  'kp'
      , 'Keyword.Reserved'       :  'kr'
      , 'Keyword.Type'           :  'kt'

      , Name                     :  'n'
      , 'Name.Attribute'         :  'na'
      , 'Name.Builtin'           :  'nb'
      , 'Name.Builtin.Pseudo'    :  'bp'
      , 'Name.Class'             :  'nc'
      , 'Name.Constant'          :  'no'
      , 'Name.Decorator'         :  'nd'
      , 'Name.Entity'            :  'ni'
      , 'Name.Exception'         :  'ne'
      , 'Name.Function'          :  'nf'
      , 'Name.Property'          :  'py'
      , 'Name.Label'             :  'nl'
      , 'Name.Namespace'         :  'nn'
      , 'Name.Other'             :  'nx'
      , 'Name.Tag'               :  'nt'
      , 'Name.Variable'          :  'nv'
      , 'Name.Variable.Class'    :  'vc'
      , 'Name.Variable.Global'   :  'vg'
      , 'Name.Variable.Instance' :  'vi'

      , Literal                  :  'l'
      , 'Literal.Date'           :  'ld'

      , Operator                 :  'o'
      , Punctuation              :  'p'

      , Comment                  :  'c'
      , 'Comment.Multiline'      :  'cm'
      , 'Comment.Preproc'        :  'cp'
      , 'Comment.Single'         :  'c1'
      , 'Comment.Special'        :  'cs'

      , Generic                  :  'g'
      , 'Generic.Deleted'        :  'gd'
      , 'Generic.Emph'           :  'ge'
      , 'Generic.Error'          :  'gr'
      , 'Generic.Heading'        :  'gh'
      , 'Generic.Inserted'       :  'gi'
      , 'Generic.Output'         :  'go'
      , 'Generic.Prompt'         :  'gp'
      , 'Generic.Strong'         :  'gs'
      , 'Generic.Subheading'     :  'gu'
      , 'Generic.Traceback'      :  'gt'
      }
    , spans = {};

  function escapeHtml (s) {
    return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
  }

  function wrap (clazz) {
    return function escapeAndWrap (s) {
      return [
          ''
        , escapeHtml(s)
        , ''
        ].join('');
    };
  }

  Object.keys(classes)
    .forEach(function (k) {
      spans[k] = wrap(classes[k]);
    });

  //@ sourceMappingURL=themes/default.js.map

  var defaultTheme = {

      'Boolean': {
        'true'   :  undefined
      , 'false'  :  undefined
      , _default :  spans['Keyword.Constant']
      }

    , 'Identifier': {
        'Date': spans['Literal.Date']
      , 'Error': spans['Generic.Error']
      , _default: spans.Name.Other
      }

    , 'Null': {
        _default :  spans['Keyword.Constant']
      }

    , 'Numeric': {
        _default: spans.Number
      }

    , 'String': {
        _default: spans.String
      }

    , 'Keyword': {
        'break'       :  undefined

      , 'case'        :  undefined
      , 'catch'       :  undefined
      , 'continue'    :  undefined

      , 'debugger'    :  undefined
      , 'default'     :  undefined
      , 'delete'      :  undefined
      , 'do'          :  undefined

      , 'else'        :  undefined

      , 'finally'     :  undefined
      , 'for'         :  undefined
      , 'function'    :  undefined

      , 'if'          :  undefined
      , 'in'          :  undefined
      , 'instanceof'  :  undefined

      , 'new'         :  undefined
      , 'return'      :  undefined
      , 'switch'      :  undefined

      , 'this'        :  undefined
      , 'throw'       :  undefined
      , 'try'         :  undefined
      , 'typeof'      :  undefined

      , 'var'         :  undefined
      , 'void'        :  undefined

      , 'while'       :  undefined
      , 'with'        :  undefined
      , _default      :  spans.Keyword
    }
    , 'Punctuator': {
        ';': spans.Punctuation
      , '.': spans.Punctuation
      , ',': spans.Punctuation

      , '{': spans.Punctuation
      , '}': spans.Punctuation
      , '(': spans.Punctuation
      , ')': spans.Punctuation
      , '[': spans.Punctuation
      , ']': spans.Punctuation

      , '<': undefined
      , '>': undefined
      , '+': undefined
      , '-': undefined
      , '*': undefined
      , '%': undefined
      , '&': undefined
      , '|': undefined
      , '^': undefined
      , '!': undefined
      , '~': undefined
      , '?': undefined
      , ':': undefined
      , '=': undefined

      , '<=': undefined
      , '>=': undefined
      , '==': undefined
      , '!=': undefined
      , '++': undefined
      , '--': undefined
      , '<<': undefined
      , '>>': undefined
      , '&&': undefined
      , '||': undefined
      , '+=': undefined
      , '-=': undefined
      , '*=': undefined
      , '%=': undefined
      , '&=': undefined
      , '|=': undefined
      , '^=': undefined
      , '/=': undefined

      , '===': undefined
      , '!==': undefined
      , '>>>': undefined
      , '<<=': undefined
      , '>>=': undefined

      , '>>>=': undefined

      , _default: spans.Operator
    }
    , Line: {
       _default: spans['Comment.Single']
      }

    , Block: {
       _default: spans.Comment
      }

    , _default: undefined
  };

  //@ sourceMappingURL=peacock.js.map

  function resolveTheme() {
    throw new Error('Resolving a theme by filename only works server side. \n' +
                    'Manually resolve or create a theme {Object} and pass that to "highlight" instead.');
  }

var redeyed = redeyed || exports.redeyed;

  function highlight(code, theme_) {
    var toString = Object.prototype.toString;

    function isObject (obj) {
      return toString.call(obj) === '[object Object]';
    }

    var theme;

    if(theme_)
      theme = isObject(theme_) ? theme_ : resolveTheme(theme_);
    else
      theme = defaultTheme;

    var highlightedCode = redeyed(code, theme).code;

    return [
        '

'
      , highlightedCode
      , '

'
    ].join('\n');
  }

  exports.peacock = { highlight: highlight };

})(window);<commit_msg>manually created browser version that supports amd<commit_after>/*
 * Copyright 2012 Thorsten Lorenz.
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 */
;(function () {
  function bootstrap (redeyed, exports) {
    'use strict';
    //@ sourceMappingURL=spans.js.map
    var classes = {
          String                   :  's'
        , Number                   :  'f'

        , Keyword                  :  'k'
        , 'Keyword.Constant'       :  'kc'
        , 'Keyword.Declaration'    :  'kd'
        , 'Keyword.Namespace'      :  'kn'
        , 'Keyword.Pseudo'         :  'kp'
        , 'Keyword.Reserved'       :  'kr'
        , 'Keyword.Type'           :  'kt'

        , Name                     :  'n'
        , 'Name.Attribute'         :  'na'
        , 'Name.Builtin'           :  'nb'
        , 'Name.Builtin.Pseudo'    :  'bp'
        , 'Name.Class'             :  'nc'
        , 'Name.Constant'          :  'no'
        , 'Name.Decorator'         :  'nd'
        , 'Name.Entity'            :  'ni'
        , 'Name.Exception'         :  'ne'
        , 'Name.Function'          :  'nf'
        , 'Name.Property'          :  'py'
        , 'Name.Label'             :  'nl'
        , 'Name.Namespace'         :  'nn'
        , 'Name.Other'             :  'nx'
        , 'Name.Tag'               :  'nt'
        , 'Name.Variable'          :  'nv'
        , 'Name.Variable.Class'    :  'vc'
        , 'Name.Variable.Global'   :  'vg'
        , 'Name.Variable.Instance' :  'vi'

        , Literal                  :  'l'
        , 'Literal.Date'           :  'ld'

        , Operator                 :  'o'
        , Punctuation              :  'p'

        , Comment                  :  'c'
        , 'Comment.Multiline'      :  'cm'
        , 'Comment.Preproc'        :  'cp'
        , 'Comment.Single'         :  'c1'
        , 'Comment.Special'        :  'cs'

        , Generic                  :  'g'
        , 'Generic.Deleted'        :  'gd'
        , 'Generic.Emph'           :  'ge'
        , 'Generic.Error'          :  'gr'
        , 'Generic.Heading'        :  'gh'
        , 'Generic.Inserted'       :  'gi'
        , 'Generic.Output'         :  'go'
        , 'Generic.Prompt'         :  'gp'
        , 'Generic.Strong'         :  'gs'
        , 'Generic.Subheading'     :  'gu'
        , 'Generic.Traceback'      :  'gt'
        }
      , spans = {};

    function escapeHtml (s) {
      return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
    }

    function wrap (clazz) {
      return function escapeAndWrap (s) {
        return [
            ''
          , escapeHtml(s)
          , ''
          ].join('');
      };
    }

    Object.keys(classes)
      .forEach(function (k) {
        spans[k] = wrap(classes[k]);
      });

    //@ sourceMappingURL=themes/default.js.map

    var defaultTheme = {

        'Boolean': {
          'true'   :  undefined
        , 'false'  :  undefined
        , _default :  spans['Keyword.Constant']
        }

      , 'Identifier': {
          'Date': spans['Literal.Date']
        , 'Error': spans['Generic.Error']
        , _default: spans.Name.Other
        }

      , 'Null': {
          _default :  spans['Keyword.Constant']
        }

      , 'Numeric': {
          _default: spans.Number
        }

      , 'String': {
          _default: spans.String
        }

      , 'Keyword': {
          'break'       :  undefined

        , 'case'        :  undefined
        , 'catch'       :  undefined
        , 'continue'    :  undefined

        , 'debugger'    :  undefined
        , 'default'     :  undefined
        , 'delete'      :  undefined
        , 'do'          :  undefined

        , 'else'        :  undefined

        , 'finally'     :  undefined
        , 'for'         :  undefined
        , 'function'    :  undefined

        , 'if'          :  undefined
        , 'in'          :  undefined
        , 'instanceof'  :  undefined

        , 'new'         :  undefined
        , 'return'      :  undefined
        , 'switch'      :  undefined

        , 'this'        :  undefined
        , 'throw'       :  undefined
        , 'try'         :  undefined
        , 'typeof'      :  undefined

        , 'var'         :  undefined
        , 'void'        :  undefined

        , 'while'       :  undefined
        , 'with'        :  undefined
        , _default      :  spans.Keyword
      }
      , 'Punctuator': {
          ';': spans.Punctuation
        , '.': spans.Punctuation
        , ',': spans.Punctuation

        , '{': spans.Punctuation
        , '}': spans.Punctuation
        , '(': spans.Punctuation
        , ')': spans.Punctuation
        , '[': spans.Punctuation
        , ']': spans.Punctuation

        , '<': undefined
        , '>': undefined
        , '+': undefined
        , '-': undefined
        , '*': undefined
        , '%': undefined
        , '&': undefined
        , '|': undefined
        , '^': undefined
        , '!': undefined
        , '~': undefined
        , '?': undefined
        , ':': undefined
        , '=': undefined

        , '<=': undefined
        , '>=': undefined
        , '==': undefined
        , '!=': undefined
        , '++': undefined
        , '--': undefined
        , '<<': undefined
        , '>>': undefined
        , '&&': undefined
        , '||': undefined
        , '+=': undefined
        , '-=': undefined
        , '*=': undefined
        , '%=': undefined
        , '&=': undefined
        , '|=': undefined
        , '^=': undefined
        , '/=': undefined

        , '===': undefined
        , '!==': undefined
        , '>>>': undefined
        , '<<=': undefined
        , '>>=': undefined

        , '>>>=': undefined

        , _default: spans.Operator
      }
      , Line: {
        _default: spans['Comment.Single']
        }

      , Block: {
        _default: spans.Comment
        }

      , _default: undefined
    };

    //@ sourceMappingURL=peacock.js.map

    function resolveTheme() {
      throw new Error('Resolving a theme by filename only works server side. \n' +
                      'Manually resolve or create a theme {Object} and pass that to "highlight" instead.');
    }

    function highlight(code, theme_) {
      var toString = Object.prototype.toString;

      function isObject (obj) {
        return toString.call(obj) === '[object Object]';
      }

      var theme;

      if(theme_)
        theme = isObject(theme_) ? theme_ : resolveTheme(theme_);
      else
        theme = defaultTheme;

      var highlightedCode = redeyed(code, theme).code;

      return [
          '

'
        , highlightedCode
        , '

'
      ].join('\n');
    }

    return { highlight: highlight };
  }

  if (typeof define === 'function' && define.amd) {
    // amd
    define(['redeyed'], function (redeyed) {
      return bootstrap(redeyed);
    });

  } else if (typeof window === 'object') {
    // no amd -> attach to window if it exists
    // Note that this requires 'redeyed' to be defined on the window which in turn requires 'esprima'
    // Therefore those scripts have to be loaded first
    window.peacock = bootstrap(window.redeyed);
  }
})();
<|endoftext|>


<commit_before>window.eventHandlers.click['show-frame'] = function(event)
{
  var frame = stop_at.getFrame(event.target['ref-id']);
  if (frame)
  {
    topCell.showView(views['inspection'].id);
    messages.post('active-inspection-type', {inspection_type: 'frame'});
    messages.post('frame-selected', {frame_index: event.target['ref-id']});
    if (event.type == 'click')
    {
      helpers.setSelected(event);
      if (views.js_source.isvisible())
      {
        if (frame.script_id)
        {
          var plus_lines = views.js_source.getMaxLines() <= 10
            ? views.js_source.getMaxLines() / 2 >> 0
            : 10;
          views.js_source.showLine(frame.script_id, frame.line - plus_lines);
          views.js_source.showLinePointer(frame.line, frame.id == 0);
        }
        else
        {
          views.js_source.clearView();
        }
      }
    }
  }
  else
  {
    opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + "missing frame in 'show-frame' handler");
  }
};

window.eventHandlers.click['expand-value'] = function(event, target)
{
  var
  val = target.parentNode.getElementsByTagName('value')[0],
  text_content = val.textContent;

  val.textContent = val.getAttribute('data-value');
  val.setAttribute('data-value', text_content);
  if (target.style.backgroundPosition)
  {
    target.style.removeProperty('background-position');
  }
  else
  {
    target.style.backgroundPosition = '0px -11px';
  }
};

window.eventHandlers.click['examine-object-2'] = function(event, target)
{
  var
  parent = target.parentNode,
  parent_parent = parent.parentNode,
  obj_id = parseInt(parent.getAttribute('obj-id')),
  depth = parseInt(parent.getAttribute('depth')),
  rt_id = parseInt(parent_parent.getAttribute('rt-id')),
  data_id = parent_parent.getAttribute('data-id'),
  data = null,
  examine_object = parent.getElementsByTagName('examine-objects')[0];

  if (window[data_id])
  {
    if (examine_object) // is unfolded
    {
      if (!target.disabled)
      {
        window[data_id].clearData(rt_id, obj_id, depth, parent.getElementsByTagName('key')[0].textContent);
        parent.removeChild(examine_object);
        target.style.removeProperty("background-position");
      }
    }
    else
    {
      if (data = window[data_id].getData(rt_id, obj_id, depth, arguments))
      {
        if (data.length)
        {
          examine_object = parent_parent.cloneNode(false);
          examine_object.innerHTML = window[data_id].prettyPrint(data, depth,
            settings['inspection'].get("hide-default-properties"), window[data_id].filter_type);
          parent.appendChild(examine_object);
          target.style.backgroundPosition = "0px -11px";
        }
        else
        {
          target.disabled = true;
        }
      }
    }
  }
};

window.eventHandlers.click['examine-object'] = function(event, target)
{
  var
  parent = target.parentNode,
  parent_parent = parent.parentNode,
  obj_id = parseInt(parent.getAttribute('obj-id')),
  rt_id = parseInt(parent_parent.getAttribute('rt-id')),
  data_id = parent_parent.getAttribute('data-id'),
  data = null,
  examine_object = parent.getElementsByTagName('examine-objects')[0],
  cur = parent,
  path = [];

  while (cur && cur.parentNode && cur.parentNode.nodeName.toLowerCase() == 'examine-objects')
  {
    path.push(parseInt(cur.getAttribute('obj-id')));
    cur = cur.parentNode.parentNode;
  }
  path.push(parseInt(parent_parent.getAttribute('obj-id')));
  path.reverse();

  if (window[data_id])
  {
    if (examine_object) // is unfolded
    {
      if (!target.disabled)
      {
        window[data_id].clearData(rt_id, obj_id, path);
        parent.removeChild(examine_object);
        target.style.removeProperty("background-position");
      }
    }
    else
    {
      if (data = window[data_id].getData(rt_id, obj_id, path, arguments))
      {
        if (data.length)
        {
          examine_object = parent_parent.cloneNode(false);
          examine_object.innerHTML = window[data_id].prettyPrint(data, path,
            settings['inspection'].get("hide-default-properties"), window[data_id].filter_type);
          parent.appendChild(examine_object);
          target.style.backgroundPosition = "0px -11px";
        }
        else
        {
          target.disabled = true;
        }
      }
    }
  }
};

window.eventHandlers.click['show-scripts'] = function(event)
{
  var runtime_id = event.target.getAttribute('runtime_id');
  var scripts = runtimes.getScripts(runtime_id);
  var scripts_container = event.target.parentNode.getElementsByTagName('ul')[0];
  var script = null, i = 0;

  if (scripts_container)
  {
    event.target.parentNode.removeChild(scripts_container);
    event.target.style.removeProperty('background-position');
    runtimes.setUnfolded(runtime_id, 'script', false);
  }
  else
  {
    scripts_container = ['ul'];
    for ( ; script = scripts[i]; i++)
    {
      scripts_container.push(templates.scriptLink(script));
    }
    scripts_container.splice(scripts_container.length, 0, 'runtime-id', runtime_id);
    event.target.parentNode.render(scripts_container);
    event.target.style.backgroundPosition = '0 -11px';
    runtimes.setUnfolded(runtime_id, 'script', true);
  }
};

window.eventHandlers.click['show-stylesheets'] = function(event, target)
{
  var rt_id = target.getAttribute('runtime_id');
  // stylesheets.getStylesheets will call this function again if data is not avaible
  // handleGetAllStylesheets in stylesheets will
  // set for this reason __call_count on the event object
  var sheets = stylesheets.getStylesheets(rt_id, arguments);
  if (sheets)
  {
    var container = event.target.parentNode.getElementsByTagName('ul')[0];
    var sheet = null, i = 0;
    if (container)
    {
      target.parentNode.removeChild(container);
      target.style.removeProperty('background-position');
      runtimes.setUnfolded(rt_id, 'css', false);
    }
    else
    {
      container = ['ul'];
      for ( ; sheet = sheets[i]; i++)
      {
        container.push(templates.sheetLink(sheet, i));
      }
      container.splice(container.length, 0, 'runtime-id', rt_id);
      event.target.parentNode.render(container);
      event.target.style.backgroundPosition = '0 -11px';
      runtimes.setUnfolded(rt_id, 'css', true);
    }
  }
};

window.eventHandlers.click['display-stylesheet'] = function(event, target)
{
  var index = parseInt(target.getAttribute('index'));
  var rt_id = target.parentNode.getAttribute('runtime-id');
  // stylesheets.getRulesWithSheetIndex will call this function again if data is not avaible
  // handleGetRulesWithIndex in stylesheets will
  // set for this reason __call_count on the event object
  var rules = stylesheets.getRulesWithSheetIndex(rt_id, index, arguments);

  if (rules)
  {
    stylesheets.setSelectedSheet(rt_id, index, rules);
    topCell.showView(views.stylesheets.id);
    helpers.setSelected(event);
  }
};

window.eventHandlers.click['show-runtimes'] = function(event)
{
  var window_id = event.target.parentNode.getAttribute('window_id');
  var rts = runtimes.getRuntimes(window_id);
  var runtime_container = event.target.parentNode.getElementsByTagName('ul')[0];
  var rt = null, i = 0;
  var template_type = event.target.parentNode.parentNode.getAttribute('template-type');

  if (runtime_container)
  {
    event.target.parentNode.removeChild(runtime_container);
    event.target.style.removeProperty('background-position');
    runtimes.setWindowUnfolded(window_id, false);
  }
  else
  {
    event.target.parentNode.render(templates.runtimes(rts, template_type));
    event.target.style.backgroundPosition = '0 -11px';
    runtimes.setWindowUnfolded(window_id, true);
  }
};

window.eventHandlers.click['display-script'] = function(event)
{
  var script_id = event.target.getAttribute('script-id');

  if (script_id)
  {
    runtimes.setSelectedScript(script_id);
    views.runtimes.updateSelectedScript(event.target, script_id);
    topCell.showView(views.js_source.id);
  }
  else
  {
    opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
      "missing script id in window.eventHandlers.click['display-script']")
  }
};

window.eventHandlers.click['continue'] = function(event)
{
  views.js_source.clearLinePointer();
  views.callstack.clearView();
  views.inspection.clearView();
  stop_at.__continue(event.target.id.slice(9));
};

window.eventHandlers.click['set-stop-at'] = function(event)
{
  stop_at.setUserStopAt(event.target.value, event.target.checked);
};

window.eventHandlers.click['set-break-point'] = function(event)
{
  var line = parseInt(event.target.parentElement.children[0].value);
  var script_id = views.js_source.getCurrentScriptId();

  if (line)
  {
    if (runtimes.hasBreakpoint(script_id, line))
    {
      runtimes.removeBreakpoint(script_id, line);
      views.js_source.removeBreakpoint(line);
    }
    else
    {
      runtimes.setBreakpoint(script_id, line);
      views.js_source.addBreakpoint(line);
    }
  }
};

window.eventHandlers.click['get-children'] = function(event)
{
  var container = event.target.parentNode;
  var level = (parseInt(container.style.marginLeft) || 0) / 16;
  var level_next = (container.nextSibling && parseInt(container.nextSibling.style.marginLeft) || 0) / 16;
  var ref_id = parseInt(container.getAttribute('ref-id'));

  if (level_next > level)
  {
    dom_data.closeNode(ref_id);
  }
  else
  {
    dom_data.getChildernFromNode(ref_id, event.ctrlKey ? 'subtree' : 'children');
  }
};

window.eventHandlers.click['spotlight-node'] = function(event, current_target)
{
  var obj_id = parseInt(current_target.getAttribute('ref-id'));
  if (obj_id)
  {
    hostspotlighter.spotlight(obj_id,
      settings.dom.get('scroll-into-view-on-spotlight') && obj_id != dom_data.getCurrentTarget());
    dom_data.setCurrentTarget(obj_id);
    views['dom'].updateTarget(current_target, obj_id);
  }
};

window.eventHandlers.click['create-all-runtimes'] = function()
{
  services['ecmascript-debugger'].createAllRuntimes();
};

window.eventHandlers.click['update-global-scope'] = function(event)
{
  window.eventHandlers.click['show-frame']({'target': { 'ref-id': 0 } });
};

window.eventHandlers.click['dom-inspection-export'] = function(event)
{
  export_data.data = views['dom'].exportMarkup();
  topCell.showView('export_data');
};

window.eventHandlers.click['inspect-object-link'] = function(event, target)
{
  var rt_id = parseInt(target.getAttribute('rt-id'));
  var obj_id = parseInt(target.getAttribute('obj-id'));
  messages.post('active-inspection-type', {inspection_type: 'object'});
  // if that works it should be just inspection
  topCell.showView(views.inspection.id);
  messages.post('object-selected', {rt_id: rt_id, obj_id: obj_id});
};

window.eventHandlers.click['dom-resource-link'] = function(event, target)
{
  window.eventHandlers.dblclick['edit-dom'].delay(arguments.callee.execute, event, target);
};

window.eventHandlers.click['dom-resource-link'].execute = function(event, target)
{
  var
  url = target.textContent,
  rt_id = target.parentNode.parentNode.parentNode.getAttribute('rt-id')
    // for the case of dom tree-style
    || target.parentNode.parentNode.parentNode.parentNode.getAttribute('rt-id');
  // TODO use the exec service to open new link when it's ready
  window.open(helpers.resolveURLS(runtimes.getURI(rt_id), url.slice(1, url.length - 1)), "_blank");
};

<commit_msg>removed handlers for ecma 6.0<commit_after>window.eventHandlers.click['show-frame'] = function(event)
{
  var frame = stop_at.getFrame(event.target['ref-id']);
  if (frame)
  {
    topCell.showView(views['inspection'].id);
    messages.post('active-inspection-type', {inspection_type: 'frame'});
    messages.post('frame-selected', {frame_index: event.target['ref-id']});
    if (event.type == 'click')
    {
      helpers.setSelected(event);
      if (views.js_source.isvisible())
      {
        if (frame.script_id)
        {
          var plus_lines = views.js_source.getMaxLines() <= 10
            ? views.js_source.getMaxLines() / 2 >> 0
            : 10;
          views.js_source.showLine(frame.script_id, frame.line - plus_lines);
          views.js_source.showLinePointer(frame.line, frame.id == 0);
        }
        else
        {
          views.js_source.clearView();
        }
      }
    }
  }
  else
  {
    opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE + "missing frame in 'show-frame' handler");
  }
};

window.eventHandlers.click['expand-value'] = function(event, target)
{
  var
  val = target.parentNode.getElementsByTagName('value')[0],
  text_content = val.textContent;

  val.textContent = val.getAttribute('data-value');
  val.setAttribute('data-value', text_content);
  if (target.style.backgroundPosition)
  {
    target.style.removeProperty('background-position');
  }
  else
  {
    target.style.backgroundPosition = '0px -11px';
  }
};

window.eventHandlers.click['examine-object-2'] = function(event, target)
{
  var
  parent = target.parentNode,
  parent_parent = parent.parentNode,
  obj_id = parseInt(parent.getAttribute('obj-id')),
  depth = parseInt(parent.getAttribute('depth')),
  rt_id = parseInt(parent_parent.getAttribute('rt-id')),
  data_id = parent_parent.getAttribute('data-id'),
  data = null,
  examine_object = parent.getElementsByTagName('examine-objects')[0];

  if (window[data_id])
  {
    if (examine_object) // is unfolded
    {
      if (!target.disabled)
      {
        window[data_id].clearData(rt_id, obj_id, depth, parent.getElementsByTagName('key')[0].textContent);
        parent.removeChild(examine_object);
        target.style.removeProperty("background-position");
      }
    }
    else
    {
      if (data = window[data_id].getData(rt_id, obj_id, depth, arguments))
      {
        if (data.length)
        {
          examine_object = parent_parent.cloneNode(false);
          examine_object.innerHTML = window[data_id].prettyPrint(data, depth,
            settings['inspection'].get("hide-default-properties"), window[data_id].filter_type);
          parent.appendChild(examine_object);
          target.style.backgroundPosition = "0px -11px";
        }
        else
        {
          target.disabled = true;
        }
      }
    }
  }
};

window.eventHandlers.click['show-scripts'] = function(event)
{
  var runtime_id = event.target.getAttribute('runtime_id');
  var scripts = runtimes.getScripts(runtime_id);
  var scripts_container = event.target.parentNode.getElementsByTagName('ul')[0];
  var script = null, i = 0;

  if (scripts_container)
  {
    event.target.parentNode.removeChild(scripts_container);
    event.target.style.removeProperty('background-position');
    runtimes.setUnfolded(runtime_id, 'script', false);
  }
  else
  {
    scripts_container = ['ul'];
    for ( ; script = scripts[i]; i++)
    {
      scripts_container.push(templates.scriptLink(script));
    }
    scripts_container.splice(scripts_container.length, 0, 'runtime-id', runtime_id);
    event.target.parentNode.render(scripts_container);
    event.target.style.backgroundPosition = '0 -11px';
    runtimes.setUnfolded(runtime_id, 'script', true);
  }
};

window.eventHandlers.click['show-stylesheets'] = function(event, target)
{
  var rt_id = target.getAttribute('runtime_id');
  // stylesheets.getStylesheets will call this function again if data is not avaible
  // handleGetAllStylesheets in stylesheets will
  // set for this reason __call_count on the event object
  var sheets = stylesheets.getStylesheets(rt_id, arguments);
  if (sheets)
  {
    var container = event.target.parentNode.getElementsByTagName('ul')[0];
    var sheet = null, i = 0;
    if (container)
    {
      target.parentNode.removeChild(container);
      target.style.removeProperty('background-position');
      runtimes.setUnfolded(rt_id, 'css', false);
    }
    else
    {
      container = ['ul'];
      for ( ; sheet = sheets[i]; i++)
      {
        container.push(templates.sheetLink(sheet, i));
      }
      container.splice(container.length, 0, 'runtime-id', rt_id);
      event.target.parentNode.render(container);
      event.target.style.backgroundPosition = '0 -11px';
      runtimes.setUnfolded(rt_id, 'css', true);
    }
  }
};

window.eventHandlers.click['display-stylesheet'] = function(event, target)
{
  var index = parseInt(target.getAttribute('index'));
  var rt_id = target.parentNode.getAttribute('runtime-id');
  // stylesheets.getRulesWithSheetIndex will call this function again if data is not avaible
  // handleGetRulesWithIndex in stylesheets will
  // set for this reason __call_count on the event object
  var rules = stylesheets.getRulesWithSheetIndex(rt_id, index, arguments);

  if (rules)
  {
    stylesheets.setSelectedSheet(rt_id, index, rules);
    topCell.showView(views.stylesheets.id);
    helpers.setSelected(event);
  }
};

window.eventHandlers.click['show-runtimes'] = function(event)
{
  var window_id = event.target.parentNode.getAttribute('window_id');
  var rts = runtimes.getRuntimes(window_id);
  var runtime_container = event.target.parentNode.getElementsByTagName('ul')[0];
  var rt = null, i = 0;
  var template_type = event.target.parentNode.parentNode.getAttribute('template-type');

  if (runtime_container)
  {
    event.target.parentNode.removeChild(runtime_container);
    event.target.style.removeProperty('background-position');
    runtimes.setWindowUnfolded(window_id, false);
  }
  else
  {
    event.target.parentNode.render(templates.runtimes(rts, template_type));
    event.target.style.backgroundPosition = '0 -11px';
    runtimes.setWindowUnfolded(window_id, true);
  }
};

window.eventHandlers.click['display-script'] = function(event)
{
  var script_id = event.target.getAttribute('script-id');

  if (script_id)
  {
    runtimes.setSelectedScript(script_id);
    views.runtimes.updateSelectedScript(event.target, script_id);
    topCell.showView(views.js_source.id);
  }
  else
  {
    opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
      "missing script id in window.eventHandlers.click['display-script']")
  }
};

window.eventHandlers.click['continue'] = function(event)
{
  views.js_source.clearLinePointer();
  views.callstack.clearView();
  views.inspection.clearView();
  stop_at.__continue(event.target.id.slice(9));
};

window.eventHandlers.click['set-stop-at'] = function(event)
{
  stop_at.setUserStopAt(event.target.value, event.target.checked);
};

window.eventHandlers.click['set-break-point'] = function(event)
{
  var line = parseInt(event.target.parentElement.children[0].value);
  var script_id = views.js_source.getCurrentScriptId();

  if (line)
  {
    if (runtimes.hasBreakpoint(script_id, line))
    {
      runtimes.removeBreakpoint(script_id, line);
      views.js_source.removeBreakpoint(line);
    }
    else
    {
      runtimes.setBreakpoint(script_id, line);
      views.js_source.addBreakpoint(line);
    }
  }
};

window.eventHandlers.click['get-children'] = function(event)
{
  var container = event.target.parentNode;
  var level = (parseInt(container.style.marginLeft) || 0) / 16;
  var level_next = (container.nextSibling && parseInt(container.nextSibling.style.marginLeft) || 0) / 16;
  var ref_id = parseInt(container.getAttribute('ref-id'));

  if (level_next > level)
  {
    dom_data.closeNode(ref_id);
  }
  else
  {
    dom_data.getChildernFromNode(ref_id, event.ctrlKey ? 'subtree' : 'children');
  }
};

window.eventHandlers.click['spotlight-node'] = function(event, current_target)
{
  var obj_id = parseInt(current_target.getAttribute('ref-id'));
  if (obj_id)
  {
    hostspotlighter.spotlight(obj_id,
      settings.dom.get('scroll-into-view-on-spotlight') && obj_id != dom_data.getCurrentTarget());
    dom_data.setCurrentTarget(obj_id);
    views['dom'].updateTarget(current_target, obj_id);
  }
};

window.eventHandlers.click['create-all-runtimes'] = function()
{
  services['ecmascript-debugger'].createAllRuntimes();
};

window.eventHandlers.click['update-global-scope'] = function(event)
{
  window.eventHandlers.click['show-frame']({'target': { 'ref-id': 0 } });
};

window.eventHandlers.click['dom-inspection-export'] = function(event)
{
  export_data.data = views['dom'].exportMarkup();
  topCell.showView('export_data');
};

window.eventHandlers.click['inspect-object-link'] = function(event, target)
{
  var rt_id = parseInt(target.getAttribute('rt-id'));
  var obj_id = parseInt(target.getAttribute('obj-id'));
  messages.post('active-inspection-type', {inspection_type: 'object'});
  // if that works it should be just inspection
  topCell.showView(views.inspection.id);
  messages.post('object-selected', {rt_id: rt_id, obj_id: obj_id});
};

window.eventHandlers.click['dom-resource-link'] = function(event, target)
{
  window.eventHandlers.dblclick['edit-dom'].delay(arguments.callee.execute, event, target);
};

window.eventHandlers.click['dom-resource-link'].execute = function(event, target)
{
  var
  url = target.textContent,
  rt_id = target.parentNode.parentNode.parentNode.getAttribute('rt-id')
    // for the case of dom tree-style
    || target.parentNode.parentNode.parentNode.parentNode.getAttribute('rt-id');
  // TODO use the exec service to open new link when it's ready
  window.open(helpers.resolveURLS(runtimes.getURI(rt_id), url.slice(1, url.length - 1)), "_blank");
};

<|endoftext|>