<commit_before>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', function (event) {
    event.preventDefault()
});

$(document).ready(function () {
    stopGame = false;
    firstClick = true;

    $('select#niveau').change(function(){   // Selection du niveau
      console.log($('select#niveau').val());
      switch ($('select#niveau').val()) {
        case "Facile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(15);
          $('#hauteur').val(15);
          $('#bombs').val(10);
          break;
        case "Moyen":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(15);
          $('#hauteur').val(15);
          $('#bombs').val(20);
          break;
        case "Difficile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(15);
          $('#hauteur').val(15);
          $('#bombs').val(30);
          break;
        case "Personnalisé":
          $('#menu input').prop('disabled', false);
          break;
      }
    });

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('#hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)) {
                if (testParameters(largeur, hauteur, bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {
    if (((largeur * hauteur) / 3) * 2 >= bombs) {
        if (largeur <= 40 && hauteur <= 50) {
            return true;
        }
    }
    return false;
}

function initGameboard() {
    stopGame = false;
    firstClick = true;
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('.reset').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            generateLayout(largeur, hauteur);
            firstClick = true;
            grid = new Grid(largeur, hauteur);
            grid.addBombs(bombs);
            $('#nbbombes').text(grid.flags + ' bombes');

            $('td').each(function () {
                initEvents($(this));
            });

        });
    });

    $('.menu-back').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            $('#largeur').val(largeur);
            $('#hauteur').val(hauteur);
            $('#bombs').val(bombs);

            $('#menu').css('display', 'block');
            $('#gameboard').css('display', 'none');

        });
    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem) {

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {
            console.log('clic du bouton gauche');
            if (!grid.timer) {
              timer();
            }

           if (firstClick)
           {
             if (grid.cells[x][y].isBomb()){
               grid.moveOutBomb(x, y);
             }
             firstClick=false;
           }

            var result = grid.reveal(x, y);

            result.cases.forEach(updateView);

            if (result.lost) {
                gameOverLose();
            }
            else {
                gameOverWin();
            }
        } else if (event.button == 2) {
            console.log('clic du bouton droit');

            grid.toggleFlag(x, y);

            updateView(grid.cells[x][y]);
            $('#nbbombes').text(grid.flags + ' bombes');
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].isShown()) {
                result = grid.quickReveal(x, y);
                console.log(result.cases);

                result.cases.forEach(updateView);

                if (result.lost) {
                    gameOverLose()
                }
            }
        }
    });

}

function updateView(cell)
{
    var td = $('td[data-x="' + cell.x + '"][data-y="' + cell.y + '"]').removeClass();

    //console.log(cell);

    if (cell.isShown())
    {
        if (cell.isBomb())
        {
            td.addClass('bomb');
        }
        else {
            if (cell.isFlagged())
            {
                td.addClass('flagError');
            }
            else
            {
                if (cell.getValue() === 0)
                {
                    td.addClass('empty');
                }
                else
                {
                    td.addClass('number');
                    td.html(cell.getValue());
                }
            }
        }
    }
    else if (cell.isFlagged())
    {
        td.addClass('flag');
    }
}

function gameOverLose(elem) {
    score(grid.second);
    $('#modal-lost').modal('show');
    bombCells = grid.getBombs();
    bombCells.forEach(updateView);
    stopGame = true;
    return stopGame;
}

function gameOverWin() {
    var i = 0;
    $('td').each(function () {
        if ($(this).hasClass('bomb')) {
            return false
        } else if (!$(this).hasClass('empty') && !$(this).hasClass('number')) {
            i += 1;
        } else if ($(this).hasClass('flag')) {
            i += 1;
        }
    });
    if (i == grid.bombs) {
        score(grid.second);
        $('#modal-win').modal('show');
        stopGame = true;
        return stopGame;
    }
}

function timer(){
  if (!grid.timer) {
    grid.timer = true;
  }
  grid.second++;
  $('#timer').text(grid.second);

  compte=setTimeout(function() {
    if (!stopGame) {
      timer();
    }
  },1000)
}
<commit_msg>désactive les options non personnalisé<commit_after>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', function (event) {
    event.preventDefault()
});

$(document).ready(function () {
    stopGame = false;
    firstClick = true;

    $('select#niveau').change(function(){   // Selection du niveau
      console.log($('select#niveau').val());
      switch ($('select#niveau').val()) {
        case "Facile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(15);
          $('#hauteur').val(15);
          $('#bombs').val(10);
          break;
        case "Moyen":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(15);
          $('#hauteur').val(15);
          $('#bombs').val(20);
          break;
        case "Difficile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(15);
          $('#hauteur').val(15);
          $('#bombs').val(30);
          break;
        case "Personnalisé":
          $('#menu input').prop('disabled', false);
          break;
      }
    });

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('#hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)) {
                if (testParameters(largeur, hauteur, bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {
    if (((largeur * hauteur) / 3) * 2 >= bombs) {
        if (largeur <= 40 && hauteur <= 50) {
            return true;
        }
    }
    return false;
}

function initGameboard() {
    stopGame = false;
    firstClick = true;
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('.reset').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            generateLayout(largeur, hauteur);
            firstClick = true;
            grid = new Grid(largeur, hauteur);
            grid.addBombs(bombs);
            $('#nbbombes').text(grid.flags + ' bombes');

            $('td').each(function () {
                initEvents($(this));
            });

        });
    });

    $('.menu-back').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            $('#largeur').val(largeur);
            $('#hauteur').val(hauteur);
            $('#bombs').val(bombs);

            $('#menu').css('display', 'block');
            $('#gameboard').css('display', 'none');

        });
    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem) {

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {
            console.log('clic du bouton gauche');
            if (!grid.timer) {
              timer();
            }

           if (firstClick)
           {
             if (grid.cells[x][y].isBomb()){
               grid.moveOutBomb(x, y);
             }
             firstClick=false;
           }

            var result = grid.reveal(x, y);

            result.cases.forEach(updateView);

            if (result.lost) {
                gameOverLose();
            }
            else {
                gameOverWin();
            }
        } else if (event.button == 2) {
            console.log('clic du bouton droit');

            grid.toggleFlag(x, y);

            updateView(grid.cells[x][y]);
            $('#nbbombes').text(grid.flags + ' bombes');
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].isShown()) {
                result = grid.quickReveal(x, y);
                console.log(result.cases);

                result.cases.forEach(updateView);

                if (result.lost) {
                    gameOverLose()
                }
            }
        }
    });

}

function updateView(cell)
{
    var td = $('td[data-x="' + cell.x + '"][data-y="' + cell.y + '"]').removeClass();

    //console.log(cell);

    if (cell.isShown())
    {
        if (cell.isBomb())
        {
            td.addClass('bomb');
        }
        else {
            if (cell.isFlagged())
            {
                td.addClass('flagError');
            }
            else
            {
                if (cell.getValue() === 0)
                {
                    td.addClass('empty');
                }
                else
                {
                    td.addClass('number');
                    td.html(cell.getValue());
                }
            }
        }
    }
    else if (cell.isFlagged())
    {
        td.addClass('flag');
    }
}

function gameOverLose(elem) {
    $('#modal-lost').modal('show');
    bombCells = grid.getBombs();
    bombCells.forEach(updateView);
    stopGame = true;
    return stopGame;
}

function gameOverWin() {
    var i = 0;
    $('td').each(function () {
        if ($(this).hasClass('bomb')) {
            return false
        } else if (!$(this).hasClass('empty') && !$(this).hasClass('number')) {
            i += 1;
        } else if ($(this).hasClass('flag')) {
            i += 1;
        }
    });
    if (i == grid.bombs) {
        $('#modal-win').modal('show');
        stopGame = true;
        return stopGame;
    }
}

function timer(){
  if (!grid.timer) {
    grid.timer = true;
  }
  grid.second++;
  $('#timer').text(grid.second);

  compte=setTimeout(function() {
    if (!stopGame) {
      timer();
    }
  },1000)
}
<|endoftext|>


<commit_before>/**
 * ownCloud - owncollab_timetracker
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author andy <info@eventgineering.de>
 * @copyright andy 2016
 */

(function ($, OC) {

	$(document).ready(function () {
		$('#hello').click(function () {
			alert('Hello from your script file');
		});

		$('#echo').click(function () {
			var url = OC.generateUrl('/apps/owncollab_timetracker/echo');
			var data = {
				echo: $('#echo-content').val()
			};

			$.post(url, data).success(function (response) {
				$('#echo-result').text(response.echo);
			});

		});
	});

})(jQuery, OC);

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newEvent: $('#new-event-string').text()
};

