<commit_before>var log = debug('horacat'),
    logv = debug('horacat:verbose');

debug.enable('horacat,horacat:*'); // TODO: make settable in options

function stripUrl() {
  return window.location.href.replace(/\#.*?$/, '');
}

function getIssue() {
  var issue_url = /github.com\/(.*?)\/(issues|pull)\/(\d+)$/.exec(stripUrl());
  if (!issue_url) {
    return;
  } else {
    var issue_string = issue_url[1] + '#' + issue_url[3];
    var shaObj = new jsSHA(issue_string, "TEXT");
    var hash = shaObj.getHash("SHA-1", "HEX");
    logv('getIssue hashing:', issue_string, '->', hash);
    return hash;
  }
}

function getProject() {
  var project_url = /github.com\/(.*?)\/(issues|pull)\/(\d+)$/.exec(stripUrl());
  if (!project_url) {
    return;
  } else {
    var shaObj = new jsSHA(project_url[1], "TEXT");
    var hash = shaObj.getHash("SHA-1", "HEX");
    logv('getProject hashing:', project_url[1], '->', hash);
    return hash;
  }
}

function getUser() {
  var user = $('.name').find('img').attr('data-user'); // FIXME: too insecure?
  if (!user) {
    return;
  } else {
    var shaObj = new jsSHA(user, "TEXT");
    var hash = shaObj.getHash("SHA-1", "HEX");
    logv('getUser hashing:', user, '->', hash);
    return hash;
  }
}

function init(user, project, issue) {
  log('user:', user);
  log('project:', project);
  log('issue:', issue);
  $('.gh-header-actions').prepend('Start timer');
}

chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

    var user = getUser();
    var project = getProject();
    var issue = getIssue();

    if (!user || !project || !issue) {
      log('not logged in or no issue available, disabling time tracking');
    } else {
      init(user, project, issue);
    }
	}
	}, 10);
});<commit_msg>button to log time<commit_after>var log = debug('horacat'),
    logv = debug('horacat:verbose');

debug.enable('horacat,horacat:*'); // TODO: make settable in options
// non verbose: debug.enable('horacat,horacat:*,-horacat:verbose,-horacat:*:verbose');

function stripUrl() {
  return window.location.href.replace(/\#.*?$/, '');
}

function getIssue() {
  var issue_url = /github.com\/(.*?)\/(issues|pull)\/(\d+)$/.exec(stripUrl());
  if (!issue_url) {
    return;
  } else {
    var issue_string = issue_url[1] + '#' + issue_url[3];
    var shaObj = new jsSHA(issue_string, "TEXT");
    var hash = shaObj.getHash("SHA-1", "HEX");
    logv('getIssue hashing:', issue_string, '->', hash);
    return hash;
  }
}

function getProject() {
  var project_url = /github.com\/(.*?)\/(issues|pull)\/(\d+)$/.exec(stripUrl());
  if (!project_url) {
    return;
  } else {
    var shaObj = new jsSHA(project_url[1], "TEXT");
    var hash = shaObj.getHash("SHA-1", "HEX");
    logv('getProject hashing:', project_url[1], '->', hash);
    return hash;
  }
}

function getUser() {
  var user = $('.name').find('img').attr('data-user'); // FIXME: too insecure?
  if (!user) {
    return;
  } else {
    var shaObj = new jsSHA(user, "TEXT");
    var hash = shaObj.getHash("SHA-1", "HEX");
    logv('getUser hashing:', user, '->', hash);
    return hash;
  }
}

function formatMs(s) {

  function addZ(n) {
    return (n<10? '0':'') + n;
  }

  var ms = s % 1000;
  s = (s - ms) / 1000;
  var secs = s % 60;
  s = (s - secs) / 60;
  var mins = s % 60;
  var hrs = (s - mins) / 60;

  return addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs);
}

function HoracatButton(user, project, issue) {
  this.log = debug('horacat:button');
  this.logv = debug('horacat:button:verbose');

  $('.gh-header-actions').prepend('
Log time00:00:00
');
  this.timer = document.getElementById('horacat-timer'); // timer object
  this.$ = $('.gh-header-horacat'); // jQuery object

  this.started = false;

  var _this = this;
  this.$.click(function() {
    _this.logv('clicked');
    if (_this.started) _this.stop();
    else _this.start();
  });
  this.log('initialized');
}

HoracatButton.prototype.update = function update() {
  var time = formatMs(new Date() - this.startTime);
  this.timer.innerHTML = time;
};

HoracatButton.prototype.start = function start() {
  this.started = true;

  if (!this.loggedTime) {
    this.startTime = new Date();
  } else {
    this.startTime = new Date() - this.loggedTime;
  }

  var _this = this;
  this.interval = setInterval(function () {
    _this.update();
  }, 1000);
  this.log('started:', this.startTime);
  this.update();
};

HoracatButton.prototype.stop = function stop() {
  this.started = false;

  this.loggedTime = new Date() - this.startTime;
  clearInterval(this.interval);
  this.log('stopped:', this.loggedTime);
};

function init(user, project, issue) {
  log('user:', user);
  log('project:', project);
  log('issue:', issue);
  var button = new HoracatButton(user, project, issue);
}

chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

    var user = getUser();
    var project = getProject();
    var issue = getIssue();

    if (!user || !project || !issue) {
      log('not logged in or no issue available, disabling time tracking');
    } else {
      init(user, project, issue);
    }
	}
	}, 10);
});<|endoftext|>


<commit_before>// Retriving user options
chrome.extension.sendMessage({}, function(settings) {
  initOnHashChangeAction(settings['Domains']);
})

function initOnHashChangeAction(domains) {

  // Find GitHub link and append it to tool bar on hashchange
  $(window).on('hashchange', function() {
    allDomains = "github.com,"
    if(domains) allDomains += domains

    selectors = allDomains.replace(/\s/, '').split(',').map(function (name) {
      if (name.length) return ("[href*='" + name + "']")
    }).filter(function(name) { return name }).join(", ")

    github_links = document.querySelectorAll(selectors)

    if( github_links.length ) {
      url = github_links[github_links.length-1].href

      // Go to thread instead of .diff link (pull request notifications)
      url = url.match(/\.diff/) ? url.slice(0, url.length-5) : url

      link = $("Visit Thread on GitHub")
      $(".iH > div").append(link)

      window.idled = true
    }
  })
}

$(document).on("keypress", function(event) {

  // Shortcut: bind shift + G, if a button exist and event not in a textarea
  if( event.shiftKey && event.keyCode == 71 && window.idled && $(".github-link:visible")[0] && notAnInput(event.target)) {
    triggerGitHubLink()
  }

  // Shortcut: bind ctrl + return
  selected = getVisible(document.querySelectorAll('.PE ~ [tabindex="0"]'))
  if( event.ctrlKey && event.keyCode == 13 && selected ) {
    generateUrlAndGoTo(selected)
  }
})

// Trigger the appended link in mail view
function triggerGitHubLink () {
  // avoid link being appended multiple times
  window.idled = false

  $(".github-link:visible")[0].dispatchEvent(fakeClick())
  setTimeout( function(){ window.idled = true }, 1000)
}

