<commit_before>/**
 * Module dependencies.
 */
var util = require('util')
	, OAuthStrategy = require('passport-oauth').OAuthStrategy
	, InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {

	options = options || {};
	options.requestTokenURL = options.requestTokenURL || 'https://secure.trademe.co.nz/Oauth/RequestToken';
	options.accessTokenURL = options.accessTokenURL || 'https://secure.trademe.co.nz/Oauth/AccessToken';
	options.userAuthorizationURL = options.userAuthorizationURL || 'https://secure.trademe.co.nz/Oauth/Authorize';
	options.sessionKey = options.sessionKey || 'oauth:trademe';

	OAuthStrategy.call(this, options, verify);
	this.name = 'trademe';

	this._skipExtendedUserProfile = (options.skipExtendedUserProfile === undefined) ? false : options.skipExtendedUserProfile;
}

/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);

/**
 * Authenticate request by delegating to Trademe using OAuth.
 *
 * @param {Object} req
 * @api protected
 */
Strategy.prototype.authenticate = function(req, options) {
	// authentication failure.
	if (req.query && req.query.denied) {
		return this.fail();
	}

	// Call the base class for standard OAuth authentication.
	OAuthStrategy.prototype.authenticate.call(this, req, options);
}

/**
 * Retrieve member profile from Trademe.
 *
 * http://api.trademe.co.nz/v1/Member/Profile.json
 * { "Id": 5690 }
 *
 * http://api.trademe.co.nz/v1/Member/5690/Profile.json
 * {
 * "Biography" : "",
 * "DateRemoved" : "/Date(0)/",
 * "FirstName" : "Karol",
 * "IsEnabled" : true,
 * "Member" : { "DateAddressVerified" : "/Date(0)/",
 *     "DateJoined" : "/Date(946551600000)/",
 *     "FeedbackCount" : 20,
 *     "IsAddressVerified" : false,
 *     "IsAuthenticated" : true,
 *     "IsDealer" : false,
 *     "MemberId" : 5690,
 *     "Nickname" : "silverhalides",
 *     "Suburb" : "Wellington City",
 *     "UniqueNegative" : 0,
 *     "UniquePositive" : 20
 *   },
 * "Occupation" : "",
 * "Photo" : "http://images.trademe.co.nz/photoserver/profiles/member_profile5690v1",
 * "Quote" : ""
 * }
 *
 * @param {String} token
 * @param {String} tokenSecret
 * @param {Object} params
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {

	var profile = { provider: 'trademe' };

	if (!this._skipExtendedUserProfile) {

		var url = 'http://api.trademe.co.nz/v1/Member/Profile.json';
		this._oauth.get(url, token, tokenSecret, function (err, body, res) {

			if (err) { return done(new InternalOAuthError('failed to fetch member profile', err)); }

			var object = {};

			try {
				object = JSON.parse(body);
			} catch (e) {
				object = null;
				done(e);
			}

			if (object === undefined || object === null) {
				console.log('Unfortunately the object is non-existent');
			} else {
				profile.id = object.Id;
				profile._raw = body;
				profile._json = object;

				done(null, profile);
			}
		});
	} else {
		profile.id = params.user_id;

		done(null, profile);
	}
}

//
Strategy.prototype.requestTokenParams = function(options) {
  var params = options || {};

  var scope = options.scope;
  if (scope) {
    if (Array.isArray(scope)) { scope = scope.join(' '); }
    params['scope'] = scope;
  }
  return params;
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<commit_msg>Allow more configuration (#1)<commit_after>/**
 * Module dependencies.
 */
var util = require('util')
	, OAuthStrategy = require('passport-oauth').OAuthStrategy
	, InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {

	options = options || {};
	options.sessionKey = options.sessionKey || 'oauth:trademe';
	options.apiVersion = options.apiVersion || 'v1';

	options.apiHost = options.apiHost || 'https://api.trademe.co.nz';
	options.oAuthBaseUrl = options.oAuthBaseUrl || 'https://secure.trademe.co.nz/Oauth';

	if(options.sandbox) {
		options.apiHost = options.apiHost.replace('trademe.co.nz', 'tmsandbox.co.nz');
		options.oAuthBaseUrl = options.oAuthBaseUrl.replace('trademe.co.nz', 'tmsandbox.co.nz');
	}

	options.requestTokenURL = options.requestTokenURL || options.oAuthBaseUrl + '/RequestToken';
	options.accessTokenURL = options.accessTokenURL || options.oAuthBaseUrl + '/AccessToken';
	options.userAuthorizationURL = options.userAuthorizationURL || options.oAuthBaseUrl + '/Authorize';

	OAuthStrategy.call(this, options, verify);
	this.name = 'trademe';

	this._options = options;

	this._skipExtendedUserProfile = (options.skipExtendedUserProfile === undefined) ? false : options.skipExtendedUserProfile;
}

/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);

/**
 * Authenticate request by delegating to Trademe using OAuth.
 *
 * @param {Object} req
 * @api protected
 */
Strategy.prototype.authenticate = function(req, options) {
	// authentication failure.
	if (req.query && req.query.denied) {
		return this.fail();
	}

	// Call the base class for standard OAuth authentication.
	OAuthStrategy.prototype.authenticate.call(this, req, options);
}

