<commit_before>
var app = {
  // Classes
  Collections: {},
  Models: {},
  Views: {},
  // Instances
  collections: {},
  views: {},
  //Events
  socket: {},
  init: function () {
    this.socket = socket = io.connect();

    $('#sync').click(function() {
        console.log("sync : ");
        socket.emit('redmineExtract::sync', function (data) {
          console.log(data);
        });
    });

    socket.on('redmine::connect', function(data){
        console.log("redmine connect : ");

        $('#syncIssues').click(function() {
            socket.emit('redmineExtract::sync', function (err, data) {
                console.log("err : ", err);
                console.log("data : ", data);
            });
        });

        $('#buildStats').click(function() {
            socket.emit('redmineExtract::buildStats', function (err, data) {
                console.log("err : ", err);
                console.log("data : ", data);
                console.log("stats builded !");
            });
        });

        /*
         *socket.emit('redmineExtract::getProjects', function(err, datas) {
         *    console.log("err : ", err);
         *    console.log("data : ", data);
         *    var loopCount = datas.length;
         *    for (var i = 0; i < loopCount; i++) {
         *        var data = datas[i];
         *        console.log("data : ", data);
         *    }
         *    delete loopCount;
         *});
         */
        $('#getIssues').click(function() {
            var $extract = $('#extract tbody');
            $extract.html('');
            $('#dialog-message').html('getting datas');
            socket.emit('redmineExtract::getIssues', function(err, datas) {
                //$('#dialog-message').html('');
                ////console.log("err : ", err);
                //console.log("datas[0] : ", datas[0]);
                //display.issuesArray(datas);
            });
        });

        socket.on('redmineExtract::getIssues::response', function(issue) {
            $('#dialog-message').html('');
            //console.log("err : ", err);
            //console.log("issue : ", issue.id, issue);
            display.issue(issue);
        });

        socket.on('log', function(data){
            console.log("node log : ", data);
            test = data;
        });
    });
  }
};

$(function() {
    app.init();

});

var display = (function () {
    var publicAccess = {};
    var statuses = [];
    statuses[2] = 'Assigné';
    statuses[17] = 'En cours';
    statuses[16] = 'En attente';
    statuses[4] = 'Commentaire';
    statuses[8] = 'Développé';
    statuses[14] = 'A tester';
    statuses[7] = 'Testé';
    statuses[10] = 'A valider';
    statuses[9] = 'Validé';
    statuses[15] = 'A livrer';
    statuses[3] = 'Livré';
    statuses[5] = 'Fermé';

    statuses.assigne = 2;
    statuses.enCours = 17;
    statuses.enAttente = 16;
    statuses.commentaire = 4;
    statuses.developpe = 8;
    statuses.aTester = 14;
    statuses.teste = 7;
    statuses.aValider = 10;
    statuses.valide = 9;
    statuses.aLivrer = 15;
    statuses.livre = 3;
    statuses.ferme = 5;

    var sumTimeEntry = function(data) {
        var totalTime = 0;
        var loopCount = data.time_entries.length;
        for (var i = 0; i < loopCount; i++) {
            timeEntry = data.time_entries[i];
            //totalTime += parseFloat(timeEntry.hours);
            totalTime += timeEntry.hours;
        }
        delete loopCount;
        totalTime = Math.round(totalTime * 100) / 100;
        return totalTime.toString().replace('.', ',');
    };

    var firstStatus = function(data, type) {
        var journals = data.journals;
        //var iLoopCount = journals.length -1;
        //for (var i = iLoopCount; i >= 0; i--) {
        var iLoopCount = journals.length;
        for (var i = 0; i < iLoopCount; i++) {
            var journal = journals[i];
            var details = journal.details;
            var jLoopCount = details.length;
            for (var j = 0; j < jLoopCount; j++) {
                var detail = details[j];
                //console.log("detail.name : ", detail.name);
                if (detail.name === 'status_id' && detail.new_value == statuses[type]) {
                    //console.log("journal.created_on : ", journal.created_on);
                    //console.log("journal : ", journal);
                    return journal.created_on;
                }
            }
            delete loopCount;
        }
        return '';
        delete loopCount;
    };

    var firstJournal = function(data) {
        var journals = data.journals;
        //console.log("journals : ", journals);
        if (!journals) {
            return false;
        }
        var firstJournal = journals[0];
        //console.log("firstJournal : ", firstJournal);
        return firstJournal;
    };

    var firstJournalDate = function(data) {
        return firstJournal(data) ? firstJournal(data).created_on : '';
    };

    var firstJournalUser = function(data) {
        return firstJournal(data) ? firstJournal(data).user.name : '';
    };

    var formatMoment = function(date) {
        if (date !== '') {
            //return moment(date).format("D MMMM YYYY, hh:mm");
            return moment(date).format("YY/MM/DD ddd HH:mm");
            //return new Date(date);
        }
        else {
            return '';
        }
    };

    var diffMoment = function(date, refDate) {
        //var momentDate = moment(date);
        if (date !== '') {
            //var diff =  momentDate.diff( refDate, 'hours', true);
            var diff =  date.diff( refDate, 'hours', true);
            //var diff = date - refDate;
            var diffRound = Math.round(diff * 100) / 100;
            /*
             *console.groupCollapsed("diffRound : ", diffRound);
             *console.log("diff : ", diff);
             * //console.log("momentDate : ", momentDate);
             *console.log("date : ", date);
             *console.log("refDate : ", refDate);
             *console.groupEnd();
             */
            return diffRound.toString().replace('.', ',');
        }
        else {
            return '';
        }
    };

    var setMoment = function(date) {
        if (date !== '') {
            return moment(date);
        }
        else {
            return date;
        }
    };

    publicAccess.issuesArray = function (datas) {
        var $extract = $('#extract tbody');
        var loopCount = datas.length;
        moment.lang('fr');
        for (var i = 0; i < loopCount; i++) {
            var data = datas[i];
            publicAccess.issue(data);
        }
        delete loopCount;
    };

    publicAccess.issue = function (issue) {
        var $extract = $('#extract tbody');
        //var loopCount = datas.length;
        moment.lang('fr');
        var dateDemande = formatMoment(issue.created_on);
        //var refDate = new Date(issue.created_on);

        var refMoment = moment(issue.created_on);
        //var refMoment = dateDemande;

        var momentFirstPost = setMoment(firstJournalDate(issue));
        var momentAValider = setMoment(firstStatus(issue, 'aValider'));
        var momentLivre = setMoment(firstStatus(issue, 'livre'));
        var momentALivrer = setMoment(firstStatus(issue, 'aLivrer'));
        var momentFerme = setMoment(firstStatus(issue, 'ferme'));

        var dateFirstPost = formatMoment(firstJournalDate(issue));
        var dateAValider = formatMoment(firstStatus(issue, 'aValider'));
        var dateLivre = formatMoment(firstStatus(issue, 'livre'));
        var dateALivrer = formatMoment(firstStatus(issue, 'aLivrer'));
        var dateFerme = formatMoment(firstStatus(issue, 'ferme'));

        if (dateFirstPost != dateFirstPostServ ||
            dateAValider  != dateAValiderServ ||
            dateLivre     != dateLivreServ ||
            dateALivrer   != dateALivrerServ ||
            dateFerme     != dateFermeServ) {
            console.log("issue error : ", issue.id, issue);
        }

        var delaiFirstPost = diffMoment(momentFirstPost, refMoment);
        var delaiAValider = diffMoment(momentAValider, refMoment);
        var delaiLivre = diffMoment(momentLivre, refMoment);
        var delaiALivrer = diffMoment(momentALivrer, refMoment);
        var delaiFerme = diffMoment(momentFerme, refMoment);

        var dateFirstPostServ = issue.stats.dateFirstPost ? formatMoment(issue.stats.dateFirstPost): '';
        var dateAValiderServ = issue.stats.dateAValider ? formatMoment(issue.stats.dateAValider): '';
        var dateLivreServ = issue.stats.dateLivre ? formatMoment(issue.stats.dateLivre): '';
        var dateALivrerServ = issue.stats.dateALivrer ? formatMoment(issue.stats.dateALivrer): '';
        var dateFermeServ = issue.stats.dateFerme ? formatMoment(issue.stats.dateFerme): '';

        var issueHtml = ich.issue({
            nomSousProjet: issue.project.name,
            numTache: issue.id,
            nomTache: issue.subject,
            dateDemande: dateDemande,
            userDateDemande: issue.author.name,

            userDateFirstPost: firstJournalUser(issue),
            dateFirstPost: dateFirstPost,
            dateAValider: dateAValider,
            dateLivre: dateLivre,
            dateALivrer: dateALivrer,
            dateFerme: dateFerme,

            delaiFirstPost: delaiFirstPost,
            delaiAValider: delaiAValider,
            delaiLivre: delaiLivre,
            delaiALivrer: delaiALivrer,
            delaiFerme: delaiFerme,

            userDateFirstPostServ: issue.stats.userFirstPost,
            dateFirstPostServ: dateFirstPostServ,
            dateAValiderServ: dateAValiderServ,
            dateLivreServ: dateLivreServ,
            dateALivrerServ: dateALivrerServ,
            dateFermeServ: dateFermeServ,

            delaiFirstPostServ: issue.stats.delaiFirstPost ? Math.round( moment.duration(issue.stats.delaiFirstPost).asHours() * 100 ) / 100 : null,
            delaiAValiderServ: issue.stats.delaiAValider ? Math.round( moment.duration(issue.stats.delaiAValider).asHours() * 100 ) / 100 : null,
            delaiLivreServ: issue.stats.delaiLivre ? Math.round( moment.duration(issue.stats.delaiLivre).asHours() * 100 ) / 100 : null,
            delaiALivrerServ: issue.stats.delaiALivrer ? Math.round( moment.duration(issue.stats.delaiALivrer).asHours() * 100 ) / 100 : null,
            delaiFermeServ: issue.stats.delaiFerme ? Math.round( moment.duration(issue.stats.delaiFerme).asHours() * 100 ) / 100 : null,
            time: sumTimeEntry(issue)
        });
        $extract.append($(issueHtml));
    };

    return publicAccess;
}());
<commit_msg>group stats<commit_after>
var app = {
  // Classes
  Collections: {},
  Models: {},
  Views: {},
  // Instances
  collections: {},
  views: {},
  //Events
  socket: {},
  init: function () {
    this.socket = socket = io.connect();

    $('#sync').click(function() {
        console.log("sync : ");
        socket.emit('redmineExtract::sync', function (data) {
          console.log(data);
        });
    });

    socket.on('redmine::connect', function(data){
        console.log("redmine connect : ");

        $('#syncIssues').click(function() {
            socket.emit('redmineExtract::sync', function (err, data) {
                console.log("err : ", err);
                console.log("data : ", data);
            });
        });

        $('#buildStats').click(function() {
            socket.emit('redmineExtract::buildStats', function (err, data) {
                console.log("err : ", err);
                console.log("data : ", data);
                console.log("stats builded !");
            });
        });

        /*
         *socket.emit('redmineExtract::getProjects', function(err, datas) {
         *    console.log("err : ", err);
         *    console.log("data : ", data);
         *    var loopCount = datas.length;
         *    for (var i = 0; i < loopCount; i++) {
         *        var data = datas[i];
         *        console.log("data : ", data);
         *    }
         *    delete loopCount;
         *});
         */
        $('#getIssues').click(function() {
            var $extract = $('#extract tbody');
            $extract.html('');
            $('#dialog-message').html('getting datas');
            socket.emit('redmineExtract::getIssues', function(err, datas) {
                //$('#dialog-message').html('');
                ////console.log("err : ", err);
                //console.log("datas[0] : ", datas[0]);
                //display.issuesArray(datas);
            });
        });

        socket.on('redmineExtract::getIssues::response', function(issue) {
            $('#dialog-message').html('');
            //console.log("err : ", err);
            //console.log("issue : ", issue.id, issue);
            display.issue(issue);
        });

        socket.on('log', function(data){
            console.log("node log : ", data);
            test = data;
        });
    });
  }
};

$(function() {
    app.init();

});