// Go to selected email GitHub thread
function generateUrlAndGoTo (selected) {
  if( (title = selected.innerText.match(/\[(.*)\]\s.*\s\(\#(\d*)\)/)) ) {

    // org name coms from a label
    org = selected.querySelectorAll('.av')[0].innerText.toLowerCase()

    if(org) {
      repo = title[1]
      issue_no = title[2]

      url = "https://github.com/" + org + "/" + repo + "/issues/" + issue_no
      linkWithUrl(url).dispatchEvent(fakeClick())
    }
  }
}

//
// Helpers
//

// .click() doesn't usually work as expected
function fakeClick () {
  var click = document.createEvent("MouseEvents")
  click.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
  return click
}

function linkWithUrl (url) {
  var l = document.createElement('a')
  l.href = url
  l.target = "_blank"
  return l
}

function getVisible (nodeList) {
  if(nodeList.length) {
    var node;
    $(nodeList).map(function() {
      if(typeof node == 'undefined' && (this.offsetTop > 0 || this.offsetLeft > 0)) {
        node = this
      }
    })
    return node
  }
}

function notAnInput (element) {
  return !element.className.match(/editable/) && element.tagName != "TEXTAREA" && element.tagName != "INPUT"
}
<commit_msg>Comment on code<commit_after>// Retriving user options
chrome.extension.sendMessage({}, function(settings) {
  initOnHashChangeAction(settings['Domains']);
})

function initOnHashChangeAction(domains) {

  // Find GitHub link and append it to tool bar on hashchange
  $(window).on('hashchange', function() {
    allDomains = "github.com,"
    if(domains) allDomains += domains

    // Take string -> make array -> make queries -> avoid nil -> join queries to string
    selectors = allDomains.replace(/\s/, '').split(',').map(function (name) {
      if (name.length) return ("[href*='" + name + "']")
    }).filter(function(name) { return name }).join(", ")

    github_links = document.querySelectorAll(selectors)

    if( github_links.length ) {
      url = github_links[github_links.length-1].href

      // Go to thread instead of .diff link (pull request notifications)
      url = url.match(/\.diff/) ? url.slice(0, url.length-5) : url

      link = $("Visit Thread on GitHub")
      $(".iH > div").append(link)

      window.idled = true
    }
  })
}

$(document).on("keypress", function(event) {

  // Shortcut: bind shift + G, if a button exist and event not in a textarea
  if( event.shiftKey && event.keyCode == 71 && window.idled && $(".github-link:visible")[0] && notAnInput(event.target)) {
    triggerGitHubLink()
  }

  // Shortcut: bind ctrl + return
  selected = getVisible(document.querySelectorAll('.PE ~ [tabindex="0"]'))
  if( event.ctrlKey && event.keyCode == 13 && selected ) {
    generateUrlAndGoTo(selected)
  }
})

// Trigger the appended link in mail view
function triggerGitHubLink () {
  // avoid link being appended multiple times
  window.idled = false

  $(".github-link:visible")[0].dispatchEvent(fakeClick())
  setTimeout( function(){ window.idled = true }, 1000)
}

// Go to selected email GitHub thread
function generateUrlAndGoTo (selected) {
  if( (title = selected.innerText.match(/\[(.*)\]\s.*\s\(\#(\d*)\)/)) ) {

    // org name coms from a label
    org = selected.querySelectorAll('.av')[0].innerText.toLowerCase()

    if(org) {
      repo = title[1]
      issue_no = title[2]

      url = "https://github.com/" + org + "/" + repo + "/issues/" + issue_no
      linkWithUrl(url).dispatchEvent(fakeClick())
    }
  }
}

//
// Helpers
//

// .click() doesn't usually work as expected
function fakeClick () {
  var click = document.createEvent("MouseEvents")
  click.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
  return click
}

function linkWithUrl (url) {
  var l = document.createElement('a')
  l.href = url
  l.target = "_blank"
  return l
}

function getVisible (nodeList) {
  if(nodeList.length) {
    var node;
    $(nodeList).map(function() {
      if(typeof node == 'undefined' && (this.offsetTop > 0 || this.offsetLeft > 0)) {
        node = this
      }
    })
    return node
  }
}

function notAnInput (element) {
  return !element.className.match(/editable/) && element.tagName != "TEXTAREA" && element.tagName != "INPUT"
}
<|endoftext|>


<commit_before>chrome.extension.sendMessage({}, function (response) {
    var readyStateCheckInterval = setInterval(function () {
        if (document.readyState === "complete") {
            clearInterval(readyStateCheckInterval);

            // ----------------------------------------------------------
            // This part of the script triggers when page is done loading
            console.log("Hello. This message was sent from scripts/inject.js");
            // ----------------------------------------------------------
            $.fn.scramble = function () {
                var length = this.length;
                if (length > 0) {
                    var randomIndex;
                    var tmp;
                    while (--length) {
                        randomIndex = Math.floor(Math.random() * (length + 1));
                        this.eq(randomIndex).insertBefore(this[length]);

                    }
                }
                return this;
            };

            var thing = '
' +
                '' +
                            'Auto Prioritizer' +
                                '' +
                        '
';

            var rollTheDice = function(event) {
                event.preventDefault();
                console.log("error: success!!");
                var stories = $('.backlog .story');
                for (var i = 0; i < 30; ++i) {
                    setTimeout(stories.scramble.bind(stories), i * 100)
                }
            };
            $(thing).insertAfter($('.item.project_history'));
            $('body').on('click', '.item.dice_roller', rollTheDice);
        }
    }, 10);
});<commit_msg>Add joyous music<commit_after>chrome.extension.sendMessage({}, function (response) {
    var readyStateCheckInterval = setInterval(function () {
        if (document.readyState === "complete") {
            clearInterval(readyStateCheckInterval);

            // ----------------------------------------------------------
            // This part of the script triggers when page is done loading
            console.log("Hello. This message was sent from scripts/inject.js");
            // ----------------------------------------------------------
            $.fn.scramble = function () {
                var length = this.length;
                if (length > 0) {
                    var randomIndex;
                    var tmp;
                    while (--length) {
                        randomIndex = Math.floor(Math.random() * (length + 1));
                        this.eq(randomIndex).insertBefore(this[length]);

                    }
                }
                return this;
            };

            var thing = '
' +
                '' +
                            'Auto Prioritizer' +
                                '' +
                        '
';

            var rollTheDice = function(event) {
                event.preventDefault();
                console.log("error: success!!");
                var stories = $('.backlog .story');

                $('<audio autoplay="true" src="http://mikekenyon.ca/thing_noise.mp3"></audio>').prependTo($('body'));

                for (var i = 0; i < 50; ++i) {
                    setTimeout(stories.scramble.bind(stories), i * 100);
                }
            };

            $(thing).insertAfter($('.item.project_history'));
            $('body').on('click', '.item.dice_roller', rollTheDice);
        }
    }, 10);
});<|endoftext|>


<commit_before>/* Copyright (c) 2017 Adam Browne
 * Inject.js is the content script which analyzes twitch. */

/* To observe the new messages, we need to use a MutationObserver
* and then apply a queryselector to get the new message added:
we're looking for:
 */
	var toggle_filter = false, cursize = false, pie = null, curTimestamp, prevTime;
	var setting = 0;
	//have to populate this with dictionaries regarding commands, emoji's, and sentiment.
	/* Analytics dict: (By timestamp.) */
	//have three arrays, of which 0 (sentiment), 1 (command), 2 (emoji)
	var analData = {};
	var analytics = [

	  { label: "1", value: 6 },
	  { label: "2", value: 4 },
	  { label: "3", value: 3 },
	  {label:"4",value:2},
	  {label:"5",value:1},
	  {label:"6",value:5},
	  {label:"7",value:7},
	  {label:"8",value:3},
	  {label:"9",value:9}
	];

	/* DataViz Storage Mechanism
	 * Store each by timestamp dict; inside the dict have the respective point of analytics.
	 * ["8:05"] =>
	*/
    //listener to the popup menu. We listen to it's instructions.
    chrome.runtime.onMessage.addListener(function(response){
        if(response == "tf")
            toggleFilter();
    });

    var port = chrome.runtime.connect({name: "handler"});
    port.onMessage.addListener(function(message){
        var data = message.split("|");
        var target_msg = document.getElementById(data[0]);
        if(data[3] == "1") {
            try {
                target_msg.setAttribute("style", "display:block;visibility:visible;");
            } catch(err) {}
        } else {
            try {
                target_msg.setAttribute("style", "display:none;visibility:hidden;");
            } catch(err) {}
        }
        storeAnalyticsData(data);
    });

    function storeAnalyticsData(data){
    	if(!(data[1] in analData) == true){
    		//sent, cmd, emoji storage
    		analData[data[1]] = [[],[],[],{}];
    	}
        if(data[4] != "") { //sentiment analytics
        	var sent = data[4]; //get the actual sentiment.
        	if(!(sent in analData[data[1]][3]) == true) {
        		analData[data[1]][3][sent] = 1;
        	} else {
        		++analData[data[1]][3][sent];
        	}
        	updateDataFreq(0,data[1]);
        } else { //command analytics
        	//do nothing.
        }
        if(curTimestamp != data[1]) {
        	curTimestamp = data[1];
        }
		pie.updateProp("data.content",analData[curTimestamp][setting]);
    }
	//it's guaranteed this won't be 0 at the end of this program,...
    function calcTotal(time){
    	var total = 1;
		for(var key in analData[time][3]){
			if(analData[time][3].hasOwnProperty(key)){
				total += analData[time][3][key];
			}
		}
		return total;
    }

    function updateDataFreq(type,time){
    	//we don't need the previous contents, we have the frequencies.
		analData[time][type] = [];
		var totalFreq = calcTotal(time);
		for(var key in analData[time][3]){
			if(analData[time][3].hasOwnProperty(key)){
				var val = analData[time][3][key];
				analData[time][type].push({label: key, value: (val / totalFreq)});
			}
		}
	}

    var handleTwitchMsg = function(msg) {
        var timestamp = msg.querySelector("span.timestamp").textContent
        var user = msg.querySelector("span.from").textContent
        var message = msg.querySelector("span.message").textContent.trim()
        var identifier = msg.id;
        port.postMessage({id: identifier, time: timestamp, usr: user, data: message});
    }

    var getChatBoxElement = function(main) {
        if(document.querySelector(main) != null){
            setupMessageListener(document.querySelector(main));
            var sentChart = setupDataViz();
            if(sentChart != null){
            	setupChart(sentChart);
            }
        } else {
            setTimeout(function() {
                getChatBoxElement(main);
            }, 500);
        }
    }

    var need = [];
    var handled = [];
    /* to setup the message listener, we have to first get the "ul.chat-lines" element.
     * this is added dynamically, so we'll use a mutation observer to get it, disconnect that observer,
     * and then begin listening to chat messages. */
    var setupMessageListener = function(chat_box) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                for(var i = 0; i < mutation.addedNodes.length; ++i){
                	if(toggle_filter == false) {
	                    var newTwitchMsg = mutation.addedNodes[i], identifier;
	                    var isValid = true;
	                    if(newTwitchMsg.id != "undefined" && newTwitchMsg.id != ""){ //native twitch
	                        identifier = newTwitchMsg.id;
	                    } else {
	                        identifier = newTwitchMsg.getAttribute("data-id"); //better twitch tv
	                        isValid = false;
	                    }
	                    if(handled.includes(identifier) == false){
	                        handled.push(identifier);
	                        if(isValid == false) //better twitch tv compatibility
	                            newTwitchMsg.setAttribute("id", identifier);
	                        handleTwitchMsg(newTwitchMsg);
	                    }
	                } else {
                        try {
                            var curMsg = mutation.addedNodes[i];
                            curMsg.setAttribute("style", "display:block;visibility:visible;");
                            if(curMsg.id == "" || curMsg.id == "undefined")
                                curMsg.setAttribute("id", curMsg.getAttribute("data-id"));
                            need.push(curMsg.id);
                        } catch(err) {}
                    }
                }
            })
        });
        //listen for new chat messages. We've incorporated BTTV compatibility.
        observer.observe(chat_box, {childList: true});
    }

    //if we're turning the filter back on, process all queued messages.
    function toggleFilter() {
    	toggle_filter = toggle_filter == false? true: false;
        if(toggle_filter == false){
            while(need.length > 0){
                try {
                    handleTwitchMsg(document.getElementById(need.shift()));
                } catch(err){}
            }
        }
    }

    function setupDataViz() {
    	var frame = document.getElementById("dataviz");
    	var sentiment = null;
    	if(frame == "" || frame == "undefined" || frame == null){
    		var structure = document.createElement("div");
    		// structure.style.visibility = "hidden";
    		structure.setAttribute("id","dataviz");
    		var styling = "position:absolute;top:50%;left:50%;margin-top:-250px;margin-left:-400px;width:450px;height:350px;z-index:9002;border-radius:3px;border: 1px solid #000;background-color:mintcream;cursor:pointer;";
    		structure.setAttribute("style", styling);
			sentiment = document.createElement("div");
			sentiment.setAttribute("id","sent");
    		structure.appendChild(sentiment);
    		var top = document.getElementsByTagName("body")[0];
    		if(top) top.appendChild(structure);
    		setupDrag();
    	}
    	return sentiment;
    }

    function setupChart(construct) {
        // document.getElementById("dataviz").style.visibility = "visible";
        // var construct = document.getElementById("sent");
		pie = new d3pie(construct, {
			"header": {
				"title": {
					"text": "What people are feeling / thinking",
					"fontSize": 20,
					"font": "verdana"
				},
				"subtitle": {
					"text": "General sentiment by the minute",
					"color": "#999999",
					"fontSize": 9,
					"font": "verdana"
				},
				"titleSubtitlePadding": 12
			},
			"footer": {
				"text": "generated using ",
				"color": "#999999",
				"fontSize": 11,
				"font": "open sans",
				"location": "bottom-center"
			},
			"size": {
				"canvasHeight": 300,
				"canvasWidth": 443,
				"pieOuterRadius": "100%"
			},
			"data": {
				"content": analytics
			},
			"labels": {
				"mainLabel": {
					"color": "#050506",
					"font": "verdana",
					"fontSize": 11
				},
				"percentage": {
					"color": "#ffffff",
					"font": "verdana",
					"fontSize": 10,
					"decimalPlaces": 0
				},
				"value": {
					"color": "#e1e1e1",
					"font": "verdana"
				},
				"lines": {
					"enabled": true,
					"color": "#cccccc"
				},
				"truncation": {
					"enabled": true
				}
			},
			"effects": {
				"load": {
					"effect": "none"
				},
				"pullOutSegmentOnClick": {
					"effect": "linear",
					"speed": 400,
					"size": 8
				}
			},
			"misc": {
				"colors": {
					"segmentStroke": "",
					segments: [
						"#5DA5DA","#FAA43A","#60BD68","#F17CB0","#B2912F","#B276B2","#DECF3F","#F15854","#2ECCC4"
					]
				},
				"canvasPadding": {
					"top": 2, "right": 2, "bottom": 2, "left": 2
				}
			}
		});
    }
    var oldStream = "";
    var curStream = window.location.href;
    function checkChangedStream(curStream){
        if(curStream != oldStream){
            oldStream = curStream;
            getChatBoxElement("ul.chat-lines");
        }
        oldStream = window.location.href;
        setTimeout(function() {
            checkChangedStream(window.location.href);
        }, 2000);
    }

    checkChangedStream();

	//Lines 54 - 77 credit jnoreiga stackoverflow; http://stackoverflow.com/questions/9334084/moveable-draggable-div
	var x_pos = 0, y_pos = 0;
	function setupDrag() {
	  var sent = document.getElementById('dataviz');
	  sent.addEventListener('mousedown', mouseDown, false);
	  window.addEventListener('mouseup', mouseUp, false);
	}

	function mouseUp() {
	  window.removeEventListener('mousemove', divMove, true);
	}

	function mouseDown(e) {
		if(cursize == false) {
			var div = document.getElementById('dataviz');
			x_pos = e.clientX - div.offsetLeft;
			y_pos = e.clientY - div.offsetTop;
			window.addEventListener('mousemove', divMove, true);
		}
	}

	function divMove(e) {
	  var div = document.getElementById('dataviz');
	  div.style.position = 'absolute';
	  div.style.top = (e.clientY - y_pos) + 'px';
	  div.style.left = (e.clientX - x_pos) + 'px';
	}
<commit_msg>remove some superfluous comments<commit_after>/* Copyright (c) 2017 Adam Browne
 * Inject.js is the content script which analyzes twitch. */

	var toggle_filter = false, pie = null, curTimestamp, prevTime, setting = 0;
	//have three arrays, of which 0 (sentiment), 1 (command), 2 (emoji)
	var analData = {};
	var analytics = [

	  { label: "1", value: 6 },
	  { label: "2", value: 4 },
	  { label: "3", value: 3 },
	  {label:"4",value:2},
	  {label:"5",value:1},
	  {label:"6",value:5},
	  {label:"7",value:7},
	  {label:"8",value:3},
	  {label:"9",value:9}
	];

    //listener to the popup menu. We listen to it's instructions.
    chrome.runtime.onMessage.addListener(function(response){
        if(response == "tf")
            toggleFilter();
    });

    var port = chrome.runtime.connect({name: "handler"});
    port.onMessage.addListener(function(message){
        var data = message.split("|");
        var target_msg = document.getElementById(data[0]);
        if(data[3] == "1") {
            try {
                target_msg.setAttribute("style", "display:block;visibility:visible;");
            } catch(err) {}
        } else {
            try {
                target_msg.setAttribute("style", "display:none;visibility:hidden;");
            } catch(err) {}
        }
        storeAnalyticsData(data);
    });

    function storeAnalyticsData(data){
    	//sent, emoji, and commands storage
    	if(!(data[1] in analData) == true){
    		analData[data[1]] = [[],[],[],{}];
    	}
        if(data[4] != "") { //sentiment analytics
        	var sent = data[4];
        	if(!(sent in analData[data[1]][3]) == true) {
        		analData[data[1]][3][sent] = 1;
        	} else {
        		++analData[data[1]][3][sent];
        	}
        	updateDataFreq(0,data[1]);
        } else { //command analytics
        	//do nothing.
        }
        if(curTimestamp != data[1]) {
        	curTimestamp = data[1];
        }
		pie.updateProp("data.content",analData[curTimestamp][setting]);
    }
	//it's guaranteed this won't be 0 at the end of this program,...
    function calcTotal(time){
    	var total = 1;
		for(var key in analData[time][3]){
			if(analData[time][3].hasOwnProperty(key)){
				total += analData[time][3][key];
			}
		}
		return total;
    }

    function updateDataFreq(type,time){
    	//we don't need the previous contents, we have the frequencies.
		analData[time][type] = [];
		var totalFreq = calcTotal(time);
		for(var key in analData[time][3]){
			if(analData[time][3].hasOwnProperty(key)){
				var val = analData[time][3][key];
				analData[time][type].push({label: key, value: (val / totalFreq)});
			}
		}
	}

    var handleTwitchMsg = function(msg) {
        var timestamp = msg.querySelector("span.timestamp").textContent
        var user = msg.querySelector("span.from").textContent
        var message = msg.querySelector("span.message").textContent.trim()
        var identifier = msg.id;
        port.postMessage({id: identifier, time: timestamp, usr: user, data: message});
    }

    var getChatBoxElement = function(main) {
        if(document.querySelector(main) != null){
            setupMessageListener(document.querySelector(main));
            var sentChart = setupDataViz();
            if(sentChart != null){
            	setupChart(sentChart);
            }
        } else {
            setTimeout(function() {
                getChatBoxElement(main);
            }, 500);
        }
    }

    var need = [], handled = [];
	/* To observe the new messages, we need to use a MutationObserver
	* and then apply a queryselector to get the new message added:
	we're looking for:
 */
    var setupMessageListener = function(chat_box) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                for(var i = 0; i < mutation.addedNodes.length; ++i){
                	if(toggle_filter == false) {
	                    var newTwitchMsg = mutation.addedNodes[i], identifier;
	                    var isValid = true;
	                    if(newTwitchMsg.id != "undefined" && newTwitchMsg.id != ""){ //native twitch
	                        identifier = newTwitchMsg.id;
	                    } else {
	                        identifier = newTwitchMsg.getAttribute("data-id"); //better twitch tv
	                        isValid = false;
	                    }
	                    if(handled.includes(identifier) == false){
	                        handled.push(identifier);
	                        if(isValid == false) //better twitch tv compatibility
	                            newTwitchMsg.setAttribute("id", identifier);
	                        handleTwitchMsg(newTwitchMsg);
	                    }
	                } else {
                        try {
                            var curMsg = mutation.addedNodes[i];
                            curMsg.setAttribute("style", "display:block;visibility:visible;");
                            if(curMsg.id == "" || curMsg.id == "undefined")
                                curMsg.setAttribute("id", curMsg.getAttribute("data-id"));
                            need.push(curMsg.id);
                        } catch(err) {}
                    }
                }
            })
        });
        //listen for new chat messages. We've incorporated BTTV compatibility.
        observer.observe(chat_box, {childList: true});
    }

    //if we're turning the filter back on, process all queued messages.
    function toggleFilter() {
    	toggle_filter = toggle_filter == false? true: false;
        if(toggle_filter == false){
            while(need.length > 0){
                try {
                    handleTwitchMsg(document.getElementById(need.shift()));
                } catch(err){}
            }
        }
    }

    function setupDataViz() {
    	var frame = document.getElementById("dataviz");
    	var sentiment = null;
    	if(frame == "" || frame == "undefined" || frame == null){
    		var structure = document.createElement("div");
    		// structure.style.visibility = "hidden";
    		structure.setAttribute("id","dataviz");
    		var styling = "position:absolute;top:50%;left:50%;margin-top:-250px;margin-left:-400px;width:450px;height:350px;z-index:9002;border-radius:3px;border: 1px solid #000;background-color:mintcream;cursor:pointer;";
    		structure.setAttribute("style", styling);
			sentiment = document.createElement("div");
			sentiment.setAttribute("id","sent");
    		structure.appendChild(sentiment);
    		var top = document.getElementsByTagName("body")[0];
    		if(top) top.appendChild(structure);
    		setupDrag();
    	}
    	return sentiment;
    }

    function setupChart(construct) {
        // document.getElementById("dataviz").style.visibility = "visible";
        // var construct = document.getElementById("sent");
		pie = new d3pie(construct, {
			"header": {
				"title": {
					"text": "What people are feeling / thinking",
					"fontSize": 20,
					"font": "verdana"
				},
				"subtitle": {
					"text": "General sentiment by the minute",
					"color": "#999999",
					"fontSize": 9,
					"font": "verdana"
				},
				"titleSubtitlePadding": 12
			},
			"footer": {
				"text": "generated using ",
				"color": "#999999",
				"fontSize": 11,
				"font": "open sans",
				"location": "bottom-center"
			},
			"size": {
				"canvasHeight": 300,
				"canvasWidth": 443,
				"pieOuterRadius": "100%"
			},
			"data": {
				"content": analytics
			},
			"labels": {
				"mainLabel": {
					"color": "#050506",
					"font": "verdana",
					"fontSize": 11
				},
				"percentage": {
					"color": "#ffffff",
					"font": "verdana",
					"fontSize": 10,
					"decimalPlaces": 0
				},
				"value": {
					"color": "#e1e1e1",
					"font": "verdana"
				},
				"lines": {
					"enabled": true,
					"color": "#cccccc"
				},
				"truncation": {
					"enabled": true
				}
			},
			"effects": {
				"load": {
					"effect": "none"
				},
				"pullOutSegmentOnClick": {
					"effect": "linear",
					"speed": 400,
					"size": 8
				}
			},
			"misc": {
				"colors": {
					"segmentStroke": "",
					segments: [
						"#5DA5DA","#FAA43A","#60BD68","#F17CB0","#B2912F","#B276B2","#DECF3F","#F15854","#2ECCC4"
					]
				},
				"canvasPadding": {
					"top": 2, "right": 2, "bottom": 2, "left": 2
				}
			}
		});
    }
    var oldStream = "";
    var curStream = window.location.href;
    function checkChangedStream(curStream){
        if(curStream != oldStream){
            oldStream = curStream;
            getChatBoxElement("ul.chat-lines");
        }
        oldStream = window.location.href;
        setTimeout(function() {
            checkChangedStream(window.location.href);
        }, 2000);
    }

    checkChangedStream();

	//Lines 54-77 credit jnoreiga; http://stackoverflow.com/questions/9334084/moveable-draggable-div
	var x_pos = 0, y_pos = 0;
	function setupDrag() {
	  var sent = document.getElementById('dataviz');
	  sent.addEventListener('mousedown', mouseDown, false);
	  window.addEventListener('mouseup', mouseUp, false);
	}

	function mouseUp() {
	  window.removeEventListener('mousemove', divMove, true);
	}

	function mouseDown(e) {
		var div = document.getElementById('dataviz');
		x_pos = e.clientX - div.offsetLeft;
		y_pos = e.clientY - div.offsetTop;
		window.addEventListener('mousemove', divMove, true);
	}

	function divMove(e) {
	  var div = document.getElementById('dataviz');
	  div.style.position = 'absolute';
	  div.style.top = (e.clientY - y_pos) + 'px';
	  div.style.left = (e.clientX - x_pos) + 'px';
	}