/**
 * Retrieve member profile from Trademe.
 *
 * @param {String} token
 * @param {String} tokenSecret
 * @param {Object} params
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {

	var profile = { provider: 'trademe' };

	var that = this;

	if (!this._skipExtendedUserProfile) {

		var url = this._options.apiHost + '/' + this._options.apiVersion + '/MyTradeMe/Summary.json';
		this._oauth.get(url, token, tokenSecret, function (err, body, res) {

			if (err) { return done(new InternalOAuthError('failed to fetch member profile', err)); }

			var myTradeMeObject = {};

			try {
				myTradeMeObject = JSON.parse(body);
			} catch (e) {
				myTradeMeObject = null;
				return done(e);
			}

			if (myTradeMeObject === undefined || myTradeMeObject === null) {
				return done(new Error('Unfortunately the myTradeMeObject is non-existent'));
			}

			if(!myTradeMeObject.MemberId) {
				return done(new Error('No MemberId returned'));
			}

			const memberUrl = that._options.apiHost + '/' + that._options.apiVersion + '/Member/' + myTradeMeObject.MemberId +'/Profile.json';

			that._oauth.get(memberUrl, token, tokenSecret, function (err, body, res) {

				if (err) { return done(new InternalOAuthError('failed to fetch member profile', err)); }

				var object = {};

				try {
					object = JSON.parse(body);
				} catch (e) {
					object = null;
					return done(e);
				}

				if (object === undefined || object === null) {
					return done(new Error('Unfortunately the object is non-existent'));
				}

				profile.id = object.Member.MemberId.toString();
				profile.emails = [
					{
						value: myTradeMeObject.Email
					}
				];
				profile.username = myTradeMeObject.Nickname
				profile.displayName = [
					myTradeMeObject.FirstName || '',
					myTradeMeObject.LastName || ''
				].join(' ').trim();
				profile.photos = object.Photo ? [
					{
						value: object.Photo
					}
				] : [];
				profile.member = object;
				profile.mine = myTradeMeObject;

				return done(null, profile);
			});
		});
	} else {
		profile.id = params.user_id;

		return done(null, profile);
	}
}

//
Strategy.prototype.requestTokenParams = function(options) {
  var params = options || {};

  var scope = options.scope;
  if (scope) {
    if (Array.isArray(scope)) { scope = scope.join(' '); }
    params['scope'] = scope;
  }
  return params;
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<|endoftext|>


<commit_before>ig.module(
        'plusplus.debug.maps-panel'
    )
    .requires(
        'plusplus.debug.menu',
        'plusplus.core.game',
        'plusplus.core.background-map'
    )
    .defines(function () {
        "use strict";

        ig.GameExtended.inject({
            buildLevel: function () {
                this.parent.apply( this, arguments );
                ig.debug.panels.maps.load(this);
            },
            unloadLevel: function () {
                this.parent.apply( this, arguments );
                ig.debug.panels.maps.maps = [];
            }
        });

        ig.DebugMapsPanel = ig.DebugPanel.extend({
            maps: [],
            mapScreens: [],

            init: function (name, label) {
                this.parent(name, label);
                this.load();
            },

            load: function (game) {
                this.options = [];
                this.panels = [];

                if (!game) {
                    this.container.innerHTML = 'No Maps Loaded';
                    return;
                }

                this.maps = [];

                for ( var i = 0, il = game.layers.length; i < il; i++ ) {

                    var layer = game.layers[ i ];

                    if ( layer.numBackgroundMaps > 0 ) {

                        for ( var j = 0, jl = layer.items.length; j < jl; j++ ) {

                            var item = layer.items[ j ];

                            if ( item instanceof ig.BackgroundMap ) {

                                this.maps.push( item );

                            }

                        }

                    }

                }

                if (this.maps.length === 0) {
                    this.container.innerHTML = 'No Maps Loaded';
                    return;
                }

                this.mapScreens = [];
                this.container.innerHTML = '';

                for (var m = 0; m < this.maps.length; m++) {
                    var map = this.maps[m];

                    var subPanel = new ig.DebugPanel(m, 'Layer ' + m);

                    var head = new ig.$new('strong');
                    head.textContent = m + ': ' + map.tiles.path;
                    subPanel.container.appendChild(head);

                    subPanel.addOption(new ig.DebugOption('Enabled', map, 'enabled'));
                    subPanel.addOption(new ig.DebugOption('Pre Rendered', map, 'preRender'));
                    subPanel.addOption(new ig.DebugOption('Show Chunks', map, 'debugChunks'));

                    this.generateMiniMap(subPanel, map, m);
                    this.addPanel(subPanel);
                }
            },

            generateMiniMap: function (panel, mapBase, id) {
                var s = ig.system.scale; // we'll need this a lot

                // get all maps

                var maps = [ mapBase ];

                if ( mapBase.mergedMaps ) {

                    maps = maps.concat( mapBase.mergedMaps );

                }

                // get max map size

                var totalMergedWidth = 0;
                var totalMergedHeight = 0;

                for ( var i = 0, il = maps.length; i < il; i++ ) {

                    var map = maps[ i ];

                    totalMergedWidth = Math.max( totalMergedWidth, map.width );
                    totalMergedHeight = Math.max( totalMergedHeight, map.height );

                }

                // create the minimap canvas
                var mapCanvas = ig.$new('canvas');
                mapCanvas.width = totalMergedWidth * s;
                mapCanvas.height = totalMergedHeight * s;
                var ctx = mapCanvas.getContext('2d');

                if (ig.game.clearColor) {
                    ctx.fillStyle = ig.game.clearColor;
                    ctx.fillRect(0, 0, mapCanvas.width, mapCanvas.height);
                }

                for ( var i = 0, il = maps.length; i < il; i++ ) {

                    var map = maps[ i ];

                    // resize the tileset, so that one tile is 's' pixels wide and high
                    var ts = ig.$new('canvas');
                    var tsctx = ts.getContext('2d');

                    var w = map.tiles.width * s;
                    var h = map.tiles.height * s;
                    var ws = w / map.tilesize;
                    var hs = h / map.tilesize;
                    tsctx.drawImage(map.tiles.data, 0, 0, w, h, 0, 0, ws, hs);

                    // draw the map
                    var tile = 0;
                    for (var x = 0; x < map.width; x++) {
                        for (var y = 0; y < map.height; y++) {
                            if ((tile = map.data[y][x])) {
                                ctx.drawImage(
                                    ts,
                                    Math.floor(((tile - 1) * s) % ws),
                                    Math.floor((tile - 1) * s / ws) * s,
                                    s, s,
                                    x * s, y * s,
                                    s, s
                                );
                            }
                        }
                    }
                }

                var mapContainer = ig.$new('div');
                mapContainer.className = 'ig_debug_map_container';
                mapContainer.style.width = map.width * s + 'px';
                mapContainer.style.height = map.height * s + 'px';

                var mapScreen = ig.$new('div');
                mapScreen.className = 'ig_debug_map_screen';
                mapScreen.style.width = ((ig.system.width / map.tilesize) * s - 2) + 'px';
                mapScreen.style.height = ((ig.system.height / map.tilesize) * s - 2) + 'px';
                this.mapScreens[id] = mapScreen;

                mapContainer.appendChild(mapCanvas);
                mapContainer.appendChild(mapScreen);
                panel.container.appendChild(mapContainer);
            },

            afterRun: function () {
                // Update the screen position DIV for each mini-map
                var s = ig.system.scale;
                for (var m = 0; m < this.maps.length; m++) {
                    var map = this.maps[m];
                    var screen = this.mapScreens[m];

                    if (!map || !screen) { // Quick sanity check
                        continue;
                    }

                    var x = map.scroll.x / map.tilesize;
                    var y = map.scroll.y / map.tilesize;

                    if (map.repeat) {
                        x %= map.width;
                        y %= map.height;
                    }

                    screen.style.left = (x * s) + 'px';
                    screen.style.top = (y * s) + 'px';
                }
            }
        });

        ig.debug.addPanel({
            type: ig.DebugMapsPanel,
            name: 'maps',
            label: 'Background Maps'
        });

    });<commit_msg>fix for maps debug minimap<commit_after>ig.module(
        'plusplus.debug.maps-panel'
    )
    .requires(
        'plusplus.debug.menu',
        'plusplus.core.game',
        'plusplus.core.background-map'
    )
    .defines(function () {
        "use strict";

        ig.GameExtended.inject({
            buildLevel: function () {
                this.parent.apply( this, arguments );
                ig.debug.panels.maps.load(this);
            },
            unloadLevel: function () {
                this.parent.apply( this, arguments );
                ig.debug.panels.maps.maps = [];
            }
        });

        ig.DebugMapsPanel = ig.DebugPanel.extend({
            maps: [],
            mapScreens: [],

            init: function (name, label) {
                this.parent(name, label);
                this.load();
            },

            load: function (game) {
                this.options = [];
                this.panels = [];

                if (!game) {
                    this.container.innerHTML = 'No Maps Loaded';
                    return;
                }

                this.maps = [];

                for ( var i = 0, il = game.layers.length; i < il; i++ ) {

                    var layer = game.layers[ i ];

                    if ( layer.numBackgroundMaps > 0 ) {

                        for ( var j = 0, jl = layer.items.length; j < jl; j++ ) {

                            var item = layer.items[ j ];

                            if ( item instanceof ig.BackgroundMap ) {

                                this.maps.push( item );

                            }

                        }

                    }

                }

                if (this.maps.length === 0) {
                    this.container.innerHTML = 'No Maps Loaded';
                    return;
                }

                this.mapScreens = [];
                this.container.innerHTML = '';

                for (var m = 0; m < this.maps.length; m++) {
                    var map = this.maps[m];

                    var subPanel = new ig.DebugPanel(m, 'Layer ' + m);

                    var head = new ig.$new('strong');
                    head.textContent = m + ': ' + map.tiles.path;
                    subPanel.container.appendChild(head);

                    subPanel.addOption(new ig.DebugOption('Enabled', map, 'enabled'));
                    subPanel.addOption(new ig.DebugOption('Pre Rendered', map, 'preRender'));
                    subPanel.addOption(new ig.DebugOption('Show Chunks', map, 'debugChunks'));

                    this.generateMiniMap(subPanel, map, m);
                    this.addPanel(subPanel);
                }
            },

            generateMiniMap: function (panel, mapBase, id) {
                var s = ig.system.scale; // we'll need this a lot

                // get all maps

                var maps = [ mapBase ];

                if ( mapBase.mergedMaps ) {

                    maps = maps.concat( mapBase.mergedMaps );

                }

                // get max map size

                var totalMergedWidth = 0;
                var totalMergedHeight = 0;

                for ( var i = 0, il = maps.length; i < il; i++ ) {

                    var map = maps[ i ];

                    totalMergedWidth = Math.max( totalMergedWidth, map.width );
                    totalMergedHeight = Math.max( totalMergedHeight, map.height );

                }

                // create the minimap canvas
                var mapCanvas = ig.$new('canvas');
                mapCanvas.width = totalMergedWidth * s;
                mapCanvas.height = totalMergedHeight * s;
                var ctx = mapCanvas.getContext('2d');

                if (ig.game.clearColor) {
                    ctx.fillStyle = ig.game.clearColor;
                    ctx.fillRect(0, 0, mapCanvas.width, mapCanvas.height);
                }

                for ( var i = 0, il = maps.length; i < il; i++ ) {

                    var map = maps[ i ];

					// make sure map is resized to system scale

					if ( !map.tiles.ignoreSystemScale && map.tiles._scale !== s) {

                        map.tiles.resize(s);

                    }

                    // resize the tileset, so that one tile is 's' pixels wide and high
                    var ts = ig.$new('canvas');
                    var tsctx = ts.getContext('2d');

                    var w = map.tiles.width * s;
                    var h = map.tiles.height * s;
                    var ws = w / map.tilesize;
                    var hs = h / map.tilesize;

                    tsctx.drawImage(map.tiles.data, 0, 0, w, h, 0, 0, ws, hs);

                    // draw the map
                    var tile = 0;
                    for (var x = 0; x < map.width; x++) {
                        for (var y = 0; y < map.height; y++) {
                            if ((tile = map.data[y][x])) {
                                ctx.drawImage(
                                    ts,
                                    Math.floor(((tile - 1) * s) % ws),
                                    Math.floor((tile - 1) * s / ws) * s,
                                    s, s,
                                    x * s, y * s,
                                    s, s
                                );
                            }
                        }
                    }
                }

                var mapContainer = ig.$new('div');
                mapContainer.className = 'ig_debug_map_container';
                mapContainer.style.width = map.width * s + 'px';
                mapContainer.style.height = map.height * s + 'px';

                var mapScreen = ig.$new('div');
                mapScreen.className = 'ig_debug_map_screen';
                mapScreen.style.width = ((ig.system.width / map.tilesize) * s - 2) + 'px';
                mapScreen.style.height = ((ig.system.height / map.tilesize) * s - 2) + 'px';
                this.mapScreens[id] = mapScreen;

                mapContainer.appendChild(mapCanvas);
                mapContainer.appendChild(mapScreen);
                panel.container.appendChild(mapContainer);
            },

            afterRun: function () {
                // Update the screen position DIV for each mini-map
                var s = ig.system.scale;
                for (var m = 0; m < this.maps.length; m++) {
                    var map = this.maps[m];
                    var screen = this.mapScreens[m];

                    if (!map || !screen) { // Quick sanity check
                        continue;
                    }

                    var x = map.scroll.x / map.tilesize;
                    var y = map.scroll.y / map.tilesize;

                    if (map.repeat) {
                        x %= map.width;
                        y %= map.height;
                    }

                    screen.style.left = (x * s) + 'px';
                    screen.style.top = (y * s) + 'px';
                }
            }
        });

        ig.debug.addPanel({
            type: ig.DebugMapsPanel,
            name: 'maps',
            label: 'Background Maps'
        });

    });<|endoftext|>


<commit_before>const {remote, ipcRenderer} = require('electron')
const clipboard = remote.clipboard
const Menu = remote.Menu
const MenuItem = remote.MenuItem

const menus = remote.require('./menus')

const config = remote.require('./config')
const rpc = require('../utils/rpc')

let el
let titleEl
let titleWrapper

var title = 'Ōryōki'
var isShown = config.getPreference('show_title_bar')
var isDisabled = false
let hasLightTheme = false

function init () {
  el = document.querySelector('handle')
  titleWrapper = document.querySelector('.titlewrapper')
  titleEl = el.querySelector('.title')

  titleEl.addEventListener('mousedown', openMenu)
  // no way of telling when pop-up menu has been closed, so:
  window.addEventListener('mouseup', unselectTitle)
  window.addEventListener('mousemove', unselectTitle)

  window.addEventListener('resize', updateTitleUI)

  el.querySelector('.button.close').addEventListener('click', () => {
    remote.getCurrentWindow().close()
  })

  el.querySelector('.button.minimize').addEventListener('click', () => {
    remote.getCurrentWindow().minimize()
  })

  el.querySelector('.button.fullscreen').addEventListener('click', () => {
    remote.getCurrentWindow().setFullScreen(true)
    hide()
  })

  el.ondragover = (e) => {
    e.preventDefault()
  }

  el.ondrop = (e) => {
    e.preventDefault()
  }

  rpc.on('handle:toggle', toggle)
  rpc.on('view:title-updated', updateTitle)
  rpc.on('handle:toggle-light-theme', toggleLightTheme)

  updateTitle(title)
  if (isShown) show()
  else hide()
  console.log('[handle] ✔')
}

function show () {
  el.classList.remove('hide')
  win = remote.getCurrentWindow()
  win.setSize(
    win.getSize()[0],
    win.getSize()[1] + 24
  )
  isShown = true
  win.hasTitleBar = true
  menus.refresh()
  window.dispatchEvent(new Event('resize'))
}

function hide () {
  el.classList.add('hide')
  win = remote.getCurrentWindow()
  win.setSize(
    win.getSize()[0],
    win.getSize()[1] - 24
  )
  isShown = false
  win.hasTitleBar = false
  menus.refresh()
  window.dispatchEvent(new Event('resize'))
}

function toggle () {
  if (isShown) hide()
  else show()
}

function disable () {
  el.classList.add('disabled')
  isDisabled = true
}

function enable () {
  el.classList.remove('disabled')
  isDisabled = false
}

function updateTitle (newTitle) {
  titleEl.setAttribute('title', newTitle)
  title = newTitle

  updateTitleUI()
  remote.getCurrentWindow().setTitle(newTitle)
}

function updateTitleUI () {
  titleEl.innerText = title

  let titleX = (window.innerWidth - titleEl.offsetWidth)/2
  let buttonsWidth = document.querySelector('.buttons').offsetWidth

  let titleWidth = titleEl.offsetWidth
  let available = window.innerWidth - buttonsWidth

  // clear alignement classes
  titleEl.classList.remove('align-left')
  titleWrapper.classList.remove('align-left')

  if (titleX < buttonsWidth + 5) { // 5 margin to avoid jitter
    // when centered title would overlay buttons
    titleEl.classList.add('align-left')
    titleWrapper.classList.add('align-left')
    lastVisibleCharIndex = document.caretRangeFromPoint(window.innerWidth - 20, 12).endOffset
    if(lastVisibleCharIndex > 1) titleEl.innerText = titleEl.innerText.substring(0, lastVisibleCharIndex) + '...'
    return
  }

  // else, center it on the whole page
  titleEl.classList.remove('align-left')
  titleWrapper.classList.remove('align-left')
}

function unselectTitle () {
  titleEl.classList.remove('selected')
}

function toggleLightTheme () {
  if(hasLightTheme) {
    el.classList.remove('light')
    hasLightTheme = false
  }
  else {
    el.classList.add('light')
    hasLightTheme = true
  }
}

function openMenu () {
  titleEl.classList.add('selected')

  var menu = new Menu()
  menu.append(
    new MenuItem(
      {
        label: 'Copy URL',
        click: function () {
          console.log('Copied!')
          unselectTitle()
        }
      }
    )
  )
  menu.append(
    new MenuItem(
      {
        label: 'Copy Screenshot',
        accelerator: 'Cmd+Shift+C',
        click: function () {
          unselectTitle()
          remote.require('./camera').copyScreenshot()
        }
      }
    )
  )
  menu.append(
    new MenuItem(
      {
        type: 'separator'
      }
    )
  )

  menu.popup(remote.getCurrentWindow(), {
    async: true
  })
}

module.exports = {
  init: init,
  show: show,
  hide: hide,
  updateTitle: updateTitle
}
<commit_msg>add handle menu actions<commit_after>const {remote, ipcRenderer} = require('electron')
const clipboard = remote.clipboard
const Menu = remote.Menu
const MenuItem = remote.MenuItem

const menus = remote.require('./menus')

const config = remote.require('./config')
const rpc = require('../utils/rpc')

let el
let titleEl
let titleWrapper

var title = 'Ōryōki'
var isShown = config.getPreference('show_title_bar')
var isDisabled = false
let hasLightTheme = false

function init () {
  el = document.querySelector('handle')
  titleWrapper = document.querySelector('.titlewrapper')
  titleEl = el.querySelector('.title')

  titleEl.addEventListener('mousedown', openMenu)
  // no way of telling when pop-up menu has been closed, so:
  window.addEventListener('mouseup', unselectTitle)
  window.addEventListener('mousemove', unselectTitle)

  window.addEventListener('resize', updateTitleUI)

  el.querySelector('.button.close').addEventListener('click', () => {
    remote.getCurrentWindow().close()
  })

  el.querySelector('.button.minimize').addEventListener('click', () => {
    remote.getCurrentWindow().minimize()
  })

  el.querySelector('.button.fullscreen').addEventListener('click', () => {
    remote.getCurrentWindow().setFullScreen(true)
    hide()
  })

  el.ondragover = (e) => {
    e.preventDefault()
  }

  el.ondrop = (e) => {
    e.preventDefault()
  }

  rpc.on('handle:toggle', toggle)
  rpc.on('view:title-updated', updateTitle)
  rpc.on('handle:toggle-light-theme', toggleLightTheme)

  updateTitle(title)
  if (isShown) show()
  else hide()
  console.log('[handle] ✔')
}

function show () {
  el.classList.remove('hide')
  win = remote.getCurrentWindow()
  win.setSize(
    win.getSize()[0],
    win.getSize()[1] + 24
  )
  isShown = true
  win.hasTitleBar = true
  menus.refresh()
  window.dispatchEvent(new Event('resize'))
}

function hide () {
  el.classList.add('hide')
  win = remote.getCurrentWindow()
  win.setSize(
    win.getSize()[0],
    win.getSize()[1] - 24
  )
  isShown = false
  win.hasTitleBar = false
  menus.refresh()
  window.dispatchEvent(new Event('resize'))
}

function toggle () {
  if (isShown) hide()
  else show()
}

function disable () {
  el.classList.add('disabled')
  isDisabled = true
}

function enable () {
  el.classList.remove('disabled')
  isDisabled = false
}

function updateTitle (newTitle) {
  titleEl.setAttribute('title', newTitle)
  title = newTitle

  updateTitleUI()
  remote.getCurrentWindow().setTitle(newTitle)
}

function updateTitleUI () {
  titleEl.innerText = title

  let titleX = (window.innerWidth - titleEl.offsetWidth)/2
  let buttonsWidth = document.querySelector('.buttons').offsetWidth

  let titleWidth = titleEl.offsetWidth
  let available = window.innerWidth - buttonsWidth

  // clear alignement classes
  titleEl.classList.remove('align-left')
  titleWrapper.classList.remove('align-left')

  if (titleX < buttonsWidth + 5) { // 5 margin to avoid jitter
    // when centered title would overlay buttons
    titleEl.classList.add('align-left')
    titleWrapper.classList.add('align-left')
    lastVisibleCharIndex = document.caretRangeFromPoint(window.innerWidth - 20, 12).endOffset
    if(lastVisibleCharIndex > 1) titleEl.innerText = titleEl.innerText.substring(0, lastVisibleCharIndex) + '...'
    return
  }

  // else, center it on the whole page
  titleEl.classList.remove('align-left')
  titleWrapper.classList.remove('align-left')
}

function unselectTitle () {
  titleEl.classList.remove('selected')
}

function toggleLightTheme () {
  if(hasLightTheme) {
    el.classList.remove('light')
    hasLightTheme = false
  }
  else {
    el.classList.add('light')
    hasLightTheme = true
  }
}

function openMenu () {
  titleEl.classList.add('selected')

  const win = remote.getCurrentWindow()
  const webview = document.querySelector('webview')
  const isFirstLoad = win.isFirstLoad

  const template = [
    {
      label: 'Copy URL',
      enabled: !(webview.src == ''),
      click: function () {
        clipboard.writeText(webview.src)
        unselectTitle()
      }
    },
    {
      label: 'Copy Screenshot',
      accelerator: 'Cmd+Shift+C',
      click: function () {
        unselectTitle()
        remote.require('./camera').copyScreenshot()
      }
    },
    {
      type: 'separator'
    },
    {
      label: 'Back',
      accelerator: 'CmdOrCtrl+[',
      enabled: !isFirstLoad,
      click () {
        webview.goBack()
      }
    },
    {
      label: 'Forward',
      accelerator: 'CmdOrCtrl+]',
      enabled: !isFirstLoad,
      click () {
        webview.goForward()
      }
    },
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      enabled: !isFirstLoad,
      click () {
        webview.reload()
      }
    }
  ]

  let menu = Menu.buildFromTemplate(template)
  menu.popup(win, {
    async: true
  })
}

module.exports = {
  init: init,
  show: show,
  hide: hide,
  updateTitle: updateTitle
}
<|endoftext|>


<commit_before>/**
 * Component for remote service.
 * Load remote service and add to global context.
 */