// this events object holds all our events
var Events = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._events = [];
    this._activeEvent = undefined;
};

Events.prototype = {
    load: function (id) {
        var self = this;
        this._events.forEach(function (event) {
            if (event.id === id) {
                event.active = true;
                self._activeEvent = event;
            } else {
                event.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeEvent;
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeEvent.id;
        this._events.forEach(function (event, counter) {
            if (event.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active event if necessary
            if (this._activeEvent === this._events[index]) {
                delete this._activeEvent;
            }

            this._events.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (event) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(event)
        }).done(function (event) {
            self._events.push(event);
            self._activeEvent = event;
            self.load(event.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._events;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (events) {
            self._activeEvent = undefined;
            self._events = events;
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, start, end) {
        var event = this.getActive();
        event.title = title;
        event.content = content;
        event.start = start;
        event.end = end;

        return $.ajax({
            url: this._baseUrl + '/' + event.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(event)
        });
    }
};

// this will be the view that is used to update the html
var View = function (events) {
    this._events = events;
};

View.prototype = {
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({event: this._events.getActive()});

        $('#editor').html(html);

        // handle saves
        var textarea = $('#app-content textarea');
        var self = this;
        $('#app-content button').click(function () {
            if ($('#start').attr('placeholder')==''){
                $('#start').val()=$('#start').attr('placeholder');
            }
            console.log('placeholder start value:', $('#start').attr('placeholder'));
            console.log('placeholder start value:', $('#start').attr('placeholder'));
            var content = textarea.val();
            var title = content.split('\n')[0]; // first line is the title
	        var start = $('#start').val();
            var end = $('#end').val();

            self._events.updateActive(title, content, start, end).done(function () {
                self.render();
            }).fail(function () {
                alert('Could not update event, not found');
            });
        });
    },
    renderNavigation: function () {
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({events: this._events.getAll()});

        $('#app-navigation ul').html(html);

        // create a new event
        var self = this;
        $('#new-event').click(function () {
            var event = {
                title: translations.newEvent,
                content: 'content here . . .',
		start: '01.01.2016 00:00:00',
		end: '01.01.2016 00:00:01'
            };

            self._events.create(event).done(function() {
                self.render();
                $('#editor textarea').focus();
            }).fail(function () {
                alert('Could not create event');
            });

        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a event
        $('#app-navigation .event .delete').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._events.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete event, not found');
            });
        });

        // load a event
        $('#app-navigation .event > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            self._events.load(id);
            self.render();
            $('#editor textarea').focus();
        });
    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var events = new Events(OC.generateUrl('/apps/owncollab_timetracker/events'));
var view = new View(events);
events.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load events');
});

});

})(OC, window, jQuery);
<commit_msg>js update<commit_after>/**
 * ownCloud - owncollab_timetracker
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author andy <info@eventgineering.de>
 * @copyright andy 2016
 */

(function ($, OC) {

	$(document).ready(function () {
		$('#hello').click(function () {
			alert('Hello from your script file');
		});

		$('#echo').click(function () {
			var url = OC.generateUrl('/apps/owncollab_timetracker/echo');
			var data = {
				echo: $('#echo-content').val()
			};

			$.post(url, data).success(function (response) {
				$('#echo-result').text(response.echo);
			});

		});
	});

})(jQuery, OC);

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newEvent: $('#new-event-string').text()
};

// this events object holds all our events
var Events = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._events = [];
    this._activeEvent = undefined;
};