var display = (function () {
    var publicAccess = {};
    var statuses = [];
    statuses[2] = 'Assigné';
    statuses[17] = 'En cours';
    statuses[16] = 'En attente';
    statuses[4] = 'Commentaire';
    statuses[8] = 'Développé';
    statuses[14] = 'A tester';
    statuses[7] = 'Testé';
    statuses[10] = 'A valider';
    statuses[9] = 'Validé';
    statuses[15] = 'A livrer';
    statuses[3] = 'Livré';
    statuses[5] = 'Fermé';

    statuses.assigne = 2;
    statuses.enCours = 17;
    statuses.enAttente = 16;
    statuses.commentaire = 4;
    statuses.developpe = 8;
    statuses.aTester = 14;
    statuses.teste = 7;
    statuses.aValider = 10;
    statuses.valide = 9;
    statuses.aLivrer = 15;
    statuses.livre = 3;
    statuses.ferme = 5;

    var sumTimeEntry = function(data) {
        var totalTime = 0;
        var loopCount = data.time_entries.length;
        for (var i = 0; i < loopCount; i++) {
            timeEntry = data.time_entries[i];
            //totalTime += parseFloat(timeEntry.hours);
            totalTime += timeEntry.hours;
        }
        delete loopCount;
        totalTime = Math.round(totalTime * 100) / 100;
        return totalTime.toString().replace('.', ',');
    };

    var firstStatus = function(data, type) {
        var journals = data.journals;
        //var iLoopCount = journals.length -1;
        //for (var i = iLoopCount; i >= 0; i--) {
        var iLoopCount = journals.length;
        for (var i = 0; i < iLoopCount; i++) {
            var journal = journals[i];
            var details = journal.details;
            var jLoopCount = details.length;
            for (var j = 0; j < jLoopCount; j++) {
                var detail = details[j];
                //console.log("detail.name : ", detail.name);
                if (detail.name === 'status_id' && detail.new_value == statuses[type]) {
                    //console.log("journal.created_on : ", journal.created_on);
                    //console.log("journal : ", journal);
                    return journal.created_on;
                }
            }
            delete loopCount;
        }
        return '';
        delete loopCount;
    };

    var firstJournal = function(data) {
        var journals = data.journals;
        //console.log("journals : ", journals);
        if (!journals) {
            return false;
        }
        var firstJournal = journals[0];
        //console.log("firstJournal : ", firstJournal);
        return firstJournal;
    };

    var firstJournalDate = function(data) {
        return firstJournal(data) ? firstJournal(data).created_on : '';
    };

    var firstJournalUser = function(data) {
        return firstJournal(data) ? firstJournal(data).user.name : '';
    };

    var formatMoment = function(date) {
        if (date !== '') {
            //return moment(date).format("D MMMM YYYY, hh:mm");
            return moment(date).format("YY/MM/DD ddd HH:mm");
            //return new Date(date);
        }
        else {
            return '';
        }
    };

    var diffMoment = function(date, refDate) {
        //var momentDate = moment(date);
        if (date !== '') {
            //var diff =  momentDate.diff( refDate, 'hours', true);
            var diff =  date.diff( refDate, 'hours', true);
            //var diff = date - refDate;
            var diffRound = Math.round(diff * 100) / 100;
            /*
             *console.groupCollapsed("diffRound : ", diffRound);
             *console.log("diff : ", diff);
             * //console.log("momentDate : ", momentDate);
             *console.log("date : ", date);
             *console.log("refDate : ", refDate);
             *console.groupEnd();
             */
            return diffRound.toString().replace('.', ',');
        }
        else {
            return '';
        }
    };

    var setMoment = function(date) {
        if (date !== '') {
            return moment(date);
        }
        else {
            return date;
        }
    };

    publicAccess.issuesArray = function (datas) {
        var $extract = $('#extract tbody');
        var loopCount = datas.length;
        moment.lang('fr');
        for (var i = 0; i < loopCount; i++) {
            var data = datas[i];
            publicAccess.issue(data);
        }
        delete loopCount;
    };

    publicAccess.issue = function (issue) {
        var $extract = $('#extract tbody');
        //var loopCount = datas.length;
        moment.lang('fr');
        var dateDemande = formatMoment(issue.created_on);
        //var refDate = new Date(issue.created_on);

        var refMoment = moment(issue.created_on);
        //var refMoment = dateDemande;

        var momentFirstPost = setMoment(firstJournalDate(issue));
        var momentAValider = setMoment(firstStatus(issue, 'aValider'));
        var momentLivre = setMoment(firstStatus(issue, 'livre'));
        var momentALivrer = setMoment(firstStatus(issue, 'aLivrer'));
        var momentFerme = setMoment(firstStatus(issue, 'ferme'));

        var dateFirstPost = formatMoment(firstJournalDate(issue));
        var dateAValider = formatMoment(firstStatus(issue, 'aValider'));
        var dateLivre = formatMoment(firstStatus(issue, 'livre'));
        var dateALivrer = formatMoment(firstStatus(issue, 'aLivrer'));
        var dateFerme = formatMoment(firstStatus(issue, 'ferme'));

        /*
         *if (dateFirstPost != dateFirstPostServ ||
         *    dateAValider  != dateAValiderServ ||
         *    dateLivre     != dateLivreServ ||
         *    dateALivrer   != dateALivrerServ ||
         *    dateFerme     != dateFermeServ) {
         *    console.log("issue error : ", issue.id, issue);
         *}
         */

        var delaiFirstPost = diffMoment(momentFirstPost, refMoment);
        var delaiAValider = diffMoment(momentAValider, refMoment);
        var delaiLivre = diffMoment(momentLivre, refMoment);
        var delaiALivrer = diffMoment(momentALivrer, refMoment);
        var delaiFerme = diffMoment(momentFerme, refMoment);

        var dateFirstPostServ = issue.stats.dateFirstPost ? formatMoment(issue.stats.dateFirstPost): '';
        var dateAValiderServ = issue.stats.dateAValider ? formatMoment(issue.stats.dateAValider): '';
        var dateLivreServ = issue.stats.dateLivre ? formatMoment(issue.stats.dateLivre): '';
        var dateALivrerServ = issue.stats.dateALivrer ? formatMoment(issue.stats.dateALivrer): '';
        var dateFermeServ = issue.stats.dateFerme ? formatMoment(issue.stats.dateFerme): '';

        var delaiFirstPostServ = issue.stats.delaiFirstPost ? Math.round( moment.duration(issue.stats.delaiFirstPost).asHours() * 100 ) / 100 : null;
        var delaiAValiderServ = issue.stats.delaiAValider ? Math.round( moment.duration(issue.stats.delaiAValider).asHours() * 100 ) / 100 : null;
        var delaiLivreServ = issue.stats.delaiLivre ? Math.round( moment.duration(issue.stats.delaiLivre).asHours() * 100 ) / 100 : null;
        var delaiALivrerServ = issue.stats.delaiALivrer ? Math.round( moment.duration(issue.stats.delaiALivrer).asHours() * 100 ) / 100 : null;
        var delaiFermeServ = issue.stats.delaiFerme ? Math.round( moment.duration(issue.stats.delaiFerme).asHours() * 100 ) / 100 : null;

        console.log("issue.stats.delaiFerme : ", issue.stats.delaiFerme);
        console.log("momentFerme : ", firstStatus(issue, 'ferme'));

        var issueHtml = ich.issue({
            nomSousProjet: issue.project.name,
            numTache: issue.id,
            nomTache: issue.subject,
            dateDemande: dateDemande,
            userDateDemande: issue.author.name,

            userDateFirstPost: firstJournalUser(issue),
            dateFirstPost: dateFirstPost,
            dateAValider: dateAValider,
            dateLivre: dateLivre,
            dateALivrer: dateALivrer,
            dateFerme: dateFerme,

            delaiFirstPost: delaiFirstPost,
            delaiAValider: delaiAValider,
            delaiLivre: delaiLivre,
            delaiALivrer: delaiALivrer,
            delaiFerme: delaiFerme,

            userDateFirstPostServ: issue.stats.userFirstPost,
            dateFirstPostServ: dateFirstPostServ,
            dateAValiderServ: dateAValiderServ,
            dateLivreServ: dateLivreServ,
            dateALivrerServ: dateALivrerServ,
            dateFermeServ: dateFermeServ,

            /*
             *delaiFirstPostServ: issue.stats.delaiFirstPost ? Math.round( moment.duration(issue.stats.delaiFirstPost).asHours() * 100 ) / 100 : null,
             *delaiAValiderServ: issue.stats.delaiAValider ? Math.round( moment.duration(issue.stats.delaiAValider).asHours() * 100 ) / 100 : null,
             *delaiLivreServ: issue.stats.delaiLivre ? Math.round( moment.duration(issue.stats.delaiLivre).asHours() * 100 ) / 100 : null,
             *delaiALivrerServ: issue.stats.delaiALivrer ? Math.round( moment.duration(issue.stats.delaiALivrer).asHours() * 100 ) / 100 : null,
             *delaiFermeServ: issue.stats.delaiFerme ? Math.round( moment.duration(issue.stats.delaiFerme).asHours() * 100 ) / 100 : null,
             */

            delaiFirstPostServ: delaiFirstPostServ,
            delaiAValiderServ: delaiAValiderServ,
            delaiLivreServ: delaiLivreServ,
            delaiALivrerServ: delaiALivrerServ,
            delaiFermeServ: delaiFermeServ,

            time: sumTimeEntry(issue)
        });
        $extract.append($(issueHtml));
    };

    return publicAccess;
}());
<|endoftext|>


<commit_before><commit_msg>update dendro js<commit_after><|endoftext|>