var fs = require('fs');
var pathUtil = require('../util/pathUtil');
var RemoteServer = require('pomelo-rpc').server;

/**
 * Remote component factory function
 *
 * @param {Object} app  current application context
 * @param {Object} opts construct parameters
 *                       opts.acceptorFactory {Object}: acceptorFactory.create(opts, cb)
 * @return {Object}     remote component instances
 */
module.exports = function(app, opts) {
  opts = opts || {};

  // cacheMsg is deprecated, just for compatibility here.
  opts.bufferMsg = opts.bufferMsg || opts.cacheMsg || false;
  opts.interval = opts.interval || 30;
  if(app.enabled('rpcDebugLog')) {
    opts.rpcDebugLog = true;
    opts.rpcLogger = require('pomelo-logger').getLogger('rpc-debug', __filename);
  }
  return new Component(app, opts);
};

/**
 * Remote component class
 *
 * @param {Object} app  current application context
 * @param {Object} opts construct parameters
 */
var Component = function(app, opts) {
  this.app = app;
  this.opts = opts;
};

var pro = Component.prototype;

pro.name = '__remote__';

/**
 * Remote component lifecycle function
 *
 * @param {Function} cb
 * @return {Void}
 */
pro.start = function(cb) {
  this.opts.host = this.app.getCurServer().host;
  this.opts.port = this.app.getCurServer().port;
  this.remote = genRemote(this.app, this.opts);
  this.remote.start();
  process.nextTick(cb);
};