Events.prototype = {
    load: function (id) {
        var self = this;
        this._events.forEach(function (event) {
            if (event.id === id) {
                event.active = true;
                self._activeEvent = event;
            } else {
                event.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeEvent;
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeEvent.id;
        this._events.forEach(function (event, counter) {
            if (event.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active event if necessary
            if (this._activeEvent === this._events[index]) {
                delete this._activeEvent;
            }

            this._events.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (event) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(event)
        }).done(function (event) {
            self._events.push(event);
            self._activeEvent = event;
            self.load(event.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._events;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (events) {
            self._activeEvent = undefined;
            self._events = events;
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, start, end) {
        var event = this.getActive();
        event.title = title;
        event.content = content;
        event.start = start;
        event.end = end;

        return $.ajax({
            url: this._baseUrl + '/' + event.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(event)
        });
    }
};

// this will be the view that is used to update the html
var View = function (events) {
    this._events = events;
};

View.prototype = {
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({event: this._events.getActive()});

        $('#editor').html(html);

        // handle saves
        var textarea = $('#app-content textarea');
        var self = this;
        $('#app-content button').click(function () {
            if ($('#start').attr('placeholder')==''){
                var start = $('#start').attr('placeholder');
            }
            else{
                var start = $('#start').val();
            }
            console.log('placeholder start value:', $('#start').attr('placeholder'));
            console.log(' start value:', start;
            var content = textarea.val();
            var title = content.split('\n')[0]; // first line is the title

            var end = $('#end').val();

            self._events.updateActive(title, content, start, end).done(function () {
                self.render();
            }).fail(function () {
                alert('Could not update event, not found');
            });
        });
    },
    renderNavigation: function () {
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({events: this._events.getAll()});

        $('#app-navigation ul').html(html);

        // create a new event
        var self = this;
        $('#new-event').click(function () {
            var event = {
                title: translations.newEvent,
                content: 'content here . . .',
		start: '01.01.2016 00:00:00',
		end: '01.01.2016 00:00:01'
            };

            self._events.create(event).done(function() {
                self.render();
                $('#editor textarea').focus();
            }).fail(function () {
                alert('Could not create event');
            });

        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a event
        $('#app-navigation .event .delete').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._events.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete event, not found');
            });
        });

        // load a event
        $('#app-navigation .event > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            self._events.load(id);
            self.render();
            $('#editor textarea').focus();
        });
    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var events = new Events(OC.generateUrl('/apps/owncollab_timetracker/events'));
var view = new View(events);
events.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load events');
});

});

})(OC, window, jQuery);
<|endoftext|>


<commit_before>import {
  app,
  shell,
  ipcMain,
  BrowserWindow,
  dialog,
  globalShortcut,
} from 'electron';
import path from 'path';
import rimraf from 'rimraf';
import queue from 'async/queue';
import Store from 'electron-store';
import { GitProcess } from 'dugite';
import searchQuery from 'search-query-parser';
import utilsGitLib from './git';
import utilsTrayLib from './tray';
import utilsWindowLib from './window';
import DbUtils from './db';
import GitUniversal from '../../universal/git';
import pkg from '../../../package.json';

const git = GitProcess.exec;

export class Events {
  constructor (options = {}) {
    const opt = {
      queueConcurrency: 3,
      settingsWindow: null,
      window: null
    };

    this.options = Object.assign({}, opt, options);

    this._window = this.options.window;
    this.shouldQuit = false;
    this.appIcon = null;
    this.fetchQ = null;

    this.utilsGit = utilsGitLib({
      baseCloneDir: global.baseCloneDir,
      window: this.window
    });

    this.utilsTray = utilsTrayLib({
      trayName: pkg.displayName,
      window: this.window
    });

    this.utilsWindow = utilsWindowLib({
      utils: {
        git: this.utilsGit,
        tray: this.utilsTray
      }
    });

    this.store = new Store();
    this.utilsDb = DbUtils({});
    this.gituni = GitUniversal();
  }

  get window () {
    return this._window;
  }

  set window (value) {
    this._window = value;
  }

  init () {
    this.initIpc();
    this.initApp();
  }

  initApp () {
    this.appReady();
    this.appWindowAllClosed();
    this.appActivate();
    this.appOpenUrl();
  }

  initIpc () {
    this.fetchQ = this.fetchQueue();
    this.ipcVueLog();
    this.ipcStore();
    this.ipcStoreGet();
    this.ipcStoreSet();
    this.ipcStoreHas();
    this.ipcDbSearch();
    this.ipcRemoveEntry();
    this.ipcGitPillage();
    this.ipcGitClone();
    this.ipcGitCmd();
    this.ipcGitFetchStatus();
    this.ipcGitStatus();
    this.ipcOpenFolder();
    this.ipcShowFolder();
    this.ipcOpenSettingsWindow();
    this.ipcOpenUrl();
    this.ipcSelectDir();
    this.ipcShowTray();
  }

  makeSingleInstance () {
      this.shouldQuit = app.makeSingleInstance((commandLine) => {
        const cmdArgs = this.gituni.parseUrlArgs(commandLine);

        if (this.window) {
          this.window.webContents.send('log', 'shouldQuit', [cmdArgs, this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)]);

          if (this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)) {
            this.utilsGit.clone(cmdArgs.repoUrl);
          }

          if (this.window.isVisible()) {
            this.window.focus();
          }
        }
        return true;
      });
      if (process.platform !== 'win32' && this.shouldQuit) {
        app.exit();
      }

    if (process.platform === 'win32') {
      if (this.shouldQuit) {
        app.exit();
      }
    }
  }

  fetchQueue () {
    const q = queue(({ repo, event }, callback) => {
      this.utilsGit.fetchStatus(repo).then((res) => {
        if (res) {
          event.sender.send(`repo-fetch-status-${repo._id}`, res.status);
        }
        callback();
      });
    }, this.options.queueConcurrency);

    q.drain = () => {
    };

    return q;
  }

  pillageQueue (target) {
    const group = target.owner;
    const folder = path.join(global.baseCloneDir, target.owner);

    const q = queue(async ({ repo, event }, callback) => {
      await this.utilsGit.clone(repo.clone_url, { pillaging: true })
        .then((res) => {
          event.sender.send('log', 'pillage cloned', { group, repo, res });
          callback();
        })
        .catch(callback);
    }, this.options.queueConcurrency);

    q.drain = () => {
      this.window.webContents.send('notify', target.owner, {
        body: 'Pillaged!',
        repo: target.url,
        folder: folder,
        pillage: true
      });
    };

    return q;
  }

  toggleTray (vis) {
    if (!vis) {
      this.appIcon.destroy();
    } else {
      this.utilsTray.window = this.window;
      this.appIcon = this.utilsTray.addIcon();
    }
  }

  toggleDock (vis) {
    if (process.platform === 'win32') {
      return;
    }
    if (!vis) {
      app.dock.hide();
    } else {
      app.dock.show();
    }
  }

  ipcVueLog () {
    ipcMain.on('vue-log', (event) => {
      this.utilsDb.get().then((docs) => {
        event.sender.send('local-list', docs);
      });
    });
  }

  ipcStore () {
    ipcMain.on('store', (event) => {
      event.sender.send('store:res', this.store.store);
    });
  }

  ipcStoreGet () {
    ipcMain.on('store:get', (event, key) => {
      event.sender.send('store:get:res', this.store.get(key));
    });
  }

  ipcStoreSet () {
    ipcMain.on('store:set', (event, key, item) => {
      if (typeof item !== 'undefined') {
        event.sender.send('store:set:res', this.store.set(key, item));
        if (key === 'win.showTray') {
          this.toggleTray(item);
        }
        if (key === 'win.showDock') {
          this.toggleDock(item);
        }
      } else if (typeof key === 'object') {
        event.sender.send('store:set:res', this.store.set(key));
      }
    });
  }

  ipcStoreHas () {
    ipcMain.on('store:has', (event, key) => {
      event.sender.send('store:has:res', this.store.has(key));
    });
  }

  ipcDbSearch () {
    ipcMain.on('db-search', (event, query) => {
      const searchOptions = {
        keywords: ['slug', 'branch', 'name', 'owner', 'source', 'url', 'createdAt', 'updatedAt'],
        ranges: ['createdAt', 'updatedAt']
      };
      let parsedQuery = searchQuery.parse(query, searchOptions);
      if (typeof parsedQuery === 'string') {
        if (parsedQuery !== '') {
          parsedQuery = { slug: parsedQuery };
        } else {
          parsedQuery = {};
        }
      }
      const { offsets, exclude, ...pq } = parsedQuery;
      this.utilsDb
        .get(toMongo(pq))
        .then((docs) => {
          event.sender.send('reset-list', docs);
        });
    });
  }

  ipcRemoveEntry () {
    ipcMain.on('remove-entry', (event, entry) => {
      const remEntry = this.utilsDb.removeById(entry._id);
      remEntry.then(() => {
        rimraf(entry.folder, () => {
          this.utilsDb.get().then((docs) => {
            event.sender.send('reset-list', docs);
          });
        });
      });
    });
  }

  ipcGitStatus () {
    ipcMain.on('git-status', async (event, folder) => {
      this.utilsGit.status({ folder });
    });
  }

  ipcGitFetchStatus () {
    ipcMain.on('git-fetch-status', async (event, repo) => {
      this.fetchQ.push({ repo, event }, (err) => {});
    });
  }

  ipcGitPillage () {
    ipcMain.on('git-pillage', async (event, target) => {
      if (target.source === 'github.com') {
        const pillageQ = this.pillageQueue(target);
        await this.utilsGit.pillage(target)
          .then((result) => {
            if (result) {
              const ledger = result.data.filter((repo) => {
                return !this.store.get('pillage.forked') && !repo.fork;
              });
              event.sender.send('log', 'git-pillage-res', [ledger, result.data]);

              ledger.forEach((repo) => {
                pillageQ.push({ repo, event, target }, (err) => {});
              });
            }
          });
      } else {
        // Implement GitLab and BitBucket API's
      }
    });
  }

  ipcGitClone () {
    ipcMain.on('git-clone', async (event, repoUrl) => {
      if (this.gituni.gitUrlRegexTest.test(repoUrl)) {
        this.utilsGit.clone(repoUrl);
      }
    });
  }

  ipcGitCmd () {
    ipcMain.on('git-cmd', async (event, cmd, repo) => {
      const folder = repo.folder;
      let directory = folder;
      let options = {};
      let cmdArgs = {};
      const gitArgs = [];

      gitArgs.push(cmd);
      if (['fetch', 'pull'].indexOf(cmd) > -1) {
        gitArgs.push('--progress');
        options = this.utilsGit.progressCallback(repo);
        event.sender.send('fetch-start', {
          repo: repo,
          folder: repo.folder
        });
      }
      if (cmd === 'clone') {
        cmdArgs = this.gituni.parseUrl(folder);
        gitArgs.push(folder);
        directory = path.join(global.baseCloneDir, cmdArgs.repoObj.owner, cmdArgs.repoObj.name);
        options = {
          env: {},
          processCallback: this.utilsGit.progressCallback().processCallback
        };
      }

      const result = await git(gitArgs, directory, options);
      if (result.exitCode === 0) {
        const output = result.stdout;
        event.sender.send('log', 'git', [folder, output]);
        if (cmd === 'branch') {
          event.sender.send('git-current-branch', output);
        }
        if (cmd === 'clone') {
          const repoObj = {
            slug: cmdArgs.repoObj.owner + '/' + cmdArgs.repoObj.name,
            owner: cmdArgs.repoObj.owner,
            name: cmdArgs.repoObj.name,
            source: cmdArgs.repoObj.source,
            url: cmdArgs.repoUrl,
            originalUrl: cmdArgs.originalUrl,
            folder: directory,
            createdAt: new Date(),
            updatedAt: new Date()
          };

          this.utilsDb.insert(repoObj, () => {});
        }
        if (cmd === 'pull') {
          this.utilsDb.updateById(repo._id, {
            branchAheadBehind: { ahead: 0, behind: 0 },
          }, 'updatedAt');
          event.sender.send(`repo-pull-${repo._id}`, result);
        }
      } else {
        const error = result.stderr;
        event.sender.send('err', [folder, error]);
      }
    });
  }

  ipcOpenFolder () {
    ipcMain.on('open-folder', (event, folder) => {
      const opened = shell.openItem(folder);
      event.sender.send('log', 'open-folder', [folder, opened]);
    });
  }

  ipcShowFolder () {
    ipcMain.on('show-folder', (event, folder) => {
      const opened = shell.showItemInFolder(folder);
      event.sender.send('log', 'show-folder', [folder, opened]);
    });
  }

  ipcOpenUrl () {
    ipcMain.on('open-url', (event, url) => {
      shell.openExternal(url);
    });
  }

  ipcSelectDir () {
    ipcMain.on('select-dir', (event) => {
      const selectedDir = dialog.showOpenDialog(this.window, {
        properties: ['openDirectory']
      });
      if (selectedDir && selectedDir.length > 0) {
        event.sender.send('selected-folder', selectedDir[0]);

        global.baseCloneDir = selectedDir[0];

        this.utilsGit = utilsGitLib({
          baseCloneDir: global.baseCloneDir,
          window: this.window
        });
      }
    });
  }

  ipcOpenSettingsWindow () {
    ipcMain.on('open-settings-window', function () {
      if (this.options.settingsWindow) {
        return;
      }

      const settingsWindowOptions = {
        frame: false,
        height: 580,
        width: 440,
        minWidth: 440,
        minHeight: 580,
        resizable: true,
        minimizable: false,
        maximizable: false,
        useContentSize: true,
        backgroundColor: '#232421',
        parent: this.window || null,
        modal: true,
        show: false
      };

      this.options.settingsWindow = new BrowserWindow(settingsWindowOptions);
      const settingsURL = process.env.NODE_ENV === 'development'
          ? 'http://localhost:9080/#/settings'
          : `file://${__dirname}/index.html#settings`;

      this.options.settingsWindow.loadURL(settingsURL);
      this.options.settingsWindow.setMenuBarVisibility(false);

      this.options.settingsWindow.on('closed', function () {
        this.options.settingsWindow = null;
      });

      this.options.settingsWindow.once('ready-to-show', () => {
        this.options.settingsWindow.show();
      });
    });
  }

  ipcShowTray () {
    ipcMain.on('show-tray', (event, vis) => {
      this.toggleTray(vis);
    });
  }

  appBeforeQuit () {
    app.on('before-quit', () => {
      // this.quitting = true;
    });
  }

  appReady () {
    app.on('ready', () => {
      this.window = this.utilsWindow.create(this.appIcon);
      this.utilsGit.window = this.utilsTray.window = this.window;

      globalShortcut.register('CmdOrCtrl+Q', () => {
        app.exit();
      });

      if (this.store.get('win.showTray')) {
        this.toggleTray(this.store.get('win.showTray'));
      }

      this.toggleDock(this.store.get('win.showDock'));
    });
  }

  appWindowAllClosed () {
    app.on('window-all-closed', () => {
      if (this.appIcon) {
        this.appIcon.destroy();
      }
      app.quit();
    });
  }

  appActivate () {
    app.on('activate', () => {
      if (this.window === null) {
        this.window = this.utilsWindow.create(this.appIcon);
        this.utilsGit.window = this.utilsTray.window = this.window;

        if (this.store.get('win.showTray')) {
          this.toggleTray(this.store.get('win.showTray'));
        }
      }
      if (this.window) {
        this.window.show();
      }
    });
  }

  appOpenUrl () {
    app.on('open-url', (event, url) => {
      event.preventDefault();
      const cmdArgs = this.gituni.parseUrl(url);
      if (this.window) {
        this.window.webContents.send('log', 'open-url', [event, url, cmdArgs, this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)]);

        if (this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)) {
          this.utilsGit.clone(cmdArgs.repoUrl);
        }
      }
    });
  }
}