<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var BaseObject = require('../../base/base_object');
var $ = require("jquery");
var _ = require('underscore');

var PipPlugin = BaseObject.extend({
  initialize: function(core) {
    this.core = core;
    this.pipStyle = {width: "24%", height: "24%", "z-index": 20, bottom: "47px", right: "7px"};
    this.masterStyle = {width: "100%", height: "100%", "z-index": 20, bottom: "0px", right: "0px"};
    this.masterContainer = core.containers[0];
    if (core.containers.length === 2) {
      this.pipContainer = core.containers[1];
      this.pipContainer.setStyle(this.pipStyle);
    }
    this.setupApi();
  },
  setupApi: function() {
    //FIXME we need to figure out how to manage player API (issue #51)
    window.WP3.addPip = this.addPip.bind(this);
    window.WP3.discardPip = this.discardPip.bind(this);
    window.WP3.addMaster = this.addMaster.bind(this);
    window.WP3.pipToMaster = this.pipToMaster.bind(this);
  },
  addPip: function(source) {
    this.discardPip();
    this.pipContainer = this.core.playbackHandler.createContainer(source, this.addPipCallback.bind(this));
    this.pipContainer.setStyle({'z-index': -1}); //we need to put this container behind everything until flash dispatch on:ready
    window.pip = this.pipContainer;
    this.core.$el.append(this.pipContainer.render().el);
  },
  addPipCallback: function(container) {
    this.pipContainer.setVolume(0);
    this.pipContainer.getPluginByName('watermark').disable();
    this.pipContainer.setStyle(this.pipStyle);
    this.pipContainer.play();
    this.core.containers.push(this.pipContainer);
  },
  discardPip: function() {
    if (this.pipContainer) {
      this.pipContainer.destroy();
      this.discardContainer(this.pipContainer);
      delete this.pipContainer;
    }
  },
  addMaster: function(source) {
    if (this.masterContainer) {
      this.tmpContainer = this.masterContainer;
      this.tmpContainer.setStyle({'z-index': 20});
      this.core.playbackHandler.createContainer(source, this.addMasterCallback.bind(this));
    }
  },
  addMasterCallback: function(container) {
    this.masterContainer = container;
    this.core.$el.append(this.masterContainer.render().el);
    this.masterContainer.play();
    this.discardPip();
    this.pipContainer = this.tmpContainer;
    delete this.tmpContainer;
    this.pipContainer.setVolume(0);
    this.pipContainer.getPluginByName('watermark').disable();
    if (this.pipContainer.hasPlugin('hls_playback')) { //flash breaks on animate
      this.pipContainer.setStyle(this.pipStyle);
    } else {
      this.pipContainer.animate(this.pipStyle, 400);
    }
    this.core.containers.splice(0, 0, this.masterContainer);
  },
  discardContainer: function(container) {
    this.core.containers = _.without(this.core.containers, _.findWhere(this.core.containers, container));
  },
  pipToMaster: function() {
    if (this.pipContainer) {
      this.pipContainer.animate(this.masterStyle, 400);
      setTimeout(this.afterPipToMaster.bind(this), 400);
    }
  },
  afterPipToMaster: function() {
    this.pipContainer.setVolume(100);
    this.pipContainer.getPluginByName('watermark').enable();
    this.masterContainer.destroy();
    this.discardContainer(this.masterContainer);
    delete this.masterContainer;
    this.masterContainer = this.pipContainer;
    this.masterContainer.setStyle({"z-index": 1});
    delete this.pipContainer;
  }
});