/**
 * Remote component lifecycle function
 *
 * @param {Boolean}  force whether stop the component immediately
 * @param {Function}  cb
 * @return {Void}
 */
pro.stop = function(force, cb) {
  this.remote.stop(force);
  process.nextTick(cb);
};

/**
 * Get remote paths from application
 *
 * @param {Object} app current application context
 * @return {Array} paths
 *
 */
var getRemotePaths = function(app) {
  var paths = [];

  var role;
  // master server should not come here
  if(app.isFrontend()) {
    role = 'frontend';
  } else {
    role = 'backend';
  }

  var sysPath = pathUtil.getSysRemotePath(role), serverType = app.getServerType();
  if(fs.existsSync(sysPath)) {
    paths.push(pathUtil.remotePathRecord('sys', serverType, sysPath));
  }
  var userPath = pathUtil.getUserRemotePath(app.getBase(), serverType);
  if(fs.existsSync(userPath)) {
    paths.push(pathUtil.remotePathRecord('user', serverType, userPath));
  }

  return paths;
};

/**
 * Generate remote server instance
 *
 * @param {Object} app current application context
 * @param {Object} opts contructor parameters for rpc Server
 * @return {Object} remote server instance
 */
var genRemote = function(app, opts) {
  opts.paths = getRemotePaths(app);
  opts.context = app;
  if(!!opts.rpcServer) {
    return opts.rpcServer.create(opts);
  } else {
    return RemoteServer.create(opts);
  }
};
<commit_msg>remove host option<commit_after>/**
 * Component for remote service.
 * Load remote service and add to global context.
 */
var fs = require('fs');
var pathUtil = require('../util/pathUtil');
var RemoteServer = require('pomelo-rpc').server;

/**
 * Remote component factory function
 *
 * @param {Object} app  current application context
 * @param {Object} opts construct parameters
 *                       opts.acceptorFactory {Object}: acceptorFactory.create(opts, cb)
 * @return {Object}     remote component instances
 */
module.exports = function(app, opts) {
  opts = opts || {};

  // cacheMsg is deprecated, just for compatibility here.
  opts.bufferMsg = opts.bufferMsg || opts.cacheMsg || false;
  opts.interval = opts.interval || 30;
  if(app.enabled('rpcDebugLog')) {
    opts.rpcDebugLog = true;
    opts.rpcLogger = require('pomelo-logger').getLogger('rpc-debug', __filename);
  }
  return new Component(app, opts);
};

/**
 * Remote component class
 *
 * @param {Object} app  current application context
 * @param {Object} opts construct parameters
 */
var Component = function(app, opts) {
  this.app = app;
  this.opts = opts;
};

var pro = Component.prototype;

pro.name = '__remote__';

/**
 * Remote component lifecycle function
 *
 * @param {Function} cb
 * @return {Void}
 */
pro.start = function(cb) {
  this.opts.port = this.app.getCurServer().port;
  this.remote = genRemote(this.app, this.opts);
  this.remote.start();
  process.nextTick(cb);
};

/**
 * Remote component lifecycle function
 *
 * @param {Boolean}  force whether stop the component immediately
 * @param {Function}  cb
 * @return {Void}
 */
pro.stop = function(force, cb) {
  this.remote.stop(force);
  process.nextTick(cb);
};

/**
 * Get remote paths from application
 *
 * @param {Object} app current application context
 * @return {Array} paths
 *
 */
var getRemotePaths = function(app) {
  var paths = [];

  var role;
  // master server should not come here
  if(app.isFrontend()) {
    role = 'frontend';
  } else {
    role = 'backend';
  }

  var sysPath = pathUtil.getSysRemotePath(role), serverType = app.getServerType();
  if(fs.existsSync(sysPath)) {
    paths.push(pathUtil.remotePathRecord('sys', serverType, sysPath));
  }
  var userPath = pathUtil.getUserRemotePath(app.getBase(), serverType);
  if(fs.existsSync(userPath)) {
    paths.push(pathUtil.remotePathRecord('user', serverType, userPath));
  }

  return paths;
};

/**
 * Generate remote server instance
 *
 * @param {Object} app current application context
 * @param {Object} opts contructor parameters for rpc Server
 * @return {Object} remote server instance
 */
var genRemote = function(app, opts) {
  opts.paths = getRemotePaths(app);
  opts.context = app;
  if(!!opts.rpcServer) {
    return opts.rpcServer.create(opts);
  } else {
    return RemoteServer.create(opts);
  }
};
<|endoftext|>


<commit_before>var NodeElm = require("./node")
  , LineElm = require("./line")
  , Typpy = require("typpy")
  , Deffy = require("deffy")
  ;

function Composition(input) {

    this.nodes = {};
    this.lines = {};

    // Internal caching
    this.ids = {};

    // Store composition data
    this.instances = Deffy(input.instances, {});
    this.colors = Deffy(input.colors, {});
    this.positions = Deffy(input.positions, {});
    this.moduleInfo = Deffy(input.moduleInfo, {});

    // Add the instances
    this.addInstances();
}

Composition.prototype.get = function (elm) {
    if (Typpy(elm1, String)) {
        return this.ids[elm];
    }
    return elm;
};

Composition.prototype.addNode = function (node) {
    node = new NodeElm(node);
    return this.nodes[node.id] = this.ids[node.id] = node;
};

Composition.prototype.addLine = function (line) {
    line = new LineElm(line);
    return this.lines[line.id] = this.ids[line.id] = line;
};

Composition.prototype.connect = function (e1, e2) {
    var elm1 = this.get(e1);
    var elm2 = this.get(e2);
    if (!elm1 || !elm2) {
        return console.warn("Missing element", !e1 ? e1 : "", !e2 ? e2 : "");
    }
    return this.addLine({
        source: elm1
      , target: elm2
    });
};

Composition.prototype.prepare = function () {
    return {
        nodes: this.nodes
      , lines: this.lines
    };
};

Composition.prototype.addInstance = function (cInstance, isServer) {
    var self = this
      , cColor = null
      , cPos = null
      , cNode = null
      ;

    cNode = self.addNode(cInstance);
    !!(cColor = self.colors[cNode.id]) && cNode.color(cColor);
    !!(cPos = self.positions[cNode.id]) && cNode.position(cPos);

    if (cInstance.flow && !isServer) {
        self.addInstance(cInstance, true);
    }
};

Composition.prototype.addInstances = function (instances) {
    var self = this
      , cColor = null
      , cPos = null
      , cNode = null
      ;

    instances = instances || self.instances;
    Object.keys(instances).forEach(function (cName) {
        self.addInstance(instances[cName]);
    });
};

module.exports = Composition;
<commit_msg>Iterate the nodes<commit_after>var NodeElm = require("./node")
  , LineElm = require("./line")
  , Typpy = require("typpy")
  , Deffy = require("deffy")
  , IterateObject = require("iterate-object")
  ;

function Composition(input) {

    this.nodes = {};
    this.lines = {};

    // Internal caching
    this.ids = {};

    // Store composition data
    this.instances = Deffy(input.instances, {});
    this.colors = Deffy(input.colors, {});
    this.positions = Deffy(input.positions, {});
    this.moduleInfo = Deffy(input.moduleInfo, {});

    // Add the instances
    this.addInstances();
}

Composition.prototype.get = function (elm) {
    if (Typpy(elm1, String)) {
        return this.ids[elm];
    }
    return elm;
};

Composition.prototype.addNode = function (node) {
    node = new NodeElm(node);
    return this.nodes[node.id] = this.ids[node.id] = node;
};

Composition.prototype.addLine = function (line) {
    line = new LineElm(line);
    return this.lines[line.id] = this.ids[line.id] = line;
};

Composition.prototype.connect = function (e1, e2) {
    var elm1 = this.get(e1);
    var elm2 = this.get(e2);
    if (!elm1 || !elm2) {
        return console.warn("Missing element", !e1 ? e1 : "", !e2 ? e2 : "");
    }
    return this.addLine({
        source: elm1
      , target: elm2
    });
};

Composition.prototype.prepare = function () {
    return {
        nodes: this.nodes
      , lines: this.lines
    };
};

Composition.prototype.addInstance = function (cInstance, isServer) {
    var self = this
      , cColor = null
      , cPos = null
      , cNode = null
      ;

    cNode = self.addNode(cInstance);
    !!(cColor = self.colors[cNode.id]) && cNode.color(cColor);
    !!(cPos = self.positions[cNode.id]) && cNode.position(cPos);

    if (cInstance.flow && !isServer) {
        self.addInstance(cInstance, true);
    }
};

Composition.prototype.addInstances = function (instances) {
    var self = this
      , cColor = null
      , cPos = null
      , cNode = null
      ;

    instances = instances || self.instances;
    Object.keys(instances).forEach(function (cName) {
        self.addInstance(instances[cName]);
    });
};

Composition.prototype.parseClientFlow = function () {
    var self = this;
    IterateObject(self.nodes, function (name, node) {
        debugger
    });
};

module.exports = Composition;
<|endoftext|>


<commit_before>/* global moment:false */
import config from './config/config.json'
import { find } from './utils.js'
import calculateWeeklyLevel from './weekly-levels-calculator'