function toMongo (query) {
  let newQuery = {};
  if (typeof query === 'object') {
    newQuery = Object.assign({}, query);
    Object.entries(query).forEach(([key, value]) => {
      if (typeof value === 'string') {
        newQuery[key] = new RegExp(value, 'gi');
      }
    });
  }
  return newQuery;
}

export default function (opts) {
  return new Events(opts);
}<commit_msg>fix(events): Fix eslint error in events<commit_after>import {
  app,
  shell,
  ipcMain,
  BrowserWindow,
  dialog,
  globalShortcut,
} from 'electron';
import path from 'path';
import rimraf from 'rimraf';
import queue from 'async/queue';
import Store from 'electron-store';
import { GitProcess } from 'dugite';
import searchQuery from 'search-query-parser';
import utilsGitLib from './git';
import utilsTrayLib from './tray';
import utilsWindowLib from './window';
import DbUtils from './db';
import GitUniversal from '../../universal/git';
import pkg from '../../../package.json';

const git = GitProcess.exec;

export class Events {
  constructor (options = {}) {
    const opt = {
      queueConcurrency: 3,
      settingsWindow: null,
      window: null
    };

    this.options = Object.assign({}, opt, options);

    this._window = this.options.window;
    this.shouldQuit = false;
    this.appIcon = null;
    this.fetchQ = null;

    this.utilsGit = utilsGitLib({
      baseCloneDir: global.baseCloneDir,
      window: this.window
    });

    this.utilsTray = utilsTrayLib({
      trayName: pkg.displayName,
      window: this.window
    });

    this.utilsWindow = utilsWindowLib({
      utils: {
        git: this.utilsGit,
        tray: this.utilsTray
      }
    });

    this.store = new Store();
    this.utilsDb = DbUtils({});
    this.gituni = GitUniversal();
  }

  get window () {
    return this._window;
  }

  set window (value) {
    this._window = value;
  }

  init () {
    this.initIpc();
    this.initApp();
  }

  initApp () {
    this.appReady();
    this.appWindowAllClosed();
    this.appActivate();
    this.appOpenUrl();
  }

  initIpc () {
    this.fetchQ = this.fetchQueue();
    this.ipcVueLog();
    this.ipcStore();
    this.ipcStoreGet();
    this.ipcStoreSet();
    this.ipcStoreHas();
    this.ipcDbSearch();
    this.ipcRemoveEntry();
    this.ipcGitPillage();
    this.ipcGitClone();
    this.ipcGitCmd();
    this.ipcGitFetchStatus();
    this.ipcGitStatus();
    this.ipcOpenFolder();
    this.ipcShowFolder();
    this.ipcOpenSettingsWindow();
    this.ipcOpenUrl();
    this.ipcSelectDir();
    this.ipcShowTray();
  }