<commit_before>var NetworkViz = (function () {

	var highlightBorder = 1.5;
	var highlightColor = '#d0dee4';

	var f = 32768;

	var nodeLookup = {};
	var nodeList = [];

	var initialized = false;
	var map, labelLayer, highlightLayer;

	var hoveredNode = false;
	var activeNodes = [];

	var clickHandler = false;

	function init() {
		if (!graph) return console.error('graph.js not loaded ... yet')

		initialized = true;

		var nodes = graph.nodes;
		var keys = Object.keys(nodes);
		var n = nodes[keys[0]].length;

		for (var i = 0; i < n; i++) {
			var node = {};
			keys.forEach(function (key) {
				node[key] = nodes[key][i];
			})
			node.x += f/2;
			node.y += f/2;
			node.lng =  node.x;
			node.lat = -node.y;

			//node.color = (node.type == 'person') ? '#fa7d18' : '#a3db19';
			node.color = (node.type == 'person') ? '#fee915' : '#a3db19';

			node.neighbours = [];
			nodeLookup[node.id] = node;
			nodeList.push(node);
		}

		graph.edges.forEach(function (edge) {
			var node1 = nodeList[edge[0]];
			var node2 = nodeList[edge[1]];
			node1.neighbours.push(node2);
			node2.neighbours.push(node1);
		})

		var projection = {
			project: function (latlng) {
				return L.point(latlng.lng/f, -latlng.lat/f);
			},
			unproject: function (point) {
				return L.latLng(-point.y*f, point.x*f);
			},
			bounds: L.bounds(L.point(0,0), L.point(1,1))
		};

		var crs = L.extend({}, L.CRS, {
			projection: projection,
			transformation: new L.Transformation(1, 0, 1, 0),
			scale: function (zoom) {
				return 256*Math.pow(2, zoom);
			}
		});

		$('#networkviz').css({height:'100%'});

		var margin = f;
		map = L.map('networkviz', {
			minZoom: 0,
			maxZoom: 7,
			zoom: 5,
			center: [-0.5*f, 0.5*f],
			maxBounds: L.latLngBounds([-f-margin, -margin],[margin, f+margin]),
			crs: crs,
			zoomAnimation: true,
			zoomControl: false,
			scrollWheelZoom: true
		});
		map.addControl( L.control.zoom({position: 'bottomleft'}) )

		map.on('mousemove', mousemove);
		map.on('click', mouseclick);

		var layer = L.tileLayer('https://www.lobbyradar.de/lobbynetwork/tiles/{z}/{y}/{x}.png', {
			minZoom: 0,
			maxZoom: 7,
			maxNativeZoom: 7,
			tileSize: 256,
			zoomOffset: 0,
			attribution: '',
			noWrap: true
		})

		layer.addTo(map);

		highlightLayer = L.layerGroup();
		highlightLayer.addTo(map);

		labelLayer = L.layerGroup();
		labelLayer.addTo(map);
	}

	function mousemove(e) {
		var node = findNode(e.latlng);

		if (hoveredNode !== node) {
			if (hoveredNode && !hoveredNode.active) hideLabel(hoveredNode);
			if (node && !node.active) showLabel(node);

			$('#networkviz').css( 'cursor', node ? 'pointer' : '-webkit-grab');

			hoveredNode = node;
		}
	}

	function mouseclick(e) {
		if (!clickHandler) return;
		var node = findNode(e.latlng);
		if (node) {
			clickHandler(node.id);
			e.originalEvent.preventDefault();
		}
	}

	function findNode(point) {
		var bestNode = false;
		var bestDist = 1e10;

		nodeList.forEach(function (node) {
			var d = Math.sqrt(sqr(node.lng - point.lng) + sqr(node.lat - point.lat));
			if (d < bestDist) {
				bestDist = d;
				bestNode = node;
			};
		});

		var border = Math.pow(0.5, map.getZoom()-10);

		if (bestDist < bestNode.r + border) return bestNode;
		return false;
	}

	function panToNode(node) {
		var zoom = Math.round(9 - Math.log(node.r)/Math.log(2));

		if (zoom < 3) zoom = 3;
		if (zoom > 7) zoom = 7;

		var latLng = L.latLng(node.lat, node.lng);
		var centerPoint = map.getSize();
		latLng.lng += centerPoint.x*Math.pow(0.5, zoom-5);

		map.setView(latLng, zoom, {animate:true})
	}

	function clearNodes() {
		activeNodes.forEach(function (node) {
			node.active = false;
			hideLabel(node);
		})
		highlightLayer.clearLayers();
	}

	function ensureLabel(node) {
		if (node.label) return;
		var latLng = L.latLng(node.lat - node.r, node.lng);
		node.label = L.label(latLng, {text:node.name });
		node.label.addTo(labelLayer);
	}

	function showLabel(node) {
		ensureLabel(node);
		node.label.show();
	}

	function hideLabel(node) {
		node.label.hide();
	}

	function activateNode(node) {
		node.active = true;
		activeNodes.push(node);
		showLabel(node);

		var center = L.latLng(node.lat, node.lng);

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.line(
					[center, L.latLng(neighbour.lat, neighbour.lng)],
					{ stroke:true, fill:false, color:highlightColor, highlight:true, _weight:1 }
				)
			)
		})

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.bubble(
					L.latLng(neighbour.lat, neighbour.lng), neighbour.r,
					{ stroke:false, fill:true, fillColor:highlightColor, highlight:true, fillOpacity:1.0 }
				)
			)
		})

		highlightLayer.addLayer(
			L.bubble(
				center, node.r,
				{ stroke:false, fill:true, fillColor:highlightColor, highlight:true, fillOpacity:1.0 }
			)
		)

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.line(
					[center, L.latLng(neighbour.lat, neighbour.lng)],
					{ stroke:true, fill:false, color:'rgb(20,59,82)', _weight:1 }
				)
			)
		})

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.bubble(
					L.latLng(neighbour.lat, neighbour.lng), neighbour.r,
					{ stroke:false, fill:true, fillColor:neighbour.color, fillOpacity:1.0 }
				)
			)
		})

		highlightLayer.addLayer(
			L.bubble(
				center, node.r,
				{ stroke:false, fill:true, fillColor:node.color, fillOpacity:1.0 }
			)
		)

	}

	function highlightNode(node) {
		clearNodes();
		activateNode(node);
		panToNode(node);
	}

	function setClickHandler(func) {
		clickHandler = func;
	}

	function lookupId(id, callback) {
		if (!initialized) init();
		var node = nodeLookup[id];
		if (!node) return; // console.error('id not found "'+id+'"');
		callback(node);
	}

	function sqr(v) {
		return v*v;
	}

	L.Label = L.Class.extend({

		includes: L.Mixin.Events,

		options: {
			text: 'text'
		},

		label: false,
		visible: true,

		initialize: function (latlng, options) {
			L.setOptions(this, options);
			this._latlng = L.latLng(latlng);
		},

		_layerAdd: function (a) {
			this.onAdd(a.target);
		},

		_initLabel: function () {
			this.label = $('

');
			this.label.text(this.options.text);
			if (this.options.text.length > 30) this.label.addClass('small');

			var panes = this._map._panes;

			$(panes.markerPane).append(this.label);
		},

		update: function () {
			if (this.label) {
				var pos = this._map.latLngToLayerPoint(this._latlng).round();
				this.label.css({
					left:pos.x - this.label.outerWidth()/2,
					top: pos.y + 10
				});
			}

			return this;
		},

		onAdd: function (map) {
			this._map = map;

			map.on('viewreset', this.update, this);

			this._initLabel();
			this.update();
			this.fire('add');
		},

		addTo: function (map) {
			map.addLayer(this);
			return this;
		},

		show: function () {
			if (!this.label) return;
			this.visible = true;
			this.label.removeClass('hidden');
			this.update();
		},

		hide: function () {
			if (!this.label) return;
			this.visible = false;
			this.label.addClass('hidden');
		}
	});

	L.label = function (latlng, options) {
		return new L.Label(latlng, options);
	};

	L.Bubble = L.Circle.extend({
		_project: function () {

			var map = this._map;

			this._point = map.latLngToLayerPoint(this._latlng);
			this._radius = this._mRadius * Math.pow(2, map.getZoom()-7);
			if (this.options.highlight) this._radius += highlightBorder;
			this._radiusY = false;

			this._updateBounds();
		}
	});

	L.bubble = function (latlng, radius, options) {
		return new L.Bubble(latlng, radius, options);
	};

	L.Line = L.Polyline.extend({
		_project: function () {
			var weight = this.options._weight*Math.pow(2,this._map.getZoom()-6);
			if (this.options.highlight) weight += 2*highlightBorder;
			this.setStyle({weight: weight})

			L.Polyline.prototype._project.call(this);
		}
	});

	L.line = function (latlngs, options) {
		return new L.Line(latlngs, options);
	};

	return {
		highlightEntity: function (id) { lookupId(id, highlightNode) },
		panToEntity: function (id) { lookupId(id, panToNode) },
		setClickHandler: setClickHandler
	}
})();
<commit_msg>chamnge map base<commit_after>var NetworkViz = (function () {

	var highlightBorder = 1.5;
	var highlightColor = '#d0dee4';

	var f = 32768;

	var nodeLookup = {};
	var nodeList = [];

	var initialized = false;
	var map, labelLayer, highlightLayer;

	var hoveredNode = false;
	var activeNodes = [];

	var clickHandler = false;

	function init() {
		if (!graph) return console.error('graph.js not loaded ... yet')

		initialized = true;

		var nodes = graph.nodes;
		var keys = Object.keys(nodes);
		var n = nodes[keys[0]].length;

		for (var i = 0; i < n; i++) {
			var node = {};
			keys.forEach(function (key) {
				node[key] = nodes[key][i];
			})
			node.x += f/2;
			node.y += f/2;
			node.lng =  node.x;
			node.lat = -node.y;

			//node.color = (node.type == 'person') ? '#fa7d18' : '#a3db19';
			node.color = (node.type == 'person') ? '#fee915' : '#a3db19';

			node.neighbours = [];
			nodeLookup[node.id] = node;
			nodeList.push(node);
		}

		graph.edges.forEach(function (edge) {
			var node1 = nodeList[edge[0]];
			var node2 = nodeList[edge[1]];
			node1.neighbours.push(node2);
			node2.neighbours.push(node1);
		})

		var projection = {
			project: function (latlng) {
				return L.point(latlng.lng/f, -latlng.lat/f);
			},
			unproject: function (point) {
				return L.latLng(-point.y*f, point.x*f);
			},
			bounds: L.bounds(L.point(0,0), L.point(1,1))
		};

		var crs = L.extend({}, L.CRS, {
			projection: projection,
			transformation: new L.Transformation(1, 0, 1, 0),
			scale: function (zoom) {
				return 256*Math.pow(2, zoom);
			}
		});

		$('#networkviz').css({height:'100%'});

		var margin = f;
		map = L.map('networkviz', {
			minZoom: 0,
			maxZoom: 7,
			zoom: 5,
			center: [-0.5*f, 0.5*f],
			maxBounds: L.latLngBounds([-f-margin, -margin],[margin, f+margin]),
			crs: crs,
			zoomAnimation: true,
			zoomControl: false,
			scrollWheelZoom: true
		});
		map.addControl( L.control.zoom({position: 'bottomleft'}) )

		map.on('mousemove', mousemove);
		map.on('click', mouseclick);

		var layer = L.tileLayer('https://tilt.odcdn.de/lobbyradar/{z}/{y}/{x}.png', {
//		var layer = L.tileLayer('https://www.lobbyradar.de/lobbynetwork/tiles/{z}/{y}/{x}.png', {
			minZoom: 0,
			maxZoom: 7,
			maxNativeZoom: 7,
			tileSize: 256,
			zoomOffset: 0,
			attribution: '',
			noWrap: true
		})

		layer.addTo(map);

		highlightLayer = L.layerGroup();
		highlightLayer.addTo(map);

		labelLayer = L.layerGroup();
		labelLayer.addTo(map);
	}

	function mousemove(e) {
		var node = findNode(e.latlng);

		if (hoveredNode !== node) {
			if (hoveredNode && !hoveredNode.active) hideLabel(hoveredNode);
			if (node && !node.active) showLabel(node);

			$('#networkviz').css( 'cursor', node ? 'pointer' : '-webkit-grab');

			hoveredNode = node;
		}
	}

	function mouseclick(e) {
		if (!clickHandler) return;
		var node = findNode(e.latlng);
		if (node) {
			clickHandler(node.id);
			e.originalEvent.preventDefault();
		}
	}

	function findNode(point) {
		var bestNode = false;
		var bestDist = 1e10;

		nodeList.forEach(function (node) {
			var d = Math.sqrt(sqr(node.lng - point.lng) + sqr(node.lat - point.lat));
			if (d < bestDist) {
				bestDist = d;
				bestNode = node;
			};
		});

		var border = Math.pow(0.5, map.getZoom()-10);

		if (bestDist < bestNode.r + border) return bestNode;
		return false;
	}

	function panToNode(node) {
		var zoom = Math.round(9 - Math.log(node.r)/Math.log(2));

		if (zoom < 3) zoom = 3;
		if (zoom > 7) zoom = 7;

		var latLng = L.latLng(node.lat, node.lng);
		var centerPoint = map.getSize();
		latLng.lng += centerPoint.x*Math.pow(0.5, zoom-5);

		map.setView(latLng, zoom, {animate:true})
	}

	function clearNodes() {
		activeNodes.forEach(function (node) {
			node.active = false;
			hideLabel(node);
		})
		highlightLayer.clearLayers();
	}

	function ensureLabel(node) {
		if (node.label) return;
		var latLng = L.latLng(node.lat - node.r, node.lng);
		node.label = L.label(latLng, {text:node.name });
		node.label.addTo(labelLayer);
	}

	function showLabel(node) {
		ensureLabel(node);
		node.label.show();
	}

	function hideLabel(node) {
		node.label.hide();
	}

	function activateNode(node) {
		node.active = true;
		activeNodes.push(node);
		showLabel(node);

		var center = L.latLng(node.lat, node.lng);

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.line(
					[center, L.latLng(neighbour.lat, neighbour.lng)],
					{ stroke:true, fill:false, color:highlightColor, highlight:true, _weight:1 }
				)
			)
		})

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.bubble(
					L.latLng(neighbour.lat, neighbour.lng), neighbour.r,
					{ stroke:false, fill:true, fillColor:highlightColor, highlight:true, fillOpacity:1.0 }
				)
			)
		})

		highlightLayer.addLayer(
			L.bubble(
				center, node.r,
				{ stroke:false, fill:true, fillColor:highlightColor, highlight:true, fillOpacity:1.0 }
			)
		)

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.line(
					[center, L.latLng(neighbour.lat, neighbour.lng)],
					{ stroke:true, fill:false, color:'rgb(20,59,82)', _weight:1 }
				)
			)
		})

		node.neighbours.forEach(function (neighbour) {
			highlightLayer.addLayer(
				L.bubble(
					L.latLng(neighbour.lat, neighbour.lng), neighbour.r,
					{ stroke:false, fill:true, fillColor:neighbour.color, fillOpacity:1.0 }
				)
			)
		})

		highlightLayer.addLayer(
			L.bubble(
				center, node.r,
				{ stroke:false, fill:true, fillColor:node.color, fillOpacity:1.0 }
			)
		)

	}

	function highlightNode(node) {
		clearNodes();
		activateNode(node);
		panToNode(node);
	}

	function setClickHandler(func) {
		clickHandler = func;
	}

	function lookupId(id, callback) {
		if (!initialized) init();
		var node = nodeLookup[id];
		if (!node) return; // console.error('id not found "'+id+'"');
		callback(node);
	}

	function sqr(v) {
		return v*v;
	}

	L.Label = L.Class.extend({

		includes: L.Mixin.Events,

		options: {
			text: 'text'
		},

		label: false,
		visible: true,

		initialize: function (latlng, options) {
			L.setOptions(this, options);
			this._latlng = L.latLng(latlng);
		},

		_layerAdd: function (a) {
			this.onAdd(a.target);
		},

		_initLabel: function () {
			this.label = $('

');
			this.label.text(this.options.text);
			if (this.options.text.length > 30) this.label.addClass('small');

			var panes = this._map._panes;

			$(panes.markerPane).append(this.label);
		},

		update: function () {
			if (this.label) {
				var pos = this._map.latLngToLayerPoint(this._latlng).round();
				this.label.css({
					left:pos.x - this.label.outerWidth()/2,
					top: pos.y + 10
				});
			}

			return this;
		},

		onAdd: function (map) {
			this._map = map;

			map.on('viewreset', this.update, this);

			this._initLabel();
			this.update();
			this.fire('add');
		},

		addTo: function (map) {
			map.addLayer(this);
			return this;
		},

		show: function () {
			if (!this.label) return;
			this.visible = true;
			this.label.removeClass('hidden');
			this.update();
		},

		hide: function () {
			if (!this.label) return;
			this.visible = false;
			this.label.addClass('hidden');
		}
	});

	L.label = function (latlng, options) {
		return new L.Label(latlng, options);
	};

	L.Bubble = L.Circle.extend({
		_project: function () {

			var map = this._map;

			this._point = map.latLngToLayerPoint(this._latlng);
			this._radius = this._mRadius * Math.pow(2, map.getZoom()-7);
			if (this.options.highlight) this._radius += highlightBorder;
			this._radiusY = false;

			this._updateBounds();
		}
	});

	L.bubble = function (latlng, radius, options) {
		return new L.Bubble(latlng, radius, options);
	};

	L.Line = L.Polyline.extend({
		_project: function () {
			var weight = this.options._weight*Math.pow(2,this._map.getZoom()-6);
			if (this.options.highlight) weight += 2*highlightBorder;
			this.setStyle({weight: weight})

			L.Polyline.prototype._project.call(this);
		}
	});

	L.line = function (latlngs, options) {
		return new L.Line(latlngs, options);
	};

	return {
		highlightEntity: function (id) { lookupId(id, highlightNode) },
		panToEntity: function (id) { lookupId(id, panToNode) },
		setClickHandler: setClickHandler
	}
})();
<|endoftext|>


