<commit_before>var events = require('./events.js');
var util = require('./util.js');
var type_of = require('./type-of.js');
var captcha = require('./captcha.js');
var version = require('./version.js');
var request = require('./request.js');

// globalThis 暂时不用
var _global = {};
try {
  _global = global
} catch (error) {
  _global = window
}

var YHSD = {};
YHSD.events = events;
YHSD.util = util;
YHSD.request = request;
YHSD.captcha = captcha;

_global.yhsd = _global.yhsd || {};

_global.yhsd._$interceptors = {
	request: {
		_$callback: function (oRequest, fnNext) {
			fnNext(oRequest);
		},
		use: function (_fn) {
			this._$callback = _fn;
		},
		run: function (oRequest, fnNext) {
			this._$callback(oRequest, fnNext);
		}
	},
	response: {
		_$callback: function (oResponse, fnNext) {
			fnNext(oResponse);
		},
		use: function (_fn) {
			this._$callback = _fn;
		},
		run: function (oResponse, fnNext) {
			this._$callback(oResponse, fnNext);
		}
	}
};

_global.yhsd.version = function(){
	return version.get();
};

var aFunctionReady = [];
var bHasInit = false;

var runWhenReady = function(fn){
	if(type_of(fn) === 'function'){
		if(bHasInit){
			fn(YHSD);
		}else{
			aFunctionReady.push(fn);
		}
	}
};

_global.yhsd.ready = runWhenReady;
_global.yhsd.sdk = YHSD;

if(typeof _global.yhsdDebug === 'undefined'){
	_global.yhsdDebug = false;
}

var aInitModule = ['account', 'area', 'address', 'blog', 'cart', 'shop', 'order', 'page', 'payment_method', 'product', 'type', 'vendor', 'discount', 'coupon', 'reward_point', 'page_block', 'post', 'favorite', 'service', 'trade_invoice', 'weapp'];

function checkModule(moduleName){
	return (util.inArray(moduleName, aInitModule) > -1);
}

YHSD.account = checkModule('account') ? require('./account.js') : {};
YHSD.area = checkModule('area') ? require('./area.js') : {};
YHSD.address = checkModule('address') ? require('./address.js') : {};
YHSD.blog = checkModule('blog') ? require('./blog.js') : {};
YHSD.cart = checkModule('cart') ? require('./cart.js') : {};
YHSD.discount = checkModule('discount') ? require('./discount.js') : {};
YHSD.shop = checkModule('shop') ? require('./shop.js') : {};
YHSD.order = checkModule('order') ? require('./order.js') : {};
YHSD.page = checkModule('page') ? require('./page.js') : {};
YHSD.payment_method = checkModule('payment_method') ? require('./payment_method.js') : {};
YHSD.product = checkModule('product') ? require('./product.js') : {};
YHSD.type = checkModule('type') ? require('./type.js') : {};
YHSD.vendor = checkModule('vendor') ? require('./vendor.js') : {};
YHSD.coupon = checkModule('coupon') ? require('./coupon.js') : {};
YHSD.reward_point = checkModule('reward_point') ? require('./reward_point.js') : {};
YHSD.page_block = checkModule('page_block') ? require('./page_block.js') : {};
YHSD.post = checkModule('post') ? require('./post.js') : {};
YHSD.favorite = checkModule('favorite') ? require('./favorite.js') : {};
YHSD.service = checkModule('service') ? require('./service.js') : {};
YHSD.trade_invoice = checkModule('trade_invoice') ? require('./trade_invoice.js') : {};
YHSD.weapp = checkModule('weapp') ? require('./weapp.js') : {};

function jssdkInit(){
	if(aFunctionReady.length === 0){
		bHasInit = true;
	}else{
		(aFunctionReady.shift())(YHSD);
		jssdkInit();
	}
}

(function(){
	var ajaxToken = null;
	if('ajaxToken' in _global) {
		jssdkInit();
	} else {
		Object.defineProperty(_global, 'ajaxToken', {
			set: function(token){
				if(!ajaxToken) {
					ajaxToken = token;
					jssdkInit();
				} else {
					ajaxToken = token;
				}
			},
			get: function(){
				return ajaxToken;
			}
		});
	}
})();<commit_msg>style: main.js<commit_after>var events = require('./events.js');
var util = require('./util.js');
var type_of = require('./type-of.js');
var captcha = require('./captcha.js');
var version = require('./version.js');
var request = require('./request.js');

// globalThis 暂时不用
var _global = {};
try {
  _global = global;
} catch (error) {
  _global = window;
}

var YHSD = {};
YHSD.events = events;
YHSD.util = util;
YHSD.request = request;
YHSD.captcha = captcha;

_global.yhsd = _global.yhsd || {};

_global.yhsd._$interceptors = {
	request: {
		_$callback: function (oRequest, fnNext) {
			fnNext(oRequest);
		},
		use: function (_fn) {
			this._$callback = _fn;
		},
		run: function (oRequest, fnNext) {
			this._$callback(oRequest, fnNext);
		}
	},
	response: {
		_$callback: function (oResponse, fnNext) {
			fnNext(oResponse);
		},
		use: function (_fn) {
			this._$callback = _fn;
		},
		run: function (oResponse, fnNext) {
			this._$callback(oResponse, fnNext);
		}
	}
};

_global.yhsd.version = function(){
	return version.get();
};

var aFunctionReady = [];
var bHasInit = false;

var runWhenReady = function(fn){
	if(type_of(fn) === 'function'){
		if(bHasInit){
			fn(YHSD);
		}else{
			aFunctionReady.push(fn);
		}
	}
};

_global.yhsd.ready = runWhenReady;
_global.yhsd.sdk = YHSD;

if(typeof _global.yhsdDebug === 'undefined'){
	_global.yhsdDebug = false;
}

var aInitModule = ['account', 'area', 'address', 'blog', 'cart', 'shop', 'order', 'page', 'payment_method', 'product', 'type', 'vendor', 'discount', 'coupon', 'reward_point', 'page_block', 'post', 'favorite', 'service', 'trade_invoice', 'weapp'];

function checkModule(moduleName){
	return (util.inArray(moduleName, aInitModule) > -1);
}

YHSD.account = checkModule('account') ? require('./account.js') : {};
YHSD.area = checkModule('area') ? require('./area.js') : {};
YHSD.address = checkModule('address') ? require('./address.js') : {};
YHSD.blog = checkModule('blog') ? require('./blog.js') : {};
YHSD.cart = checkModule('cart') ? require('./cart.js') : {};
YHSD.discount = checkModule('discount') ? require('./discount.js') : {};
YHSD.shop = checkModule('shop') ? require('./shop.js') : {};
YHSD.order = checkModule('order') ? require('./order.js') : {};
YHSD.page = checkModule('page') ? require('./page.js') : {};
YHSD.payment_method = checkModule('payment_method') ? require('./payment_method.js') : {};
YHSD.product = checkModule('product') ? require('./product.js') : {};
YHSD.type = checkModule('type') ? require('./type.js') : {};
YHSD.vendor = checkModule('vendor') ? require('./vendor.js') : {};
YHSD.coupon = checkModule('coupon') ? require('./coupon.js') : {};
YHSD.reward_point = checkModule('reward_point') ? require('./reward_point.js') : {};
YHSD.page_block = checkModule('page_block') ? require('./page_block.js') : {};
YHSD.post = checkModule('post') ? require('./post.js') : {};
YHSD.favorite = checkModule('favorite') ? require('./favorite.js') : {};
YHSD.service = checkModule('service') ? require('./service.js') : {};
YHSD.trade_invoice = checkModule('trade_invoice') ? require('./trade_invoice.js') : {};
YHSD.weapp = checkModule('weapp') ? require('./weapp.js') : {};

function jssdkInit(){
	if(aFunctionReady.length === 0){
		bHasInit = true;
	}else{
		(aFunctionReady.shift())(YHSD);
		jssdkInit();
	}
}

(function(){
	var ajaxToken = null;
	if('ajaxToken' in _global) {
		jssdkInit();
	} else {
		Object.defineProperty(_global, 'ajaxToken', {
			set: function(token){
				if(!ajaxToken) {
					ajaxToken = token;
					jssdkInit();
				} else {
					ajaxToken = token;
				}
			},
			get: function(){
				return ajaxToken;
			}
		});
	}
})();<|endoftext|>


<commit_before>/*
Only supported target: Chrome

mp3 MediaSource only works in Chrome, not firefox
- play song at current time after song is fully downloaded in firefox?
- download song ahead of time?
- no seeking support

Future features:
-seed & play mp3 file (not permanent in queue?)
-drawing (maybe dj whiteboard, or draw and then drawing appears above head)
-let user pause, but keep timer so on play it jumps to current time

TODO: use RSA keys to prove identities & make friend feature
-request friend
-friend sends public key
-next time peer with id appears, ask them to authenticate by decrypting string encrypted with their public key
-reciprocate (friendships must be two-way)

TODO: host sends start time, instad of time since start, for more accurate guest time calculation
TODO: fix bug if you try to join your own room

TODO: "server" version, bittorrent-tracker works on node.js (just remove player code)
--> put player code in module, don't use on server
--> don't make avatar for server
http://dexie.org/
TODO: upload images to imgur
TODO: add currently playing song to playlist
--- if mp3, download torrent and add to localstorage
TODO: export/import data (playlist, mp3s, friends)
TODO: store export/state into dropbox, etc. with api?
TODO: dj queue view

TODO: use revokeObjectURL
https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
to free up memory

TODO: convert all times to same timezone
*/

var sodium = require('sodium-universal')

var PeerTunes = require('./modules/peertunes')

var config =require('./config')

$(document).ready(function () {
  $('#btn-login').click(function (e) {
    init()
  })
})

function init () {
  config.username = $('#input-username').val()

  console.log('generating keypair...')

  var private = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES)
  var public = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES)

  // create elliptic curve key pair
  sodium.crypto_sign_keypair(public, private)

  config.keys = {
    private: private,
    public: public
  }

  console.log(config.keys.private.toString('base64'))

  var PT = new PeerTunes(config)

  $('#welcome').css('top', '100%') // slide down out of view
}
<commit_msg>removed key printing<commit_after>/*
Only supported target: Chrome

mp3 MediaSource only works in Chrome, not firefox
- play song at current time after song is fully downloaded in firefox?
- download song ahead of time?
- no seeking support

Future features:
-seed & play mp3 file (not permanent in queue?)
-drawing (maybe dj whiteboard, or draw and then drawing appears above head)
-let user pause, but keep timer so on play it jumps to current time

TODO: use RSA keys to prove identities & make friend feature
-request friend
-friend sends public key
-next time peer with id appears, ask them to authenticate by decrypting string encrypted with their public key
-reciprocate (friendships must be two-way)

TODO: host sends start time, instad of time since start, for more accurate guest time calculation
TODO: fix bug if you try to join your own room

TODO: "server" version, bittorrent-tracker works on node.js (just remove player code)
--> put player code in module, don't use on server
--> don't make avatar for server
http://dexie.org/
TODO: upload images to imgur
TODO: add currently playing song to playlist
--- if mp3, download torrent and add to localstorage
TODO: export/import data (playlist, mp3s, friends)
TODO: store export/state into dropbox, etc. with api?
TODO: dj queue view

TODO: use revokeObjectURL
https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
to free up memory

TODO: convert all times to same timezone
*/