  makeSingleInstance () {
      this.shouldQuit = app.makeSingleInstance((commandLine) => {
        const cmdArgs = this.gituni.parseUrlArgs(commandLine);

        if (this.window) {
          this.window.webContents.send('log', 'shouldQuit', [cmdArgs, this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)]);

          if (this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)) {
            this.utilsGit.clone(cmdArgs.repoUrl);
          }

          if (this.window.isVisible()) {
            this.window.focus();
          }
        }
        return true;
      });
      if (process.platform !== 'win32' && this.shouldQuit) {
        app.exit();
      }

    if (process.platform === 'win32') {
      if (this.shouldQuit) {
        app.exit();
      }
    }
  }

  fetchQueue () {
    const q = queue(({ repo, event }, callback) => {
      this.utilsGit.fetchStatus(repo).then((res) => {
        if (res) {
          event.sender.send(`repo-fetch-status-${repo._id}`, res.status);
        }
        callback();
      });
    }, this.options.queueConcurrency);

    q.drain = () => {
    };

    return q;
  }

  pillageQueue (target) {
    const group = target.owner;
    const folder = path.join(global.baseCloneDir, target.owner);

    const q = queue(async ({ repo, event }, callback) => {
      await this.utilsGit.clone(repo.clone_url, { pillaging: true })
        .then((res) => {
          event.sender.send('log', 'pillage cloned', { group, repo, res });
          callback();
        })
        .catch(callback);
    }, this.options.queueConcurrency);

    q.drain = () => {
      this.window.webContents.send('notify', target.owner, {
        body: 'Pillaged!',
        repo: target.url,
        folder: folder,
        pillage: true
      });
    };

    return q;
  }

  toggleTray (vis) {
    if (!vis) {
      this.appIcon.destroy();
    } else {
      this.utilsTray.window = this.window;
      this.appIcon = this.utilsTray.addIcon();
    }
  }

  toggleDock (vis) {
    if (process.platform === 'win32') {
      return;
    }
    if (!vis) {
      app.dock.hide();
    } else {
      app.dock.show();
    }
  }

  ipcVueLog () {
    ipcMain.on('vue-log', (event) => {
      this.utilsDb.get().then((docs) => {
        event.sender.send('local-list', docs);
      });
    });
  }

  ipcStore () {
    ipcMain.on('store', (event) => {
      event.sender.send('store:res', this.store.store);
    });
  }

  ipcStoreGet () {
    ipcMain.on('store:get', (event, key) => {
      event.sender.send('store:get:res', this.store.get(key));
    });
  }

  ipcStoreSet () {
    ipcMain.on('store:set', (event, key, item) => {
      if (typeof item !== 'undefined') {
        event.sender.send('store:set:res', this.store.set(key, item));
        if (key === 'win.showTray') {
          this.toggleTray(item);
        }
        if (key === 'win.showDock') {
          this.toggleDock(item);
        }
      } else if (typeof key === 'object') {
        event.sender.send('store:set:res', this.store.set(key));
      }
    });
  }

  ipcStoreHas () {
    ipcMain.on('store:has', (event, key) => {
      event.sender.send('store:has:res', this.store.has(key));
    });
  }

  ipcDbSearch () {
    ipcMain.on('db-search', (event, query) => {
      const searchOptions = {
        keywords: ['slug', 'branch', 'name', 'owner', 'source', 'url', 'createdAt', 'updatedAt'],
        ranges: ['createdAt', 'updatedAt']
      };
      let parsedQuery = searchQuery.parse(query, searchOptions);
      if (typeof parsedQuery === 'string') {
        if (parsedQuery !== '') {
          parsedQuery = { slug: parsedQuery };
        } else {
          parsedQuery = {};
        }
      }
      const { offsets, exclude, ...pq } = parsedQuery; // eslint-disable-line
      this.utilsDb
        .get(toMongo(pq))
        .then((docs) => {
          event.sender.send('reset-list', docs);
        });
    });
  }

  ipcRemoveEntry () {
    ipcMain.on('remove-entry', (event, entry) => {
      const remEntry = this.utilsDb.removeById(entry._id);
      remEntry.then(() => {
        rimraf(entry.folder, () => {
          this.utilsDb.get().then((docs) => {
            event.sender.send('reset-list', docs);
          });
        });
      });
    });
  }

  ipcGitStatus () {
    ipcMain.on('git-status', async (event, folder) => {
      this.utilsGit.status({ folder });
    });
  }

  ipcGitFetchStatus () {
    ipcMain.on('git-fetch-status', async (event, repo) => {
      this.fetchQ.push({ repo, event }, (err) => {});
    });
  }

  ipcGitPillage () {
    ipcMain.on('git-pillage', async (event, target) => {
      if (target.source === 'github.com') {
        const pillageQ = this.pillageQueue(target);
        await this.utilsGit.pillage(target)
          .then((result) => {
            if (result) {
              const ledger = result.data.filter((repo) => {
                return !this.store.get('pillage.forked') && !repo.fork;
              });
              event.sender.send('log', 'git-pillage-res', [ledger, result.data]);

              ledger.forEach((repo) => {
                pillageQ.push({ repo, event, target }, (err) => {});
              });
            }
          });
      } else {
        // Implement GitLab and BitBucket API's
      }
    });
  }

  ipcGitClone () {
    ipcMain.on('git-clone', async (event, repoUrl) => {
      if (this.gituni.gitUrlRegexTest.test(repoUrl)) {
        this.utilsGit.clone(repoUrl);
      }
    });
  }

  ipcGitCmd () {
    ipcMain.on('git-cmd', async (event, cmd, repo) => {
      const folder = repo.folder;
      let directory = folder;
      let options = {};
      let cmdArgs = {};
      const gitArgs = [];

      gitArgs.push(cmd);
      if (['fetch', 'pull'].indexOf(cmd) > -1) {
        gitArgs.push('--progress');
        options = this.utilsGit.progressCallback(repo);
        event.sender.send('fetch-start', {
          repo: repo,
          folder: repo.folder
        });
      }
      if (cmd === 'clone') {
        cmdArgs = this.gituni.parseUrl(folder);
        gitArgs.push(folder);
        directory = path.join(global.baseCloneDir, cmdArgs.repoObj.owner, cmdArgs.repoObj.name);
        options = {
          env: {},
          processCallback: this.utilsGit.progressCallback().processCallback
        };
      }

      const result = await git(gitArgs, directory, options);
      if (result.exitCode === 0) {
        const output = result.stdout;
        event.sender.send('log', 'git', [folder, output]);
        if (cmd === 'branch') {
          event.sender.send('git-current-branch', output);
        }
        if (cmd === 'clone') {
          const repoObj = {
            slug: cmdArgs.repoObj.owner + '/' + cmdArgs.repoObj.name,
            owner: cmdArgs.repoObj.owner,
            name: cmdArgs.repoObj.name,
            source: cmdArgs.repoObj.source,
            url: cmdArgs.repoUrl,
            originalUrl: cmdArgs.originalUrl,
            folder: directory,
            createdAt: new Date(),
            updatedAt: new Date()
          };

          this.utilsDb.insert(repoObj, () => {});
        }
        if (cmd === 'pull') {
          this.utilsDb.updateById(repo._id, {
            branchAheadBehind: { ahead: 0, behind: 0 },
          }, 'updatedAt');
          event.sender.send(`repo-pull-${repo._id}`, result);
        }
      } else {
        const error = result.stderr;
        event.sender.send('err', [folder, error]);
      }
    });
  }

  ipcOpenFolder () {
    ipcMain.on('open-folder', (event, folder) => {
      const opened = shell.openItem(folder);
      event.sender.send('log', 'open-folder', [folder, opened]);
    });
  }

  ipcShowFolder () {
    ipcMain.on('show-folder', (event, folder) => {
      const opened = shell.showItemInFolder(folder);
      event.sender.send('log', 'show-folder', [folder, opened]);
    });
  }

  ipcOpenUrl () {
    ipcMain.on('open-url', (event, url) => {
      shell.openExternal(url);
    });
  }

  ipcSelectDir () {
    ipcMain.on('select-dir', (event) => {
      const selectedDir = dialog.showOpenDialog(this.window, {
        properties: ['openDirectory']
      });
      if (selectedDir && selectedDir.length > 0) {
        event.sender.send('selected-folder', selectedDir[0]);

        global.baseCloneDir = selectedDir[0];

        this.utilsGit = utilsGitLib({
          baseCloneDir: global.baseCloneDir,
          window: this.window
        });
      }
    });
  }

  ipcOpenSettingsWindow () {
    ipcMain.on('open-settings-window', function () {
      if (this.options.settingsWindow) {
        return;
      }

      const settingsWindowOptions = {
        frame: false,
        height: 580,
        width: 440,
        minWidth: 440,
        minHeight: 580,
        resizable: true,
        minimizable: false,
        maximizable: false,
        useContentSize: true,
        backgroundColor: '#232421',
        parent: this.window || null,
        modal: true,
        show: false
      };

      this.options.settingsWindow = new BrowserWindow(settingsWindowOptions);
      const settingsURL = process.env.NODE_ENV === 'development'
          ? 'http://localhost:9080/#/settings'
          : `file://${__dirname}/index.html#settings`;

      this.options.settingsWindow.loadURL(settingsURL);
      this.options.settingsWindow.setMenuBarVisibility(false);

      this.options.settingsWindow.on('closed', function () {
        this.options.settingsWindow = null;
      });

      this.options.settingsWindow.once('ready-to-show', () => {
        this.options.settingsWindow.show();
      });
    });
  }

  ipcShowTray () {
    ipcMain.on('show-tray', (event, vis) => {
      this.toggleTray(vis);
    });
  }

  appBeforeQuit () {
    app.on('before-quit', () => {
      // this.quitting = true;
    });
  }

  appReady () {
    app.on('ready', () => {
      this.window = this.utilsWindow.create(this.appIcon);
      this.utilsGit.window = this.utilsTray.window = this.window;

      globalShortcut.register('CmdOrCtrl+Q', () => {
        app.exit();
      });

      if (this.store.get('win.showTray')) {
        this.toggleTray(this.store.get('win.showTray'));
      }

      this.toggleDock(this.store.get('win.showDock'));
    });
  }

  appWindowAllClosed () {
    app.on('window-all-closed', () => {
      if (this.appIcon) {
        this.appIcon.destroy();
      }
      app.quit();
    });
  }

  appActivate () {
    app.on('activate', () => {
      if (this.window === null) {
        this.window = this.utilsWindow.create(this.appIcon);
        this.utilsGit.window = this.utilsTray.window = this.window;

        if (this.store.get('win.showTray')) {
          this.toggleTray(this.store.get('win.showTray'));
        }
      }
      if (this.window) {
        this.window.show();
      }
    });
  }

  appOpenUrl () {
    app.on('open-url', (event, url) => {
      event.preventDefault();
      const cmdArgs = this.gituni.parseUrl(url);
      if (this.window) {
        this.window.webContents.send('log', 'open-url', [event, url, cmdArgs, this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)]);

        if (this.gituni.gitUrlRegexTest.test(cmdArgs.repoUrl)) {
          this.utilsGit.clone(cmdArgs.repoUrl);
        }
      }
    });
  }
}

function toMongo (query) {
  let newQuery = {};
  if (typeof query === 'object') {
    newQuery = Object.assign({}, query);
    Object.entries(query).forEach(([key, value]) => {
      if (typeof value === 'string') {
        newQuery[key] = new RegExp(value, 'gi');
      }
    });
  }
  return newQuery;
}

export default function (opts) {
  return new Events(opts);
}<|endoftext|>


<commit_before>

$(document).ready(function(){

    // Controla a interação do botão Seguir para o Topo

    jQuery(window).load(function() {
        jQuery("#backtotop").hide().removeAttr("href");
        if (jQuery(window).scrollTop() != "0")
            jQuery("#backtotop").fadeIn("slow")
        var scrollDiv = jQuery("#backtotop");
        jQuery(window).scroll(function(){
            if (jQuery(window).scrollTop() == "0")
                jQuery(scrollDiv).fadeOut("slow")
            else
                jQuery(scrollDiv).fadeIn("slow")
        });
    });

    $('#backtotop').click(function() {
        $('body,html').animate({scrollTop:0},2500,"easeOutQuart");
    });

});
<commit_msg>Acrescenta uma função para ajustar conteúdos no grid, extendendo o jQuery.<commit_after>