<commit_before>/*globals console location*/

define([
    'module',
    'underscore',
    'backbone',
    'zepto',
    'handlebars',

    'pokerface/service'
], function (module, _, Backbone, $, Handlebars, Pokerface) {
    'use strict';

    var appRoot = module.config().root;

    var NewRoomView = Backbone.View.extend({
        events: {
            'click button.new-room': 'newRoom'
        },

        render: function () {
            var template = Handlebars.compile($('#new-room-tmpl').html());
            this.$el.html(template());
        },

        newRoom: function (evt) {
            Pokerface.create(evt.currentTarget.id, function (err, room) {
                if (err) {
                    console.error(err);
                    return;
                }

                PokerfaceApp.openRoom(room);
            });
        }
    });

    var PokerfaceRouter = Backbone.Router.extend({
        routes: {
            '':           'index',
            ':room_id':   'room'
        },

        index: function () {
            new NewRoomView({
                el: 'body'
            }).render();
        },

        room: function (room_id) {
            console.log('room ' + room_id);
        }
    });

    var PokerfaceApp = {
        running: false,
        router: null,

        openRoom: function (room) {
            if (this.running) {
                if (_.isString(room)) {
                    // TODO load room
                }

                this.router.navigate(room.id);
            }
        },

        start: function () {
            if (! this.running) {
                this.running = true;
                this.router = new PokerfaceRouter();

                Backbone.history.start({
                    pushState: true,
                    root: appRoot
                });
            }
        }
    };

    return PokerfaceApp;
});

<commit_msg>Implement room backbone route<commit_after>/*globals console location*/

define([
    'module',
    'underscore',
    'backbone',
    'zepto',
    'handlebars',

    'pokerface/service'
], function (module, _, Backbone, $, Handlebars, Pokerface) {
    'use strict';

    var appRoot = module.config().root;

    var NewRoomView = Backbone.View.extend({
        events: {
            'click button.new-room': 'newRoom'
        },

        render: function () {
            var template = Handlebars.compile($('#new-room-tmpl').html());
            this.$el.html(template());
        },

        newRoom: function (evt) {
            Pokerface.create(evt.currentTarget.id, function (err, room) {
                if (err) {
                    console.error(err);
                    return;
                }

                PokerfaceApp.openRoom(room);
            });
        }
    });

    var PokerfaceRouter = Backbone.Router.extend({
        routes: {
            '':           'index',
            ':room_id':   'room'
        },

        index: function () {
            new NewRoomView({
                el: 'body'
            }).render();
        },

        room: function (room_id) {
            PokerfaceApp.openRoom(room_id);
        }
    });

    var PokerfaceApp = {
        running: false,
        router: null,

        openRoom: function (room) {
            if (this.running) {
                if (_.isString(room)) {
                    // TODO load room via service api
                    room = {
                        id: room
                    };
                }

                this.router.navigate(room.id);
            }
        },

        start: function () {
            if (! this.running) {
                this.running = true;
                this.router = new PokerfaceRouter();

                Backbone.history.start({
                    pushState: true,
                    root: appRoot
                });
            }
        }
    };

    return PokerfaceApp;
});

<|endoftext|>


<commit_before>var fs = require('fs');
var cfs = fs.readdirSync('./json');
var constants = {};
cfs.forEach(function(f) {
    constants[f.split(".")[0]] = require('./json/' + f);
});
var heroes = constants.heroes.result.heroes;
//key heroes by id
constants.heroes = {};
//key heroes by name
constants.hero_names = {};
heroes.forEach(function(h) {
    h.img = "http://cdn.dota2.com/apps/dota2/images/heroes/" + h.name.replace("npc_dota_hero_", "") + "_sb.png";
    constants.heroes[h.id] = h;
    constants.hero_names[h.name] = h;
});
/*
//leagues, key by id
var leagues = JSON.parse(JSON.stringify(constants.leagues.result.leagues));
constants.leagues = {};
leagues.forEach(function(l) {
    l.name = l.name.replace("#DOTA_Item_", "").split("_").join(" ");
    constants.leagues[l.leagueid] = l;
});
*/
//items, already keyed by name
var items = constants.items.itemdata;
constants.item_ids = {};
for (var key in items) {
    constants.item_ids[items[key].id] = key;
    items[key].img = "http://cdn.dota2.com/apps/dota2/images/items/" + items[key].img;
}
constants.items = items;
//abilities, already keyed by name
var abilities = constants.abilities.abilitydata;
for (var key2 in abilities) {
    abilities[key2].img = "http://cdn.dota2.com/apps/dota2/images/abilities/" + key2 + "_md.png";
}
abilities.nevermore_shadowraze2 = abilities.nevermore_shadowraze1;
abilities.nevermore_shadowraze3 = abilities.nevermore_shadowraze1;
abilities.stats = {
    dname: "Stats",
    img: '../../public/images/Stats.png',
    attrib: "+2 All Attributes"
};
constants.abilities = abilities;
constants.lanes = [];
for (var i = 0; i < 128; i++) {
    constants.lanes.push([]);
    for (var j = 0; j < 128; j++) {
        var lane;
        if (Math.abs(i - (127 - j)) < 8) {
            lane = 2; //mid
        }
        else if (j < 27 || i < 27) {
            lane = 3; //top
        }
        else if (j >= 100 || i >= 100) {
            lane = 1; //bot
        }
        else if (i < 50) {
            lane = 5; //djung
        }
        else if (i >= 77) {
            lane = 4; //rjung
        }
        else {
            lane = 2; //mid
        }
        constants.lanes[i].push(lane);
    }
}
var cluster = {};
var regions = constants.regions.regions;
for (var key in regions) {
    if (regions[key].clusters) {
        regions[key].clusters.forEach(function(c) {
            cluster[c] = regions[key].display_name.slice("#dota_region_".length).split("_").map(function(s) {
                return s.toUpperCase();
            }).join(" ");
        });
    }
}
cluster["121"] = "US EAST";
constants.cluster = cluster;
constants.anonymous_account_id = 4294967295;
module.exports = constants;<commit_msg>fix mmstats<commit_after>var fs = require('fs');
var cfs = fs.readdirSync('./json');
var constants = {};
cfs.forEach(function(f) {
    constants[f.split(".")[0]] = require('./json/' + f);
});
var heroes = constants.heroes.result.heroes;
//key heroes by id
constants.heroes = {};
//key heroes by name
constants.hero_names = {};
heroes.forEach(function(h) {
    h.img = "http://cdn.dota2.com/apps/dota2/images/heroes/" + h.name.replace("npc_dota_hero_", "") + "_sb.png";
    constants.heroes[h.id] = h;
    constants.hero_names[h.name] = h;
});
/*
//leagues, key by id
var leagues = JSON.parse(JSON.stringify(constants.leagues.result.leagues));
constants.leagues = {};
leagues.forEach(function(l) {
    l.name = l.name.replace("#DOTA_Item_", "").split("_").join(" ");
    constants.leagues[l.leagueid] = l;
});
*/
//items, already keyed by name
var items = constants.items.itemdata;
constants.item_ids = {};
for (var key in items) {
    constants.item_ids[items[key].id] = key;
    items[key].img = "http://cdn.dota2.com/apps/dota2/images/items/" + items[key].img;
}
constants.items = items;
//abilities, already keyed by name
var abilities = constants.abilities.abilitydata;
for (var key2 in abilities) {
    abilities[key2].img = "http://cdn.dota2.com/apps/dota2/images/abilities/" + key2 + "_md.png";
}
abilities.nevermore_shadowraze2 = abilities.nevermore_shadowraze1;
abilities.nevermore_shadowraze3 = abilities.nevermore_shadowraze1;
abilities.stats = {
    dname: "Stats",
    img: '../../public/images/Stats.png',
    attrib: "+2 All Attributes"
};
constants.abilities = abilities;
constants.lanes = [];
for (var i = 0; i < 128; i++) {
    constants.lanes.push([]);
    for (var j = 0; j < 128; j++) {
        var lane;
        if (Math.abs(i - (127 - j)) < 8) {
            lane = 2; //mid
        }
        else if (j < 27 || i < 27) {
            lane = 3; //top
        }
        else if (j >= 100 || i >= 100) {
            lane = 1; //bot
        }
        else if (i < 50) {
            lane = 5; //djung
        }
        else if (i >= 77) {
            lane = 4; //rjung
        }
        else {
            lane = 2; //mid
        }
        constants.lanes[i].push(lane);
    }
}
var cluster = {};
//Remove regions nesting
constants.regions = constants.regions.regions;
var regions = constants.regions.regions;
for (var key in regions) {
    if (regions[key].clusters) {
        regions[key].clusters.forEach(function(c) {
            cluster[c] = regions[key].display_name.slice("#dota_region_".length).split("_").map(function(s) {
                return s.toUpperCase();
            }).join(" ");
        });
    }
}
cluster["121"] = "US EAST";
constants.cluster = cluster;
constants.anonymous_account_id = 4294967295;
module.exports = constants;<|endoftext|>