var sodium = require('sodium-universal')

var PeerTunes = require('./modules/peertunes')

var config =require('./config')

$(document).ready(function () {
  $('#btn-login').click(function (e) {
    init()
  })
})

function init () {
  config.username = $('#input-username').val()

  console.log('generating keypair...')

  var private = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES)
  var public = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES)

  // create elliptic curve key pair
  sodium.crypto_sign_keypair(public, private)

  config.keys = {
    private: private,
    public: public
  }

  var PT = new PeerTunes(config)

  $('#welcome').css('top', '100%') // slide down out of view
}
<|endoftext|>


<commit_before>const LANG = 'en';
const AND = 'AND';
const OR = 'OR';

function main() {

    const needsDom = document.querySelector('.needs');
    for (let right of data.common.rights) {
        needsDom.innerHTML += `

                <input type="radio" name="needs" value="${right}" />
                ${right}

        `;
    }

    document.querySelector('.button_search').onclick = () => {

        const need = needsDom.querySelector(':checked').value;

        const countryData = getSuitableStatus(need);

        let message = '';

        for (let country of countryData) {
            message += `<h2>For ${country.id}</h2>`;
            for (let status of country.status) {
                message += `<h3>${status.name[LANG]}</h3>`;

                let transition = {};
                for (let region of data.region) {
                    if (region.id === country.id) {
                        for (let transition of region.transitions) {
                            if (transition.to === `${country.id} ${status.id}`) {
                                message += `<h4>${transition.name[LANG]}</h4>`;
                                message += 'Prerequisites:
';
                                if (typeof transition.prerequisites === 'object') {
                                    for (let prerequisite of transition.prerequisites.value) {
                                        message += stringifyPrerequisite(prerequisite);
                                    }
                                    message += ` Except ${transition.prerequisites.exception}`;
                                } else {
                                    for (let prerequisite of transition.prerequisites) {
                                        message += stringifyPrerequisite(prerequisite);
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }

        document.querySelector('.message').innerHTML = message;

    };
}

function getSuitableStatus(need) {
    const result = [];
    for (let country of data.region) {
        const statusSuitable = [];
        for (let statusName of Object.keys(country.status)) {
            const status = country.status[statusName];
            if (status.rights.includes(need)) {
                statusSuitable.push(status);
            }
        }
        result.push({
            id: country.id,
            status: statusSuitable
        });
    }

    return result;
}

function stringifyPrerequisite(prerequisite) {
    let result = '';
    if (prerequisite === AND) {
        result += `<strong>and</strong> <br/>`;
    } else if (prerequisite === OR) {
        result += `<strong>or</strong> <br />`;
    } else if (Array.isArray(prerequisite)) {
        result += `

                       ${prerequisite.map(p => stringifyPrerequisite(p)).join('\n')}

`;
    } else {
        result += prerequisite;
    }

    return result;
}

main();
<commit_msg>Fix referential bug<commit_after>const LANG = 'en';
const AND = 'AND';
const OR = 'OR';

function main() {

    const needsDom = document.querySelector('.needs');
    for (let right of data.common.rights) {
        needsDom.innerHTML += `

                <input type="radio" name="needs" value="${right}" />
                ${right}

        `;
    }

    document.querySelector('.button_search').onclick = () => {

        const need = needsDom.querySelector(':checked').value;

        const countryData = getSuitableStatus(need);

        let message = '';

        for (let country of countryData) {
            message += `<h2>For ${country.id}</h2>`;
            for (let status of country.status) {
                message += `<h3>${status.name[LANG]}</h3>`;

                let transition = {};
                for (let region of data.region) {
                    if (region.id === country.id) {
                        for (let transition of region.transitions) {
                            if (transition.to === `${country.id} ${status.id}`) {
                                message += `<h4>${transition.name[LANG]}</h4>`;
                                message += 'Prerequisites:
';
                                if (transition.prerequisites.value) {
                                    for (let prerequisite of transition.prerequisites.value) {
                                        message += stringifyPrerequisite(prerequisite);
                                    }
                                    message += ` Except ${transition.prerequisites.exception}`;
                                } else {
                                    for (let prerequisite of transition.prerequisites) {
                                        message += stringifyPrerequisite(prerequisite);
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }

        document.querySelector('.message').innerHTML = message;

    };
}

function getSuitableStatus(need) {
    const result = [];
    for (let country of data.region) {
        const statusSuitable = [];
        for (let statusName of Object.keys(country.status)) {
            const status = country.status[statusName];
            if (status.rights.includes(need)) {
                statusSuitable.push(status);
            }
        }
        result.push({
            id: country.id,
            status: statusSuitable
        });
    }

    return result;
}

function stringifyPrerequisite(prerequisite) {
    let result = '';
    if (prerequisite === AND) {
        result += `<strong>and</strong> <br/>`;
    } else if (prerequisite === OR) {
        result += `<strong>or</strong> <br />`;
    } else if (Array.isArray(prerequisite)) {
        result += `

                       ${prerequisite.map(p => stringifyPrerequisite(p)).join('\n')}

`;
    } else {
        result += prerequisite;
    }

    return result;
}

main();
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Simon Edwards <simon@simonzone.com>
 */

var _ = require('lodash-node');
var fs = require('fs');
var path = require('path');

var terminal = require('./terminal.js');
var configure_panel = require('./configure_panel.js');

/*************************************************************************/
exports.startUp = (function() {
  "use strict";

  var CONFIG_FILENAME = "config";
  var THEMES_DIRECTORY = "themes";
  var THEME_CONFIG = "theme.json";

  var terminalIdCounter = 0;
  var themes;
  var configurePanel = null;
  var gui;
  var config;
  var doc;
  var terminalList = [];  // -> {id, terminal, terminaltab, tabheader};
  var focusedTerminalInfo = null;

  function createTerminal() {
    var term;
    var info;
    var doc = window.document;
    var container;
    var terminaltab;
    var tabbar;
    var tabheader;
    var thisId;

    thisId = terminalIdCounter;
    terminalIdCounter++;

    // Create something to put the terminal in.
    terminaltab = doc.createElement("div");
    terminaltab.className = "terminal_tab_inactive";
    container = doc.getElementById("tab_container");
    container.appendChild(terminaltab);

    // Create the terminal itself.
    term = new terminal.Terminal(terminaltab);
    term.setBlinkingCursor(config.blinkingCursor);
    term.on('ptyclose', handlePtyClose);
    term.on('unknown-keydown', handleUnknownKeyDown);
    term.on('title', handleTitle);
    term.startUp();

    // Create the tab header.
    tabheader = doc.createElement("div");
    tabheader.className = "tab_active";
    tabheader.innerText = "New Tab";
    tabheader.addEventListener('click', function() {
      focusTerminal(thisId);
    });
    tabbar = doc.getElementById("tabbar");
    tabbar.insertBefore(tabheader, doc.getElementById("new_tab_button"));

    info = {id: thisId, terminal: term, terminaltab: terminaltab, tabheader: tabheader};
    terminalList[thisId] = info;
    return thisId;
  }

  function focusTerminal(id) {
    terminalList.forEach(function(info) {
      if (info.id === id) {
        // Activate this one.
        info.terminaltab.className = "terminal_tab_active";
        info.tabheader.className = "tab_active";
        info.terminal.focus();
        focusedTerminalInfo = info;
        setWindowTitle(info.terminal.getTitle());
      } else {
        // Deactive the rest.
        info.terminaltab.className = "terminal_tab_inactive";
        info.tabheader.className = "tab_inactive";
      }
    });
  }

  function setWindowTitle(title) {
    window.document.title = "Extraterm - " + title;
  }

  function handlePtyClose(term) {
    destroyTerminal(_.find(terminalList, function(info) { return info.terminal === term; }).id);

    if (terminalList.length !== 0) {
      focusTerminal(terminalList[0].id);
    } else {
      quit();
    }
  }

  function shiftTab(direction) {
    if (terminalList.length === 0) {
      return;
    }

    var i = terminalList.indexOf(focusedTerminalInfo);
    i = i + direction;
    if (i < 0) {
      i = terminalList.length - 1;
    } else if (i >= terminalList.length) {
      i = 0;
    }
    focusTerminal(terminalList[i].id);
  }

  function handleUnknownKeyDown(term, ev) {
    if (ev.keyCode === 37 && ev.shiftKey) {
      // left-arrow
      shiftTab(-1);

    } else if (ev.keyCode === 39 && ev.shiftKey) {
      // right-arrow
      shiftTab(1);

    } else if (ev.keyCode === 67 && ev.shiftKey) {
      // Ctrl+Shift+C
      copyToClipboard();

    } else if (ev.keyCode === 86 && ev.shiftKey) {
      // Ctrl+Shift+V
      pasteFromClipboard();

    } else if (ev.keyCode === 84 && ev.shiftKey) {
      // Ctrl+Shift+T
      focusTerminal(createTerminal());

    } else {
      console.log("Unknown key:",ev);
    }
  }

  function copyToClipboard() {
    var text;
    var selection;
    var range;
    var clipboard;

    selection = window.getSelection();
    range = selection.getRangeAt(0);
    if (range.collapsed) {
      return;
    }
    text = range.toString();
    clipboard = gui.Clipboard.get();
    clipboard.set(text, 'text');
  }

  function pasteFromClipboard() {
    var clipboard = gui.Clipboard.get();
    var text = clipboard.get();
    focusedTerminalInfo.terminal.send(text);
  }

  function handleTitle(term, title) {
    var info = _.find(terminalList, function(info) { return info.terminal === term; });
    var header = info.tabheader;
    header.innerText = title;
    header.setAttribute('title',title);
    if (info === focusedTerminalInfo) {
      setWindowTitle(title);
    }
  }

  function destroyTerminal(id) {
    var i = terminalList.findIndex(function(item) { return item.id === id; });
    var info = terminalList[i];
    info.terminal.destroy();
    info.terminaltab.remove();
    info.tabheader.remove();
    terminalList.splice(i, 1);
  }

  function startUp(windowGui) {
    var themesdir;

    gui = windowGui;
    doc = window.document;

    config = readConfiguration();

    config.blinkingCursor = _.isBoolean(config.blinkingCursor) ? config.blinkingCursor : false;

    // Themes
    themesdir = path.join(__dirname, THEMES_DIRECTORY);
    themes = scanThemes(themesdir);
    if (themes[config.theme] === undefined) {
      config.theme = "default";
    }
    setupConfiguration(config);

    // Configure panel.
    configurePanel = new configure_panel.ConfigurePanel(
            {element: window.document.getElementById("configure_panel"), themes: themes});
    configurePanel.on('ok', function(newConfig) {
      config = newConfig;
      writeConfiguration(newConfig);
      setupConfiguration(newConfig);
    });
    doc.getElementById("configure_button").addEventListener('click', function() {
      configurePanel.open(config);
    });

    doc.getElementById("new_tab_button").addEventListener('click', function() { focusTerminal(createTerminal()); });

    focusTerminal(createTerminal());
  }

  function quit() {
    window.close();
  }

  function setupConfiguration(config) {
    installTheme(config.theme);
    terminalList.forEach(function(info) {
      info.term.setBlinkingCursor(config.blinkingCursor);
    });
  }

  /*
   * config object format: { theme: String, blinkingCursor: boolean}
   */

  /**
   * Read the configuration.
   *
   * @returns {Object} The configuration object.
   */
  function readConfiguration() {
    var filename = path.join(gui.App.dataPath, CONFIG_FILENAME);
    var configJson;
    var config = {};

    if (fs.existsSync(filename)) {
      configJson = fs.readFileSync(filename);
      config = JSON.parse(configJson);
    }
    return config;
  }

  /**
   * Write out the configuration to disk.
   *
   * @param {Object} config The configuration to write.
   */
  function writeConfiguration(config) {
    var filename = path.join(gui.App.dataPath, CONFIG_FILENAME);
    fs.writeFileSync(filename, JSON.stringify(config));
  }

  /**
   * Scan for themes.
   *
   * @param {String} themesdir The directory to scan for themes.
   * @returns {Array} Array of found theme config objects.
   */
  function scanThemes(themesdir) {
    var contents;
    var thememap = {};

    if (fs.existsSync(themesdir)) {
      contents = fs.readdirSync(themesdir);
      contents.forEach(function(item) {
        var infopath = path.join(themesdir, item, THEME_CONFIG);
        try {
          var infostr = fs.readFileSync(infopath, {encoding: "utf8"});
          var themeinfo = JSON.parse(infostr);

          if (validateThemeInfo(themeinfo)) {
            thememap[item] = themeinfo;
          }

        } catch(err) {
          console.log("Warning: Unable to read file ",infopath);
        }
      });
      return thememap;
    }
  }

  function validateThemeInfo(themeinfo) {
    return _.isString(themeinfo["name"]) && themeinfo["name"] !== "";
  }

  function installTheme(themename) {
    var themeLink = doc.getElementById("theme_link");
    themeLink.href = THEMES_DIRECTORY+ "/" + themename + "/theme.css";
  }

  return startUp;
})();
<commit_msg>Convert non-breaking space to normal space char when copying text to the clipboard.<commit_after>/**
 * Copyright 2014 Simon Edwards <simon@simonzone.com>
 */

var _ = require('lodash-node');
var fs = require('fs');
var path = require('path');

var terminal = require('./terminal.js');
var configure_panel = require('./configure_panel.js');

/*************************************************************************/
exports.startUp = (function() {
  "use strict";

  var CONFIG_FILENAME = "config";
  var THEMES_DIRECTORY = "themes";
  var THEME_CONFIG = "theme.json";

  var terminalIdCounter = 0;
  var themes;
  var configurePanel = null;
  var gui;
  var config;
  var doc;
  var terminalList = [];  // -> {id, terminal, terminaltab, tabheader};
  var focusedTerminalInfo = null;

  function createTerminal() {
    var term;
    var info;
    var doc = window.document;
    var container;
    var terminaltab;
    var tabbar;
    var tabheader;
    var thisId;

    thisId = terminalIdCounter;
    terminalIdCounter++;

    // Create something to put the terminal in.
    terminaltab = doc.createElement("div");
    terminaltab.className = "terminal_tab_inactive";
    container = doc.getElementById("tab_container");
    container.appendChild(terminaltab);

    // Create the terminal itself.
    term = new terminal.Terminal(terminaltab);
    term.setBlinkingCursor(config.blinkingCursor);
    term.on('ptyclose', handlePtyClose);
    term.on('unknown-keydown', handleUnknownKeyDown);
    term.on('title', handleTitle);
    term.startUp();

    // Create the tab header.
    tabheader = doc.createElement("div");
    tabheader.className = "tab_active";
    tabheader.innerText = "New Tab";
    tabheader.addEventListener('click', function() {
      focusTerminal(thisId);
    });
    tabbar = doc.getElementById("tabbar");
    tabbar.insertBefore(tabheader, doc.getElementById("new_tab_button"));

    info = {id: thisId, terminal: term, terminaltab: terminaltab, tabheader: tabheader};
    terminalList[thisId] = info;
    return thisId;
  }

  function focusTerminal(id) {
    terminalList.forEach(function(info) {
      if (info.id === id) {
        // Activate this one.
        info.terminaltab.className = "terminal_tab_active";
        info.tabheader.className = "tab_active";
        info.terminal.focus();
        focusedTerminalInfo = info;
        setWindowTitle(info.terminal.getTitle());
      } else {
        // Deactive the rest.
        info.terminaltab.className = "terminal_tab_inactive";
        info.tabheader.className = "tab_inactive";
      }
    });
  }

  function setWindowTitle(title) {
    window.document.title = "Extraterm - " + title;
  }

  function handlePtyClose(term) {
    destroyTerminal(_.find(terminalList, function(info) { return info.terminal === term; }).id);

    if (terminalList.length !== 0) {
      focusTerminal(terminalList[0].id);
    } else {
      quit();
    }
  }

  function shiftTab(direction) {
    if (terminalList.length === 0) {
      return;
    }

    var i = terminalList.indexOf(focusedTerminalInfo);
    i = i + direction;
    if (i < 0) {
      i = terminalList.length - 1;
    } else if (i >= terminalList.length) {
      i = 0;
    }
    focusTerminal(terminalList[i].id);
  }

  function handleUnknownKeyDown(term, ev) {
    if (ev.keyCode === 37 && ev.shiftKey) {
      // left-arrow
      shiftTab(-1);

    } else if (ev.keyCode === 39 && ev.shiftKey) {
      // right-arrow
      shiftTab(1);

    } else if (ev.keyCode === 67 && ev.shiftKey) {
      // Ctrl+Shift+C
      copyToClipboard();

    } else if (ev.keyCode === 86 && ev.shiftKey) {
      // Ctrl+Shift+V
      pasteFromClipboard();

    } else if (ev.keyCode === 84 && ev.shiftKey) {
      // Ctrl+Shift+T
      focusTerminal(createTerminal());

    } else {
      console.log("Unknown key:",ev);
    }
  }

  function copyToClipboard() {
    var text;
    var selection;
    var range;
    var clipboard;

    selection = window.getSelection();
    range = selection.getRangeAt(0);
    if (range.collapsed) {
      return;
    }
    text = range.toString();
    clipboard = gui.Clipboard.get();
    clipboard.set(text.replace(/\u00a0/g,' '), 'text');
  }

  function pasteFromClipboard() {
    var clipboard = gui.Clipboard.get();
    var text = clipboard.get();
    focusedTerminalInfo.terminal.send(text);
  }

  function handleTitle(term, title) {
    var info = _.find(terminalList, function(info) { return info.terminal === term; });
    var header = info.tabheader;
    header.innerText = title;
    header.setAttribute('title',title);
    if (info === focusedTerminalInfo) {
      setWindowTitle(title);
    }
  }

  function destroyTerminal(id) {
    var i = terminalList.findIndex(function(item) { return item.id === id; });
    var info = terminalList[i];
    info.terminal.destroy();
    info.terminaltab.remove();
    info.tabheader.remove();
    terminalList.splice(i, 1);
  }

  function startUp(windowGui) {
    var themesdir;

    gui = windowGui;
    doc = window.document;

    config = readConfiguration();

    config.blinkingCursor = _.isBoolean(config.blinkingCursor) ? config.blinkingCursor : false;

    // Themes
    themesdir = path.join(__dirname, THEMES_DIRECTORY);
    themes = scanThemes(themesdir);
    if (themes[config.theme] === undefined) {
      config.theme = "default";
    }
    setupConfiguration(config);

    // Configure panel.
    configurePanel = new configure_panel.ConfigurePanel(
            {element: window.document.getElementById("configure_panel"), themes: themes});
    configurePanel.on('ok', function(newConfig) {
      config = newConfig;
      writeConfiguration(newConfig);
      setupConfiguration(newConfig);
    });
    doc.getElementById("configure_button").addEventListener('click', function() {
      configurePanel.open(config);
    });

    doc.getElementById("new_tab_button").addEventListener('click', function() { focusTerminal(createTerminal()); });

    focusTerminal(createTerminal());
  }

  function quit() {
    window.close();
  }

  function setupConfiguration(config) {
    installTheme(config.theme);
    terminalList.forEach(function(info) {
      info.term.setBlinkingCursor(config.blinkingCursor);
    });
  }

  /*
   * config object format: { theme: String, blinkingCursor: boolean}
   */

  /**
   * Read the configuration.
   *
   * @returns {Object} The configuration object.
   */
  function readConfiguration() {
    var filename = path.join(gui.App.dataPath, CONFIG_FILENAME);
    var configJson;
    var config = {};

    if (fs.existsSync(filename)) {
      configJson = fs.readFileSync(filename);
      config = JSON.parse(configJson);
    }
    return config;
  }

  /**
   * Write out the configuration to disk.
   *
   * @param {Object} config The configuration to write.
   */
  function writeConfiguration(config) {
    var filename = path.join(gui.App.dataPath, CONFIG_FILENAME);
    fs.writeFileSync(filename, JSON.stringify(config));
  }

  /**
   * Scan for themes.
   *
   * @param {String} themesdir The directory to scan for themes.
   * @returns {Array} Array of found theme config objects.
   */
  function scanThemes(themesdir) {
    var contents;
    var thememap = {};

    if (fs.existsSync(themesdir)) {
      contents = fs.readdirSync(themesdir);
      contents.forEach(function(item) {
        var infopath = path.join(themesdir, item, THEME_CONFIG);
        try {
          var infostr = fs.readFileSync(infopath, {encoding: "utf8"});
          var themeinfo = JSON.parse(infostr);

          if (validateThemeInfo(themeinfo)) {
            thememap[item] = themeinfo;
          }

        } catch(err) {
          console.log("Warning: Unable to read file ",infopath);
        }
      });
      return thememap;
    }
  }

  function validateThemeInfo(themeinfo) {
    return _.isString(themeinfo["name"]) && themeinfo["name"] !== "";
  }

  function installTheme(themename) {
    var themeLink = doc.getElementById("theme_link");
    themeLink.href = THEMES_DIRECTORY+ "/" + themename + "/theme.css";
  }

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


<commit_before>define('main', [
    "jquery",
    "./registry",

    "modernizer",
    "less",
    "prefixfree",
    "./patterns/autofocus",
    "./patterns/autoscale",
    "./patterns/autosubmit",
    "./patterns/autosubmit2",
    "./patterns/autosuggest",
    "./patterns/breadcrumbs",
    "./patterns/bumper",
    "./patterns/carousel",
    "./patterns/checkedflag",
    "./patterns/checklist",
    "./patterns/chosen",
    "./patterns/collapsible",
    "./patterns/depends",
    "./patterns/edit-tinymce",
    "./patterns/expandable",
    "./patterns/focus",
    "./patterns/form-state",
    "./patterns/fullcalendar",
    "./patterns/image-crop",
    "./patterns/inject",
    "./patterns/markdown",
    "./patterns/menu",
    "./patterns/modal",
    "./patterns/navigation",
    "./patterns/placeholder",
    "./patterns/setclass",
    "./patterns/sortable",
    "./patterns/switch",
    "./patterns/transforms",
    "./patterns/toggle",
    "./patterns/tooltip",
    "./patterns/validate",
    "./patterns/zoom"
], function($, registry) {
    $(document).ready(function() {
        registry.scan(document.body);
    });
});
require('main');
<commit_msg>make require in main compatible with modular<commit_after>define('main', [
    "jquery",
    "./registry",

    "modernizer",
    "less",
    "prefixfree",
    "./patterns/autofocus",
    "./patterns/autoscale",
    "./patterns/autosubmit",
    "./patterns/autosubmit2",
    "./patterns/autosuggest",
    "./patterns/breadcrumbs",
    "./patterns/bumper",
    "./patterns/carousel",
    "./patterns/checkedflag",
    "./patterns/checklist",
    "./patterns/chosen",
    "./patterns/collapsible",
    "./patterns/depends",
    "./patterns/edit-tinymce",
    "./patterns/expandable",
    "./patterns/focus",
    "./patterns/form-state",
    "./patterns/fullcalendar",
    "./patterns/image-crop",
    "./patterns/inject",
    "./patterns/markdown",
    "./patterns/menu",
    "./patterns/modal",
    "./patterns/navigation",
    "./patterns/placeholder",
    "./patterns/setclass",
    "./patterns/sortable",
    "./patterns/switch",
    "./patterns/transforms",
    "./patterns/toggle",
    "./patterns/tooltip",
    "./patterns/validate",
    "./patterns/zoom"
], function($, registry) {
    $(document).ready(function() {
        registry.scan(document.body);
    });
});
require(['main']);
<|endoftext|>


<commit_before>'use strict';

/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2016 SIRAP Group All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * plugin.js Tinymce plugin headersfooters
 * @file plugin.js
 * @module
 * @name tinycmce-plugin-headersfooters
 * @description A plugin for tinymce WYSIWYG HTML editor that allow to insert headers and footers - requires tinymce-plugin-paginate.
 * @link https://github.com/sirap-group/tinymce-plugin-headersfooters
 * @author Rémi Becheras
 * @author Groupe SIRAP
 * @license GNU GPL-v2 http://www.tinymce.com/license
 * @version 1.0.0
 */

/**
 * Tinymce library - injected by the plugin loader.
 * @external tinymce
 * @see {@link https://www.tinymce.com/docs/api/class/tinymce/|Tinymce API Reference}
 */
/*global tinymce:true */

/**
 * The jQuery plugin namespace - plugin dependency.
 * @external "jQuery.fn"
 * @see {@link http://learn.jquery.com/plugins/|jQuery Plugins}
 */
/*global jquery:true */

/**
 * Tinymce plugin headers/footers
 * @function
 * @global
 * @param {tinymce.Editor} editor - The injected tinymce editor.
 * @returns void
 */
function tinymcePluginHeadersFooters(editor) {

  function onInitHandler(){
    headerFooterFactory = new HeaderFooterFactory(editor);

    ui.menuItems.insertHeader.onclick = function(){
      headerFooterFactory.insertHeader();
    };
    ui.menuItems.insertFooter.onclick = function(){
      headerFooterFactory.insertFooter();
    };
  }

  window.alert('tinymcePluginHeadersFooters');

  var headerFooterFactory;

  editor.on('init',onInitHandler);

  editor.addMenuItem('insertHeader', ui.menuItems.insertHeader);
  editor.addMenuItem('insertFooter', ui.menuItems.insertFooter);

}

// Add the plugin to the tinymce PluginManager
tinymce.PluginManager.add('headersfooters', tinymcePluginHeadersFooters);
<commit_msg>add require insructions<commit_after>'use strict';

/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2016 SIRAP Group All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * plugin.js Tinymce plugin headersfooters
 * @file plugin.js
 * @module
 * @name tinycmce-plugin-headersfooters
 * @description A plugin for tinymce WYSIWYG HTML editor that allow to insert headers and footers - requires tinymce-plugin-paginate.
 * @link https://github.com/sirap-group/tinymce-plugin-headersfooters
 * @author Rémi Becheras
 * @author Groupe SIRAP
 * @license GNU GPL-v2 http://www.tinymce.com/license
 * @version 1.0.0
 */

/**
 * Tinymce library - injected by the plugin loader.
 * @external tinymce
 * @see {@link https://www.tinymce.com/docs/api/class/tinymce/|Tinymce API Reference}
 */
/*global tinymce:true */

/**
 * The jQuery plugin namespace - plugin dependency.
 * @external "jQuery.fn"
 * @see {@link http://learn.jquery.com/plugins/|jQuery Plugins}
 */
/*global jquery:true */

var HeaderFooterFactory = require('classes/HeaderFooterFactory');
var ui = require('utils/ui');

/**
 * Tinymce plugin headers/footers
 * @function
 * @global
 * @param {tinymce.Editor} editor - The injected tinymce editor.
 * @returns void
 */
function tinymcePluginHeadersFooters(editor) {

  function onInitHandler(){
    headerFooterFactory = new HeaderFooterFactory(editor);

    ui.menuItems.insertHeader.onclick = function(){
      headerFooterFactory.insertHeader();
    };
    ui.menuItems.insertFooter.onclick = function(){
      headerFooterFactory.insertFooter();
    };
  }

  window.alert('tinymcePluginHeadersFooters');

  var headerFooterFactory;

  editor.on('init',onInitHandler);

  editor.addMenuItem('insertHeader', ui.menuItems.insertHeader);
  editor.addMenuItem('insertFooter', ui.menuItems.insertFooter);

}

// Add the plugin to the tinymce PluginManager
tinymce.PluginManager.add('headersfooters', tinymcePluginHeadersFooters);
<|endoftext|>


<commit_before>'use strict';

const APP_NAME = 'KongDash';
const VERSION = '0.3.0';

const electron  = require('electron');
const path      = require('path');
const ospath = require('ospath');
const jsonfile  = require('jsonfile');

let absPath = path.dirname(__dirname), configFile = ospath.data() + '/' + APP_NAME + '/config.json';
let {app, ipcMain, BrowserWindow, Menu} = electron;
let mainWindow, appConfig = {kong: {}, app: {enableAnimation: true}};

let startMainWindow = function () {
    mainWindow = new BrowserWindow({
        backgroundColor: '#1A242D',
        width: 1100,
        height: 580,
        center: true,
        title: app.getName(),
        minHeight: 500,
        minWidth: 900,
        icon: absPath + '/kongdash-256x256.png',
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        }
    });
    mainWindow.loadURL('file://' + absPath + '/src/initialize.html');

    //* Debugging
    mainWindow.webContents.openDevTools();
    //*/

    mainWindow.on('closed', () => {
        mainWindow = null;
    });
};

app.setName(APP_NAME);

app.on('ready', () => {
    try {
        appConfig = jsonfile.readFileSync(configFile);

    } catch (e) {
        /* Ignore. Uses default settings. */
    } finally {
        startMainWindow();
    }
});

app.on('activate', () => {
    if (mainWindow === null) startMainWindow();
});

app.on('browser-window-created', (e, window) => {
    let menuTemplate = [{
        label: 'File',
        submenu: [{
            label: 'Settings',
            click: () => {
                mainWindow.webContents.send('open-settings-view', '');
            }
        }, { type: 'separator' }, { role: 'quit' }]
    }, {
        label: 'Edit',
        submenu: [{ role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }]
    }, {
        label: 'Window',
        submenu: [{role: 'togglefullscreen'}]
    }, {
        label: 'Help',
        submenu: [{
            label: 'GitHub Repository',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/KongDash');
            }
        }, {
            label: 'Report Issues',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/KongDash/issues');
            }
        }, {
            type: 'separator'
        }, {
            label: 'About KongDash',
            click: () => {
                electron.shell.openExternal('https://ajaysreedhar.github.io/KongDash/');
            }
        }]
    }];

    let menu = Menu.buildFromTemplate(menuTemplate);

    if (process.platform === 'darwin' || process.platform === 'mas') {
        Menu.setApplicationMenu(menu);

    } else {
        window.setMenu(menu);
    }
});

app.on('window-all-closed', () => {
    if(process.platform !== 'darwin') app.quit();
});

ipcMain.on('get-config', (event, arg) => {
    if (arg === 'VERSION') {
        event.returnValue = VERSION;
        return;
    }

    event.returnValue = appConfig[arg];
});

ipcMain.on('write-config', (event, arg) => {
    appConfig[arg.name] = arg.config;

    jsonfile.writeFile(configFile, appConfig, function (error) {
        if (error) {
            event.sender.send('write-config-error', {message: 'Could not write configuration file.' + error});

        } else {
            event.sender.send('write-config-success', {message: 'Configuration saved successfully'});
        }
    });
});

ipcMain.on('open-external', (event, arg) => {
    electron.shell.openExternal(arg);
});
<commit_msg>change: set minWidth and minHeight to 1280x800<commit_after>'use strict';

const APP_NAME = 'KongDash';
const VERSION = '0.3.0';

const electron  = require('electron');
const path      = require('path');
const ospath = require('ospath');
const jsonfile  = require('jsonfile');

let absPath = path.dirname(__dirname), configFile = ospath.data() + '/' + APP_NAME + '/config.json';
let {app, ipcMain, BrowserWindow, Menu} = electron;
let mainWindow, appConfig = {kong: {}, app: {enableAnimation: true}};

let startMainWindow = function () {
    mainWindow = new BrowserWindow({
        backgroundColor: '#1A242D',
        width: 1570,
        height: 800,
        center: true,
        title: app.getName(),
        minWidth: 1280,
        minHeight: 800,
        icon: absPath + '/kongdash-256x256.png',
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        }
    });
    mainWindow.loadURL('file://' + absPath + '/src/initialize.html');

    //* Debugging
    mainWindow.webContents.openDevTools();
    //*/

    mainWindow.on('closed', () => {
        mainWindow = null;
    });
};

app.setName(APP_NAME);

app.on('ready', () => {
    try {
        appConfig = jsonfile.readFileSync(configFile);

    } catch (e) {
        /* Ignore. Uses default settings. */
    } finally {
        startMainWindow();
    }
});

app.on('activate', () => {
    if (mainWindow === null) startMainWindow();
});

app.on('browser-window-created', (e, window) => {
    let menuTemplate = [{
        label: 'File',
        submenu: [{
            label: 'Settings',
            click: () => {
                mainWindow.webContents.send('open-settings-view', '');
            }
        }, { type: 'separator' }, { role: 'quit' }]
    }, {
        label: 'Edit',
        submenu: [{ role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }]
    }, {
        label: 'Window',
        submenu: [{role: 'togglefullscreen'}]
    }, {
        label: 'Help',
        submenu: [{
            label: 'GitHub Repository',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/KongDash');
            }
        }, {
            label: 'Report Issues',
            click: () => {
                electron.shell.openExternal('https://github.com/ajaysreedhar/KongDash/issues');
            }
        }, {
            type: 'separator'
        }, {
            label: 'About KongDash',
            click: () => {
                electron.shell.openExternal('https://ajaysreedhar.github.io/KongDash/');
            }
        }]
    }];

    let menu = Menu.buildFromTemplate(menuTemplate);

    if (process.platform === 'darwin' || process.platform === 'mas') {
        Menu.setApplicationMenu(menu);

    } else {
        window.setMenu(menu);
    }
});

app.on('window-all-closed', () => {
    if(process.platform !== 'darwin') app.quit();
});

ipcMain.on('get-config', (event, arg) => {
    if (arg === 'VERSION') {
        event.returnValue = VERSION;
        return;
    }

    event.returnValue = appConfig[arg];
});

ipcMain.on('write-config', (event, arg) => {
    appConfig[arg.name] = arg.config;

    jsonfile.writeFile(configFile, appConfig, function (error) {
        if (error) {
            event.sender.send('write-config-error', {message: 'Could not write configuration file.' + error});

        } else {
            event.sender.send('write-config-success', {message: 'Configuration saved successfully'});
        }
    });
});

ipcMain.on('open-external', (event, arg) => {
    electron.shell.openExternal(arg);
});
<|endoftext|>


<commit_before>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import VueResource from 'vue-resource';
import VeeValidate from 'vee-validate';
import VueCookie from 'vue-cookie';
import validadeEn from 'vee-validate/dist/locale/en';
import validadePtBR from 'vee-validate/dist/locale/pt_BR';
import store from './store';
import router from './router';

import App from './App';

VeeValidate.Validator.addLocale(validadePtBR);
VeeValidate.Validator.addLocale(validadeEn);

Vue.use(VueResource);
Vue.use(VueCookie);
Vue.http.options.root = process.env.API_URL ? process.env.API_URL : 'http://localhost:3000';

Vue.filter('currency', (value) => {
  const val = (value / 1).toFixed(2).replace('.', ',');
  return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
});

Vue.use(VeeValidate,
  {
    locale: 'pt_BR',
    enableAutoClasses: true,
  },
);

Vue.http.interceptors.push((req, next) => {
  // é possível colocar informações no header antes do envio da requisição
  req.headers.set('Authorization', 'informação de segurança aqui');
  // eslint-disable-next-line
  console.log('Lidando com o request');
  next((res) => {
    // eslint-disable-next-line
    console.log('Lidando com a resposta', res);
    // é possível acessar os dados da reposta e realizar transformações antes
    // eslint-disable-next-line
    console.log(res.body);
  });
});

Vue.config.productionTip = false;

router.beforeEach((to, from, next) => {
  const requireAuth = !to.matched.some(record => record.meta.noAuth);
  let redirectTo = {};

  store.dispatch('getLoggedUser');

  const isLoggedUser = store.getters.isLoggedUser;

  if (requireAuth && !isLoggedUser) {
    redirectTo = { path: '/entrar', query: { redirect: to.fullPath } };
  } else if (isLoggedUser && to.path === '/entrar') {
    redirectTo = { path: to.query.redirect || '/restaurantes/bar-do-ze' };
  }
  return next(redirectTo);
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: { App },
});
<commit_msg>remove code useless<commit_after>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import VueResource from 'vue-resource';
import VeeValidate from 'vee-validate';
import VueCookie from 'vue-cookie';
import validadeEn from 'vee-validate/dist/locale/en';
import validadePtBR from 'vee-validate/dist/locale/pt_BR';
import store from './store';
import router from './router';

import App from './App';

VeeValidate.Validator.addLocale(validadePtBR);
VeeValidate.Validator.addLocale(validadeEn);

Vue.use(VueResource);
Vue.use(VueCookie);
Vue.http.options.root = process.env.API_URL ? process.env.API_URL : 'http://localhost:3000';

Vue.filter('currency', (value) => {
  const val = (value / 1).toFixed(2).replace('.', ',');
  return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
});

Vue.use(VeeValidate,
  {
    locale: 'pt_BR',
    enableAutoClasses: true,
  },
);

Vue.http.interceptors.push((req, next) => {
  // é possível colocar informações no header antes do envio da requisição
  req.headers.set('Authorization', 'informação de segurança aqui');
  // eslint-disable-next-line
  console.log('Lidando com o request');
  next((res) => {
    // eslint-disable-next-line
    console.log('Lidando com a resposta', res);
    // é possível acessar os dados da reposta e realizar transformações antes
    // eslint-disable-next-line
    console.log(res.body);
  });
});

Vue.config.productionTip = false;

router.beforeEach((to, from, next) => {
  const requireAuth = !to.matched.some(record => record.meta.noAuth);
  let redirectTo = {};

  const isLoggedUser = store.getters.isLoggedUser;

  if (requireAuth && !isLoggedUser) {
    redirectTo = { path: '/entrar', query: { redirect: to.fullPath } };
  } else if (isLoggedUser && to.path === '/entrar') {
    redirectTo = { path: to.query.redirect || '/restaurantes/bar-do-ze' };
  }
  return next(redirectTo);
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: { App },
});
<|endoftext|>


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

  if (typeof sigma === 'undefined')
    throw 'sigma is not declared';

  if (typeof EdgeShapeLibrary === 'undefined')
    throw 'EdgeShapeLibrary is not declared';

  // Initialize package:
  sigma.utils.pkg('sigma.canvas.edges');

  var sigInst = undefined;

  var initPlugin = function(inst) {
    sigInst = inst;
  }

  var register = function(name,drawShape) {
    sigma.canvas.edges[name] = function(edge, source, target, context, settings) {
      var prefix = settings('prefix') || '',
          color = edge.color,
          edgeColor = settings('edgeColor'),
          defaultNodeColor = settings('defaultNodeColor'),
          defaultEdgeColor = settings('defaultEdgeColor');

      if (!color) {
        switch (edgeColor) {
          case 'source':
            color = source.color || defaultNodeColor;
            break;
          case 'target':
            color = target.color || defaultNodeColor;
            break;
          default:
            color = defaultEdgeColor;
            break;
        }
      }

      context.save();

      if(drawShape) {
        drawShape(edge, source, target, color, prefix, context);
      }

      context.restore();
    };
  }

  EdgeShapeLibrary.enumerate().forEach(function(shape) {
    register(shape.name, shape.drawShape);
  });

  /**
   * Exporting
   * ----------
   */
  this.CustomEdgeShapes = {

    // Functions
    init: initPlugin,

    // Version
    version: '0.1'
  };

}).call(this);
<commit_msg>Add compatibility with the active-state plugin<commit_after>;(function(undefined) {
  'use strict';

  if (typeof sigma === 'undefined')
    throw 'sigma is not declared';

  if (typeof EdgeShapeLibrary === 'undefined')
    throw 'EdgeShapeLibrary is not declared';

  // Initialize package:
  sigma.utils.pkg('sigma.canvas.edges');

  var sigInst = undefined;

  var initPlugin = function(inst) {
    sigInst = inst;
  }

  var register = function(name,drawShape) {
    sigma.canvas.edges[name] = function(edge, source, target, context, settings) {
      var prefix = settings('prefix') || '',
          color = edge.active ?
            edge.active_color || settings('defaultEdgeActiveColor') :
            edge.color,
          edgeColor = settings('edgeColor'),
          defaultNodeColor = settings('defaultNodeColor'),
          defaultEdgeColor = settings('defaultEdgeColor');

      if (!color) {
        switch (edgeColor) {
          case 'source':
            color = source.color || defaultNodeColor;
            break;
          case 'target':
            color = target.color || defaultNodeColor;
            break;
          default:
            color = defaultEdgeColor;
            break;
        }
      }

      context.save();

      if (edge.active) {
        context.strokeStyle = settings('edgeActiveColor') === 'edge' ?
          (color || defaultEdgeColor) :
          settings('defaultEdgeActiveColor');
      }
      else {
        context.strokeStyle = color;
      }

      if(drawShape) {
        drawShape(edge, source, target, color, prefix, context);
      }

      context.restore();
    };
  }

  EdgeShapeLibrary.enumerate().forEach(function(shape) {
    register(shape.name, shape.drawShape);
  });

  /**
   * Exporting
   * ----------
   */
  this.CustomEdgeShapes = {

    // Functions
    init: initPlugin,

    // Version
    version: '0.1'
  };

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


<commit_before>/*
 * Copyright 2015 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var Util = require('./util.js');
var WebVRPolyfill = require('./webvr-polyfill.js').WebVRPolyfill;

// Initialize a WebVRConfig just in case.
window.WebVRConfig = Util.extend({
  // Forces availability of VR mode, even for non-mobile devices.
  FORCE_ENABLE_VR: false,

  // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
  K_FILTER: 0.98,

  // How far into the future to predict during fast motion (in seconds).
  PREDICTION_TIME_S: 0.040,

  // Flag to enable touch panner. In case you have your own touch controls.
  TOUCH_PANNER_DISABLED: true,

  // Flag to disabled the UI in VR Mode.
  CARDBOARD_UI_DISABLED: false, // Default: false

  // Flag to disable the instructions to rotate your device.
  ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false.

  // Enable yaw panning only, disabling roll and pitch. This can be useful
  // for panoramas with nothing interesting above or below.
  YAW_ONLY: false,

  // To disable keyboard and mouse controls, if you want to use your own
  // implementation.
  MOUSE_KEYBOARD_CONTROLS_DISABLED: false,

  // Prevent the polyfill from initializing immediately. Requires the app
  // to call InitializeWebVRPolyfill() before it can be used.
  DEFER_INITIALIZATION: false,

  // Enable the deprecated version of the API (navigator.getVRDevices).
  ENABLE_DEPRECATED_API: false,

  // Scales the recommended buffer size reported by WebVR, which can improve
  // performance.
  // UPDATE(2016-05-03): Setting this to 0.5 by default since 1.0 does not
  // perform well on many mobile devices.
  BUFFER_SCALE: 0.5,

  // Allow VRDisplay.submitFrame to change gl bindings, which is more
  // efficient if the application code will re-bind its resources on the
  // next frame anyway. This has been seen to cause rendering glitches with
  // THREE.js.
  // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
  // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
  // and gl.TEXTURE_BINDING_2D for texture unit 0.
  DIRTY_SUBMIT_FRAME_BINDINGS: false
}, window.WebVRConfig);

if (!window.WebVRConfig.DEFER_INITIALIZATION) {
  new WebVRPolyfill();
} else {
  window.InitializeWebVRPolyfill = function() {
    new WebVRPolyfill();
  }
}
<commit_msg>Support module.exports.<commit_after>/*
 * Copyright 2015 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var Util = require('./util.js');
var WebVRPolyfill = require('./webvr-polyfill.js').WebVRPolyfill;

// Initialize a WebVRConfig just in case.
window.WebVRConfig = Util.extend({
  // Forces availability of VR mode, even for non-mobile devices.
  FORCE_ENABLE_VR: false,

  // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
  K_FILTER: 0.98,

  // How far into the future to predict during fast motion (in seconds).
  PREDICTION_TIME_S: 0.040,

  // Flag to enable touch panner. In case you have your own touch controls.
  TOUCH_PANNER_DISABLED: true,

  // Flag to disabled the UI in VR Mode.
  CARDBOARD_UI_DISABLED: false, // Default: false

  // Flag to disable the instructions to rotate your device.
  ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false.

  // Enable yaw panning only, disabling roll and pitch. This can be useful
  // for panoramas with nothing interesting above or below.
  YAW_ONLY: false,

  // To disable keyboard and mouse controls, if you want to use your own
  // implementation.
  MOUSE_KEYBOARD_CONTROLS_DISABLED: false,

  // Prevent the polyfill from initializing immediately. Requires the app
  // to call InitializeWebVRPolyfill() before it can be used.
  DEFER_INITIALIZATION: false,

  // Enable the deprecated version of the API (navigator.getVRDevices).
  ENABLE_DEPRECATED_API: false,

  // Scales the recommended buffer size reported by WebVR, which can improve
  // performance.
  // UPDATE(2016-05-03): Setting this to 0.5 by default since 1.0 does not
  // perform well on many mobile devices.
  BUFFER_SCALE: 0.5,

  // Allow VRDisplay.submitFrame to change gl bindings, which is more
  // efficient if the application code will re-bind its resources on the
  // next frame anyway. This has been seen to cause rendering glitches with
  // THREE.js.
  // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
  // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
  // and gl.TEXTURE_BINDING_2D for texture unit 0.
  DIRTY_SUBMIT_FRAME_BINDINGS: false
}, window.WebVRConfig);

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  module.exports = WebVRPolyfill;
} else {
  if (!window.WebVRConfig.DEFER_INITIALIZATION) {
    new WebVRPolyfill();
  } else {
    window.InitializeWebVRPolyfill = function() {
      new WebVRPolyfill();
    }
  }
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import Vue from 'vue';
import i18next from 'i18next';
import i18nextXHR from 'i18next-xhr-backend';
import VueI18Next from '@panter/vue-i18next';

import AvailableLocales from '@/res/locales/available.json';
import FallbackLocale from '@/../static/locales/en-us.json';
import App from '@/components/App';
import StartupError from '@/components/StartupError';
import Logger from '@/libs/Logger';
import ConfigLoader from '@/libs/ConfigLoader';
import state from '@/libs/state';
import ThemeManager from '@/libs/ThemeManager';
import InputHandler from '@/libs/InputHandler';
import StatePersistence from '@/libs/StatePersistence';
import * as Storage from '@/libs/storage/Local';
import * as Misc from '@/helpers/Misc';
import GlobalApi from '@/libs/GlobalApi';

// Global utilities
import '@/components/utils/TabbedView';
import '@/components/utils/InputText';
import '@/components/utils/IrcInput';
import '@/components/utils/InputPrompt';
import '@/components/utils/InputConfirm';

let logLevelMatch = window.location.href.match(/kiwi-loglevel=(\d)/);
if (logLevelMatch && logLevelMatch[1]) {
    Logger.setLevel(parseInt(logLevelMatch[1], 10));
}

let log = Logger.namespace('main');

// Add the global API as soon as possible so that things can start listening to it
let api = window.kiwi = GlobalApi.singleton();

// Third party imports now have access to the state and api
/* eslint-disable import/first */
import '@/thirdparty/';

function getQueryVariable(variable) {
    let query = window.location.search.substring(1);
    let vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split('=');
        if (pair[0] === variable) {
            return pair[1];
        }
    }

    return false;
}

// Add a handy this.listen() fn to Vue instances. Saves on the need to add an event listener
// and then manually remove them all the time.
Vue.mixin({
    beforeDestroy: function beforeDestroy() {
        (this.listeningEvents || []).forEach(fn => fn());
    },
    methods: {
        listen: function listen(source, event, fn) {
            this.listeningEvents = this.listeningEvents || [];
            this.listeningEvents.push(() => {
                (source.$off || source.off).call(source, event, fn);
            });
            (source.$on || source.on).call(source, event, fn);
        },
        listenOnce: function listenOnce(source, event, fn) {
            this.listeningEvents = this.listeningEvents || [];
            this.listeningEvents.push(() => {
                (source.$off || source.off).call(source, event, fn);
            });
            (source.$once || source.once).call(source, event, fn);
        },
    },
});

// Make the state available to all components by default
Vue.mixin({
    computed: {
        $state() {
            return state;
        },
    },
});

// Allow adding existing raw elements to component templates
// Eg:

// Eg:

Vue.directive('rawElement', {
    bind(el, binding) {
        if (binding.value.nodeName) {
            el.appendChild(binding.value);
        } else if (binding.value.el) {
            let rawEl = binding.value.el;
            el.appendChild(rawEl);

            // Add any data attributes to the raw element
            if (binding.value.data) {
                Object.keys(binding.value.data).forEach((key) => {
                    rawEl.dataset[key] = binding.value.data[key];
                });
            }

            // Add any properties to the raw element
            if (binding.value.props) {
                Object.keys(binding.value.props).forEach((key) => {
                    rawEl[key] = binding.value.props[key];
                });
            }
        }
    },
});

// Register a global custom directive called `v-focus`
Vue.directive('focus', {
    // When the bound element is inserted into the DOM...
    inserted(el) {
        // Element is input so focus it
        if (el.tagName === 'INPUT') {
            el.focus();
            return;
        }
        // Try to focus the first input element
        let input = el.getElementsByTagName('input')[0];
        if (input) {
            input.focus();
        }
    },
});

loadApp();

function loadApp() {
    let configFile = 'static/config.json';
    let configObj = null;

    /**
     * Finding the config file
     * In order, looks in the following places:
     *   1. If a 'config' argument is in the query string, static/config_THEVALUE_.json
     *   2. If a window.kiwiConfig function exists, use it's return value as the config object.
     *   3. If a <meta name="kiwiconfig" content=""> is found, then the content becomes the config
     *      URL.
     *   4. If a  is found, then the
     *      content becomes the config JSON without making another web request.
     */
    if (getQueryVariable('config')) {
        configFile = 'static/config_' + getQueryVariable('config') + '.json';
    } else if (typeof window.kiwiConfig === 'function') {
        try {
            configObj = window.kiwiConfig();
        } catch (err) {
            log.error('Config file: ' + err.stack);
            showError();
        }
    } else if (document.querySelector('meta[name="kiwiconfig"]')) {
        configFile = document.querySelector('meta[name="kiwiconfig"]').content;
    } else if (document.querySelector('script[name="kiwiconfig"]')) {
        let configContents = document.querySelector('script[name="kiwiconfig"]').innerHTML;

        try {
            configObj = JSON.parse(configContents);
        } catch (parseErr) {
            log.error('Config file: ' + parseErr.stack);
            showError();
        }
    }

    let configLoader = new ConfigLoader();
    (configObj ? configLoader.loadFromObj(configObj) : configLoader.loadFromUrl(configFile))
        .then(applyConfig)
        .then(initState)
        .then(initInputCommands)
        .then(initLocales)
        .then(initThemes)
        .then(loadPlugins)
        .then(startApp)
        .catch(showError);
}

function applyConfig(config) {
    Misc.dedotObject(config);
    applyConfigObj(config, state.settings);

    // Update the window title if we have one
    if (state.settings.windowTitle) {
        window.document.title = state.settings.windowTitle;
    }
    state.$watch('settings.windowTitle', (newVal) => {
        window.document.title = newVal;
    });
}

// Recursively merge an object onto another via Vue.$set
function applyConfigObj(obj, target) {
    _.each(obj, (val, key) => {
        if (typeof val === 'object') {
            if (typeof target[key] !== 'object') {
                // Create the correct type of object
                let newVal = _.isArray(val) ?
                    [] :
                    {};

                Vue.set(target, key, newVal);
            }
            applyConfigObj(val, target[key]);
        } else {
            Vue.set(target, key, val);
        }
    });
}

function loadPlugins() {
    return new Promise((resolve, reject) => {
        let plugins = state.settings.plugins || [];
        let pluginIdx = -1;

        loadNextScript();

        function loadNextScript(sSrc, fOnload) {
            let plugin = plugins[++pluginIdx];

            if (!plugin) {
                resolve();
                return;
            }

            let scr = document.createElement('script');
            scr.onerror = () => {
                log.error(`Error loading plugin '${plugin.name}' from '${plugin.url}'`);
                loadNextScript();
            };
            scr.onload = () => {
                loadNextScript();
            };

            document.body.appendChild(scr);
            scr.src = plugin.url;
        }
    });
}

function initLocales() {
    Vue.use(VueI18Next);

    // Make the translation services available via the global API
    api.i18n = i18next;

    i18next.use(i18nextXHR);
    i18next.init({
        whitelist: AvailableLocales.locales,
        fallbackLng: 'en-us',
        lowerCaseLng: true,
        backend: {
            loadPath: 'static/locales/{{lng}}.json',

            // allow cross domain requests
            crossDomain: false,

            // allow credentials on cross domain requests
            withCredentials: false,
        },
        interpolation: {
            // We let vuejs handle HTML output escaping
            escapeValue: false,
        },
    });

    // Build in the english translation so it can be used as a fallback
    i18next.addResourceBundle('en-us', 'translation', FallbackLocale);

    // Override the $t function so that empty translations fallback to en-us
    Vue.mixin({
        computed: {
            $t() {
                return (key, options) => {
                    let val = this.$i18n.i18next.t(key, options, this.$i18n.i18nLoadedAt);
                    if (!val) {
                        let opts = options || {};
                        opts.lng = 'en-us';
                        val = this.$i18n.i18next.t(key, opts, this.$i18n.i18nLoadedAt);
                    }
                    return val;
                };
            },
        },
    });

    let defaultLang = state.setting('language');
    let preferredLangs = _.clone(window.navigator && window.navigator.languages) || [];

    // our configs default lang overrides all others
    if (defaultLang) {
        preferredLangs.unshift(defaultLang);
    }

    // set a default language
    i18next.changeLanguage('en-us');

    // Go through our browser languages until we find one that we support
    for (let idx = 0; idx < preferredLangs.length; idx++) {
        let lang = preferredLangs[idx];

        // if this is a language such as 'fr', add a following one of 'fr-fr' to cover
        // both cases
        if (lang.length === 2) {
            preferredLangs.splice(idx + 1, 0, lang + '-' + lang);
        }

        if (_.includes(AvailableLocales.locales, lang.toLowerCase())) {
            i18next.changeLanguage(lang, (err, t) => {
                if (err) {
                    // setting the language failed so set default again
                    i18next.changeLanguage('en-us');
                }
            });
            break;
        }
    }
}

async function initState() {
    let stateKey = state.settings.startupOptions.state_key;

    // Default to a preset key if it wasn't set
    if (typeof stateKey === 'undefined') {
        stateKey = 'kiwi-state';
    }

    let persistLog = Logger.namespace('StatePersistence');
    let persist = new StatePersistence(stateKey || '', state, Storage, persistLog);
    persist.includeBuffers = !!state.settings.startupOptions.remember_buffers;

    if (stateKey) {
        await persist.loadStateIfExists();
    }

    api.setState(state);
}

function initThemes() {
    let themeMgr = ThemeManager.instance(state);
    api.setThemeManager(themeMgr);

    let argTheme = getQueryVariable('theme');
    if (argTheme) {
        themeMgr.setTheme(argTheme);
    }
}

function initInputCommands() {
    /* eslint-disable no-new */
    new InputHandler(state);
}

function startApp() {
    api.emit('init');

    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(App),
        i18n: new VueI18Next(i18next),
    });

    api.emit('ready');
}

function showError(err) {
    if (err) {
        log.error('Error starting Kiwi IRC:', err);
    } else {
        log.error('Unknown error starting Kiwi IRC');
    }

    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(StartupError),
    });
}
<commit_msg>Support .html plugin formats<commit_after>import _ from 'lodash';
import Vue from 'vue';
import i18next from 'i18next';
import i18nextXHR from 'i18next-xhr-backend';
import VueI18Next from '@panter/vue-i18next';

import AvailableLocales from '@/res/locales/available.json';
import FallbackLocale from '@/../static/locales/en-us.json';
import App from '@/components/App';
import StartupError from '@/components/StartupError';
import Logger from '@/libs/Logger';
import ConfigLoader from '@/libs/ConfigLoader';
import state from '@/libs/state';
import ThemeManager from '@/libs/ThemeManager';
import InputHandler from '@/libs/InputHandler';
import StatePersistence from '@/libs/StatePersistence';
import * as Storage from '@/libs/storage/Local';
import * as Misc from '@/helpers/Misc';
import GlobalApi from '@/libs/GlobalApi';

// Global utilities
import '@/components/utils/TabbedView';
import '@/components/utils/InputText';
import '@/components/utils/IrcInput';
import '@/components/utils/InputPrompt';
import '@/components/utils/InputConfirm';

let logLevelMatch = window.location.href.match(/kiwi-loglevel=(\d)/);
if (logLevelMatch && logLevelMatch[1]) {
    Logger.setLevel(parseInt(logLevelMatch[1], 10));
}

let log = Logger.namespace('main');

// Add the global API as soon as possible so that things can start listening to it
let api = window.kiwi = GlobalApi.singleton();

// Third party imports now have access to the state and api
/* eslint-disable import/first */
import '@/thirdparty/';

function getQueryVariable(variable) {
    let query = window.location.search.substring(1);
    let vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split('=');
        if (pair[0] === variable) {
            return pair[1];
        }
    }

    return false;
}

// Add a handy this.listen() fn to Vue instances. Saves on the need to add an event listener
// and then manually remove them all the time.
Vue.mixin({
    beforeDestroy: function beforeDestroy() {
        (this.listeningEvents || []).forEach(fn => fn());
    },
    methods: {
        listen: function listen(source, event, fn) {
            this.listeningEvents = this.listeningEvents || [];
            this.listeningEvents.push(() => {
                (source.$off || source.off).call(source, event, fn);
            });
            (source.$on || source.on).call(source, event, fn);
        },
        listenOnce: function listenOnce(source, event, fn) {
            this.listeningEvents = this.listeningEvents || [];
            this.listeningEvents.push(() => {
                (source.$off || source.off).call(source, event, fn);
            });
            (source.$once || source.once).call(source, event, fn);
        },
    },
});

// Make the state available to all components by default
Vue.mixin({
    computed: {
        $state() {
            return state;
        },
    },
});

// Allow adding existing raw elements to component templates
// Eg:

// Eg:

Vue.directive('rawElement', {
    bind(el, binding) {
        if (binding.value.nodeName) {
            el.appendChild(binding.value);
        } else if (binding.value.el) {
            let rawEl = binding.value.el;
            el.appendChild(rawEl);

            // Add any data attributes to the raw element
            if (binding.value.data) {
                Object.keys(binding.value.data).forEach((key) => {
                    rawEl.dataset[key] = binding.value.data[key];
                });
            }

            // Add any properties to the raw element
            if (binding.value.props) {
                Object.keys(binding.value.props).forEach((key) => {
                    rawEl[key] = binding.value.props[key];
                });
            }
        }
    },
});

// Register a global custom directive called `v-focus`
Vue.directive('focus', {
    // When the bound element is inserted into the DOM...
    inserted(el) {
        // Element is input so focus it
        if (el.tagName === 'INPUT') {
            el.focus();
            return;
        }
        // Try to focus the first input element
        let input = el.getElementsByTagName('input')[0];
        if (input) {
            input.focus();
        }
    },
});

loadApp();

function loadApp() {
    let configFile = 'static/config.json';
    let configObj = null;

    /**
     * Finding the config file
     * In order, looks in the following places:
     *   1. If a 'config' argument is in the query string, static/config_THEVALUE_.json
     *   2. If a window.kiwiConfig function exists, use it's return value as the config object.
     *   3. If a <meta name="kiwiconfig" content=""> is found, then the content becomes the config
     *      URL.
     *   4. If a  is found, then the
     *      content becomes the config JSON without making another web request.
     */
    if (getQueryVariable('config')) {
        configFile = 'static/config_' + getQueryVariable('config') + '.json';
    } else if (typeof window.kiwiConfig === 'function') {
        try {
            configObj = window.kiwiConfig();
        } catch (err) {
            log.error('Config file: ' + err.stack);
            showError();
        }
    } else if (document.querySelector('meta[name="kiwiconfig"]')) {
        configFile = document.querySelector('meta[name="kiwiconfig"]').content;
    } else if (document.querySelector('script[name="kiwiconfig"]')) {
        let configContents = document.querySelector('script[name="kiwiconfig"]').innerHTML;

        try {
            configObj = JSON.parse(configContents);
        } catch (parseErr) {
            log.error('Config file: ' + parseErr.stack);
            showError();
        }
    }

    let configLoader = new ConfigLoader();
    (configObj ? configLoader.loadFromObj(configObj) : configLoader.loadFromUrl(configFile))
        .then(applyConfig)
        .then(initState)
        .then(initInputCommands)
        .then(initLocales)
        .then(initThemes)
        .then(loadPlugins)
        .then(startApp)
        .catch(showError);
}

function applyConfig(config) {
    Misc.dedotObject(config);
    applyConfigObj(config, state.settings);

    // Update the window title if we have one
    if (state.settings.windowTitle) {
        window.document.title = state.settings.windowTitle;
    }
    state.$watch('settings.windowTitle', (newVal) => {
        window.document.title = newVal;
    });
}

// Recursively merge an object onto another via Vue.$set
function applyConfigObj(obj, target) {
    _.each(obj, (val, key) => {
        if (typeof val === 'object') {
            if (typeof target[key] !== 'object') {
                // Create the correct type of object
                let newVal = _.isArray(val) ?
                    [] :
                    {};

                Vue.set(target, key, newVal);
            }
            applyConfigObj(val, target[key]);
        } else {
            Vue.set(target, key, val);
        }
    });
}

function loadPlugins() {
    return new Promise((resolve, reject) => {
        let plugins = state.settings.plugins || [];
        let pluginIdx = -1;

        loadNextScript();

        function loadNextScript(sSrc, fOnload) {
            let plugin = plugins[++pluginIdx];

            if (!plugin) {
                resolve();
                return;
            }

            if (plugin.url.indexOf('.js') > -1) {
                // The plugin is a .js file so inject it as a script
                let scr = document.createElement('script');
                scr.onerror = () => {
                    log.error(`Error loading plugin '${plugin.name}' from '${plugin.url}'`);
                    loadNextScript();
                };
                scr.onload = () => {
                    loadNextScript();
                };

                document.body.appendChild(scr);
                scr.src = plugin.url;
            } else {
                // Treat the plugin as a HTML document and just inject it into the document
                fetch(plugin.url).then(response => response.text()).then((pluginRaw) => {
                    let el = document.createElement('div');
                    el.id = 'kiwi_plugin_' + plugin.name.replace(/[ "']/g, '');
                    el.style.display = 'none';
                    el.innerHTML = pluginRaw;

                    // The browser won't execute any script elements so we need to extract them and
                    // place them into the DOM using our own script elements
                    el.querySelectorAll('script').forEach(limitedScr => {
                        limitedScr.parentElement.removeChild(limitedScr);
                        let scr = document.createElement('script');
                        scr.text = limitedScr.text;
                        el.appendChild(scr);
                    });

                    document.body.appendChild(el);
                    loadNextScript();
                }).catch(() => {
                    log.error(`Error loading plugin '${plugin.name}' from '${plugin.url}'`);
                    loadNextScript();
                });
            }
        }
    });
}

function initLocales() {
    Vue.use(VueI18Next);

    // Make the translation services available via the global API
    api.i18n = i18next;

    i18next.use(i18nextXHR);
    i18next.init({
        whitelist: AvailableLocales.locales,
        fallbackLng: 'en-us',
        lowerCaseLng: true,
        backend: {
            loadPath: 'static/locales/{{lng}}.json',

            // allow cross domain requests
            crossDomain: false,

            // allow credentials on cross domain requests
            withCredentials: false,
        },
        interpolation: {
            // We let vuejs handle HTML output escaping
            escapeValue: false,
        },
    });

    // Build in the english translation so it can be used as a fallback
    i18next.addResourceBundle('en-us', 'translation', FallbackLocale);

    // Override the $t function so that empty translations fallback to en-us
    Vue.mixin({
        computed: {
            $t() {
                return (key, options) => {
                    let val = this.$i18n.i18next.t(key, options, this.$i18n.i18nLoadedAt);
                    if (!val) {
                        let opts = options || {};
                        opts.lng = 'en-us';
                        val = this.$i18n.i18next.t(key, opts, this.$i18n.i18nLoadedAt);
                    }
                    return val;
                };
            },
        },
    });

    let defaultLang = state.setting('language');
    let preferredLangs = _.clone(window.navigator && window.navigator.languages) || [];

    // our configs default lang overrides all others
    if (defaultLang) {
        preferredLangs.unshift(defaultLang);
    }

    // set a default language
    i18next.changeLanguage('en-us');

    // Go through our browser languages until we find one that we support
    for (let idx = 0; idx < preferredLangs.length; idx++) {
        let lang = preferredLangs[idx];

        // if this is a language such as 'fr', add a following one of 'fr-fr' to cover
        // both cases
        if (lang.length === 2) {
            preferredLangs.splice(idx + 1, 0, lang + '-' + lang);
        }

        if (_.includes(AvailableLocales.locales, lang.toLowerCase())) {
            i18next.changeLanguage(lang, (err, t) => {
                if (err) {
                    // setting the language failed so set default again
                    i18next.changeLanguage('en-us');
                }
            });
            break;
        }
    }
}

async function initState() {
    let stateKey = state.settings.startupOptions.state_key;

    // Default to a preset key if it wasn't set
    if (typeof stateKey === 'undefined') {
        stateKey = 'kiwi-state';
    }

    let persistLog = Logger.namespace('StatePersistence');
    let persist = new StatePersistence(stateKey || '', state, Storage, persistLog);
    persist.includeBuffers = !!state.settings.startupOptions.remember_buffers;

    if (stateKey) {
        await persist.loadStateIfExists();
    }

    api.setState(state);
}

function initThemes() {
    let themeMgr = ThemeManager.instance(state);
    api.setThemeManager(themeMgr);

    let argTheme = getQueryVariable('theme');
    if (argTheme) {
        themeMgr.setTheme(argTheme);
    }
}

function initInputCommands() {
    /* eslint-disable no-new */
    new InputHandler(state);
}

function startApp() {
    api.emit('init');

    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(App),
        i18n: new VueI18Next(i18next),
    });

    api.emit('ready');
}

function showError(err) {
    if (err) {
        log.error('Error starting Kiwi IRC:', err);
    } else {
        log.error('Unknown error starting Kiwi IRC');
    }

    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(StartupError),
    });
}
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import {
  domain,
  fromNow,
  dataMatchFormatter,
  formatTimestamp
} from './filters'
import App from './components/App.vue'
import Home from './components/Home.vue'
import Task from './components/Task.vue'
import TaskIndex from './components/TaskIndex.vue'
import TaskNew from './components/TaskNew.vue'
import Log from './components/Log.vue'
import Monitor from './components/Monitor.vue'
import Alert from './components/Alert.vue'

// install router
Vue.use(Router)

// register filters globally
Vue.filter('fromNow', fromNow)
Vue.filter('domain', domain)
Vue.filter('dataMatchFormatter', dataMatchFormatter)
Vue.filter('formatTimestamp', formatTimestamp)

// routing
var router = new Router()

router.map({
  '/': {
    component: Home
  },
  '/task': {
    component: Task,
    subRoutes: {
      '/index': {
        component: TaskIndex
      },
      '/new': {
        component: TaskNew
      }
    }
  },
  '/log': {
    component: Log
  },
  '/monitor': {
    component: Monitor
  },
  '/alert': {
    component: Alert
  }
})

router.beforeEach(() => {
  window.scrollTo(0, 0)
})

router.redirect({
  '*': '/'
})

router.start(App, '#app')
<commit_msg>add TaskShow<commit_after>import Vue from 'vue'
import Router from 'vue-router'
import {
  domain,
  fromNow,
  dataMatchFormatter,
  formatTimestamp
} from './filters'
import App from './components/App.vue'
import Home from './components/Home.vue'
import Task from './components/Task.vue'
import TaskIndex from './components/TaskIndex.vue'
import TaskNew from './components/TaskNew.vue'
import TaskShow from './components/TaskShow.vue'
import Log from './components/Log.vue'
import Monitor from './components/Monitor.vue'
import Alert from './components/Alert.vue'

// install router
Vue.use(Router)

// register filters globally
Vue.filter('fromNow', fromNow)
Vue.filter('domain', domain)
Vue.filter('dataMatchFormatter', dataMatchFormatter)
Vue.filter('formatTimestamp', formatTimestamp)

// routing
var router = new Router()

router.map({
  '/': {
    component: Home
  },
  '/task': {
    component: Task,
    subRoutes: {
      '/index': {
        component: TaskIndex
      },
      '/new': {
        component: TaskNew
      },
      '/:id': {
        component: TaskShow
      }
    }
  },
  '/log': {
    component: Log
  },
  '/monitor': {
    component: Monitor
  },
  '/alert': {
    component: Alert
  }
})

router.beforeEach(() => {
  window.scrollTo(0, 0)
})

router.redirect({
  '*': '/'
})

router.start(App, '#app')
<|endoftext|>


<commit_before>/* global
    UserAccounts: false,
    UALog: false,
    UALinkPlugin: false
*/
'use strict';

// ------------------------------------------
//  Logs the start of execution for this file
// ------------------------------------------
UALog.trace('Loading main.js');

UALog.trace('Adding links plugin');
var links = new UALinkPlugin();
UserAccounts.registerPlugin(links);
<commit_msg>inline plugin instantiation<commit_after>/* global
    UserAccounts: false,
    UALog: false,
    UALinkPlugin: false
*/
'use strict';

// ------------------------------------------
//  Logs the start of execution for this file
// ------------------------------------------
UALog.trace('Loading main.js');

UALog.trace('Adding links plugin');
UserAccounts.registerPlugin(new UALinkPlugin());
<|endoftext|>


<commit_before>var _ = require('underscore')._;

var commands = function(dbot) {
    return {
        '~usage': function(event) {
            var commandName = event.params[1];
            if(_.has(dbot.usage, commandName)) {
                event.reply(dbot.t('usage', {
                    'command': commandName,
                    'usage': dbot.usage[commandName]
                }));
            } else {
                event.reply(dbot.t('no_usage_info', {
                    'command': commandName
                }));
            }
        },

        '~help': function(event) {
            var moduleName = event.params[1];
            if(!_.has(dbot.modules, moduleName)) {
                var moduleName = dbot.commands[moduleName].module;
            }

            if(moduleName && _.has(dbot.config[moduleName], 'help')) {
                var help = dbot.config[moduleName].help;
                event.reply(dbot.t('help_link', {
                    'module': moduleName,
                    'link': help
                }));
            } else {
                if(!moduleName) {
                    moduleName = event.params[1];
                }
                event.reply(dbot.t('no_help', { 'module': moduleName }))
            }
        }
    };
};

exports.fetch = function(dbot) {
    return commands(dbot);
};
<commit_msg>adding some extra checks to ~help command to prevent errors<commit_after>var _ = require('underscore')._;

var commands = function(dbot) {
    return {
        '~usage': function(event) {
            var commandName = event.params[1];
            if(_.has(dbot.usage, commandName)) {
                event.reply(dbot.t('usage', {
                    'command': commandName,
                    'usage': dbot.usage[commandName]
                }));
            } else {
                event.reply(dbot.t('no_usage_info', {
                    'command': commandName
                }));
            }
        },

        '~help': function(event) {
            var moduleName = event.params[1];
            if(!moduleName) {
                event.reply(dbot.t('usage', {
                    'command': '~help',
                    'usage': '~help [module]'
                }));
                return;
            }

            if(!_.has(dbot.modules, moduleName)) {
                if(_.has(dbot.commands, moduleName)) {
                    var moduleName = dbot.commands[moduleName].module;
                } else {
                    var moduleName = undefined;
                }
            }

            if(moduleName && _.has(dbot.config[moduleName], 'help')) {
                var help = dbot.config[moduleName].help;
                event.reply(dbot.t('help_link', {
                    'module': moduleName,
                    'link': help
                }));
            } else {
                if(!moduleName) {
                    moduleName = event.params[1];
                }
                event.reply(dbot.t('no_help', { 'module': moduleName }))
            }
        }
    };
};

exports.fetch = function(dbot) {
    return commands(dbot);
};
<|endoftext|>