$(document).ready(function(){

    // Controla a interação do botão Seguir para o Topo

    jQuery(window).load(function() {
        jQuery("#backtotop").hide().removeAttr("href");
        if (jQuery(window).scrollTop() != "0")
            jQuery("#backtotop").fadeIn("slow")
        var scrollDiv = jQuery("#backtotop");
        jQuery(window).scroll(function(){
            if (jQuery(window).scrollTop() == "0")
                jQuery(scrollDiv).fadeOut("slow")
            else
                jQuery(scrollDiv).fadeIn("slow")
        });
    });

    $('#backtotop').click(function() {
        $('body,html').animate({scrollTop:0},2500,"easeOutQuart");
    });

    /**
     * Corrige a altura da caixa de elementos HTML para se enquadrar no grid
     * @author Vinicius Braga
     * @link
     */

    $.fn.fixHeight = function(){

        $.each( $(this), function() {
            var new_box_height = 30 * Math.ceil( $(this).outerHeight() / 30 ) ;
            $(this).css("min-height", new_box_height );
            // console.log( 'new_box_height: ' + new_box_height );
        });

    };

    // Aplica a correção do grid para elementos da página.
    setTimeout( function(){
        $('.main figure').fixHeight();
        $( ".crayon-syntax" ).wrap( "

" );
        $('.frame-crayon-syntax').fixHeight();
        } , 1000);

    // Aplica a correção do grid para a área de comentários depois de 5s.
    setTimeout( function(){
        $('#frame-comment').fixHeight();
        } , 5000);

});
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        document.getElementById("paintbtn").onclick = paint;

        function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
        function toHex(n) {
            n = parseInt(n,10);
            if (isNaN(n)) return "00";
            n = Math.max(0,Math.min(n,255));
            return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
        }

        function floodfill(node, targetcolor, replacementcolor, pathWidth, pathHeight){
            var nodeimgdata = c.getImageData(node.x,node.y,1,1).data;
            var nodecolor = "#" + rgbToHex(nodeimgdata[0],nodeimgdata[1],nodeimgdata[2]);

            if(nodecolor == replacementcolor){
                return;
            }
            if(targetcolor == replacementcolor){
                return;
            }

            if(nodecolor != targetcolor){
                return;
            }
            if(node.x < 0 || node.x >= pathWidth * 30 || node.y < 0 || node.y >= pathHeight*30){
                return;
            }

            c.fillStyle = replacementcolor;
            c.fillRect(node.x, node.y, 8, 8);
            var westnode = {
                x:0,
                y:0
            };
            westnode.x = node.x - 8;
            westnode.y = node.y;
            var eastnode = {
                x:0,
                y:0
            };
            eastnode.x = node.x + 8;
            eastnode.y = node.y
            var northnode = {
                x:0,
                y:0
            };
            northnode.x = node.x;
            northnode.y = node.y - 8;
            var southnode = {
                x:0,
                y:0
            };
            southnode.x = node.x;
            southnode.y = node.y + 8;
            floodfill(westnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(eastnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(northnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(southnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            return;

        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isvisited: 0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           var branch = 0;
           var branchpoint = {
               x: -1,
               y: -1
           };
           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + movedirX*l + 8, movingpointold.y*30 + movedirY*l + 8, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               if( i >= Math.floor(walkArray.length/2) && branch < 1){
                   branchpoint.x = movingpoint.x;
                   branchpoint.y = movingpoint.y;

                   branch++;
               }

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            //c.fillStyle = "#33CC33";
            c.fillStyle = "#FFFFFF";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            //c.fillStyle = "#CC0000";
            c.fillStyle = "#FFFFFF";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            var startnode = {
                x:0,
                y:0
            };
            startnode.x = startpoint.x*30;
            startnode.y = startpoint.y*30;
            //floodfill(startnode,"#FFFFFF","#0099FF", pathWidth, pathHeight);
            var imgdata = c.getImageData(0,0,1,1).data;

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            c.fillStyle = "#CC66FF";
            c.fillRect(branchpoint.x*30, branchpoint.y*30, 24, 24);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        document.getElementById("paintbtn").onclick = paint;

        function rgbToHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
        function toHex(n) {
            n = parseInt(n,10);
            if (isNaN(n)) return "00";
            n = Math.max(0,Math.min(n,255));
            return "0123456789ABCDEF".charAt((n-n%16)/16) + "0123456789ABCDEF".charAt(n%16);
        }

        function floodfill(node, targetcolor, replacementcolor, pathWidth, pathHeight){
            var nodeimgdata = c.getImageData(node.x,node.y,1,1).data;
            var nodecolor = "#" + rgbToHex(nodeimgdata[0],nodeimgdata[1],nodeimgdata[2]);

            if(nodecolor == replacementcolor){
                return;
            }
            if(targetcolor == replacementcolor){
                return;
            }

            if(nodecolor != targetcolor){
                return;
            }
            if(node.x < 0 || node.x >= pathWidth * 30 || node.y < 0 || node.y >= pathHeight*30){
                return;
            }

            c.fillStyle = replacementcolor;
            c.fillRect(node.x, node.y, 8, 8);
            var westnode = {
                x:0,
                y:0
            };
            westnode.x = node.x - 8;
            westnode.y = node.y;
            var eastnode = {
                x:0,
                y:0
            };
            eastnode.x = node.x + 8;
            eastnode.y = node.y
            var northnode = {
                x:0,
                y:0
            };
            northnode.x = node.x;
            northnode.y = node.y - 8;
            var southnode = {
                x:0,
                y:0
            };
            southnode.x = node.x;
            southnode.y = node.y + 8;
            floodfill(westnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(eastnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(northnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            floodfill(southnode, targetcolor, replacementcolor, pathWidth, pathHeight);
            return;

        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * (pw/2) + 1) );
            var randh = Math.floor((Math.random() * (ph/2) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isvisited: 0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           var branch = 0;
           var branchpoint = {
               x: -1,
               y: -1
           };
           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + movedirX*l + 8, movingpointold.y*30 + movedirY*l + 8, 6, 6);
               }
               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
               }else{
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
               }else{
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
               }
               nodemap[movingpoint.x][movingpoint.y].isVisited = 1
               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               if( i >= Math.floor(walkArray.length/2) && branch < 1){
                   branchpoint.x = movingpoint.x;
                   branchpoint.y = movingpoint.y;

                   branch++;
               }

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - 6, roomDim[1]*30 - 6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            //c.fillStyle = "#33CC33";
            c.fillStyle = "#FFFFFF";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            //c.fillStyle = "#CC0000";
            c.fillStyle = "#FFFFFF";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            var startnode = {
                x:0,
                y:0
            };
            startnode.x = startpoint.x*30;
            startnode.y = startpoint.y*30;
            //floodfill(startnode,"#FFFFFF","#0099FF", pathWidth, pathHeight);
            var imgdata = c.getImageData(0,0,1,1).data;

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);

            c.fillStyle = "#CC66FF";
            c.fillRect(branchpoint.x*30, branchpoint.y*30, 24, 24);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>/* Author:

*/

<commit_msg>Added basic mongodb connection script<commit_after>/* Author:

*/
(function ($) {
	var serviceUrl = 'http://localhost:27080/';
	$(function () {
		$.post(
			serviceUrl + "_connect",
			"server=http://localhost:27017",
			function (result) {
				log(result);
				$('body').append($("div").text(result));
			}
		});
	})
}(jQuery));

<|endoftext|>


<commit_before>const tabs = document.getElementById("tab-wrap").children,
    tabActive = "tab-active",
    articleActive = "article-active";

// What happens when you click a tab..
function tabClick () {
    const article = this.getAttribute("data-article");

    location.hash = article;

    removeClasses(tabActive);
    this.classList.add(tabActive);
}

// Simple function that removes classes based on the given class name.
function removeClasses (classname) {
    const elems = document.getElementsByClassName(classname);

    for (let i = 0; i < elems.length; i++) {
        elems[i].classList.remove(classname);
    }
}

// Function that runs to check the location hash and enables the according tab.
function hashParser () {
    const hash = location.hash.replace("#", "");

    if (hash) {
        article = document.getElementById(hash);

        if (article) {
            removeClasses(articleActive);
            article.classList.add(articleActive);

            // And tab..
            removeClasses(tabActive);
            tabs[0].parentNode.querySelector(`[data-article="${hash}"]`).classList.add(tabActive);
        }
    }
}

// Function to calculate age from a data, plus action to take if date is current
// Date in format DD-MM-YYYY (AND NO OTHER FFS!)
function getAge (date, onDate) {
    // Manual parse to avoid inconsistancies with Date.parse implementation.
    const unparsedArr = date.split("-"),
        history = new Date(+unparsedArr[2], (+unparsedArr[1] - 1), (+unparsedArr[0] + 1)),
        today = new Date(),
        tY = today.getUTCFullYear(),
        hY = history.getUTCFullYear(),
        tM = today.getUTCMonth(),
        hM = history.getUTCMonth(),
        tD = today.getUTCDate(),
        hD = history.getUTCDate();

    let age = tY - hY,
        month = tM - hM;

    if (month < 0 || (month === 0 && (tD < hD))) {
        age--;
    }

    if (onDate) {
        if (tM === hM && tD === hD) {
            onDate(age);
        }
    }
    return age;
}

for (let i = 0; i < tabs.length; i++) {
    tabs[i].addEventListener("click", tabClick);
}
// Execute as soon as the script is parsed, a hash could be available;
hashParser();
// Look for hash changes (tab click);
window.addEventListener("hashchange", hashParser);

// Sets age specific to my birthday (31-03-1987);
(function setAge() {
    const elems = document.getElementsByClassName("set-age"),
        currentAge = getAge("31-03-1987", (age) => {
            document.getElementById("header-title").textContent = `FEEST! Ik ben vandaag ${age} geworden!`;
        });

    for (let i = 0; i < elems.length; i++) {
        elems[i].textContent = currentAge;
    }
})();
<commit_msg>Unchained the variables<commit_after>"use strict";

const tabs = document.getElementById("tab-wrap").children;
const tabActive = "tab-active";
const articleActive = "article-active";

// What happens when you click a tab..
function tabClick () {
    const article = this.getAttribute("data-article");

    location.hash = article;

    removeClasses(tabActive);
    this.classList.add(tabActive);
}

// Simple function that removes classes based on the given class name.
function removeClasses (classname) {
    const elems = document.getElementsByClassName(classname);

    for (let i = 0; i < elems.length; i++) {
        elems[i].classList.remove(classname);
    }
}

// Function that runs to check the location hash and enables the according tab.
function hashParser () {
    const hash = location.hash.replace("#", "");

    if (hash) {
        const article = document.getElementById(hash);

        if (article) {
            removeClasses(articleActive);
            article.classList.add(articleActive);

            // And tab..
            removeClasses(tabActive);
            tabs[0].parentNode.querySelector(`[data-article="${hash}"]`).classList.add(tabActive);
        }
    }
}

// Function to calculate age from a data, plus action to take if date is current
// Date in format DD-MM-YYYY (AND NO OTHER FFS!)
function getAge (date, onDate) {
    // Manual parse to avoid inconsistancies with Date.parse implementation.
    const unparsedArr = date.split("-");
    const history = new Date(+unparsedArr[2], (+unparsedArr[1] - 1), (+unparsedArr[0] + 1));
    const today = new Date();
    const tY = today.getUTCFullYear();
    const hY = history.getUTCFullYear();
    const tM = today.getUTCMonth();
    const hM = history.getUTCMonth();
    const tD = today.getUTCDate();
    const hD = history.getUTCDate();

    let age = tY - hY;
    let month = tM - hM;

    if (month < 0 || (month === 0 && (tD < hD))) {
        age--;
    }

    if (onDate) {
        if (tM === hM && tD === hD) {
            onDate(age);
        }
    }
    return age;
}

for (let i = 0; i < tabs.length; i++) {
    tabs[i].addEventListener("click", tabClick);
}
// Execute as soon as the script is parsed, a hash could be available;
hashParser();
// Look for hash changes (tab click);
window.addEventListener("hashchange", hashParser);

// Sets age specific to my birthday (31-03-1987);
(function setAge() {
    const elems = document.getElementsByClassName("set-age");
    const currentAge = getAge("31-03-1987", (age) => {
            document.getElementById("header-title").textContent = `FEEST! Ik ben vandaag ${age} geworden!`;
        });

    for (let i = 0; i < elems.length; i++) {
        elems[i].textContent = currentAge;
    }
})();
<|endoftext|>


<commit_before>(function() {
  var iconsIndex = new AlgoliaSearch("9JQV0RIHU0", "2219d421236cba4cf37a98e7f97b3ec5").initIndex('icons'),
    innerTemplate = '
' +
      '
{{{class}}}
' +
      '
{{{html}}}
' +
      '
{{{_highlightResult.name.value}}}
' +
      '
{{{_highlightResult.tags.value}}}
' +
      '
',
    allTemplate = '
' +
      '
{{{class}}}
' +
      '
{{{html}}}
' +
      '
{{{name}}}
' +
      '
{{{tags}}}
' +
      '
',
    innerTemplateCompiled = Hogan.compile(innerTemplate),
    allTemplateCompiled = Hogan.compile(allTemplate),
    icons = {},
    clip,
    flashEnabled = false;

  var state = {
    library: "all",
    query: "",
    copy: "markup"
  };

  var qs = $.url().param();
  setState("library", qs.library);
  setState("copy", qs.copy);

  $.getJSON("./data/batch.json", function(data) {
    generate(data, allTemplateCompiled, icons);
    handlers();

    setState("query", qs.query);
  });

  function setLibrary(library) {
    var qs = $.url().param();
    library = library || "all";

    $("#libraries > .btn").removeClass("active");
    $("[data-library='" + library + "']").addClass("active");

    if (library == "all") {
      delete qs.library;
      $("body").addClass("all");
      $(".section").removeClass("hide");
      refreshSticky();
    } else {
      qs.library = library;
      $("body").removeClass("all");
      $(".section").addClass("hide");
      $(".section#" + library).removeClass("hide");
    }

    updateURL(qs);
  }

  function setCopy(copy) {
    var qs = $.url().param();
    copy = copy || "markup";

    $("#copy > .btn").removeClass("active");
    $("[data-copy='" + copy + "']").addClass("active");

    if (copy == "markup") {
      delete qs.copy;
	} else {
      qs.copy = copy;
	}
    updateURL(qs);
  }

  function search(v) {
    v = v || "";
    v = $.trim(v);

    if ($('#search').data('q') == v) {
      // do not perform the same query twice, results will not change
      return;
    }

    $('#search').val(v).data('q', v);

    if (v.length === 0) {
      loadAll(icons);
    } else {
      iconsIndex.search(v, function(success, content) {
        if (!success) return;

        var result = {};
        generate(content.hits, innerTemplateCompiled, result);
        loadAll(result);

      }, {hitsPerPage: 1000});
    }

    var qs = $.url().param();

    if (v.length > 0) {
      qs.query = v;
    } else {
      delete qs.query;
    }

    updateURL(qs);
  }

  function generate(data, template, output) {
    data.forEach(function(v){
      var lib,
          html;

      if (v.name) {
        lib = v._tags[0];
        html = template.render(v);

        if (!output[lib]) {
          output[lib] = html;
        } else {
          output[lib] += html;
        }
      }
    });
  }

  function loadAll(htmls) {
    $('.section').hide();
    $('.icons').empty();

    for (var i in htmls) {
      $('#' + i + ' .icons').html(htmls[i]).parent().show();
    }

    if (flashEnabled) {
      clip.clip($(".entry"));
    }

    refreshSticky();
  }

  function refreshSticky() {
    $(".header").fixedsticky("destroy").fixedsticky();
  }

  function updateURL(qs) {
    qs = $.param(qs);

    if (qs.length === 0) {
      history.replaceState(null, "GlyphSearch", "./");
    } else {
      history.replaceState(null, "GlyphSearch", "?" + qs);
    }

    window.scrollTo(0, 0);
  }

  function handlers() {
    $(window).on("resize", debounce(function() {
      refreshSticky();
    }, 250));

    $('#search').keydown(function(e) {
      if (e.which == 13) {
        e.preventDefault();
        return;
      }
    })
    .keyup(function(e) {
      if (e.which == 27) {
        setState("query", "");
        return;
      }

      setState("query", $(this).val());
    })
    .on("change", function() {
      setState("query", $(this).val());
    })
    .on("input", function() {
      var val = $(this).val();
      if (val.length === 0) {
        setState("query", "");
      }
    });

    $("#libraries .btn").click(function(e) {
      e.preventDefault();
      var library = $(this).attr("data-library");
      setState("library", library);
    });

    $("#copy .btn").click(function(e) {
      e.preventDefault();
      $("#copy > .btn").removeClass("active");
      $(this).addClass("active");

      var copy = $(this).attr("data-copy");
      setState("copy", copy);
    });

    FixedSticky.tests.sticky = false; // force firefox to use polyfill
    $(".header").fixedsticky();

    ZeroClipboard.config({
      moviePath: "bower_components/zeroclipboard/dist/ZeroClipboard.swf",
      forceHandCursor: true
    });

    clip = new ZeroClipboard($(".entry"));

    clip.on("ready", function() {
      flashEnabled = true;

      clip.on("copy", function(e) {
        var text = copyText($(e.target));
        e.clipboardData.setData("text/plain", text);
      });

      clip.on("aftercopy", function(e) {
        var c = $(e.target).find(".thumb").html();
        $("#big-icon").empty().html(c);

        $(".copied").show().find("div")
          .addClass("animateIn").delay(700).queue(function(next) {
            var that = $(this);
            that.removeClass("animateIn").addClass("animateOut");
            that.parent().fadeOut(function() {
              that.removeClass("animateOut");
            });
            next();
          });
      });

      clip.clip($(".entry"));
    });

    clip.on("error", function(e) {
      $(".icons").on("click", ".entry", function() {
        var text = copyText($(this));
        window.prompt("Copy to clipboard:", text);
      });
    });
  }

  function copyText(target) {
    var text;

    if (state.copy === "markup") {
      text = target.find(".thumb").html();
    } else if (state.copy === "class") {
      text = target.find(".description").html();
    } else if (state.copy === "name") {
      text = target.attr("data-name");
    } else if (state.copy === "unicode") {
      if (target.find("i").hasClass("material-icons")) {
        text = target.attr("data-unicode");
      } else {
        var hex = target.attr("data-unicode");
        text = String.fromCharCode(parseInt(hex, 16));
      }
    }

    return text;
  }

  function setState(prop, val) {
    if (prop == "library") {
      setLibrary(val);
    } else if (prop == "copy") {
      setCopy(val);
    } else if (prop == "query") {
      search(val);
    }

    state[prop] = val;
  }

  function debounce(fn, delay) {
    var timer = null;
    return function () {
      var context = this, args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    };
  }
}());

<commit_msg>set "state" to default value when query string is empty<commit_after>(function() {
  var iconsIndex = new AlgoliaSearch("9JQV0RIHU0", "2219d421236cba4cf37a98e7f97b3ec5").initIndex('icons'),
    innerTemplate = '
' +
      '
{{{class}}}
' +
      '
{{{html}}}
' +
      '
{{{_highlightResult.name.value}}}
' +
      '
{{{_highlightResult.tags.value}}}
' +
      '
',
    allTemplate = '
' +
      '
{{{class}}}
' +
      '
{{{html}}}
' +
      '
{{{name}}}
' +
      '
{{{tags}}}
' +
      '
',
    innerTemplateCompiled = Hogan.compile(innerTemplate),
    allTemplateCompiled = Hogan.compile(allTemplate),
    icons = {},
    clip,
    flashEnabled = false;

  var state = {
    library: "all",
    query: "",
    copy: "markup"
  };

  var qs = $.url().param();
  setState("library", qs.library || "all");
  setState("copy", qs.copy || "markup");

  $.getJSON("./data/batch.json", function(data) {
    generate(data, allTemplateCompiled, icons);
    handlers();

    setState("query", qs.query || "");
  });

  function setLibrary(library) {
    var qs = $.url().param();
    library = library || "all";

    $("#libraries > .btn").removeClass("active");
    $("[data-library='" + library + "']").addClass("active");

    if (library == "all") {
      delete qs.library;
      $("body").addClass("all");
      $(".section").removeClass("hide");
      refreshSticky();
    } else {
      qs.library = library;
      $("body").removeClass("all");
      $(".section").addClass("hide");
      $(".section#" + library).removeClass("hide");
    }

    updateURL(qs);
  }

  function setCopy(copy) {
    var qs = $.url().param();
    copy = copy || "markup";

    $("#copy > .btn").removeClass("active");
    $("[data-copy='" + copy + "']").addClass("active");

    if (copy == "markup") {
      delete qs.copy;
	} else {
      qs.copy = copy;
	}
    updateURL(qs);
  }

  function search(v) {
    v = v || "";
    v = $.trim(v);

    if ($('#search').data('q') == v) {
      // do not perform the same query twice, results will not change
      return;
    }

    $('#search').val(v).data('q', v);

    if (v.length === 0) {
      loadAll(icons);
    } else {
      iconsIndex.search(v, function(success, content) {
        if (!success) return;

        var result = {};
        generate(content.hits, innerTemplateCompiled, result);
        loadAll(result);

      }, {hitsPerPage: 1000});
    }

    var qs = $.url().param();

    if (v.length > 0) {
      qs.query = v;
    } else {
      delete qs.query;
    }

    updateURL(qs);
  }

  function generate(data, template, output) {
    data.forEach(function(v){
      var lib,
          html;

      if (v.name) {
        lib = v._tags[0];
        html = template.render(v);

        if (!output[lib]) {
          output[lib] = html;
        } else {
          output[lib] += html;
        }
      }
    });
  }

  function loadAll(htmls) {
    $('.section').hide();
    $('.icons').empty();

    for (var i in htmls) {
      $('#' + i + ' .icons').html(htmls[i]).parent().show();
    }

    if (flashEnabled) {
      clip.clip($(".entry"));
    }

    refreshSticky();
  }

  function refreshSticky() {
    $(".header").fixedsticky("destroy").fixedsticky();
  }

  function updateURL(qs) {
    qs = $.param(qs);

    if (qs.length === 0) {
      history.replaceState(null, "GlyphSearch", "./");
    } else {
      history.replaceState(null, "GlyphSearch", "?" + qs);
    }

    window.scrollTo(0, 0);
  }

  function handlers() {
    $(window).on("resize", debounce(function() {
      refreshSticky();
    }, 250));

    $('#search').keydown(function(e) {
      if (e.which == 13) {
        e.preventDefault();
        return;
      }
    })
    .keyup(function(e) {
      if (e.which == 27) {
        setState("query", "");
        return;
      }

      setState("query", $(this).val());
    })
    .on("change", function() {
      setState("query", $(this).val());
    })
    .on("input", function() {
      var val = $(this).val();
      if (val.length === 0) {
        setState("query", "");
      }
    });

    $("#libraries .btn").click(function(e) {
      e.preventDefault();
      var library = $(this).attr("data-library");
      setState("library", library);
    });

    $("#copy .btn").click(function(e) {
      e.preventDefault();
      $("#copy > .btn").removeClass("active");
      $(this).addClass("active");

      var copy = $(this).attr("data-copy");
      setState("copy", copy);
    });

    FixedSticky.tests.sticky = false; // force firefox to use polyfill
    $(".header").fixedsticky();

    ZeroClipboard.config({
      moviePath: "bower_components/zeroclipboard/dist/ZeroClipboard.swf",
      forceHandCursor: true
    });

    clip = new ZeroClipboard($(".entry"));

    clip.on("ready", function() {
      flashEnabled = true;

      clip.on("copy", function(e) {
        var text = copyText($(e.target));
        e.clipboardData.setData("text/plain", text);
      });

      clip.on("aftercopy", function(e) {
        var c = $(e.target).find(".thumb").html();
        $("#big-icon").empty().html(c);

        $(".copied").show().find("div")
          .addClass("animateIn").delay(700).queue(function(next) {
            var that = $(this);
            that.removeClass("animateIn").addClass("animateOut");
            that.parent().fadeOut(function() {
              that.removeClass("animateOut");
            });
            next();
          });
      });

      clip.clip($(".entry"));
    });

    clip.on("error", function(e) {
      $(".icons").on("click", ".entry", function() {
        var text = copyText($(this));
        window.prompt("Copy to clipboard:", text);
      });
    });
  }

  function copyText(target) {
    var text;

    if (state.copy === "markup") {
      text = target.find(".thumb").html();
    } else if (state.copy === "class") {
      text = target.find(".description").html();
    } else if (state.copy === "name") {
      text = target.attr("data-name");
    } else if (state.copy === "unicode") {
      if (target.find("i").hasClass("material-icons")) {
        text = target.attr("data-unicode");
      } else {
        var hex = target.attr("data-unicode");
        text = String.fromCharCode(parseInt(hex, 16));
      }
    }

    return text;
  }

  function setState(prop, val) {
    if (prop == "library") {
      setLibrary(val);
    } else if (prop == "copy") {
      setCopy(val);
    } else if (prop == "query") {
      search(val);
    }

    state[prop] = val;
  }

  function debounce(fn, delay) {
    var timer = null;
    return function () {
      var context = this, args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);
    };
  }
}());

<|endoftext|>