module.exports = PipPlugin;
<commit_msg>pip: oops, removing line<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var BaseObject = require('../../base/base_object');
var $ = require("jquery");
var _ = require('underscore');

var PipPlugin = BaseObject.extend({
  initialize: function(core) {
    this.core = core;
    this.pipStyle = {width: "24%", height: "24%", "z-index": 20, bottom: "47px", right: "7px"};
    this.masterStyle = {width: "100%", height: "100%", "z-index": 20, bottom: "0px", right: "0px"};
    this.masterContainer = core.containers[0];
    if (core.containers.length === 2) {
      this.pipContainer = core.containers[1];
      this.pipContainer.setStyle(this.pipStyle);
    }
    this.setupApi();
  },
  setupApi: function() {
    //FIXME we need to figure out how to manage player API (issue #51)
    window.WP3.addPip = this.addPip.bind(this);
    window.WP3.discardPip = this.discardPip.bind(this);
    window.WP3.addMaster = this.addMaster.bind(this);
    window.WP3.pipToMaster = this.pipToMaster.bind(this);
  },
  addPip: function(source) {
    this.discardPip();
    this.pipContainer = this.core.playbackHandler.createContainer(source, this.addPipCallback.bind(this));
    this.pipContainer.setStyle({'z-index': -1}); //we need to put this container behind everything until flash dispatch on:ready
    this.core.$el.append(this.pipContainer.render().el);
  },
  addPipCallback: function(container) {
    this.pipContainer.setVolume(0);
    this.pipContainer.getPluginByName('watermark').disable();
    this.pipContainer.setStyle(this.pipStyle);
    this.pipContainer.play();
    this.core.containers.push(this.pipContainer);
  },
  discardPip: function() {
    if (this.pipContainer) {
      this.pipContainer.destroy();
      this.discardContainer(this.pipContainer);
      delete this.pipContainer;
    }
  },
  addMaster: function(source) {
    if (this.masterContainer) {
      this.tmpContainer = this.masterContainer;
      this.tmpContainer.setStyle({'z-index': 20});
      this.core.playbackHandler.createContainer(source, this.addMasterCallback.bind(this));
    }
  },
  addMasterCallback: function(container) {
    this.masterContainer = container;
    this.core.$el.append(this.masterContainer.render().el);
    this.masterContainer.play();
    this.discardPip();
    this.pipContainer = this.tmpContainer;
    delete this.tmpContainer;
    this.pipContainer.setVolume(0);
    this.pipContainer.getPluginByName('watermark').disable();
    if (this.pipContainer.hasPlugin('hls_playback')) { //flash breaks on animate
      this.pipContainer.setStyle(this.pipStyle);
    } else {
      this.pipContainer.animate(this.pipStyle, 400);
    }
    this.core.containers.splice(0, 0, this.masterContainer);
  },
  discardContainer: function(container) {
    this.core.containers = _.without(this.core.containers, _.findWhere(this.core.containers, container));
  },
  pipToMaster: function() {
    if (this.pipContainer) {
      this.pipContainer.animate(this.masterStyle, 400);
      setTimeout(this.afterPipToMaster.bind(this), 400);
    }
  },
  afterPipToMaster: function() {
    this.pipContainer.setVolume(100);
    this.pipContainer.getPluginByName('watermark').enable();
    this.masterContainer.destroy();
    this.discardContainer(this.masterContainer);
    delete this.masterContainer;
    this.masterContainer = this.pipContainer;
    this.masterContainer.setStyle({"z-index": 1});
    delete this.pipContainer;
  }
});

module.exports = PipPlugin;
<|endoftext|>


<commit_before>//  Phaser.Input.Pointer

var Class = require('../utils/Class');
var Vector2 = require('../math/Vector2');

//  DOM event button value:
// A number representing a given button:
// 0: Main button pressed, usually the left button or the un-initialized state
// 1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
// 2: Secondary button pressed, usually the right button
// 3: Fourth button, typically the Browser Back button
// 4: Fifth button, typically the Browser Forward button
// For a mouse configured for left-handed use, the button actions are reversed. In this case, the values are read from right to left.