// centralized for whenever we implement #16
const somethingIsWrong = () => undefined

const isVersion = (date, version) => {
  const momentDate = moment().isoWeekYear(date.year).isoWeek(date.week).isoWeekday(1).startOf('day')
  const momentVersionStartDate = moment(version.date, config.versionDateFormat).startOf('isoWeek').startOf('day')
  return momentDate.isSameOrAfter(momentVersionStartDate)
}

const getFactor = (versions, date) => {
  const reverseVersions = versions.slice(0).reverse()
  const factor = find(reverseVersions, isVersion.bind(null, date))
  // If the doc is too old to have a matching version, default to the oldest one
  if (!factor) {
    return versions[0]
  }
  return factor
}

const getCoefficients = (productCoefficients, date) => {
  if (!(productCoefficients && productCoefficients.versions && productCoefficients.versions.length)) {
    somethingIsWrong()
  }
  const version = getFactor(productCoefficients.versions, date)
  return version && version.coefficients
}

const getWeeksOfStock = (location, date) => {
  if (!(location.plans && location.plans.length)) {
    somethingIsWrong()
  }

  const plans = getFactor(location.plans, date)
  return plans && plans.weeksOfStock
}

const getTargetPopulations = (location, date) => {
  if (location.targetPopulations && location.targetPopulations.length) {
    const targetPopulations = getFactor(location.targetPopulations, date)

    return {
      version: targetPopulations.version,
      monthlyTargetPopulations: targetPopulations && targetPopulations.monthlyTargetPopulations
    }
  }

  // For backwards compatibility to version before introducing `targetPopulations`,
  // since we have no control about when the dashboards are going
  // to replicate the new location docs
  if (!(location.targetPopulation && Object.keys(location.targetPopulation).length)) {
    return {
      version: 1
    }
  }

  return {
    version: 1,
    monthlyTargetPopulations: location.targetPopulation
  }
}

const getWeeklyLevels = (location, date) => {
  if (!(location.allocations && location.allocations.length)) {
    somethingIsWrong()
  }

  const allocations = getFactor(location.allocations, date)
  return allocations && allocations.weeklyLevels
}

const calculateWeeklyLevels = (monthlyTargetPopulations, coefficients) => {
  const weeklyLevelForProduct = (weeklyLevels, productId) => {
    const coefficient = coefficients[productId]
    const targetPopulation = monthlyTargetPopulations[productId]
    if (!(typeof targetPopulation !== 'undefined' && coefficient)) {
      // TODO: throw error? See #16
      return weeklyLevels
    }
    weeklyLevels[productId] = calculateWeeklyLevel(
      weeklyLevels, coefficient, targetPopulation / 4, productId
    )
    return weeklyLevels
  }
  return Object.keys(monthlyTargetPopulations).reduce(weeklyLevelForProduct, {})
}

export default function transform (location, productCoefficients, date) {
  const weeksOfStock = getWeeksOfStock(location, date)

  if (!weeksOfStock) { somethingIsWrong() }

  const isOldDoc = !location.targetPopulations
  const { version, monthlyTargetPopulations } = getTargetPopulations(location, date)

  // For backwards compatibility to version before introducing `targetPopulations`,
  // since for that version `weeklyAllocations` were not always calculated
  // based on target population
  if (isOldDoc || version === 1) {
    const weeklyLevels = getWeeklyLevels(location, date)

    if (!weeklyLevels) { somethingIsWrong() }

    return {
      level: location.level,
      weeklyLevels,
      weeksOfStock,
      monthlyTargetPopulations
    }
  }

  const coefficients = getCoefficients(productCoefficients, date)
  if (!(monthlyTargetPopulations && coefficients)) { somethingIsWrong() }

  const weeklyLevels = calculateWeeklyLevels(monthlyTargetPopulations, coefficients)
  if (!weeklyLevels) { somethingIsWrong() }

  return {
    level: location.level,
    weeklyLevels,
    weeksOfStock,
    monthlyTargetPopulations
  }
}
<commit_msg>refactor: remove unneeded isOldDoc check<commit_after>/* global moment:false */
import config from './config/config.json'
import { find } from './utils.js'
import calculateWeeklyLevel from './weekly-levels-calculator'

// centralized for whenever we implement #16
const somethingIsWrong = () => undefined

const isVersion = (date, version) => {
  const momentDate = moment().isoWeekYear(date.year).isoWeek(date.week).isoWeekday(1).startOf('day')
  const momentVersionStartDate = moment(version.date, config.versionDateFormat).startOf('isoWeek').startOf('day')
  return momentDate.isSameOrAfter(momentVersionStartDate)
}

const getFactor = (versions, date) => {
  const reverseVersions = versions.slice(0).reverse()
  const factor = find(reverseVersions, isVersion.bind(null, date))
  // If the doc is too old to have a matching version, default to the oldest one
  if (!factor) {
    return versions[0]
  }
  return factor
}

const getCoefficients = (productCoefficients, date) => {
  if (!(productCoefficients && productCoefficients.versions && productCoefficients.versions.length)) {
    somethingIsWrong()
  }
  const version = getFactor(productCoefficients.versions, date)
  return version && version.coefficients
}

const getWeeksOfStock = (location, date) => {
  if (!(location.plans && location.plans.length)) {
    somethingIsWrong()
  }

  const plans = getFactor(location.plans, date)
  return plans && plans.weeksOfStock
}

const getTargetPopulations = (location, date) => {
  if (location.targetPopulations && location.targetPopulations.length) {
    const targetPopulations = getFactor(location.targetPopulations, date)

    return {
      version: targetPopulations.version,
      monthlyTargetPopulations: targetPopulations && targetPopulations.monthlyTargetPopulations
    }
  }

  // For backwards compatibility to version before introducing `targetPopulations`,
  // since we have no control about when the dashboards are going
  // to replicate the new location docs
  if (!(location.targetPopulation && Object.keys(location.targetPopulation).length)) {
    return {
      version: 1
    }
  }

  return {
    version: 1,
    monthlyTargetPopulations: location.targetPopulation
  }
}

const getWeeklyLevels = (location, date) => {
  if (!(location.allocations && location.allocations.length)) {
    somethingIsWrong()
  }

  const allocations = getFactor(location.allocations, date)
  return allocations && allocations.weeklyLevels
}

const calculateWeeklyLevels = (monthlyTargetPopulations, coefficients) => {
  const weeklyLevelForProduct = (weeklyLevels, productId) => {
    const coefficient = coefficients[productId]
    const targetPopulation = monthlyTargetPopulations[productId]
    if (!(typeof targetPopulation !== 'undefined' && coefficient)) {
      // TODO: throw error? See #16
      return weeklyLevels
    }
    weeklyLevels[productId] = calculateWeeklyLevel(
      weeklyLevels, coefficient, targetPopulation / 4, productId
    )
    return weeklyLevels
  }
  return Object.keys(monthlyTargetPopulations).reduce(weeklyLevelForProduct, {})
}

export default function transform (location, productCoefficients, date) {
  const weeksOfStock = getWeeksOfStock(location, date)
  if (!weeksOfStock) {
    somethingIsWrong()
  }

  const { version, monthlyTargetPopulations } = getTargetPopulations(location, date)

  // For backwards compatibility to version before introducing `targetPopulations`,
  // since for that version `weeklyAllocations` were not always calculated
  // based on target population
  if (version === 1) {
    const weeklyLevels = getWeeklyLevels(location, date)
    if (!weeklyLevels) {
      somethingIsWrong()
    }

    return {
      level: location.level,
      weeklyLevels,
      weeksOfStock,
      monthlyTargetPopulations
    }
  }

  const coefficients = getCoefficients(productCoefficients, date)
  if (!(monthlyTargetPopulations && coefficients)) {
    somethingIsWrong()
  }

  const weeklyLevels = calculateWeeklyLevels(monthlyTargetPopulations, coefficients)
  if (!weeklyLevels) {
    somethingIsWrong()
  }

  return {
    level: location.level,
    weeklyLevels,
    weeksOfStock,
    monthlyTargetPopulations
  }
}
<|endoftext|>


<commit_before>/**
 * @module constants/formats
 * @private
 * @description Exports different types of formatting for {@link Date#format}.
 */

import Str from '../String';

const zero = new Str('0');

/**
 * @callback module:constants/formats~matchCallback
 * @param {HtmlElement} date - D-wrap of a date to apply format to.
 * @param {String} string - Matched applied expression.
 */

/**
 * @typedef {Object} module:constants/formats~formatExpr
 * @property {String} format - Matched format.
 * @property {module:constants/formats~matchCallback} match - Callback if there was a match.
 */

/**
 * @type {module:constants/formats~formatExpr[]}
 * @description Array of different formats.
 */
export default [
  {
    format: 'ccc',
    match: (date, utc) => round(date[utc]('c'), 3)
  },
  {
    format: 'cc',
    match: (date, utc) => cut(date[utc]('c'), 3, 2).replace(/^0\./, '')
  },
  {
    format: 'c',
    match: (date, utc) => cut(date[utc]('c'), 3, 1).replace(/^0\./, '')
  },
  {
    format: 'ss',
    match: (date, utc) => round(date[utc]('s'), 2)
  },
  {
    format: 's',
    match: (date, utc) => String(date[utc]('s'))
  },
  {
    format: 'mm',
    match: (date, utc) => round(date[utc]('m'), 2)
  },
  {
    format: 'm',
    match: (date, utc) => String(date[utc]('m'))
  },
  {
    format: 'hh',
    match: (date, utc) => round(date[utc]('h'), 2)
  },
  {
    format: 'h',
    match: (date, utc) => String(date[utc]('h'))
  },
  {
    format: 'DDDD',
    match: (date, utc) => date[utc]('dwn')
  },
  {
    format: 'DDD',
    match: (date, utc) => date[utc]('dwa')
  },
  {
    format: 'dd',
    match: (date, utc) => round(date[utc]('d'), 2)
  },
  {
    format: 'd',
    match: (date, utc) => String(date[utc]('d'))
  },
  {
    format: 'MMMM',
    match: (date, utc) => date[utc]('Mn')
  },
  {
    format: 'MMM',
    match: (date, utc) => date[utc]('Ma')
  },
  {
    format: 'MM',
    match: (date, utc) => round(date[utc]('M'), 2)
  },
  {
    format: 'M',
    match: (date, utc) => String(date[utc]('M'))
  },
  {
    format: 'yyyy',
    match: (date, utc) => round(date[utc]('y'), 4)
  },
  {
    format: 'yy',
    match: (date, utc) => String(date[utc]('y')).substring(2)
  },
  {
    format: 'y',
    match: (date, utc) => date[utc]('y')
  }
];