<commit_before>'use strict';

var _ = require('../tools.js');
var mapData = require('../mapData.js')
var svg = require('wout/svg.js');
var sockets = require('../sockets.js');

var chooseFaction = require('./chooseFaction.js');
var flashMessages = require('./flashMessages.js');

var map = {
  player: {},
  currentPos: null,

  showPlayer: function(player) {
    var self = this;
    self.player = player;
    if (player.position !== null) {
      if (self.currentPos !== null)
        self.currentPos.element.back().first().stroke({'width': 1, 'color': '#111'});

      var tile = mapData.board[player.position];
      tile.element.front().first().stroke({'width': 4, 'color': '#fff'});

      self.currentPos = tile;
    }
    else {
      if (self.currentPos !== null)
        self.currentPos.element.back().first().stroke({'width': 1, 'color': '#181818'});
      if (player.faction === null)
        flashMessages.show('Welcome.
Click on a tile owned by your team to spawn');
      else
        flashMessages.show('You are dead
Click on a tile owned by your team to respawn');

    }
  },

  showTurret: function(position, oldPos) {
    if (oldPos != null) {
      var children = mapData.board[oldPos].element.children();
      children[4].style('opacity', 0);
    }
    if (position != null) {
      var children = mapData.board[position].element.children();
      children[4].style('opacity', 1);
    }
  },

  tileClick: function(e) {
    e.preventDefault();
    var el = e.target || e.toElement;
    el = el.parentNode;
    var index = parseInt(el.id);

    // spawn
    var game = require('../game.js');
    if (map.player.position === null &&
        game.map[index] &&
        game.map[index].ownedBy === map.player.team) {
      chooseFaction.show();
      game.tileToSpawn = index;
    }

    // move
    else if (mapData.board[index].adjacents.indexOf(map.player.position)>-1) {
      sockets.move(index);
    }
  },

  /**
    * UPDATE MAP
  */
  visibleTiles: [],
  updateMap: function(map) {
    var self = this;
    var children = null;
    (function(visibleTiles) {
      for (var i=0;i<visibleTiles.length;i++) {
        if (map[visibleTiles[i]] === undefined) {
          mapData.board[visibleTiles[i]].element.first().fill('#1d1d1e');
        }
        children = mapData.board[visibleTiles[i]].element.children();
        if (children[1].style('opacity') == 1) children[1].style('opacity', 0);
        if (children[2].style('opacity') == 1) children[2].style('opacity', 0);
        if (children[3].style('opacity') == 1) children[3].style('opacity', 0);
      }
    })(self.visibleTiles);

    self.visibleTiles = [];
    for (var tile in map) {
      self.visibleTiles.push(map[tile].index);
      // colors the map
      if (map[tile].ownedBy === "alpha")
        mapData.board[map[tile].index].element.first().fill('#bf2318');
      else if (map[tile].ownedBy === "beta")
        mapData.board[map[tile].index].element.first().fill('#459d42');
      else if (map[tile].ownedBy === "gamma")
        mapData.board[map[tile].index].element.first().fill('#2a5faa');
      else
        mapData.board[map[tile].index].element.first().fill('#bbb');
      // display players dots
      children = mapData.board[map[tile].index].element.children();
      if (Object.keys(map[tile].players.alpha).length)
        children[1].style({opacity: 1});
      if (Object.keys(map[tile].players.beta).length)
        children[2].style({opacity: 1});
      if (Object.keys(map[tile].players.gamma).length)
        children[3].style({opacity: 1});
    }
  },

  /**
    * INITAL MAPPING
  */
  drawMap: function(median) {
    var self = this;

    /** SVG.JS */
    var boardContainer = SVG(mapData.boardName);
    var tiles   = boardContainer.group();
    var nested  = null;
    var hexagon = null;
    var circle  = null;
    var turret  = null;
    var coords  = null;
    var t       = null;
    var circleRadius = 4;

    var delta = (median/2)-(circleRadius/2);

    var colors = {'alpha': '#DD4B39', 'beta': '#7AB800', 'gamma': '#4183C4'};
    for(var i=0;i<mapData.board.length;i++) {
      t = mapData.board[i];

      coords = t.angles[0].x+','+t.angles[0].y+' '+
               t.angles[1].x+','+t.angles[1].y+' '+
               t.angles[2].x+','+t.angles[2].y+' '+
               t.angles[3].x+','+t.angles[3].y+' '+
               t.angles[4].x+','+t.angles[4].y+' '+
               t.angles[5].x+','+t.angles[5].y;

      nested  = tiles.nested();
      hexagon = nested.polygon(coords)
                      .fill('#1d1d1e')
                      .stroke({width: 1, color: '#111'});

      circle = nested.circle(circleRadius) // alha
                      .fill('#e74238')
                      .style({'opacity': 0})
                      .move(t.angles[5].x+delta+1.5,t.angles[5].y+delta-1.4);
      circle = nested.circle(circleRadius) // beta
                      .fill('#77b829')
                      .style({'opacity': 0})
                      .move(t.angles[3].x-(delta*2),t.angles[3].y+delta-3.7);
      circle = nested.circle(circleRadius) // gamma
                      .fill('#4e82c2')
                      .style({'opacity': 0})
                      .move(t.angles[1].x-delta+5.5,t.angles[1].y-(delta*2)-1.1);

      coords = t.angles[0].x+','+t.angles[0].y+' '+
               t.angles[2].x+','+t.angles[2].y+' '+
               t.angles[4].x+','+t.angles[4].y;

      turret = nested.polygon(coords)
                     .scale(.4, .4)
                     .rotate(-30)
                     .dmove(6.5, 6.5)
                     .style({'opacity': 0})
                     .stroke({width: 0})
                     .fill('#fff');

      nested.attr('id', i);
      nested.attr('name', t.id);
      nested.attr('data-rank', i);
      mapData.board[i].element = nested;
      nested.on('click', self.tileClick);
    }

    // center and resize the map
    tiles.move(_.getWindowWidth()/2, _.getWindowHeight()/2);
    var scale = 1;
    var deltaX=0,deltaY=0,newDeltaX=0,newDeltaY=0,tx=0,ty=0;
    tx = tiles.x()-_.getWindowWidth()/2;
    ty = tiles.y()-_.getWindowHeight()/2;
    deltaX = tx/scale;
    deltaY = ty/scale;
    scale = 0.5;
    newDeltaX = tx/scale;
    newDeltaY = ty/scale;
    tiles.scale(scale, scale);
    tiles.dmove(deltaX - newDeltaX, deltaY - newDeltaY);

    window.addEventListener('resize', function() {
      tiles.move(_.getWindowWidth()/2, _.getWindowHeight()/2);
    });
    self.setupMapInterractions(boardContainer, tiles, scale);
  },

  setupMapInterractions: function(boardContainer, tiles, scale) {
    var self = this;
    var scale = scale;

    self.readyToMove = false;
    boardContainer.on('mousedown', function() {
      self.readyToMove = true;
    });

    boardContainer.on('mouseup', function() {
      self.readyToMove = false;
    });

    boardContainer.on('mousemove', function(e) {
      if (self.readyToMove) {
        var x = e.movementX || e.mozMovementX;
        var y = e.movementY || e.mozMovementY;
        var bgL, bgT;
        window.requestAnimationFrame(function() {
          tiles.dmove(x/scale, y/scale);
        });
      }
    });

    var deltaX=0,deltaY=0,newDeltaX=0,newDeltaY=0,tx=0,ty=0;
    boardContainer.on('wheel', function(e) {
      if ((e.deltaY>0 && scale-e.deltaY/1000>.35) // zoom out
          || (e.deltaY<0 && scale-e.deltaY/1000<3)) { // zoom in

        tx = tiles.x()-e.pageX;
        ty = tiles.y()-e.pageY;

        // Get the current distance between the
        // pointer and the center of the map
        deltaX = tx/scale;
        deltaY = ty/scale;

        scale -= e.deltaY/1000;

        // Get the new distance
        newDeltaX = tx/scale;
        newDeltaY = ty/scale;

        // Move the map so the newDeltas match with the old ones
        // TODO: move it to the "animation" function that rune in a RAF
        tiles.scale(scale, scale);
        tiles.dmove(deltaX - newDeltaX, deltaY - newDeltaY);
      }
    });
  }
}

module.exports = map;
<commit_msg>Icon center<commit_after>'use strict';

var _ = require('../tools.js');
var mapData = require('../mapData.js')
var svg = require('wout/svg.js');
var sockets = require('../sockets.js');

var chooseFaction = require('./chooseFaction.js');
var flashMessages = require('./flashMessages.js');

var map = {
  player: {},
  currentPos: null,

  showPlayer: function(player) {
    var self = this;
    self.player = player;
    if (player.position !== null) {
      if (self.currentPos !== null)
        self.currentPos.element.back().first().stroke({'width': 1, 'color': '#111'});

      var tile = mapData.board[player.position];
      tile.element.front().first().stroke({'width': 4, 'color': '#fff'});

      self.currentPos = tile;
    }
    else {
      if (self.currentPos !== null)
        self.currentPos.element.back().first().stroke({'width': 1, 'color': '#181818'});
      if (player.faction === null)
        flashMessages.show('Welcome.
Click on a tile owned by your team to spawn');
      else
        flashMessages.show('You are dead
Click on a tile owned by your team to respawn');

    }
  },

  showTurret: function(position, oldPos) {
    if (oldPos != null) {
      var children = mapData.board[oldPos].element.children();
      children[4].style('opacity', 0);
    }
    if (position != null) {
      var children = mapData.board[position].element.children();
      children[4].style('opacity', 1);
    }
  },

  tileClick: function(e) {
    e.preventDefault();
    var el = e.target || e.toElement;
    el = el.parentNode;
    var index = parseInt(el.id);

    // spawn
    var game = require('../game.js');
    if (map.player.position === null &&
        game.map[index] &&
        game.map[index].ownedBy === map.player.team) {
      chooseFaction.show();
      game.tileToSpawn = index;
    }

    // move
    else if (mapData.board[index].adjacents.indexOf(map.player.position)>-1) {
      sockets.move(index);
    }
  },

  /**
    * UPDATE MAP
  */
  visibleTiles: [],
  updateMap: function(map) {
    var self = this;
    var children = null;
    (function(visibleTiles) {
      for (var i=0;i<visibleTiles.length;i++) {
        if (map[visibleTiles[i]] === undefined) {
          mapData.board[visibleTiles[i]].element.first().fill('#1d1d1e');
        }
        children = mapData.board[visibleTiles[i]].element.children();
        if (children[1].style('opacity') == 1) children[1].style('opacity', 0);
        if (children[2].style('opacity') == 1) children[2].style('opacity', 0);
        if (children[3].style('opacity') == 1) children[3].style('opacity', 0);
      }
    })(self.visibleTiles);

    self.visibleTiles = [];
    for (var tile in map) {
      self.visibleTiles.push(map[tile].index);
      // colors the map
      if (map[tile].ownedBy === "alpha")
        mapData.board[map[tile].index].element.first().fill('#bf2318');
      else if (map[tile].ownedBy === "beta")
        mapData.board[map[tile].index].element.first().fill('#459d42');
      else if (map[tile].ownedBy === "gamma")
        mapData.board[map[tile].index].element.first().fill('#2a5faa');
      else
        mapData.board[map[tile].index].element.first().fill('#bbb');
      // display players dots
      children = mapData.board[map[tile].index].element.children();
      if (Object.keys(map[tile].players.alpha).length)
        children[1].style({opacity: 1});
      if (Object.keys(map[tile].players.beta).length)
        children[2].style({opacity: 1});
      if (Object.keys(map[tile].players.gamma).length)
        children[3].style({opacity: 1});
    }
  },

  /**
    * INITAL MAPPING
  */
  drawMap: function(median) {
    var self = this;

    /** SVG.JS */
    var boardContainer = SVG(mapData.boardName);
    var tiles   = boardContainer.group();
    var nested  = null;
    var hexagon = null;
    var circle  = null;
    var turret  = null;
    var coords  = null;
    var t       = null;
    var circleRadius = 4;

    var delta = (median/2)-(circleRadius/2);

    var colors = {'alpha': '#DD4B39', 'beta': '#7AB800', 'gamma': '#4183C4'};
    for(var i=0;i<mapData.board.length;i++) {
      t = mapData.board[i];

      coords = t.angles[0].x+','+t.angles[0].y+' '+
               t.angles[1].x+','+t.angles[1].y+' '+
               t.angles[2].x+','+t.angles[2].y+' '+
               t.angles[3].x+','+t.angles[3].y+' '+
               t.angles[4].x+','+t.angles[4].y+' '+
               t.angles[5].x+','+t.angles[5].y;

      nested  = tiles.nested();
      hexagon = nested.polygon(coords)
                      .fill('#1d1d1e')
                      .stroke({width: 1, color: '#111'});

      circle = nested.circle(circleRadius) // alha
                      .fill('#e74238')
                      .style({'opacity': 0})
                      .move(t.angles[5].x+delta+1.5,t.angles[5].y+delta-1.4);
      circle = nested.circle(circleRadius) // beta
                      .fill('#77b829')
                      .style({'opacity': 0})
                      .move(t.angles[3].x-(delta*2),t.angles[3].y+delta-3.7);
      circle = nested.circle(circleRadius) // gamma
                      .fill('#4e82c2')
                      .style({'opacity': 0})
                      .move(t.angles[1].x-delta+5.5,t.angles[1].y-(delta*2)-1.1);

      coords = t.angles[0].x+','+t.angles[0].y+' '+
               t.angles[2].x+','+t.angles[2].y+' '+
               t.angles[4].x+','+t.angles[4].y;

      turret = nested.polygon(coords)
                     .scale(.4, .4)
                     .rotate(-30)
                     .dmove(6.5, 6.5)
                     .style({'opacity': 0})
                     .stroke({width: 0})
                     .fill('#fff');

      if (i==0) {
        var center = nested.path('M249.7 422.7l28.3-49h-56.6zM388.6 180.8H332l28.3 49zM166.3 181.4h-56.6l28.3 49zM275.2 306.2l50.9-.1-50.9-88.1v.1L249.7 174l-50.9 88.2h.1l-25.5 44.1h101.8zm-25.5-44.1zM409.1 354.1l-106.2-184v.1l-53.1-92-106.2 184h.1l-53.1 92H303v-.1h106.1zM213.2 198.9l36.5-63.3 73 126.5h.1l36.5 63.2H213.2v.1h-73l73-126.5z');

        center.move(-159, -173)
              .fill('#fff')
              .stroke({width: 0})
              .scale(.07);
      }

      nested.attr('id', i);
      nested.attr('name', t.id);
      nested.attr('data-rank', i);
      mapData.board[i].element = nested;
      nested.on('click', self.tileClick);
    }

    // center and resize the map
    tiles.move(_.getWindowWidth()/2, _.getWindowHeight()/2);
    var scale = 1;
    var deltaX=0,deltaY=0,newDeltaX=0,newDeltaY=0,tx=0,ty=0;
    tx = tiles.x()-_.getWindowWidth()/2;
    ty = tiles.y()-_.getWindowHeight()/2;
    deltaX = tx/scale;
    deltaY = ty/scale;
    scale = 0.5;
    newDeltaX = tx/scale;
    newDeltaY = ty/scale;
    tiles.scale(scale, scale);
    tiles.dmove(deltaX - newDeltaX, deltaY - newDeltaY);

    window.addEventListener('resize', function() {
      tiles.move(_.getWindowWidth()/2, _.getWindowHeight()/2);
    });
    self.setupMapInterractions(boardContainer, tiles, scale);
  },

  setupMapInterractions: function(boardContainer, tiles, scale) {
    var self = this;
    var scale = scale;

    self.readyToMove = false;
    boardContainer.on('mousedown', function() {
      self.readyToMove = true;
    });

    boardContainer.on('mouseup', function() {
      self.readyToMove = false;
    });

    boardContainer.on('mousemove', function(e) {
      if (self.readyToMove) {
        var x = e.movementX || e.mozMovementX;
        var y = e.movementY || e.mozMovementY;
        var bgL, bgT;
        window.requestAnimationFrame(function() {
          tiles.dmove(x/scale, y/scale);
        });
      }
    });

    var deltaX=0,deltaY=0,newDeltaX=0,newDeltaY=0,tx=0,ty=0;
    boardContainer.on('wheel', function(e) {
      if ((e.deltaY>0 && scale-e.deltaY/1000>.35) // zoom out
          || (e.deltaY<0 && scale-e.deltaY/1000<3)) { // zoom in

        tx = tiles.x()-e.pageX;
        ty = tiles.y()-e.pageY;

        // Get the current distance between the
        // pointer and the center of the map
        deltaX = tx/scale;
        deltaY = ty/scale;

        scale -= e.deltaY/1000;

        // Get the new distance
        newDeltaX = tx/scale;
        newDeltaY = ty/scale;

        // Move the map so the newDeltas match with the old ones
        // TODO: move it to the "animation" function that rune in a RAF
        tiles.scale(scale, scale);
        tiles.dmove(deltaX - newDeltaX, deltaY - newDeltaY);
      }
    });
  }
}

module.exports = map;
<|endoftext|>


<commit_before>var Tinkerforge = require('tinkerforge');
var get_name = require('./get_name.js');
var ipcon;
var PORT;
var HOST;
console.log('');
/* istanbul ignore next */
function tfinit() {
  ipcon = new Tinkerforge.IPConnection();
  ipcon.connect(HOST, PORT,
    function(error) {
      switch (error) {
        case 11:
          console.log('Error: ALREADY CONNECTED');
          break;
        case 12:
          console.log('Error: NOT CONNECTED');
          break;
        case 13:
          console.log('Error: CONNECT FAILED');
          break;
        case 21:
          console.log('Error: INVALID FUNCTION ID');
          break;
        case 31:
          console.log('Error: TIMEOUT');
          break;
        case 41:
          console.log('Error: INVALID PARAMETER');
          break;
        case 42:
          console.log('Error: FUNCTION NOT SUPPORTED');
          break;
        default:
          console.log('Error: UNKNOWN');
          break;
      }
      process.exit();
    }
  );
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function(connectReason) {
      ipcon.enumerate();
    }
  );
  console.log('Used HOST: %s\nUsed PORT: %s\n', HOST, PORT);
}
/* istanbul ignore next */
function tfget(advanced) {
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
    function(uid, connectedUid, position, hardwareVersion, firmwareVersion, deviceIdentifier) {
      console.log('NAME: %s', get_name.get(deviceIdentifier));
      console.log('UID : %s', uid);
      if (advanced === true) {
        console.log('Enumeration Type:  %s', enumerationType);
        if (enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
          console.log('');
          return;
        }
        console.log('Connected UID:     %s', connectedUid);
        console.log('Position:          %s', position);
        console.log('Hardware Version:  %s', hardwareVersion);
        console.log('Firmware Version:  %s', firmwareVersion);
        console.log('Device Identifier: %s', deviceIdentifier);
      }
      console.log(' ');
    });
}
/* istanbul ignore next */
function exit() {
  process.stdin.on('data',
    function(data) {
      ipcon.disconnect();
      process.exit(0);
    }
  );
}
/* istanbul ignore next */
function get(port, host, advanced) {
  PORT = port;
  HOST = host;
  tfinit();
  if (advanced === true) {
    tfget(advanced === true);
  } else {
    tfget(advanced === false);
  }
  exit();
}
exports.get = get;
<commit_msg>update branch<commit_after>var Tinkerforge = require('tinkerforge');
var get_name = require('./get_name.js');
var ipcon;
var PORT;
var HOST;
console.log('');
/* istanbul ignore next */
function tfinit() {
  ipcon = new Tinkerforge.IPConnection();
  ipcon.connect(HOST, PORT,
    function(error) {
      switch (error) {
        case 11:
          console.log('Error: ALREADY CONNECTED');
          break;
        case 12:
          console.log('Error: NOT CONNECTED');
          break;
        case 13:
          console.log('Error: CONNECT FAILED');
          break;
        case 21:
          console.log('Error: INVALID FUNCTION ID');
          break;
        case 31:
          console.log('Error: TIMEOUT');
          break;
        case 41:
          console.log('Error: INVALID PARAMETER');
          break;
        case 42:
          console.log('Error: FUNCTION NOT SUPPORTED');
          break;
        default:
          console.log('Error: UNKNOWN');
          break;
      }
      process.exit();
    }
  );
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function(connectReason) {
      ipcon.enumerate();
    }
  );
  console.log('Used HOST: %s\nUsed PORT: %s\n', HOST, PORT);
}
/* istanbul ignore next */
function tfget(advanced) {
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
    function(uid, connectedUid, position, hardwareVersion, firmwareVersion, deviceIdentifier, enumerationType) {
      console.log('NAME: %s', get_name.get(deviceIdentifier));
      console.log('UID : %s', uid);
      if (advanced === true) {
        console.log('Enumeration Type:  %s', enumerationType);
        if (enumerationType === Tinkerforge.IPConnection.ENUMERATION_TYPE_DISCONNECTED) {
          console.log('');
          return;
        }
        console.log('Connected UID:     %s', connectedUid);
        console.log('Position:          %s', position);
        console.log('Hardware Version:  %s', hardwareVersion);
        console.log('Firmware Version:  %s', firmwareVersion);
        console.log('Device Identifier: %s', deviceIdentifier);
      }
      console.log(' ');
    });
}
/* istanbul ignore next */
module.exports.get = function get(port, host, advanced) {
  PORT = port;
  HOST = host;
  tfinit();
  if (advanced === true) {
    tfget(advanced);
  } else {
    tfget(advanced);
  }
  setTimeout(function() {
    ipcon.disconnect();
    process.exit(0);
  }, 1000);
  process.stdin.on('data',
    function(data) {
      ipcon.disconnect();
      process.exit(0);
    }
  );
};
<|endoftext|>