var Pointer = new Class({

    initialize:

    function Pointer (manager, id)
    {
        this.manager = manager;

        this.id = id;

        this.event;

        //  The camera the Pointer interacted with during its last update
        //  A Pointer can only ever interact with 1 camera at once, which will be the top-most camera
        //  in the list should multiple cameras be positioned on-top of each other.
        this.camera = null;

        // 0  : No button or un-initialized
        // 1  : Left button
        // 2  : Right button
        // 4  : Wheel button or middle button
        // 8  : 4th button (typically the "Browser Back" button)
        // 16 : 5th button (typically the "Browser Forward" button)
        this.buttons = 0;

        this.position = new Vector2();

        //  Coordinates and time of the pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects
        this.downX = 0;
        this.downY = 0;
        this.downTime = 0;

        //  Coordinates and time of the pointer when Button 1 (left button), or Touch, was released, used for dragging objects
        this.upX = 0;
        this.upY = 0;
        this.upTime = 0;

        //  Is the primary button down? (usually button 0, the left mouse button)
        this.primaryDown = false;

        //  0 = Not dragging anything
        //  1 = Being checked if dragging
        //  2 = Dragging something
        this.dragState = 0;

        //  Is *any* button on this pointer considered as being down?
        this.isDown = false;

        this.dirty = false;

        this.justDown = false;
        this.justUp = false;
        this.justMoved = false;

        //  Did the previous input event come from a Touch input (true) or Mouse? (false)
        this.wasTouch = false;

        /**
         * @property {number} movementX - If the mouse is locked, the horizontal relative movement
         * of the Pointer in pixels since last frame.
         */
        this.movementX = 0;

        /**
         * @property {number} movementY - If the mouse is locked, the vertical relative movement of
         * the Pointer in pixels since last frame.
         */
        this.movementY = 0;
    },

    positionToCamera: function (camera, output)
    {
        return camera.getWorldPoint(this.x, this.y, output);
    },

    x: {

        get: function ()
        {
            return this.position.x;
        },

        set: function (value)
        {
            this.position.x = value;
        }

    },

    y: {

        get: function ()
        {
            return this.position.y;
        },

        set: function (value)
        {
            this.position.y = value;
        }

    },

    reset: function ()
    {
        this.buttons = 0;

        this.dirty = false;
        this.isDown = false;
        this.justDown = false;
        this.justUp = false;
        this.justMoved = false;
        this.movementX = 0;
        this.movementY = 0;
    },

    touchmove: function (event, time)
    {
        this.event = event;

        this.x = this.manager.transformX(event.changedTouches[0].pageX);
        this.y = this.manager.transformY(event.changedTouches[0].pageY);

        this.justMoved = true;

        this.dirty = true;

        this.wasTouch = true;
    },

    move: function (event, time)
    {
        if (event.buttons)
        {
            this.buttons = event.buttons;
        }

        this.event = event;

        this.x = this.manager.transformX(event.pageX);
        this.y = this.manager.transformY(event.pageY);

        if (this.manager.mouse.locked)
        {
            // Multiple DOM events may occur within one frame, but only one Phaser event will fire
            this.movementX += event.movementX || event.mozMovementX || event.webkitMovementX || 0;
            this.movementY += event.movementY || event.mozMovementY || event.webkitMovementY || 0;
        }

        this.justMoved = true;

        this.dirty = true;

        this.wasTouch = false;
    },

    down: function (event, time)
    {
        if (event.buttons)
        {
            this.buttons = event.buttons;
        }

        this.event = event;

        this.x = this.manager.transformX(event.pageX);
        this.y = this.manager.transformY(event.pageY);

        //  0: Main button pressed, usually the left button or the un-initialized state
        if (event.button === 0)
        {
            this.primaryDown = true;
            this.downX = this.x;
            this.downY = this.y;
            this.downTime = time;
        }

        this.justDown = true;
        this.isDown = true;

        this.dirty = true;

        this.wasTouch = false;
    },

    touchstart: function (event, time)
    {
        this.buttons = 1;

        this.event = event;

        this.x = this.manager.transformX(event.changedTouches[0].pageX);
        this.y = this.manager.transformY(event.changedTouches[0].pageY);

        this.primaryDown = true;
        this.downX = this.x;
        this.downY = this.y;
        this.downTime = time;

        this.justDown = true;
        this.isDown = true;

        this.dirty = true;

        this.wasTouch = true;
    },

    up: function (event, time)
    {
        if (event.buttons)
        {
            this.buttons = event.buttons;
        }

        this.event = event;

        this.x = this.manager.transformX(event.pageX);
        this.y = this.manager.transformY(event.pageY);

        //  0: Main button pressed, usually the left button or the un-initialized state
        if (event.button === 0)
        {
            this.primaryDown = false;
            this.upX = this.x;
            this.upY = this.y;
            this.upTime = time;
        }

        this.justUp = true;
        this.isDown = false;

        this.dirty = true;

        this.wasTouch = false;
    },

    touchend: function (event, time)
    {
        this.buttons = 0;

        this.event = event;

        this.x = this.manager.transformX(event.changedTouches[0].pageX);
        this.y = this.manager.transformY(event.changedTouches[0].pageY);

        this.primaryDown = false;
        this.upX = this.x;
        this.upY = this.y;
        this.upTime = time;

        this.justUp = true;
        this.isDown = false;

        this.dirty = true;

        this.wasTouch = true;
    },

    noButtonDown: function ()
    {
        return (this.buttons === 0);
    },

    leftButtonDown: function ()
    {
        return (this.buttons & 1);
    },

    rightButtonDown: function ()
    {
        return (this.buttons & 2);
    },

    middleButtonDown: function ()
    {
        return (this.buttons & 4);
    },

    backButtonDown: function ()
    {
        return (this.buttons & 8);
    },

    forwardButtonDown: function ()
    {
        return (this.buttons & 16);
    }

});

module.exports = Pointer;
<commit_msg>Pointer.reset no longer resets the `isDown` state or buttons<commit_after>//  Phaser.Input.Pointer

var Class = require('../utils/Class');
var Vector2 = require('../math/Vector2');

//  DOM event button value:
// A number representing a given button:
// 0: Main button pressed, usually the left button or the un-initialized state
// 1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
// 2: Secondary button pressed, usually the right button
// 3: Fourth button, typically the Browser Back button
// 4: Fifth button, typically the Browser Forward button
// For a mouse configured for left-handed use, the button actions are reversed. In this case, the values are read from right to left.

var Pointer = new Class({

    initialize:

    function Pointer (manager, id)
    {
        this.manager = manager;

        this.id = id;

        this.event;

        //  The camera the Pointer interacted with during its last update
        //  A Pointer can only ever interact with 1 camera at once, which will be the top-most camera
        //  in the list should multiple cameras be positioned on-top of each other.
        this.camera = null;

        // 0  : No button or un-initialized
        // 1  : Left button
        // 2  : Right button
        // 4  : Wheel button or middle button
        // 8  : 4th button (typically the "Browser Back" button)
        // 16 : 5th button (typically the "Browser Forward" button)
        this.buttons = 0;

        this.position = new Vector2();

        //  Coordinates and time of the pointer when Button 1 (left button), or Touch, was pressed, used for dragging objects
        this.downX = 0;
        this.downY = 0;
        this.downTime = 0;

        //  Coordinates and time of the pointer when Button 1 (left button), or Touch, was released, used for dragging objects
        this.upX = 0;
        this.upY = 0;
        this.upTime = 0;

        //  Is the primary button down? (usually button 0, the left mouse button)
        this.primaryDown = false;

        //  0 = Not dragging anything
        //  1 = Being checked if dragging
        //  2 = Dragging something
        this.dragState = 0;

        //  Is *any* button on this pointer considered as being down?
        this.isDown = false;

        this.dirty = false;

        this.justDown = false;
        this.justUp = false;
        this.justMoved = false;

        //  Did the previous input event come from a Touch input (true) or Mouse? (false)
        this.wasTouch = false;

        /**
         * @property {number} movementX - If the mouse is locked, the horizontal relative movement
         * of the Pointer in pixels since last frame.
         */
        this.movementX = 0;

        /**
         * @property {number} movementY - If the mouse is locked, the vertical relative movement of
         * the Pointer in pixels since last frame.
         */
        this.movementY = 0;
    },

    positionToCamera: function (camera, output)
    {
        return camera.getWorldPoint(this.x, this.y, output);
    },

    x: {

        get: function ()
        {
            return this.position.x;
        },

        set: function (value)
        {
            this.position.x = value;
        }

    },

    y: {

        get: function ()
        {
            return this.position.y;
        },

        set: function (value)
        {
            this.position.y = value;
        }

    },

    reset: function ()
    {
        // this.buttons = 0;

        this.dirty = false;

        this.justDown = false;
        this.justUp = false;
        this.justMoved = false;

        this.movementX = 0;
        this.movementY = 0;
    },

    touchmove: function (event, time)
    {
        this.event = event;

        this.x = this.manager.transformX(event.changedTouches[0].pageX);
        this.y = this.manager.transformY(event.changedTouches[0].pageY);

        this.justMoved = true;

        this.dirty = true;

        this.wasTouch = true;
    },

    move: function (event, time)
    {
        if (event.buttons)
        {
            this.buttons = event.buttons;
        }

        this.event = event;

        this.x = this.manager.transformX(event.pageX);
        this.y = this.manager.transformY(event.pageY);

        if (this.manager.mouse.locked)
        {
            // Multiple DOM events may occur within one frame, but only one Phaser event will fire
            this.movementX += event.movementX || event.mozMovementX || event.webkitMovementX || 0;
            this.movementY += event.movementY || event.mozMovementY || event.webkitMovementY || 0;
        }

        this.justMoved = true;

        this.dirty = true;

        this.wasTouch = false;
    },

    down: function (event, time)
    {
        if (event.buttons)
        {
            this.buttons = event.buttons;
        }

        this.event = event;

        this.x = this.manager.transformX(event.pageX);
        this.y = this.manager.transformY(event.pageY);

        //  0: Main button pressed, usually the left button or the un-initialized state
        if (event.button === 0)
        {
            this.primaryDown = true;
            this.downX = this.x;
            this.downY = this.y;
            this.downTime = time;
        }

        this.justDown = true;
        this.isDown = true;

        this.dirty = true;

        this.wasTouch = false;
    },

    touchstart: function (event, time)
    {
        this.buttons = 1;

        this.event = event;

        this.x = this.manager.transformX(event.changedTouches[0].pageX);
        this.y = this.manager.transformY(event.changedTouches[0].pageY);

        this.primaryDown = true;
        this.downX = this.x;
        this.downY = this.y;
        this.downTime = time;

        this.justDown = true;
        this.isDown = true;

        this.dirty = true;

        this.wasTouch = true;
    },

    up: function (event, time)
    {
        if (event.buttons)
        {
            this.buttons = event.buttons;
        }

        this.event = event;

        this.x = this.manager.transformX(event.pageX);
        this.y = this.manager.transformY(event.pageY);

        //  0: Main button pressed, usually the left button or the un-initialized state
        if (event.button === 0)
        {
            this.primaryDown = false;
            this.upX = this.x;
            this.upY = this.y;
            this.upTime = time;
        }

        this.justUp = true;
        this.isDown = false;

        this.dirty = true;

        this.wasTouch = false;
    },

    touchend: function (event, time)
    {
        this.buttons = 0;

        this.event = event;

        this.x = this.manager.transformX(event.changedTouches[0].pageX);
        this.y = this.manager.transformY(event.changedTouches[0].pageY);

        this.primaryDown = false;
        this.upX = this.x;
        this.upY = this.y;
        this.upTime = time;

        this.justUp = true;
        this.isDown = false;

        this.dirty = true;

        this.wasTouch = true;
    },

    noButtonDown: function ()
    {
        return (this.buttons === 0);
    },

    leftButtonDown: function ()
    {
        return (this.buttons & 1);
    },

    rightButtonDown: function ()
    {
        return (this.buttons & 2);
    },

    middleButtonDown: function ()
    {
        return (this.buttons & 4);
    },

    backButtonDown: function ()
    {
        return (this.buttons & 8);
    },

    forwardButtonDown: function ()
    {
        return (this.buttons & 16);
    }

});

module.exports = Pointer;
<|endoftext|>


<commit_before>/*!
  * instantsearch: GOOGish autocomplete © Kurt Ruppel 2013
  *
  * https://github.com/kruppel/instantsearch
  * LICENSE: MIT
  */