/**
 * @name module:constants/formats~round
 * @function
 * @param {Number} number - Number to round.
 * @param {Number} digits - Number of the digits of the output.
 * @returns {String} String with necessary additional starting zeroes.
 */
function round(number, digits) {
  const string = String(number);
  let zeroes = digits - string.length;
  zeroes = zeroes < 0 ? 0 : zeroes;

  return zero.repeat(zeroes).$ + string;
}

/**
 *
 * @param {Number} number - Number to cut.
 * @param {Number} max - Number of digits in number.
 * @param {Number} digits - Number of the digits of the output.
 * @returns {string} Cut input.
 */
function cut(number, max, digits) {
  return (number / Math.pow(10, max)).toFixed(digits);
}
<commit_msg>constants.formats: remove 'cc' format.<commit_after>/**
 * @module constants/formats
 * @private
 * @description Exports different types of formatting for {@link Date#format}.
 */

import Str from '../String';

const zero = new Str('0');

/**
 * @callback module:constants/formats~matchCallback
 * @param {Dat} date - D-wrap of a date to apply format to.
 * @param {String} string - Matched applied expression.
 */

/**
 * @typedef {Object} module:constants/formats~formatExpr
 * @property {String} format - Matched format.
 * @property {module:constants/formats~matchCallback} match - Callback if there was a match.
 */

/**
 * @type {module:constants/formats~formatExpr[]}
 * @description Array of different formats.
 */
export default [
  {
    format: 'ccc',
    match: (date, utc) => round(date[utc]('c'), 3)
  },
  {
    format: 'c',
    match: (date, utc) => cut(date[utc]('c'), 3, 1).replace(/^0\./, '')
  },
  {
    format: 'ss',
    match: (date, utc) => round(date[utc]('s'), 2)
  },
  {
    format: 's',
    match: (date, utc) => String(date[utc]('s'))
  },
  {
    format: 'mm',
    match: (date, utc) => round(date[utc]('m'), 2)
  },
  {
    format: 'm',
    match: (date, utc) => String(date[utc]('m'))
  },
  {
    format: 'hh',
    match: (date, utc) => round(date[utc]('h'), 2)
  },
  {
    format: 'h',
    match: (date, utc) => String(date[utc]('h'))
  },
  {
    format: 'dddd',
    match: (date, utc) => date[utc]('dwn')
  },
  {
    format: 'ddd',
    match: (date, utc) => date[utc]('dwa')
  },
  {
    format: 'dd',
    match: (date, utc) => round(date[utc]('d'), 2)
  },
  {
    format: 'd',
    match: (date, utc) => String(date[utc]('d'))
  },
  {
    format: 'MMMM',
    match: (date, utc) => date[utc]('Mn')
  },
  {
    format: 'MMM',
    match: (date, utc) => date[utc]('Ma')
  },
  {
    format: 'MM',
    match: (date, utc) => round(date[utc]('M'), 2)
  },
  {
    format: 'M',
    match: (date, utc) => String(date[utc]('M'))
  },
  {
    format: 'yyyy',
    match: (date, utc) => round(date[utc]('y'), 4)
  },
  {
    format: 'yy',
    match: (date, utc) => String(date[utc]('y')).slice(2)
  },
  {
    format: 'y',
    match: (date, utc) => date[utc]('y')
  }
];

/**
 * @function round
 * @private
 * @param {Number} number - Number to round.
 * @param {Number} digits - Number of the digits of the output.
 * @returns {String} String with necessary additional starting zeroes.
 */
function round(number, digits) {
  const string = String(number);
  let zeroes = digits - string.length;
  zeroes = zeroes < 0 ? 0 : zeroes;

  return zero.repeat(zeroes).$ + string;
}

/**
 * @function cut
 * @private
 * @param {Number} number - Number to cut.
 * @param {Number} max - Number of digits in number.
 * @param {Number} digits - Number of the digits of the output.
 * @returns {string} Cut input.
 */
function cut(number, max, digits) {
  return (number / Math.pow(10, max)).toFixed(digits);
}
<|endoftext|>


<commit_before>/* @flow */
'use strict';

import Relay from 'react-relay';
import React from 'react-native';
const { ScrollView, View } = React;

import Header from '../components/artist/header';
import Biography from '../components/artist/biography';
import Shows from '../components/artist/shows';
import Articles from '../components/artist/articles';
import RelatedArtists from '../components/artist/related_artists'
import Artworks from '../components/artworks';

import TabView from '../components/tab_view';
import type TabSelectionEvent from '../components/tab_view';

class Artist extends React.Component {
  constructor() {
    super();
    this.state = { selectedTabIndex: 0 };

    this.tabSelectionDidChange = this.tabSelectionDidChange.bind(this);
    this.renderTabViewContent = this.renderTabViewContent.bind(this);
  }

  tabSelectionDidChange(event: TabSelectionEvent) {
    this.setState({ selectedTabIndex: event.nativeEvent.selectedIndex });
  }

  renderTabViewContent() {
    switch (this.state.selectedTabIndex) {
      case 0: return (
        <View>
          <Biography artist={this.props.artist} />
          <Articles articles={this.props.artist.articles}/>
          <RelatedArtists artists={this.props.artist.related_artists} />
        </View>
      );
      case 1: return (
        <Artworks artworks={this.props.artist.artworks} />
      );
      case 2: return (
        <Shows artist={this.props.artist} />
      );
    }
  }

  render() {
    return (
      <ScrollView>
        <View style={{ paddingLeft: 20, paddingRight: 20 }}>
          <Header artist={this.props.artist} />
          <TabView titles={['ABOUT', 'WORKS', 'SHOWS']} onSelectionChange={this.tabSelectionDidChange}>
            {this.renderTabViewContent()}
          </TabView>
        </View>
      </ScrollView>
    );
  }
}

export default Relay.createContainer(Artist, {
  fragments: {
    artist: () => Relay.QL`
      fragment on Artist {
        ${Header.getFragment('artist')}
        ${Biography.getFragment('artist')}
        ${Shows.getFragment('artist')}
        related_artists: artists(size: 16) {
          ${RelatedArtists.getFragment('artists')}
        }
        articles {
          ${Articles.getFragment('articles')}
        }
        artworks(sort: published_at_asc, size: 10, page: 1) {
          ${Artworks.getFragment('artworks')}
        }
      }
    `,
  }
});
<commit_msg>[Artist] Remove Relay field for now that’s not yet in our schema dumps.<commit_after>/* @flow */
'use strict';

import Relay from 'react-relay';
import React from 'react-native';
const { ScrollView, View } = React;

import Header from '../components/artist/header';
import Biography from '../components/artist/biography';
import Shows from '../components/artist/shows';
import Articles from '../components/artist/articles';
import RelatedArtists from '../components/artist/related_artists'
import Artworks from '../components/artworks';

import TabView from '../components/tab_view';
import type TabSelectionEvent from '../components/tab_view';

class Artist extends React.Component {
  constructor() {
    super();
    this.state = { selectedTabIndex: 0 };

    this.tabSelectionDidChange = this.tabSelectionDidChange.bind(this);
    this.renderTabViewContent = this.renderTabViewContent.bind(this);
  }

  tabSelectionDidChange(event: TabSelectionEvent) {
    this.setState({ selectedTabIndex: event.nativeEvent.selectedIndex });
  }

  renderTabViewContent() {
    switch (this.state.selectedTabIndex) {
      case 0: return (
        <View>
          <Biography artist={this.props.artist} />
          <Articles articles={this.props.artist.articles}/>
          <RelatedArtists artists={this.props.artist.related_artists} />
        </View>
      );
      case 1: return (
        <Artworks artworks={this.props.artist.artworks} />
      );
      case 2: return (
        <Shows artist={this.props.artist} />
      );
    }
  }

  render() {
    return (
      <ScrollView>
        <View style={{ paddingLeft: 20, paddingRight: 20 }}>
          <Header artist={this.props.artist} />
          <TabView titles={['ABOUT', 'WORKS', 'SHOWS']} onSelectionChange={this.tabSelectionDidChange}>
            {this.renderTabViewContent()}
          </TabView>
        </View>
      </ScrollView>
    );
  }
}

export default Relay.createContainer(Artist, {
  fragments: {
    artist: () => Relay.QL`
      fragment on Artist {
        ${Header.getFragment('artist')}
        ${Biography.getFragment('artist')}
        ${Shows.getFragment('artist')}
        related_artists: artists(size: 16) {
          ${RelatedArtists.getFragment('artists')}
        }
        articles {
          ${Articles.getFragment('articles')}
        }
        artworks(sort: published_at_asc, size: 10) {
          ${Artworks.getFragment('artworks')}
        }
      }
    `,
  }
});
<|endoftext|>


<commit_before>function ExpensesController(Expense) {
  var ctrl = this;

  ctrl.expenses = Expense.query();
}

angular
  .module('app')
  .controller('ExpensesController', ExpensesController)<commit_msg>Added deletexpense function to controller<commit_after>function ExpensesController(Expense) {
  var ctrl = this;

  ctrl.expenses = Expense.query();

  ctrl.deleteExpense = function(expense){
    expense.$delete(function(){
      $state.go($state.current, {}, {reload: true});
    });
  };
};

angular
  .module('app')
  .controller('ExpensesController', ExpensesController)<|endoftext|>