<commit_before>const utils = require('./src/utils');
const CustomElementRegistry = require('./src/CustomElementRegistry');
const Document = require('./src/Document');
const HTMLElement = require('./src/HTMLElement');
const HTMLUnknownElement = require('./src/HTMLUnknownElement');
module.exports = {
  Attr: require('./src/Attr'),
  CharacterData: require('./src/CharacterData'),
  Comment: require('./src/Comment'),
  CustomElementRegistry: CustomElementRegistry,
  CustomEvent: require('./src/CustomEvent'),
  Document: Document,
  DocumentFragment: require('./src/DocumentFragment'),
  DocumentType: require('./src/DocumentType'),
  DOMStringMap: require('./src/DOMStringMap'),
  DOMTokenList: require('./src/DOMTokenList'),
  Element: require('./src/Element'),
  Event: require('./src/Event'),
  EventTarget: require('./src/EventTarget'),
  HTMLElement: HTMLElement,
  HTMLUnknownElement: HTMLUnknownElement,
  HTMLHtmlElement: require('./src/HTMLHtmlElement'),
  HTMLTemplateElement: require('./src/HTMLTemplateElement'),
  Node: require('./src/Node'),
  Text: require('./src/Text'),
  init: (options) => {
    if (!options) options = {};
    const window = options.window ||
      (typeof self === 'undefined' ? global : self);
    window.customElements = options.customElements ||
      new CustomElementRegistry();
    window.document = new Document(window.customElements);
    window.window = window;
    window.HTMLElement = HTMLElement;
    window.HTMLUnknownElement = HTMLUnknownElement;
    if (options.selector) {
      const $ = options.selector.$;
      const selector = options.selector.module ?
        options.selector.module(window) :
        require(options.selector.name);
      utils.querySelectorAll = function querySelectorAll(css) {
        return $(selector, this, css);
      };
    }
    return window;
  }
};
<commit_msg>feat: 🎸 Add CustomEvent to the window interface<commit_after>const utils = require('./src/utils');
const CustomElementRegistry = require('./src/CustomElementRegistry');
const Document = require('./src/Document');
const HTMLElement = require('./src/HTMLElement');
const HTMLUnknownElement = require('./src/HTMLUnknownElement');
const CustomEvent = require('./src/CustomEvent');