(function ($) {

  var IGNORED_KEY_CODES = [
    16//shift
  , 17//ctrl
  , 18//alt
  , 19//pause/break
  , 20//caps lock
  , 33//page up
  , 34//page down
  , 35//end
  , 36//home
  , 37//left
  , 45//insert
  , 91//windows-key/cmd
  , 92
  , 93//select
  , 112//f1
  , 113//f2
  , 114//f3
  , 115//f4
  , 116//f5
  , 117//f6
  , 118//f7
  , 119//f8
  , 120//f9
  , 121//f10
  , 122//f11
  , 123//f12
  , 124//f13
  , 125//f14
  , 126//f15
  ];

  function SearchResult(term, value) {
    var regex = new RegExp('(' + term + ')(.*)', 'i')
      , matchset = value.match(regex) || {}
      , start = value.substr(0, matchset.index)
      , match = matchset[1] || ''
      , rest =  matchset[2] || '';

    this.guess = (start === '' && rest !== '') ? term + rest : '';
    this.el = '
' + start + '' + match + '' + rest + '
';
  }

  $.fn.instantSearch = function (options) {
    var opts = $.extend({}, options);

    return this.each(function () {
      var $this = $(this);

      $this.data('instantsearch', new $.InstantSearch($this, opts));
    });
  };

  $.InstantSearch = function ($el, options) {
    var self    = this
      , id      = $el.attr('id')
      , name    = $el.attr('name')
      , classes = $el.attr('class');

    this.src             = options.source;
    this.action          = options.action;
    this.closeOnBlur     = options.closeOnBlur;
    this.completeOnEnter = options.completeOnEnter;
    this.showNoResults   = options.showNoResults;

    this.$el = $(
      '
'+
      '<input class="input" type="text" autocomplete="off" spellcheck="false" dir="ltr">'+
      '<input class="ghost" disabled autocomplete="off">'+
      '
'
    );
    $el.replaceWith(this.$el);

    this.$res = $(
      '
' +
      '

' +
      '
'
    ).hide().appendTo('body');

    this.$input = this.$el.find('.input');
    this.$input.attr({ id: id, name: name })
               .addClass(classes);

    this.$ghost = this.$el.find('.ghost');

    this.$input.on('keydown', function (e) {
      var keyCode = e.keyCode;

      if (IGNORED_KEY_CODES.indexOf(keyCode) !== -1) return;

      switch(keyCode) {

        // up
        case 38:
          self.navigate(-1);
          e.preventDefault();
          break;

        // right
        case 39:
          self.complete();
          break;

        // down
        case 40:
          self.navigate(1);
          e.preventDefault();
          break;

        // tab
        case 9:
          if (self.complete()) {
            self.search();
            e.preventDefault();
          }
          break;

        // return
        case 13:
          if (self.completeOnEnter) {
            self.complete();
            self.trigger();
          } else {
            self.reset();
            self.trigger();
          }
          e.preventDefault();
          break;

        // escape
        case 27:
          self.reset();
          break;

        default:
          self.search();
      }

    });

    this.$input.on('cut paste', function (e) {
      self.search();
    });

    if (this.closeOnBlur) {
      this.$input.on('blur', function (e) {
        self.reset();
      });

      this.$input.on('focus', function (e) {
        self.search();
      });
    }

    this.$res.on('mouseenter', 'ul.list li.result', function (e) {
      var items = self.$res.find('ul.list li.result')
        , index = items.index(this);

      self.navigateTo(index);
    });

    this.$res.on('mouseleave', function (e) {
      self.navigateTo(-1);
    });

    this.$res.on('mousedown', function (e) {
      self.complete();
      self.reset();
      self.trigger();
    });
  };

  $.InstantSearch.prototype = {

    _rel: ''

  , _sel: -1

  , search: function () {
      var self = this;

      this._tid && clearTimeout(this._tid);
      this._tid = setTimeout(function () {
        var q = self._val = self.$input.val()
          , part;

        if (q === '') return self.showResults();

        part = self._rel.slice(0, q.length);

        if (q.toLowerCase() === part.toLowerCase()) {
          // Case doesn't match, match casing in ghost
          if (q !== part) {
            self.$ghost.val(q + self._rel.slice(q.length));
          }
        } else {
          // Hide ghost if we no longer match it
          self.$ghost.val('');
        }

        self.src({ term: q }, function (data, err) {
          if (err) throw new Error(err);

          self._data = data;
          self.showResults(data, self.showNoResults);
        });
      }, 0);
    }

  , showResults: function (data, showNoResults) {
      var self = this
        , res = this.$res
        , list = res.find('ul.list')
        , ghost = this.$ghost
        , val = this.$input.val()
        , len = data && data.length
        , $body = $('body')
        , i = 0
        , content = ''
        , onEscape
        , result
        , guess;

      // Don't show results again if value hasn't changed
      if (val === this._triggeredValue) { return; }
      this._triggeredValue = null;

      list.empty();

      this._sel = -1;

      if (val === '' || !data || data.length === 0) {
        ghost.val('');

        if (showNoResults && val !== '') {
          res.show();
          list.append('
No Results
');
        } else {
          res.hide();
          $body.off('keydown', onEscape);
        }

        return false;
      }

      $('body').on('keydown', onEscape = function (e) {
        e.keyCode === 27 && self.reset();
      });

      for (; i < len; i++) {
        result = new SearchResult(val, data[i]);

        //
        if (i === 0) {
          guess = result.guess;

          this._rel = guess;
          ghost.val(guess);
        }

        content += result.el;
      }

      list.append(content);

      if (res.is(':hidden')) {
        res.css({
          position: 'absolute',
          top:      this.$el.offset().top + this.$el.outerHeight(),
          left:     this.$el.offset().left,
          width:    this.$el.outerWidth()
        }).show();
      }

      return true;
    }

  , navigate: function (dir) {
      var items = this.$res.find('ul.list li.result')
        , sel;

      if (items.length === 0) return;

      sel = this._sel + dir;
      if (sel < -1) {
        sel += (items.length + 1);
      } else if (sel >= items.length) {
        sel -= (items.length + 1);
      }

      this.navigateTo(sel);
    }

  , navigateTo: function (sel) {
      var items = this.$res.find('ul.list li.result');

      items.removeClass('highlight');
      $(items[sel]).addClass('highlight');

      if (sel === -1) {
        this.$input.val(this._val) && this.$ghost.val(this._rel);
      } else {
        this.$input.val(this._data[sel]) && this.$ghost.val('');
      }

      this._sel = sel;
    }

  , reset: function () {
      this.showResults(null);
    }

  , complete: function () {
      if (this.$ghost.val()) {
        this._val = this._data[0];
        this._rel = '';
        this.$input.val(this._val);
        this.$ghost.val('');

        return true;
      } else {
        return false;
      }
    }

  , valueIsInList: function (value) {
      return this._data && $.inArray(value, this._data) !== -1;
    }

  , trigger: function () {
      var value = this._triggeredValue = this.$input.val();

      if (this.action) {
        this.action.call(this, value);
      } else {
        this.$el.parent('form').submit();
      }
    }

  };

}(jQuery));
<commit_msg>Remove unnecessary parens around increment of selection index.<commit_after>/*!
  * instantsearch: GOOGish autocomplete © Kurt Ruppel 2013
  *
  * https://github.com/kruppel/instantsearch
  * LICENSE: MIT
  */

(function ($) {

  var IGNORED_KEY_CODES = [
    16//shift
  , 17//ctrl
  , 18//alt
  , 19//pause/break
  , 20//caps lock
  , 33//page up
  , 34//page down
  , 35//end
  , 36//home
  , 37//left
  , 45//insert
  , 91//windows-key/cmd
  , 92
  , 93//select
  , 112//f1
  , 113//f2
  , 114//f3
  , 115//f4
  , 116//f5
  , 117//f6
  , 118//f7
  , 119//f8
  , 120//f9
  , 121//f10
  , 122//f11
  , 123//f12
  , 124//f13
  , 125//f14
  , 126//f15
  ];

  function SearchResult(term, value) {
    var regex = new RegExp('(' + term + ')(.*)', 'i')
      , matchset = value.match(regex) || {}
      , start = value.substr(0, matchset.index)
      , match = matchset[1] || ''
      , rest =  matchset[2] || '';

    this.guess = (start === '' && rest !== '') ? term + rest : '';
    this.el = '
' + start + '' + match + '' + rest + '
';
  }

  $.fn.instantSearch = function (options) {
    var opts = $.extend({}, options);

    return this.each(function () {
      var $this = $(this);

      $this.data('instantsearch', new $.InstantSearch($this, opts));
    });
  };

  $.InstantSearch = function ($el, options) {
    var self    = this
      , id      = $el.attr('id')
      , name    = $el.attr('name')
      , classes = $el.attr('class');

    this.src             = options.source;
    this.action          = options.action;
    this.closeOnBlur     = options.closeOnBlur;
    this.completeOnEnter = options.completeOnEnter;
    this.showNoResults   = options.showNoResults;

    this.$el = $(
      '
'+
      '<input class="input" type="text" autocomplete="off" spellcheck="false" dir="ltr">'+
      '<input class="ghost" disabled autocomplete="off">'+
      '
'
    );
    $el.replaceWith(this.$el);

    this.$res = $(
      '
' +
      '

' +
      '
'
    ).hide().appendTo('body');

    this.$input = this.$el.find('.input');
    this.$input.attr({ id: id, name: name })
               .addClass(classes);

    this.$ghost = this.$el.find('.ghost');

    this.$input.on('keydown', function (e) {
      var keyCode = e.keyCode;

      if (IGNORED_KEY_CODES.indexOf(keyCode) !== -1) return;

      switch(keyCode) {

        // up
        case 38:
          self.navigate(-1);
          e.preventDefault();
          break;

        // right
        case 39:
          self.complete();
          break;

        // down
        case 40:
          self.navigate(1);
          e.preventDefault();
          break;

        // tab
        case 9:
          if (self.complete()) {
            self.search();
            e.preventDefault();
          }
          break;

        // return
        case 13:
          if (self.completeOnEnter) {
            self.complete();
            self.trigger();
          } else {
            self.reset();
            self.trigger();
          }
          e.preventDefault();
          break;

        // escape
        case 27:
          self.reset();
          break;

        default:
          self.search();
      }

    });

    this.$input.on('cut paste', function (e) {
      self.search();
    });

    if (this.closeOnBlur) {
      this.$input.on('blur', function (e) {
        self.reset();
      });

      this.$input.on('focus', function (e) {
        self.search();
      });
    }

    this.$res.on('mouseenter', 'ul.list li.result', function (e) {
      var items = self.$res.find('ul.list li.result')
        , index = items.index(this);

      self.navigateTo(index);
    });

    this.$res.on('mouseleave', function (e) {
      self.navigateTo(-1);
    });

    this.$res.on('mousedown', function (e) {
      self.complete();
      self.reset();
      self.trigger();
    });
  };

  $.InstantSearch.prototype = {

    _rel: ''

  , _sel: -1

  , search: function () {
      var self = this;

      this._tid && clearTimeout(this._tid);
      this._tid = setTimeout(function () {
        var q = self._val = self.$input.val()
          , part;

        if (q === '') return self.showResults();

        part = self._rel.slice(0, q.length);

        if (q.toLowerCase() === part.toLowerCase()) {
          // Case doesn't match, match casing in ghost
          if (q !== part) {
            self.$ghost.val(q + self._rel.slice(q.length));
          }
        } else {
          // Hide ghost if we no longer match it
          self.$ghost.val('');
        }

        self.src({ term: q }, function (data, err) {
          if (err) throw new Error(err);

          self._data = data;
          self.showResults(data, self.showNoResults);
        });
      }, 0);
    }

  , showResults: function (data, showNoResults) {
      var self = this
        , res = this.$res
        , list = res.find('ul.list')
        , ghost = this.$ghost
        , val = this.$input.val()
        , len = data && data.length
        , $body = $('body')
        , i = 0
        , content = ''
        , onEscape
        , result
        , guess;

      // Don't show results again if value hasn't changed
      if (val === this._triggeredValue) { return; }
      this._triggeredValue = null;

      list.empty();

      this._sel = -1;

      if (val === '' || !data || data.length === 0) {
        ghost.val('');

        if (showNoResults && val !== '') {
          res.show();
          list.append('
No Results
');
        } else {
          res.hide();
          $body.off('keydown', onEscape);
        }

        return false;
      }

      $('body').on('keydown', onEscape = function (e) {
        e.keyCode === 27 && self.reset();
      });

      for (; i < len; i++) {
        result = new SearchResult(val, data[i]);

        //
        if (i === 0) {
          guess = result.guess;

          this._rel = guess;
          ghost.val(guess);
        }

        content += result.el;
      }

      list.append(content);

      if (res.is(':hidden')) {
        res.css({
          position: 'absolute',
          top:      this.$el.offset().top + this.$el.outerHeight(),
          left:     this.$el.offset().left,
          width:    this.$el.outerWidth()
        }).show();
      }

      return true;
    }

  , navigate: function (dir) {
      var items = this.$res.find('ul.list li.result')
        , sel;

      if (items.length === 0) return;

      sel = this._sel + dir;
      if (sel < -1) {
        sel += items.length + 1;
      } else if (sel >= items.length) {
        sel -= items.length + 1;
      }

      this.navigateTo(sel);
    }

  , navigateTo: function (sel) {
      var items = this.$res.find('ul.list li.result');

      items.removeClass('highlight');
      $(items[sel]).addClass('highlight');

      if (sel === -1) {
        this.$input.val(this._val) && this.$ghost.val(this._rel);
      } else {
        this.$input.val(this._data[sel]) && this.$ghost.val('');
      }

      this._sel = sel;
    }

  , reset: function () {
      this.showResults(null);
    }

  , complete: function () {
      if (this.$ghost.val()) {
        this._val = this._data[0];
        this._rel = '';
        this.$input.val(this._val);
        this.$ghost.val('');

        return true;
      } else {
        return false;
      }
    }

  , valueIsInList: function (value) {
      return this._data && $.inArray(value, this._data) !== -1;
    }

  , trigger: function () {
      var value = this._triggeredValue = this.$input.val();

      if (this.action) {
        this.action.call(this, value);
      } else {
        this.$el.parent('form').submit();
      }
    }

  };

}(jQuery));
<|endoftext|>


<commit_before>'use strict';

/*!
 * Collection
 * https://github.com/kobezzza/Collection
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Collection/blob/master/LICENSE
 */

import { Collection } from '../core';

import { isFunction, isArray, isPromise, iterators } from '../helpers/types';
import { byLink } from '../helpers/link';
import { any } from '../helpers/gcc';

import { FN_LENGTH } from '../consts/symbols';

/**
 * Sets a new value for collection elements by the specified condition/link
 *
 * @see Collection.prototype.forEach
 * @param {(?|$$CollectionCb)} value - new value (function will execute)
 * @param {($$CollectionFilter|$$Collection_set|$$CollectionLink)=} filter - link, function filter or an array of functions
 * @param {?$$Collection_set=} [opt_params] - additional parameters:
 *
 *   *) [key] - key (null for array.push) of a new element (if search elements nof found)
 *   *) [create = true] - if false, in the absence of the requested property will be thrown an exception, otherwise it will be created
 *
 * @return {($$CollectionSetReport|!Promise<$$CollectionSetReport>)}
 */
Collection.prototype.set = function (value, filter, opt_params) {
	let p = opt_params || {};

	const
		{data} = this;

	if (
		!isFunction(filter) && (
			isArray(filter) && !isFunction(filter[1]) ||
			filter != null && typeof filter !== 'object'
		)

	) {
		return byLink(data, filter, {value, create: p.create !== false, error: true});
	}

	if (!isArray(filter) && !isFunction(filter)) {
		p = filter || p;
		filter = null;
	}

	this._initParams(p, filter);
	p = any(Object.assign(Object.create(this.p), p));

	const
		valIsFunc = isFunction(value);

	if (iterators[p.type]) {
		throw new TypeError('Incorrect data type');
	}

	const
		mult = p.mult !== false,
		report = [];

	if (mult) {
		p.result = report;

	} else {
		p.result = {
			notFound: true,
			result: false,
			key: undefined,
			value: undefined
		};
	}

	let fn;
	if (valIsFunc) {
		switch (p.type) {
			case 'map':
				fn = function (el, key, data) {
					const
						res = value.apply(null, arguments);

					//#if iterators/async

					if (p.async && isPromise(res)) {
						return res.then((res) => {
							let
								status = false;

							if (data.get(key) !== res) {
								data.set(key, res);
								status = data.get(key) === res;
							}

							const o = {
								key,
								value: el,
								newValue: res,
								result: status
							};

							if (mult) {
								report.push(o);

							} else {
								p.result = o;
							}
						});
					}

					//#endif

					let
						status = false;

					if (data.get(key) !== res) {
						data.set(key, res);
						status = data.get(key) === res;
					}

					const o = {
						key,
						value: el,
						newValue: res,
						result: status
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			case 'set':
				fn = function (el, key, data) {
					const
						res = value.apply(null, arguments);

					//#if iterators/async

					if (p.async && isPromise(res)) {
						return res.then((res) => {
							let status = false;
							data.delete(el);

							if (!data.has(res)) {
								data.add(res);
								status = data.has(res);
							}

							const o = {
								key: null,
								value: el,
								newValue: res,
								result: status
							};

							if (mult) {
								report.push(o);

							} else {
								p.result = o;
							}
						});
					}

					//#endif

					let status = false;
					data.delete(el);

					if (!data.has(res)) {
						data.add(res);
						status = data.has(res);
					}

					const o = {
						key: null,
						value: el,
						newValue: res,
						result: status
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			default:
				fn = function (el, key, data) {
					const
						res = value.apply(null, arguments);

					//#if iterators/async

					if (p.async && isPromise(res)) {
						return res.then((res) => {
							let
								status = false;

							if (data[key] !== res) {
								data[key] = res;
								status = data[key] === res;
							}

							const o = {
								key,
								value: el,
								newValue: res,
								result: status
							};

							if (mult) {
								report.push(o);

							} else {
								p.result = o;
							}
						});
					}

					//#endif

					let
						status = false;

					if (data[key] !== res) {
						data[key] = res;
						status = data[key] === res;
					}

					const o = {
						key,
						value: el,
						newValue: res,
						result: status
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};
		}

		fn[FN_LENGTH] = fn.length > value.length ? fn.length : value.length;

	} else {
		switch (p.type) {
			case 'map':
				fn = (el, key, data) => {
					let result = false;
					if (data.get(key) !== value) {
						data.set(key, value);
						result = data.get(key) === value;
					}

					const o = {
						key,
						value: el,
						newValue: value,
						result
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			case 'set':
				fn = (el, key, data) => {
					let result = false;
					data.delete(el);

					if (!data.has(value)) {
						data.add(value);
						result = data.has(value);
					}

					const o = {
						key: null,
						value: el,
						newValue: value,
						result
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			default:
				fn = (el, key, data) => {
					let result = false;
					if (data[key] !== value) {
						data[key] = value;
						result = data[key] === value;
					}

					const o = {
						key,
						value: el,
						newValue: value,
						result
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};
		}
	}

	const {onIterationEnd} = p;
	p.onIterationEnd = (ctx) => {
		if ((mult ? p.result.notFound : !p.result.length) && 'key' in p) {
			if (p.key == null && isArray(data)) {
				p.key = data.length;
			}

			const res = byLink(data, p.key, {
				value: valIsFunc ? value(undefined, undefined, data, ctx) : value,
				create: p.create !== false
			});

			if (mult) {
				p.result.push(res);

			} else {
				p.result = res;
			}
		}

		onIterationEnd && onIterationEnd(ctx);
	};

	const
		returnVal = any(this.forEach(any(fn), p));

	if (returnVal !== this) {
		return returnVal;
	}

	return p.result;
};
<commit_msg>Fixed creation within an iteration mode<commit_after>'use strict';

/*!
 * Collection
 * https://github.com/kobezzza/Collection
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Collection/blob/master/LICENSE
 */

import { Collection } from '../core';

import { isFunction, isArray, isPromise, iterators } from '../helpers/types';
import { byLink } from '../helpers/link';
import { any } from '../helpers/gcc';

import { FN_LENGTH } from '../consts/symbols';

/**
 * Sets a new value for collection elements by the specified condition/link
 *
 * @see Collection.prototype.forEach
 * @param {(?|$$CollectionCb)} value - new value (function will execute)
 * @param {($$CollectionFilter|$$Collection_set|$$CollectionLink)=} filter - link, function filter or an array of functions
 * @param {?$$Collection_set=} [opt_params] - additional parameters:
 *
 *   *) [key] - key (null for array.push) of a new element (if search elements nof found)
 *   *) [create = true] - if false, in the absence of the requested property will be thrown an exception, otherwise it will be created
 *
 * @return {($$CollectionSetReport|!Promise<$$CollectionSetReport>)}
 */
Collection.prototype.set = function (value, filter, opt_params) {
	let p = opt_params || {};

	const
		{data} = this;

	if (
		!isFunction(filter) && (
			isArray(filter) && !isFunction(filter[1]) ||
			filter != null && typeof filter !== 'object'
		)

	) {
		return byLink(data, filter, {value, create: p.create !== false, error: true});
	}

	if (!isArray(filter) && !isFunction(filter)) {
		p = filter || p;
		filter = null;
	}

	this._initParams(p, filter);
	p = any(Object.assign(Object.create(this.p), p));

	const
		valIsFunc = isFunction(value);

	if (iterators[p.type]) {
		throw new TypeError('Incorrect data type');
	}

	const
		mult = p.mult !== false,
		report = [];

	if (mult) {
		p.result = report;

	} else {
		p.result = {
			notFound: true,
			result: false,
			key: undefined,
			value: undefined
		};
	}

	let fn;
	if (valIsFunc) {
		switch (p.type) {
			case 'map':
				fn = function (el, key, data) {
					const
						res = value.apply(null, arguments);

					//#if iterators/async

					if (p.async && isPromise(res)) {
						return res.then((res) => {
							let
								status = false;

							if (data.get(key) !== res) {
								data.set(key, res);
								status = data.get(key) === res;
							}

							const o = {
								key,
								value: el,
								newValue: res,
								result: status
							};

							if (mult) {
								report.push(o);

							} else {
								p.result = o;
							}
						});
					}

					//#endif

					let
						status = false;

					if (data.get(key) !== res) {
						data.set(key, res);
						status = data.get(key) === res;
					}

					const o = {
						key,
						value: el,
						newValue: res,
						result: status
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			case 'set':
				fn = function (el, key, data) {
					const
						res = value.apply(null, arguments);

					//#if iterators/async

					if (p.async && isPromise(res)) {
						return res.then((res) => {
							let status = false;
							data.delete(el);

							if (!data.has(res)) {
								data.add(res);
								status = data.has(res);
							}

							const o = {
								key: null,
								value: el,
								newValue: res,
								result: status
							};

							if (mult) {
								report.push(o);

							} else {
								p.result = o;
							}
						});
					}

					//#endif

					let status = false;
					data.delete(el);

					if (!data.has(res)) {
						data.add(res);
						status = data.has(res);
					}

					const o = {
						key: null,
						value: el,
						newValue: res,
						result: status
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			default:
				fn = function (el, key, data) {
					const
						res = value.apply(null, arguments);

					//#if iterators/async

					if (p.async && isPromise(res)) {
						return res.then((res) => {
							let
								status = false;

							if (data[key] !== res) {
								data[key] = res;
								status = data[key] === res;
							}

							const o = {
								key,
								value: el,
								newValue: res,
								result: status
							};

							if (mult) {
								report.push(o);

							} else {
								p.result = o;
							}
						});
					}

					//#endif

					let
						status = false;

					if (data[key] !== res) {
						data[key] = res;
						status = data[key] === res;
					}

					const o = {
						key,
						value: el,
						newValue: res,
						result: status
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};
		}

		fn[FN_LENGTH] = fn.length > value.length ? fn.length : value.length;

	} else {
		switch (p.type) {
			case 'map':
				fn = (el, key, data) => {
					let result = false;
					if (data.get(key) !== value) {
						data.set(key, value);
						result = data.get(key) === value;
					}

					const o = {
						key,
						value: el,
						newValue: value,
						result
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			case 'set':
				fn = (el, key, data) => {
					let result = false;
					data.delete(el);

					if (!data.has(value)) {
						data.add(value);
						result = data.has(value);
					}

					const o = {
						key: null,
						value: el,
						newValue: value,
						result
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};

				break;

			default:
				fn = (el, key, data) => {
					let result = false;
					if (data[key] !== value) {
						data[key] = value;
						result = data[key] === value;
					}

					const o = {
						key,
						value: el,
						newValue: value,
						result
					};

					if (mult) {
						report.push(o);

					} else {
						p.result = o;
					}
				};
		}
	}

	const {onIterationEnd} = p;
	p.onIterationEnd = (ctx) => {
		if ((mult ? !p.result.length : p.result.notFound) && p.create !== false && 'key' in p) {
			if (isArray(data) && !p.key && p.key !== 0) {
				p.key = data.length;
			}

			const res = byLink(data, p.key, {
				value: valIsFunc ? value(undefined, undefined, data, ctx) : value,
				create: true
			});

			if (mult) {
				p.result.push(res);

			} else {
				p.result = res;
			}
		}

		onIterationEnd && onIterationEnd(ctx);
	};

	const
		returnVal = any(this.forEach(any(fn), p));

	if (returnVal !== this) {
		return returnVal;
	}

	return p.result;
};
<|endoftext|>


<commit_before>angular.module('progressButton', [])
	.directive('progressButton', function($timeout) {
		return {
			restrict: 'E',
			transclude: true,
			replace: true,
			scope: {
				value: '&',
				type: '@',
				inProgressText: '@inProgress',
				completionText: '@complete'
			},
			template: '',
			link: function(scope, element, attrs) {
				var bar = angular.element(element[0].querySelectorAll('.progress-button-bar'))
				var buttonText = angular.element(element[0].querySelectorAll('.progress-button-text'))

				scope.defaultText = buttonText.text()
				attrs.$observe('type', function(value) { scope.type = value || 'horizontal' })
				attrs.$observe('inProgress', function(value) { scope.inProgressText = value || 'Loading…' })
				attrs.$observe('complete', function(value) { scope.completionText = value || 'Complete.' })

				scope.$watch('value()', function(value) {
					if(!value) value = 0
					if(value > 1.0) value = 1.0

					if(value === 0.0) {
						buttonText.text(scope.defaultText)
						bar.css('display', 'none')
					} else if(value === 1.0) {
						buttonText.text(scope.completionText)
						bar.css('display', 'block')

						$timeout(function() {
							fadeOut(bar)
						}, 500)
					} else {
						buttonText.text(scope.inProgressText)
						bar.css('display', 'block')
					}

					// Allow ‘display: block’ above to be applied before setting the
					// bar’s width/height. This allows the CSS transition to happen if
					// the original value was zero.
					$timeout(function() {
						if(scope.type === 'vertical') {
							bar.css('height', (value * 100) + '%')
						} else {
							bar.css('width', (value * 100) + '%')
						}
					})
				})

				var fadeOut = function(el, callback) {
					el.css('opacity', 1)

					var last = +new Date()

					var tick = function() {
						el.css('opacity', +el.css('opacity') - (new Date() - last) / 400)
						last = +new Date()

						if(+el.css('opacity') > 0) {
							(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
						} else {
							el.css('display', 'none')
							el.css('opacity', 1)

							if(typeof callback === 'function') {
								callback()
							}
						}
					}

					tick()
				}
			}
		}
	})
<commit_msg>Add closing semicolon to progress-button.js<commit_after>angular.module('progressButton', [])
	.directive('progressButton', function($timeout) {
		return {
			restrict: 'E',
			transclude: true,
			replace: true,
			scope: {
				value: '&',
				type: '@',
				inProgressText: '@inProgress',
				completionText: '@complete'
			},
			template: '',
			link: function(scope, element, attrs) {
				var bar = angular.element(element[0].querySelectorAll('.progress-button-bar'))
				var buttonText = angular.element(element[0].querySelectorAll('.progress-button-text'))

				scope.defaultText = buttonText.text()
				attrs.$observe('type', function(value) { scope.type = value || 'horizontal' })
				attrs.$observe('inProgress', function(value) { scope.inProgressText = value || 'Loading…' })
				attrs.$observe('complete', function(value) { scope.completionText = value || 'Complete.' })

				scope.$watch('value()', function(value) {
					if(!value) value = 0
					if(value > 1.0) value = 1.0

					if(value === 0.0) {
						buttonText.text(scope.defaultText)
						bar.css('display', 'none')
					} else if(value === 1.0) {
						buttonText.text(scope.completionText)
						bar.css('display', 'block')

						$timeout(function() {
							fadeOut(bar)
						}, 500)
					} else {
						buttonText.text(scope.inProgressText)
						bar.css('display', 'block')
					}

					// Allow ‘display: block’ above to be applied before setting the
					// bar’s width/height. This allows the CSS transition to happen if
					// the original value was zero.
					$timeout(function() {
						if(scope.type === 'vertical') {
							bar.css('height', (value * 100) + '%')
						} else {
							bar.css('width', (value * 100) + '%')
						}
					})
				})

				var fadeOut = function(el, callback) {
					el.css('opacity', 1)

					var last = +new Date()

					var tick = function() {
						el.css('opacity', +el.css('opacity') - (new Date() - last) / 400)
						last = +new Date()

						if(+el.css('opacity') > 0) {
							(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
						} else {
							el.css('display', 'none')
							el.css('opacity', 1)

							if(typeof callback === 'function') {
								callback()
							}
						}
					}

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


<commit_before>$(function(){
	$.get("/ssids", function(data){
		if(data.length == 0){
			$('.before-submit').hide();
			$('#no-networks-message').removeClass('hidden');
		} else {
			$.each(data, function(i, val){
				$("#ssid-select").append("<option value='" + val.ssid + "'>" + val.ssid + "</option>");
			});
		}
	})

	$('#connect-form').submit(function(ev){
		$.post('/connect', $('#connect-form').serialize(), function(data){
			$('.before-submit').hide();
			$('#submit-message').removeClass('hidden');
		});
		ev.preventDefault();
	});
});
<commit_msg>Fix escaping issues<commit_after>$(function(){
	$.get("/ssids", function(data){
		if(data.length == 0){
			$('.before-submit').hide();
			$('#no-networks-message').removeClass('hidden');
		} else {
			$.each(data, function(i, val){
				$("#ssid-select").append($('<option>').attr('val', val.ssid).text(val.ssid));
			});
		}
	})

	$('#connect-form').submit(function(ev){
		$.post('/connect', $('#connect-form').serialize(), function(data){
			$('.before-submit').hide();
			$('#submit-message').removeClass('hidden');
		});
		ev.preventDefault();
	});
});
<|endoftext|>


<commit_before>//
// AuthBucket
//
(function(hello){
    hello.init({
        authbucket: {
            name: 'AuthBucket',
            base: 'http://oauth2-symfony-bundle.authbucket.com/api/v1.0/oauth2/',
            oauth: {
                version: 2,
                auth: 'http://oauth2-symfony-bundle.authbucket.com/oauth2/authorize',
                grant: 'http://oauth2-symfony-bundle.authbucket.com/api/v1.0/oauth2/token',
            },
            refresh: true,
            scope: {
                basic:  'debug',
            },
            get: {
                'debug': 'debug',
            },
        },
    });
});
<commit_msg>Fix syntax error.<commit_after>//
// AuthBucket
//
(function(hello){
    hello.init({
        authbucket: {
            name: 'AuthBucket',
            base: 'http://oauth2-symfony-bundle.authbucket.com/api/v1.0/oauth2/',
            oauth: {
                version: 2,
                auth: 'http://oauth2-symfony-bundle.authbucket.com/oauth2/authorize',
                grant: 'http://oauth2-symfony-bundle.authbucket.com/api/v1.0/oauth2/token',
            },
            refresh: true,
            scope: {
                basic:  'debug',
            },
            get: {
                'debug': 'debug',
            },
        },
    });
})(hello);
<|endoftext|>