<commit_before>class ComponentView {

  constructor($rootScope, componentManager, desktopManager, $timeout) {
    this.restrict = "E";
    this.templateUrl = "directives/component-view.html";
    this.scope = {
      component: "=",
      manualDealloc: "="
    };

    this.$rootScope = $rootScope;
    this.componentManager = componentManager;
    this.desktopManager = desktopManager;
    this.timeout = $timeout;
  }

  link($scope, el, attrs, ctrl) {
    $scope.el = el;

    $scope.identifier = "component-view-" + Math.random();

    // console.log("Registering handler", $scope.identifier, $scope.component.name);

    this.componentManager.registerHandler({identifier: $scope.identifier, areas: [$scope.component.area], activationHandler: (component) => {
      if(component.active) {
        this.timeout(() => {
          var iframe = this.componentManager.iframeForComponent(component);
          if(iframe) {
            iframe.onload = function() {
              this.componentManager.registerComponentWindow(component, iframe.contentWindow);
            }.bind(this);
          }
        });
      }
    },
    actionHandler: (component, action, data) => {
       if(action == "set-size") {
         this.componentManager.handleSetSizeEvent(component, data);
       }
    }});

    $scope.updateObserver = this.desktopManager.registerUpdateObserver((component) => {
      if(component == $scope.component && component.active) {
        $scope.reloadComponent();
      }
    })

    $scope.$watch('component', function(component, prevComponent){
      ctrl.componentValueChanging(component, prevComponent);
    });
  }

  controller($scope, $rootScope, $timeout, componentManager, desktopManager) {
    'ngInject';

    this.componentValueChanging = (component, prevComponent) => {
      if(prevComponent && component !== prevComponent) {
        // Deactive old component
        componentManager.deactivateComponent(prevComponent);
      }

      if(component) {
        componentManager.activateComponent(component);
        console.log("Loading", $scope.component.name, $scope.getUrl(), component.valid_until);

        $scope.reloadStatus();
      }
    }

    $scope.$on("ext-reload-complete", () => {
      $scope.reloadStatus();
    })

    $scope.reloadComponent = function() {
      console.log("Reloading component", $scope.component);
      componentManager.reloadComponent($scope.component);
    }

    $scope.reloadStatus = function() {
      let component = $scope.component;
      $scope.reloading = true;
      let previouslyValid = $scope.componentValid;

      var expired, offlineRestricted, urlError;

      offlineRestricted = component.offlineOnly && !isDesktopApplication();

      urlError =
        (!isDesktopApplication() && (!component.url && !component.hosted_url))
        ||
        (isDesktopApplication() && (!component.local_url && !component.url && !component.hosted_url))

      expired = component.valid_until && component.valid_until <= new Date();

      $scope.componentValid = !offlineRestricted && !urlError && !expired;

      if(offlineRestricted) $scope.error = 'offline-restricted';
      else if(urlError) $scope.error = 'url-missing';
      else if(expired) $scope.error = 'expired';
      else $scope.error = null;

      if($scope.componentValid !== previouslyValid) {
        if($scope.componentValid) {
          componentManager.activateComponent(component);
        }
      }

      if(expired && !$scope.triedReloading) {
        // Try reloading, handled by footer, which will open Extensions window momentarily to pull in latest data
        $scope.triedReloading = true;
        $rootScope.$broadcast("reload-ext-data");
      }

      $timeout(() => {
        $scope.reloading = false;
      }, 500)
    }

    $scope.getUrl = function() {
      var url = componentManager.urlForComponent($scope.component);
      $scope.component.runningLocally = (url !== $scope.component.url) && url !== ($scope.component.hosted_url);
      return url;
    }

    $scope.$on("$destroy", function() {
      // console.log("Deregistering handler", $scope.identifier, $scope.component.name);
      componentManager.deregisterHandler($scope.identifier);
      if($scope.component && !$scope.manualDealloc) {
        componentManager.deactivateComponent($scope.component);
      }

      desktopManager.deregisterUpdateObserver($scope.updateObserver);
    });
  }

}

angular.module('app').directive('componentView', ($rootScope, componentManager, desktopManager, $timeout) => new ComponentView($rootScope, componentManager, desktopManager, $timeout));
<commit_msg>Don't sync components if just activating/deactivating on a local level<commit_after>class ComponentView {

  constructor($rootScope, componentManager, desktopManager, $timeout) {
    this.restrict = "E";
    this.templateUrl = "directives/component-view.html";
    this.scope = {
      component: "=",
      manualDealloc: "="
    };

    this.$rootScope = $rootScope;
    this.componentManager = componentManager;
    this.desktopManager = desktopManager;
    this.timeout = $timeout;
  }

  link($scope, el, attrs, ctrl) {
    $scope.el = el;

    $scope.identifier = "component-view-" + Math.random();

    // console.log("Registering handler", $scope.identifier, $scope.component.name);

    this.componentManager.registerHandler({identifier: $scope.identifier, areas: [$scope.component.area], activationHandler: (component) => {
      if(component.active) {
        this.timeout(() => {
          var iframe = this.componentManager.iframeForComponent(component);
          if(iframe) {
            iframe.onload = function() {
              this.componentManager.registerComponentWindow(component, iframe.contentWindow);
            }.bind(this);
          }
        });
      }
    },
    actionHandler: (component, action, data) => {
       if(action == "set-size") {
         this.componentManager.handleSetSizeEvent(component, data);
       }
    }});

    $scope.updateObserver = this.desktopManager.registerUpdateObserver((component) => {
      if(component == $scope.component && component.active) {
        $scope.reloadComponent();
      }
    })

    $scope.$watch('component', function(component, prevComponent){
      ctrl.componentValueChanging(component, prevComponent);
    });
  }

  controller($scope, $rootScope, $timeout, componentManager, desktopManager) {
    'ngInject';

    /*
    General note regarding activation/deactivation of components:
    We pass `true` to componentManager.ac/detivateComponent for the `dontSync` parameter.
    The activation we do in here is not global, but just local, so we don't need to sync the state.
    For example, if we activate an editor, we just need to do that for display purposes, but dont
    need to perform a sync to propagate that .active flag.
    */

    this.componentValueChanging = (component, prevComponent) => {
      //
      // See comment above about passing true to componentManager.ac/detivateComponent
      //
      if(prevComponent && component !== prevComponent) {
        // Deactive old component
        componentManager.deactivateComponent(prevComponent, true);
      }

      if(component) {
        componentManager.activateComponent(component, true);
        console.log("Loading", $scope.component.name, $scope.getUrl(), component.valid_until);

        $scope.reloadStatus();
      }
    }

    $scope.$on("ext-reload-complete", () => {
      $scope.reloadStatus();
    })

    $scope.reloadComponent = function() {
      console.log("Reloading component", $scope.component);
      componentManager.reloadComponent($scope.component);
    }

    $scope.reloadStatus = function() {
      let component = $scope.component;
      $scope.reloading = true;
      let previouslyValid = $scope.componentValid;

      var expired, offlineRestricted, urlError;

      offlineRestricted = component.offlineOnly && !isDesktopApplication();

      urlError =
        (!isDesktopApplication() && (!component.url && !component.hosted_url))
        ||
        (isDesktopApplication() && (!component.local_url && !component.url && !component.hosted_url))

      expired = component.valid_until && component.valid_until <= new Date();

      $scope.componentValid = !offlineRestricted && !urlError && !expired;

      if(offlineRestricted) $scope.error = 'offline-restricted';
      else if(urlError) $scope.error = 'url-missing';
      else if(expired) $scope.error = 'expired';
      else $scope.error = null;

      if($scope.componentValid !== previouslyValid) {
        if($scope.componentValid) {
          componentManager.activateComponent(component, true);
        }
      }

      if(expired && !$scope.triedReloading) {
        // Try reloading, handled by footer, which will open Extensions window momentarily to pull in latest data
        $scope.triedReloading = true;
        $rootScope.$broadcast("reload-ext-data");
      }

      $timeout(() => {
        $scope.reloading = false;
      }, 500)
    }

    $scope.getUrl = function() {
      var url = componentManager.urlForComponent($scope.component);
      $scope.component.runningLocally = (url !== $scope.component.url) && url !== ($scope.component.hosted_url);
      return url;
    }

    $scope.$on("$destroy", function() {
      // console.log("Deregistering handler", $scope.identifier, $scope.component.name);
      componentManager.deregisterHandler($scope.identifier);
      if($scope.component && !$scope.manualDealloc) {
        componentManager.deactivateComponent($scope.component, true);
      }

      desktopManager.deregisterUpdateObserver($scope.updateObserver);
    });
  }

}

angular.module('app').directive('componentView', ($rootScope, componentManager, desktopManager, $timeout) => new ComponentView($rootScope, componentManager, desktopManager, $timeout));
<|endoftext|>


<commit_before>define([
  'abstract/layer/CartoDBLayerClass',
], function(CartoDBLayerClass) {

  'use strict';

  var GladCoverageLayer = CartoDBLayerClass.extend({

    options: {
      sql: 'SELECT *, \'{tableName}\' AS layer, \'{tableName}\' AS name FROM {tableName}'
    }

  });

  return GladCoverageLayer;

});
<commit_msg>Update geographic coverage<commit_after>define([
  'abstract/layer/CartoDBLayerClass',
], function(CartoDBLayerClass) {

  'use strict';

  var GladCoverageLayer = CartoDBLayerClass.extend({

    options: {
      sql: 'SELECT *, \'{tableName}\' AS layer, \'{tableName}\' AS name FROM glad_coverage_1'
    }

  });
  console.log(GladCoverageLayer)
  return GladCoverageLayer;

});
<|endoftext|>