module.exports = {
  Attr: require('./src/Attr'),
  CharacterData: require('./src/CharacterData'),
  Comment: require('./src/Comment'),
  CustomElementRegistry: CustomElementRegistry,
  CustomEvent: CustomEvent,
  Document: Document,
  DocumentFragment: require('./src/DocumentFragment'),
  DocumentType: require('./src/DocumentType'),
  DOMStringMap: require('./src/DOMStringMap'),
  DOMTokenList: require('./src/DOMTokenList'),
  Element: require('./src/Element'),
  Event: require('./src/Event'),
  EventTarget: require('./src/EventTarget'),
  HTMLElement: HTMLElement,
  HTMLUnknownElement: HTMLUnknownElement,
  HTMLHtmlElement: require('./src/HTMLHtmlElement'),
  HTMLTemplateElement: require('./src/HTMLTemplateElement'),
  Node: require('./src/Node'),
  Text: require('./src/Text'),
  init: (options) => {
    if (!options) options = {};
    const window = options.window ||
      (typeof self === 'undefined' ? global : self);
    window.customElements = options.customElements ||
      new CustomElementRegistry();
    window.document = new Document(window.customElements);
    window.window = window;
    window.HTMLElement = HTMLElement;
    window.HTMLUnknownElement = HTMLUnknownElement;
    window.CustomEvent = CustomEvent;
    if (options.selector) {
      const $ = options.selector.$;
      const selector = options.selector.module ?
        options.selector.module(window) :
        require(options.selector.name);
      utils.querySelectorAll = function querySelectorAll(css) {
        return $(selector, this, css);
      };
    }
    return window;
  }
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import config from 'config';
import fetch from 'isomorphic-fetch';
import sgDomain from './domain';
import { objects as sgObjects } from './object';
import { objectCalls as sgObjectCalls } from './object-call';
import { names as sgObjectNames } from './object';
import sgUtil from './util';
import URI from 'urijs';

// https://apihelp.surveygizmo.com/help/article/link/versions-methods
const restApiVersion = 'v4';

const prototype = {
  config: Object.assign({}, config.get('restApi')),
  getRestApiUri(path) {
    return new URI(
      {
        protocol: 'https',
        hostname: sgDomain(this.config.regionName).hostname,
        path: `/${restApiVersion}/${path}`,
      }
    )
    .query({
      api_token: this.config.auth.key,
      api_token_secret: this.config.auth.secretKey,
    })
    ;
  },

  wrapRestApiFetch(method, path, options = {}, callback = undefined) {
    const restApiUri = this.getRestApiUri(path);
    return fetch(
      restApiUri.toString(), {
        method,
      }
    )
    .then(response => {
      if (response.status >= 400) {
        throw new Error(
          `REST API responded to ${method} ${restApiUri.path()} with status ${response.status}`
        );
      }
      return response.json();
    })
    .then(result => {
      if (_.isUndefined(result.result_ok)) {
        throw new Error(
          `REST API responded to ${method} ${restApiUri.path()} with undefined result`
        );
      }

      if (!result.result_ok) {
        throw new Error(
          `REST API responded to ${method} ${restApiUri.path()} with error result: `
          + `${result.message} (code ${result.code})`
        );
      }

      return result.data;
    })
    .then(data => {
      if (_.isUndefined(callback)) {
        return data;
      }
      return callback(null, data);
    })
    .catch(reason => {
      if (_.isUndefined(callback)) {
        throw new Error(reason);
      }
      return callback(reason);
    })
    ;
  },
};

const assignOptionsAndCallbackFromArgs = (args) => {
  let options = {};
  let callback;

  if (args.length !== 0) {
    if (args.length === 1) {
      if (!_.isFunction(args[0]) && _.isObject(args[0])) {
        options = args[0];
      } else if (_.isFunction(args[0])) {
        callback = args[0];
      } else {
        throw new Error(
          'Invalid argument'
        );
      }
    } else if (args.length === 2) {
      if ((!_.isFunction(args[0]) && _.isObject(args[0])) && _.isFunction(args[1])) {
        [options, callback] = args;
      } else {
        throw new Error(
          'Invalid arguments'
        );
      }
    } else {
      throw new Error(
        'Invalid number of arguments'
      );
    }
  }

  return [options, callback];
};

const objectCallerFactories = {};

objectCallerFactories[sgObjectCalls.LIST.name] = object => ({
  name: `get${_.upperFirst(object.pluralName)}`,
  func(...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    return this.wrapRestApiFetch(
      'GET', `${object.getRoute(options)}`, options, callback
    );
  },
});

objectCallerFactories[sgObjectCalls.GET.name] = object => ({
  name: `get${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    return this.wrapRestApiFetch(
      'GET', `${object.getRoute(options)}`, options, callback
    );
  },
});

objectCallerFactories[sgObjectCalls.CREATE.name] = object => ({
  name: `create${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    console.log('Stub CREATE ${object.name}');
  },
});

objectCallerFactories[sgObjectCalls.UPDATE.name] = object => ({
  name: `update${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    console.log('Stub UPDATE ${object.name} ${objectId}');
  },
});

objectCallerFactories[sgObjectCalls.DELETE.name] = object => ({
  name: `delete${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    return this.wrapRestApiFetch(
      'DELETE', `${object.getRoute(options)}`, options, callback
    );
  },
});

objectCallerFactories[sgObjectCalls.COPY.name] = object => ({
  name: `copy${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    console.log('Stub COPY ${object.name} ${objectId}');
  },
});

sgObjectNames.forEach(objectName => {
  const object = sgObjects[objectName];
  if (!_.isUndefined(object.calls)) {
    Object.keys(object.calls).forEach(objectCallName => {
      if (!sgUtil.isValidObjectCallName(objectCallName)) {
        throw new Error(`SurveyGizmo Object ${objectName} defines invalid call ${objectCallName}`);
      }
      const objectCaller = objectCallerFactories[objectCallName](object);
      prototype[objectCaller.name] = objectCaller.func;
    });
  }
});

const restApi = (configOverrides = {}) => {
  const instance = Object.create(prototype);
  instance.config = Object.assign({}, instance.config, configOverrides);

  return instance;
};

export default restApi;
<commit_msg>fix(rest-api): copy options and callback objects<commit_after>import _ from 'lodash';
import config from 'config';
import fetch from 'isomorphic-fetch';
import sgDomain from './domain';
import { objects as sgObjects } from './object';
import { objectCalls as sgObjectCalls } from './object-call';
import { names as sgObjectNames } from './object';
import sgUtil from './util';
import URI from 'urijs';

// https://apihelp.surveygizmo.com/help/article/link/versions-methods
const restApiVersion = 'v4';

const prototype = {
  config: Object.assign({}, config.get('restApi')),
  getRestApiUri(path) {
    return new URI(
      {
        protocol: 'https',
        hostname: sgDomain(this.config.regionName).hostname,
        path: `/${restApiVersion}/${path}`,
      }
    )
    .query({
      api_token: this.config.auth.key,
      api_token_secret: this.config.auth.secretKey,
    })
    ;
  },

  wrapRestApiFetch(method, path, options = {}, callback = undefined) {
    const restApiUri = this.getRestApiUri(path);
    return fetch(
      restApiUri.toString(), {
        method,
      }
    )
    .then(response => {
      if (response.status >= 400) {
        throw new Error(
          `REST API responded to ${method} ${restApiUri.path()} with status ${response.status}`
        );
      }
      return response.json();
    })
    .then(result => {
      if (_.isUndefined(result.result_ok)) {
        throw new Error(
          `REST API responded to ${method} ${restApiUri.path()} with undefined result`
        );
      }

      if (!result.result_ok) {
        throw new Error(
          `REST API responded to ${method} ${restApiUri.path()} with error result: `
          + `${result.message} (code ${result.code})`
        );
      }

      return result.data;
    })
    .then(data => {
      if (_.isUndefined(callback)) {
        return data;
      }
      return callback(null, data);
    })
    .catch(reason => {
      if (_.isUndefined(callback)) {
        throw new Error(reason);
      }
      return callback(reason);
    })
    ;
  },
};

/*
 * () => [,]
 * ({}) => [{},]
 * (() => {}) => [,() => {}]
 * ({}, () => {}) => [{}, () => {}]
 */
const assignOptionsAndCallbackFromArgs = (args) => {
  let options = {};
  let callback;

  if (args.length !== 0) {
    if (args.length === 1) {
      if (!_.isFunction(args[0]) && _.isObject(args[0])) {
        options = Object.assign({}, args[0]);
      } else if (_.isFunction(args[0])) {
        callback = args[0];
      } else {
        throw new Error(
          'Invalid argument'
        );
      }
    } else if (args.length === 2) {
      if ((!_.isFunction(args[0]) && _.isObject(args[0])) && _.isFunction(args[1])) {
        options = Object.assign({}, args[0]);
        callback = args[1];
      } else {
        throw new Error(
          'Invalid arguments'
        );
      }
    } else {
      throw new Error(
        'Invalid number of arguments'
      );
    }
  }

  return [options, callback];
};

const objectCallerFactories = {};

objectCallerFactories[sgObjectCalls.LIST.name] = object => ({
  name: `get${_.upperFirst(object.pluralName)}`,
  func(...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    return this.wrapRestApiFetch(
      'GET', `${object.getRoute(options)}`, options, callback
    );
  },
});

objectCallerFactories[sgObjectCalls.GET.name] = object => ({
  name: `get${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    return this.wrapRestApiFetch(
      'GET', `${object.getRoute(options)}`, options, callback
    );
  },
});

objectCallerFactories[sgObjectCalls.CREATE.name] = object => ({
  name: `create${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    console.log('Stub CREATE ${object.name}');
  },
});

objectCallerFactories[sgObjectCalls.UPDATE.name] = object => ({
  name: `update${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    console.log('Stub UPDATE ${object.name} ${objectId}');
  },
});

objectCallerFactories[sgObjectCalls.DELETE.name] = object => ({
  name: `delete${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    return this.wrapRestApiFetch(
      'DELETE', `${object.getRoute(options)}`, options, callback
    );
  },
});

objectCallerFactories[sgObjectCalls.COPY.name] = object => ({
  name: `copy${_.upperFirst(object.name)}`,
  func(objectId, ...args) {
    const [options, callback] = assignOptionsAndCallbackFromArgs(args);
    options[`${object.name}Id`] = objectId;
    console.log('Stub COPY ${object.name} ${objectId}');
  },
});

sgObjectNames.forEach(objectName => {
  const object = sgObjects[objectName];
  if (!_.isUndefined(object.calls)) {
    Object.keys(object.calls).forEach(objectCallName => {
      if (!sgUtil.isValidObjectCallName(objectCallName)) {
        throw new Error(`SurveyGizmo Object ${objectName} defines invalid call ${objectCallName}`);
      }
      const objectCaller = objectCallerFactories[objectCallName](object);
      prototype[objectCaller.name] = objectCaller.func;
    });
  }
});

const restApi = (configOverrides = {}) => {
  const instance = Object.create(prototype);
  instance.config = Object.assign({}, instance.config, configOverrides);

  return instance;
};

export default restApi;
<|endoftext|>


<commit_before>describe('middleware/api/methods', () => {
  describe('create', () => {
    it('should validate the body');
    it('should set defaults on the body');
  });

  describe('update', () => {
    it('should ignore read only fields given in the body');
    it('should validate the body');
    it('should set defaults on the body');
  });

  describe('patch', () => {
    it('should validate the body');
    it('should set defaults on the body');
  });
});
<commit_msg>Remove unnecessary test stubs<commit_after><|endoftext|>


<commit_before>$(window).on('load', () => {
	$(document).foundation();
	for (let applet of global.applets) {
		applet.run($);
	}
});
<commit_msg>fix exception when no applets have been registered<commit_after>$(window).on('load', () => {
	$(document).foundation();
	for (let applet of (global.applets || [])) {
		applet.run($);
	}
});
<|endoftext|>


<commit_before>
var Capsule = {

    extend: function(rootObject, coreObject, deadEndObject){

        if(typeof rootObject !== "object") rootObject = {};
        if(coreObject === undefined) coreObject = rootObject;
        if(typeof coreObject !== "object") coreObject = {};
        if(typeof deadEndObject !== "object") deadEndObject = {};

        // to not insert deadend properties into the inherited closures
        var rootMergeObject = {};
        var coreMergeObject = {};

        // add a extension method to each object within its core, which others can inherit from
        coreObject.extend = function(rootExtension, coreExtension, deadEndObject){

            //inherit from parent root
            var rootProps = Object.keys(rootObject);
            for(var k = 0; k < rootProps.length; k++){
                rootExtension[rootProps[k]] = rootObject[rootProps[k]];

            }

            //inherit from parent core
            var coreProps = Object.keys(coreObject);
            for(var j = 0; j < coreProps.length; j++){
                coreExtension[coreProps[j]] = coreObject[coreProps[j]];
            }

            return Capsule.extend(rootExtension, coreExtension, deadEndObject);
        };

        var coreDeadend = {};
        if(typeof deadEndObject === "object"){

            if(deadEndObject.constructor === Array){
                if(deadEndObject.length === 1 && typeof deadEndObject[0] === "object"){

                    coreDeadend = deadEndObject[0];

                } else if(deadEndObject.length >= 2 && typeof deadEndObject[1] === "object"){
                    coreDeadend = deadEndObject[1];
                }
            } else {
                coreDeadend = deadEndObject;
            }

        }
        // extend the core merge object with the deadend core properties from the deadend object
        var deadProps = Object.keys(coreDeadend);
        for(var r = 0; r < deadProps.length; r++){

            coreMergeObject[deadProps[r]] = coreDeadend[deadProps[r]];

        }

        // freeze the core
        var frozenCore = Object.freeze(coreObject);
        var frozenMergeCore = Object.freeze(coreMergeObject);
        var coreProps = Object.keys(frozenCore);
        var mergeCoreProps = Object.keys(frozenMergeCore);

        //now extend the root merge object with the core properties and their descriptors
        for(var l = 0; l < coreProps.length; l++){

            Object.defineProperty(rootMergeObject, coreProps[l], Object.getOwnPropertyDescriptor(frozenCore, coreProps[l]) );
            rootMergeObject[coreProps[l]] = frozenCore[coreProps[l]];

        }
        //extend the root merge object with the rootobject
        var rootProps = Object.keys(rootObject);
        for(var h = 0; h < rootProps.length; h++){

            rootMergeObject[rootProps[h]] = rootObject[rootProps[h]];
        }
        //now extend the root merge object with the core deadend properties and their descriptors
        for(var t = 0; t < mergeCoreProps.length; t++){

            Object.defineProperty(rootMergeObject, mergeCoreProps[t], Object.getOwnPropertyDescriptor(frozenMergeCore, mergeCoreProps[t]) );
            rootMergeObject[mergeCoreProps[t]] = frozenMergeCore[mergeCoreProps[t]];

        }

        var rootDeadend = {};
        if(deadEndObject.constructor === Array &&
            deadEndObject.length >= 2 &&
            typeof deadEndObject[0] === "object"){

            rootDeadend = deadEndObject[0];
        }
        //extend the root merge object with the root deadend properties
        var deadRootProps = Object.keys(rootDeadend);
        for(var y = 0; y < deadRootProps.length; y++){

            rootMergeObject[deadRootProps[y]] = rootDeadend[deadRootProps[y]];
        }

        // return the sealed the root object
        return Object.seal(rootMergeObject);
    }

};

module.exports = Capsule;<commit_msg>refactored classic for loops to forEach loops<commit_after>
var Capsule = {

    extend: function(rootObject, coreObject, deadEndObject){

        if(typeof rootObject !== "object") rootObject = {};
        if(coreObject === undefined) coreObject = rootObject;
        if(typeof coreObject !== "object") coreObject = {};
        if(typeof deadEndObject !== "object") deadEndObject = {};

        // to not insert deadend properties into the inherited closures
        var rootMergeObject = {};
        var coreMergeObject = {};

        // add a extension method to each object within its core, which others can inherit from
        coreObject.extend = function(rootExtension, coreExtension, deadEndObject){

            //inherit from parent root
            Object.keys(rootObject).forEach(function(property){
                rootExtension[property] = rootObject[property];
            });

            //inherit from parent core
            Object.keys(coreObject).forEach(function(property){
                coreExtension[property] = coreObject[property];
            });

            return Capsule.extend(rootExtension, coreExtension, deadEndObject);
        };

        var coreDeadend = {};
        if(typeof deadEndObject === "object"){

            if(deadEndObject.constructor === Array){
                if(deadEndObject.length === 1 && typeof deadEndObject[0] === "object"){

                    coreDeadend = deadEndObject[0];

                } else if(deadEndObject.length >= 2 && typeof deadEndObject[1] === "object"){
                    coreDeadend = deadEndObject[1];
                }
            } else {
                coreDeadend = deadEndObject;
            }

        }
        // extend the core merge object with the deadend core properties from the deadend object
        Object.keys(coreDeadend).forEach(function(property){
            coreMergeObject[property] = coreDeadend[property];
        });

        // freeze the core
        var frozenCore = Object.freeze(coreObject);
        var frozenMergeCore = Object.freeze(coreMergeObject);
        var coreProps = Object.keys(frozenCore);
        var mergeCoreProps = Object.keys(frozenMergeCore);

        //now extend the root merge object with the core properties and their descriptors
        Object.keys(frozenCore).forEach(function(property){
            Object.defineProperty(rootMergeObject, property, Object.getOwnPropertyDescriptor(frozenCore, property) );
            rootMergeObject[property] = frozenCore[property];

        });

        //extend the root merge object with the rootobject
        Object.keys(rootObject).forEach(function(property){
            rootMergeObject[property] = rootObject[property];
        });

        //now extend the root merge object with the core deadend properties and their descriptors
        Object.keys(frozenMergeCore).forEach(function(property){
            Object.defineProperty(rootMergeObject, property, Object.getOwnPropertyDescriptor(frozenMergeCore, property) );
            rootMergeObject[property] = frozenMergeCore[property];

        });

        var rootDeadend = {};
        if(deadEndObject.constructor === Array &&
            deadEndObject.length >= 2 &&
            typeof deadEndObject[0] === "object"){

            rootDeadend = deadEndObject[0];
        }
        //extend the root merge object with the root deadend properties
        Object.keys(rootDeadend).forEach(function(property){
            rootMergeObject[property] = rootDeadend[property];

        });

        // return the object sealed
        return Object.seal(rootMergeObject);
    }

};

module.exports = Capsule;<|endoftext|>


<commit_before>//  Grid Data Provider
//	===================
//
//	provides data to a lux.grid using websockets
define(['angular',
        'lux/grid',
        'lux/services/stream'], function (angular) {
    'use strict';

    angular.module('lux.grid.stream', ['lux.grid', 'lux.stream'])

        .run(['$lux', 'luxGridDataProviders', function ($lux, dataProvider) {

            dataProvider.register('websocket', gridDataProviderWebsocketFactory($lux, dataProvider));
        }]);

    function gridDataProviderWebsocketFactory ($lux, dataProvider) {

        function GridDataProviderWebsocket (grid) {
            this._grid = grid;
            this._websocketUrl = grid.options.target.url;
            this._channel = grid.options.target.channel;
            this._model = grid.options.target.model;
        }

        GridDataProviderWebsocket.prototype.destroy = function() {
            this._grid = null;
        };

        GridDataProviderWebsocket.prototype.connect = function() {
            dataProvider.check(this);

            function onConnect () {
                this.getPage();
            }

            function onMetadataReceived(msg) {
                this._grid.onMetadataReceived(msg.result);
            }

            function onMessage (msg) {
                var tasks;

                if (msg.data.event === 'record-update') {
                    tasks = msg.data.data;

                    this._grid.onDataReceived({
                        total: msg.data.total,
                        result: tasks,
                        type: 'update'
                    });

                } else if (msg.data.event === 'records') {
                    tasks = msg.data.data;

                    this._grid.onDataReceived({
                        total: msg.data.total,
                        result: tasks,
                        type: 'update'
                    });

                } else if (msg.data.event === 'columns-metadata') {
                    this._grid.onMetadataReceived(msg.result);
                }
            }

            this._stream = $lux.stream(this._websocketUrl);

            this._stream.rpc(
                'model_metadata',
                { 'model': this._model },
                onMetadataReceived.bind(this),
                function() { console.log('rpc error', arguments); } // TODO display error on grid?
            );
        };

        GridDataProviderWebsocket.prototype.getPage = function (options) {
        };

        GridDataProviderWebsocket.prototype.deleteItem = function(identifier, onSuccess, onFailure) {
            var options = {id: identifier};
            this._stream.rpc(this._channel, options).then(onSuccess, onFailure);
        };

        return GridDataProviderWebsocket;
    }

});
<commit_msg>Websocket grid now receiving data from back-end<commit_after>//  Grid Data Provider
//	===================
//
//	provides data to a lux.grid using websockets
define(['angular',
        'lux/grid',
        'lux/services/stream'], function (angular) {
    'use strict';

    angular.module('lux.grid.stream', ['lux.grid', 'lux.stream'])

        .run(['$lux', 'luxGridDataProviders', function ($lux, dataProvider) {

            dataProvider.register('websocket', gridDataProviderWebsocketFactory($lux, dataProvider));
        }]);

    function gridDataProviderWebsocketFactory ($lux, dataProvider) {

        function GridDataProviderWebsocket (grid) {
            this._grid = grid;
            this._websocketUrl = grid.options.target.url;
            this._channel = grid.options.target.channel;
            this._model = grid.options.target.model;
        }

        GridDataProviderWebsocket.prototype.destroy = function() {
            this._grid = null;
        };

        GridDataProviderWebsocket.prototype.connect = function() {
            dataProvider.check(this);

            function onMessage (msg) {
                var tasks;

                if (msg.data.event === 'record-update') {
                    tasks = msg.data.data;

                    this._grid.onDataReceived({
                        total: msg.data.total,
                        result: tasks,
                        type: 'update'
                    });

                } else if (msg.data.event === 'records') {
                    tasks = msg.data.data;

                    this._grid.onDataReceived({
                        total: msg.data.total,
                        result: tasks,
                        type: 'update'
                    });

                } else if (msg.data.event === 'columns-metadata') {
                    this._grid.onMetadataReceived(msg.result);
                }
            }

            this._stream = $lux.stream(this._websocketUrl);

            this._stream.rpc(
                'model_metadata',
                { 'model': this._model },
                onMetadataReceived.bind(this),
                function() { console.log('rpc error', arguments); } // TODO display error on grid?
            );
        };

        GridDataProviderWebsocket.prototype.getPage = function (options) {
            this._stream.rpc(
                'model_data',
                { 'model': this._model },
                onDataReceived.bind(this),
                function() { console.log('rpc error', arguments); }
            );
        };

        GridDataProviderWebsocket.prototype.deleteItem = function(identifier, onSuccess, onFailure) {
            var options = {id: identifier};
            this._stream.rpc(this._channel, options).then(onSuccess, onFailure);
        };

        function onMetadataReceived(msg) {
            this._grid.onMetadataReceived(msg.result);
        }

        function onDataReceived(msg) {
            this._grid.onDataReceived(msg.result);
        }

        return GridDataProviderWebsocket;
    }

});
<|endoftext|>