<commit_before>var KeywordParser = (function () {

  var keywordsObject = {};
  var blackListKeywords = ["the","be","to","of","and","a","in","that","have","I","it","for","not","on","with","he","as","you","do","at","this","but","his","by","from","they","we","say","her","she","or","an","will","my","one","all","would","there","their","what","so","up","out","if","about","who","get","which","go","me","when","make","can","like","time","no","just","him","know","take","people","into","year","your","good","some","could","them","see","other","than","then","now","look","only","come","its","over","think","also","back","after","use","two","how","our","work","first","well","way","even","new","want","because","any","these","give","day","most","us", "theyre", "youre"];

  var setTopKeywordsList = function(html) {
    keywordsObject = {};
    var allKeywords = getAllKeywords(html);
    for (var keywordIndex = 0; keywordIndex < allKeywords.length; keywordIndex++) {
      var keyword = allKeywords[keywordIndex];

      if (keywordIsBlacklisted(keyword)) { continue; }
      if (keyword in keywordsObject) {
        keywordsObject[keyword] += 1
      } else {
        keywordsObject[keyword] = 1
      }
    }
  };

  var keywordIsBlacklisted = function(keyword) {
    // test if keyword length greater then 2 to prevent logging small words
    // test if keyword in blacklist
    return (keyword.length <= 2) || (blackListKeywords.indexOf(keyword.toLowerCase()) != -1)
  };

  var getAllKeywords = function(html) {
    // strip html tags
    // ignore everything except letters
    return html.replace(/<\/?[^>]+(>|$)/g, "").replace(/[^a-zA-Z ]/g, "").match(/\S+/g);
  };

  var sortKeywords = function() {
    var keywordsList = [];
    for (var keyword in keywordsObject) {
      keywordsList.push([keyword, keywordsObject[keyword]])
    }
    return keywordsList.sort(function(a, b) {return b[1] - a[1]});
  };

  var getTopKeywordsList = function() {
    var allowedKeywordsNumber = 20;
    var keywordsList = sortKeywords();
    var topKeywordsList = [];

    for(var index = 0; index < allowedKeywordsNumber; index ++) {
      if (index < keywordsList.length){
        topKeywordsList.push(keywordsList[index]);
      }
    }
    return topKeywordsList;
  };

  var formatOutput = function(topKeywordsList) {
    var keywords = "";
    for (var index = 0; index < topKeywordsList.length; index++) {
      keywords += "
kw: " + topKeywordsList[index][0] + " - nr: " + topKeywordsList[index][1];
    }
    return keywords;
  };

  var showTopKeywords = function(html) {
    setTopKeywordsList(html);
    var keywords = formatOutput(getTopKeywordsList())
    if ($("#simple-blog-form-keywords-view").length == 0) {
      $("#simple-blog-form-keywords").after("
" + keywords +  "
");
    } else {
      $("#simple-blog-form-keywords-view").html(keywords);
    }
  };

  return {
    showTopKeywords: showTopKeywords
  };
})();
<commit_msg>rename a few things<commit_after>var KeywordParser = (function () {

  var keywordsObject = {};
  var blackListKeywords = ["the","be","to","of","and","a","in","that","have","I","it","for","not","on","with","he","as","you","do","at","this","but","his","by","from","they","we","say","her","she","or","an","will","my","one","all","would","there","their","what","so","up","out","if","about","who","get","which","go","me","when","make","can","like","time","no","just","him","know","take","people","into","year","your","good","some","could","them","see","other","than","then","now","look","only","come","its","over","think","also","back","after","use","two","how","our","work","first","well","way","even","new","want","because","any","these","give","day","most","us", "theyre", "youre"];

  var setTopKeywordsList = function(html) {
    keywordsObject = {};
    var allKeywords = getAllKeywords(html);
    for (var keywordIndex = 0; keywordIndex < allKeywords.length; keywordIndex++) {
      var keyword = allKeywords[keywordIndex];

      if (keywordIsBlacklisted(keyword)) { continue; }
      if (keyword in keywordsObject) {
        keywordsObject[keyword] += 1
      } else {
        keywordsObject[keyword] = 1
      }
    }
  };

  var keywordIsBlacklisted = function(keyword) {
    //skip if keyword is shorter than 2 characters
    // and skip if word is in blackListKeywords"
    return (keyword.length <= 2) || (blackListKeywords.indexOf(keyword.toLowerCase()) != -1)
  };

  var getAllKeywords = function(html) {
    // strip html tags
    // ignore everything except letters
    return html.replace(/<\/?[^>]+(>|$)/g, "").replace(/[^a-zA-Z ]/g, "").match(/\S+/g);
  };

  var sortKeywords = function() {
    var keywordsList = [];
    for (var keyword in keywordsObject) {
      keywordsList.push([keyword, keywordsObject[keyword]])
    }
    return keywordsList.sort(function(a, b) {return b[1] - a[1]});
  };

  var getTopKeywordsList = function() {
    var totalAllowedKeywords = 20;
    var keywordsList = sortKeywords();
    var topKeywordsList = [];

    for(var index = 0; index < totalAllowedKeywords; index ++) {
      if (index < keywordsList.length){
        topKeywordsList.push(keywordsList[index]);
      }
    }
    return topKeywordsList;
  };

  var formatOutput = function(topKeywordsList) {
    var keywords = "";
    for (var index = 0; index < topKeywordsList.length; index++) {
      keywords += "
kw: " + topKeywordsList[index][0] + " - nr: " + topKeywordsList[index][1];
    }
    return keywords;
  };

  var showTopKeywords = function(html) {
    setTopKeywordsList(html);
    var keywords = formatOutput(getTopKeywordsList())
    if ($("#simple-blog-form-keywords-view").length == 0) {
      $("#simple-blog-form-keywords").after("
" + keywords +  "
");
    } else {
      $("#simple-blog-form-keywords-view").html(keywords);
    }
  };

  return {
    showTopKeywords: showTopKeywords
  };
})();
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import classnames from 'classnames';
import {keys} from 'ramda';
import * as styles from './TableDropdown.css';
import Select from 'react-select';

/*
 *    Displays in a dropdown menu all available tables
 *    using `ipc`.
 *    Sends a preset query to show all tables within a database/
 *    scheme that was chosen in the dropdown using `sessionsActions`.
 */

export default class TableDropdown extends Component {
    constructor(props) {
        super(props);
        this.testClass = this.testClass.bind(this);
        this.state = {table: null};
        this.onSelectTable = this.onSelectTable.bind(this);
    }

    onSelectTable(table) {
        if (table.value) {
            this.setState({table: table.value});
            this.props.sessionsActions.previewTables([table.value]);
        } else {
            this.setState({table: ''});
            this.props.sessionsActions.updateIpcState({previews: null});
        }
    }

    testClass(options) {
        /*
         *    'connected' if has enabled database options
         */
        return (!options[0].disabled) ? 'test-connected' : 'test-disconnected';

    }

	render() {
        const {ipc} = this.props;

        const tableNames = ipc.get('tables');

        let tablesDropdownOptions;
        /*
            disable the selector for sqlite which does not have databases, only
            tables
        */

        if (tableNames === null) {
            tablesDropdownOptions = [
                {
                    value: 'Please Select a Database',
                    label: 'Please Select a Database',
                    disabled: true
                }
            ];
        } else if (tableNames.length === 0) {
            tablesDropdownOptions = [
                {value: 'None', label: 'None Found', disabled: true}
            ];
        } else {
            tablesDropdownOptions = tableNames.toJS().map(tableName => (
                {
                    value: keys(tableName)[0], label: keys(tableName)[0],
                    disabled: false
                }
            ));
        }

        return (

                <Select
                    name="form-field-name"
                    placeholder="Select a Table"
                    options={tablesDropdownOptions}
                    onChange={this.onSelectTable}
                    value={this.state.table}
                    resetValue="null"
                    matchPos="start"
                />

        );
    }
}

TableDropdown.propTypes = {
    ipc: ImmutablePropTypes.map.isRequired,
    sessionsActions: PropTypes.object
};
<commit_msg>:bug: :wrench:<commit_after>import React, {Component, PropTypes} from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import classnames from 'classnames';
import {keys} from 'ramda';
import * as styles from './TableDropdown.css';
import Select from 'react-select';

/*
 *    Displays in a dropdown menu all available tables
 *    using `ipc`.
 *    Sends a preset query to show all tables within a database/
 *    scheme that was chosen in the dropdown using `sessionsActions`.
 */

export default class TableDropdown extends Component {
    constructor(props) {
        super(props);
        this.testClass = this.testClass.bind(this);
        this.state = {table: null};
        this.onSelectTable = this.onSelectTable.bind(this);
    }

    onSelectTable(table) {
        if (table.value) {
            this.setState({table: table.value});
            this.props.sessionsActions.previewTables([table.value]);
        } else {
            this.setState({table: ''});
            this.props.sessionsActions.updateIpcState({previews: null});
        }
    }

    testClass(options) {
        /*
         *    'connected' if has enabled database options
         */
        return (!options[0].disabled) ? 'test-connected' : 'test-disconnected';

    }

	render() {
        const {ipc} = this.props;

        const tableNames = ipc.get('tables');

        let tablesDropdownOptions;
        /*
            disable the selector for sqlite which does not have databases, only
            tables
        */
        debugger;
        if (tableNames === null) {
            tablesDropdownOptions = [
                {
                    value: 'Please Select a Database',
                    label: 'Please Select a Database',
                    disabled: true
                }
            ];
        } else if (tableNames.size === 0) {
            tablesDropdownOptions = [
                {value: 'None', label: 'None Found', disabled: true}
            ];
        } else {
            tablesDropdownOptions = tableNames.toJS().map(tableName => (
                {
                    value: keys(tableName)[0], label: keys(tableName)[0],
                    disabled: false
                }
            ));
        }

        return (

                <Select
                    name="form-field-name"
                    placeholder="Select a Table"
                    options={tablesDropdownOptions}
                    onChange={this.onSelectTable}
                    value={this.state.table}
                    resetValue="null"
                    matchPos="start"
                />

        );
    }
}

TableDropdown.propTypes = {
    ipc: ImmutablePropTypes.map.isRequired,
    sessionsActions: PropTypes.object
};
<|endoftext|>