<commit_before>function Tab(li, session, editor) {
  this.li = li;
  this.li.data('tab', this);
  this.session = session;
  this.editor = editor;
};

Tab.prototype.getSiblings = function() {
  return this.li.siblings().map(function (i, li) {
    return $(li).data('tab');
  });
};

Tab.prototype.unselect = function() {
  this.li.removeClass('active');
};

Tab.prototype.select = function() {
  this.li.addClass('active');
  this.getSiblings().each(function (i, tab) { tab.unselect(); });
  this.editor.editor.setSession(this.session);
};

Tab.prototype.close = function() {
  this.li.remove();
};

function TabbedEditor(id, aceId) {
  this.el = $('#' + id);
  this.editor_el = $('#' + aceId);
  this.editor = ace.edit(aceId);
  this.editor.setTheme('ace/theme/solarized_dark');
  this.editor.setFontSize(14);
  this.editor.setSession(this.newSession(''));
  this.editor.resize();
  this.editor.focus();

  $(window).resize(this.resizeAce.bind(this));
  this.resizeAce();

  this.tabs = {};

  this.el.find('ul.editor-tabs')
    .on('click', 'li:not(.editor-add-file)', function () {
      $(this).data('tab').select();
    })
    .on('click', 'span.glyphicon-remove', function() {
      $(this).parents('li').first().data('tab').close();
      return false;
    });

  this.newTabButton = this.el.find('.editor-add-file').first();
  this.newTabButton.on('click', (function () {
    var filename = prompt('Name: ');
    if (/[^\s]/.test(filename)) {
      this.createTab(filename).select();
    }
  }).bind(this));
};

TabbedEditor.prototype.getTabLabeled = function(name) {
  return this.tabs[name];
};

TabbedEditor.prototype.hasTabLabeled = function(name) {
  return name in this.tabs;
}

var makeIcon = function(icon) {
  return $('<span>').addClass('glyphicon glyphicon-' + icon);
}

TabbedEditor.prototype.createTab = function(filename, contents) {
  if (contents === undefined) {
    contents = '';
  }
  var li = $('<li>').append($('<a>').attr('href', '#').append(
    filename, ' ', makeIcon('remove')));
  li.insertBefore(this.newTabButton);
  this.tabs[filename] = new Tab(li, this.newSession(contents), this);
  return this.tabs[filename];
}

TabbedEditor.prototype.newSession = function(text) {
  var session = ace.createEditSession(text, 'ace/mode/matlab');
  session.setUseSoftTabs(true);
  return session;
}

TabbedEditor.prototype.resizeAce = function() {
    var height = $(window).height();
    this.editor_el.height(3 * height / 4);
    this.editor.resize();
    // TODO(isbadawi): This shouldn't be here
    $('#console').height(height / 4);
    ace.edit('console').resize();
};

TabbedEditor.prototype.overlayErrors = function(errors) {
  if (errors === undefined) {
    errors = [];
  }
  this.editor.getSession().setAnnotations(
    errors.map(function (err) {
      return {
        row: err.line - 1,
        column: err.col - 1,
        text: err.message,
        type: 'error'
      };
    })
  );
};

TabbedEditor.prototype.tryParse = function() {
  Ajax.parseCode(this.editor.getValue(), (function (data) {
    this.overlayErrors(data.errors);
  }).bind(this));
};

TabbedEditor.prototype.startSyntaxChecker = function() {
  var typingTimer = null;
  var doneTypingInterval = 1000;

  var doneTyping = (function() {
    this.tryParse();
    typingTimer = null;
  }).bind(this);

  this.editor.on('change', function() {
    if (typingTimer != null) {
      clearTimeout(typingTimer);
      typingTimer = null;
    }
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  });
};

var getPathFromTreeNode = function (node) {
  var parts = [];
  while (node.name !== undefined) {
    parts.unshift(node.name);
    node = node.parent;
  }
  return parts.join('/');
}

var Ajax = {
  parseCode: function(code, callback) {
    $.ajax({
      url: '/parse',
      method: 'POST',
      contentType: 'text/plain',
      data: code,
      dataType: 'json',
      success: callback,
    });
  },
  readFile: function(path, callback) {
    $.get('/read?path=' + encodeURIComponent(path), callback);
  },
  writeFile: function(path, contents) {
    $.post({
      url: '/write',
      data: {'path': path, 'contents': contents}
    });
  },
};

$(function() {
  var editor = new TabbedEditor('editor', 'editor-buffer');
  editor.startSyntaxChecker();

  var console = ace.edit('console');
  console.setTheme('ace/theme/solarized_light');
  console.setFontSize(14);
  console.setReadOnly(true);
  console.setHighlightActiveLine(false);
  console.renderer.setShowGutter(false);

  $('#projects').tree({
    dataUrl: '/projects',
    selectable: false,
  });
  $('#projects').on('tree.dblclick', function(e) {
    if (e.node.children.length > 0) {
      return;
    }
    var path = getPathFromTreeNode(e.node);
    if (editor.hasTabLabeled(path)) {
      editor.getTabLabeled(path).select();
    } else {
      Ajax.readFile(path, function (data) {
        editor.createTab(path, data).select();
      });
    }
  });
});
<commit_msg>Fix for reopening closed tabs not working<commit_after>function Tab(li, label, session, editor) {
  this.li = li;
  this.label = label;
  this.li.data('tab', this);
  this.session = session;
  this.editor = editor;
};

Tab.prototype.getSiblings = function() {
  return this.li.siblings().map(function (i, li) {
    return $(li).data('tab');
  });
};

Tab.prototype.unselect = function() {
  this.li.removeClass('active');
};

Tab.prototype.select = function() {
  this.li.addClass('active');
  this.getSiblings().each(function (i, tab) { tab.unselect(); });
  this.editor.editor.setSession(this.session);
};

Tab.prototype.close = function() {
  this.editor.removeTabLabeled(this.label);
  this.li.remove();
};

function TabbedEditor(id, aceId) {
  this.el = $('#' + id);
  this.editor_el = $('#' + aceId);
  this.editor = ace.edit(aceId);
  this.editor.setTheme('ace/theme/solarized_dark');
  this.editor.setFontSize(14);
  this.editor.setSession(this.newSession(''));
  this.editor.resize();
  this.editor.focus();

  $(window).resize(this.resizeAce.bind(this));
  this.resizeAce();

  this.tabs = {};

  this.el.find('ul.editor-tabs')
    .on('click', 'li:not(.editor-add-file)', function () {
      $(this).data('tab').select();
    })
    .on('click', 'span.glyphicon-remove', function() {
      $(this).parents('li').first().data('tab').close();
      return false;
    });

  this.newTabButton = this.el.find('.editor-add-file').first();
  this.newTabButton.on('click', (function () {
    var filename = prompt('Name: ');
    if (/[^\s]/.test(filename)) {
      this.createTab(filename).select();
    }
  }).bind(this));
};

TabbedEditor.prototype.getTabLabeled = function(name) {
  return this.tabs[name];
};

TabbedEditor.prototype.hasTabLabeled = function(name) {
  return name in this.tabs;
}

TabbedEditor.prototype.removeTabLabeled = function(name) {
  delete this.tabs[name];
}

var makeIcon = function(icon) {
  return $('<span>').addClass('glyphicon glyphicon-' + icon);
}

TabbedEditor.prototype.createTab = function(filename, contents) {
  if (contents === undefined) {
    contents = '';
  }
  var li = $('<li>').append($('<a>').attr('href', '#').append(
    filename, ' ', makeIcon('remove')));
  li.insertBefore(this.newTabButton);
  this.tabs[filename] = new Tab(li, filename, this.newSession(contents), this);
  return this.tabs[filename];
}

TabbedEditor.prototype.newSession = function(text) {
  var session = ace.createEditSession(text, 'ace/mode/matlab');
  session.setUseSoftTabs(true);
  return session;
}

TabbedEditor.prototype.resizeAce = function() {
    var height = $(window).height();
    this.editor_el.height(3 * height / 4);
    this.editor.resize();
    // TODO(isbadawi): This shouldn't be here
    $('#console').height(height / 4);
    ace.edit('console').resize();
};

TabbedEditor.prototype.overlayErrors = function(errors) {
  if (errors === undefined) {
    errors = [];
  }
  this.editor.getSession().setAnnotations(
    errors.map(function (err) {
      return {
        row: err.line - 1,
        column: err.col - 1,
        text: err.message,
        type: 'error'
      };
    })
  );
};

TabbedEditor.prototype.tryParse = function() {
  Ajax.parseCode(this.editor.getValue(), (function (data) {
    this.overlayErrors(data.errors);
  }).bind(this));
};

TabbedEditor.prototype.startSyntaxChecker = function() {
  var typingTimer = null;
  var doneTypingInterval = 1000;

  var doneTyping = (function() {
    this.tryParse();
    typingTimer = null;
  }).bind(this);

  this.editor.on('change', function() {
    if (typingTimer != null) {
      clearTimeout(typingTimer);
      typingTimer = null;
    }
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
  });
};

var getPathFromTreeNode = function (node) {
  var parts = [];
  while (node.name !== undefined) {
    parts.unshift(node.name);
    node = node.parent;
  }
  return parts.join('/');
}

var Ajax = {
  parseCode: function(code, callback) {
    $.ajax({
      url: '/parse',
      method: 'POST',
      contentType: 'text/plain',
      data: code,
      dataType: 'json',
      success: callback,
    });
  },
  readFile: function(path, callback) {
    $.get('/read?path=' + encodeURIComponent(path), callback);
  },
  writeFile: function(path, contents) {
    $.post({
      url: '/write',
      data: {'path': path, 'contents': contents}
    });
  },
};

$(function() {
  var editor = new TabbedEditor('editor', 'editor-buffer');
  editor.startSyntaxChecker();

  var consolePane = ace.edit('console');
  consolePane.setTheme('ace/theme/solarized_light');
  consolePane.setFontSize(14);
  consolePane.setReadOnly(true);
  consolePane.setHighlightActiveLine(false);
  consolePane.renderer.setShowGutter(false);

  $('#projects').tree({
    dataUrl: '/projects',
    selectable: false,
  });
  $('#projects').on('tree.dblclick', function(e) {
    if (e.node.children.length > 0) {
      return;
    }
    var path = getPathFromTreeNode(e.node);
    if (editor.hasTabLabeled(path)) {
      editor.getTabLabeled(path).select();
    } else {
      Ajax.readFile(path, function (data) {
        editor.createTab(path, data).select();
      });
    }
  });
});
<|endoftext|>


<commit_before>var shuffle = require('../../lib/index'),
    baccaratHand = require('./baccarat-hand'),
    EventEmitter = require('events').EventEmitter,
    util = require('util');
var pThirdCard = -1;
var playerThirdCard;

var srand = require('srand');
srand.seed(1000);
//var shoe = shuffle.shuffle({random: function(){ return srand.random(); }, numberOfDecks: 8}),
var shoe = shuffle.shuffle({numberOfDecks: 8}),
    player, banker;

function Game() {
  EventEmitter.call(this);

  var game = this;
  this.onPlayerInputNeeded;
  this.onEnd;

  var handsPlayed = 0;

  //this.begin = function() {
  //  while(shoe.length >= 14) {
  //    console.log("-----------------");
  //    handsPlayed++;
  //    banker = new baccaratHand();
  //    player = new baccaratHand();
  //    shoe.deal(2, [player, banker]);
  //    displayGameStatus();
  //    checkNaturals();
  //    console.log("-----------------");
  //  }
  //
  //  console.log("Hands Played : " + handsPlayed);
  //  game.emit('end');
  //};

  this.begin = function() {
    var handleInput = function(command) {
      if(command.toLocaleLowerCase() === 'n') {
        console.log("Hands Played : " + handsPlayed);
        game.emit('end');
      } else {
        playHand();
        console.log("Deal? (y)");
        game.emit('input', handleInput);
      }
    };

    console.log("========================================");
    console.log("Starting New Shoe.");
    var burnCard = shoe.draw();
    var burnCardValue = 0;

    if(burnCard.description.toLowerCase() === 'ace')
      burnCardValue = 1;
    else if(burnCard.sort >= 10)
      burnCardValue = 10;
    else
      burnCardValue = burnCard.sort;

    console.log("Burn Card : " + burnCard.toShortDisplayString() + ". Burning " + (burnCardValue + 1) + " for " + burnCardValue);
    for(var i = 1 ; i <= burnCardValue ; i++)
      shoe.draw();
    console.log("Shoe length : " + shoe.length);
    console.log("========================================");

    console.log("Deal? (y)");
    game.emit('input', handleInput);
  };

  function playHand() {
    console.log("-----------------");
    handsPlayed++;
    banker = new baccaratHand();
    player = new baccaratHand();
    shoe.deal(2, [player, banker]);
    displayGameStatus();
    checkNaturals();
    console.log("-----------------");
  }

  function checkNaturals() {
    var playerScore = player.score();
    var bankerScore = banker.score();

    if (playerScore === 8 && bankerScore < 8) {
      console.log('P');
      return;
    } else if (playerScore === 9 && bankerScore < 9) {
      console.log('P');
      return;
    } else if (bankerScore === 8 && playerScore < 8) {
      console.log('B');
      return;
    } else if (bankerScore === 9 && playerScore < 9) {
      console.log('B');
      return;
    } else if (bankerScore === 8 && playerScore === 8) {
      console.log('T');
      return;
    } else if (bankerScore === 9 && playerScore === 9) {
      console.log('T');
      return;
    } else {
      thirdCardDraw();
    }
  }

  function thirdCardDraw() {
    var playerScore = player.score();
    var bankerScore = banker.score();

    // When player score is < 6
    if (playerScore < 6 && playerScore >= 0) {
      console.log("Drawing third card for player");
      playerThirdCard = shoe.draw();
      player.push(playerThirdCard);

      // Check banker drawing rules if third card between 0 and 9...
      pThirdCard = playerThirdCard.sort;
      if(pThirdCard >= 0 && pThirdCard <= 9) {
        if (bankerScore === 3 && pThirdCard != 8 ) {
          console.log("Banker 3 and player third Card is not 8");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        } else if (bankerScore === 4 && (
            pThirdCard >= 2 && pThirdCard <= 7 )) {
          console.log("Banker 4 and player third card between 2 and 7");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        } else if (bankerScore === 5 && (
            pThirdCard >= 4 && pThirdCard <= 7 )) {
          console.log("Banker 5 and player third card between 4 and 7");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        } else if (bankerScore === 6 && (
            pThirdCard >= 6 && pThirdCard <= 7 )) {
          console.log("Banker 6 and player 3rd card between 6 and 7");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        }
      }
    }

    if(bankerScore >= 0 && bankerScore <= 5) {
      console.log("bankerscore between 0 and 5");
      var bankerThirdCard = shoe.draw();
      banker.push(bankerThirdCard);
      return checkWinner();
    } else {
      // None of the condition satisfied
      console.log("None of the conditions satisfied.");
      return checkWinner();
    }
  }

  function checkWinner() {
    var playerScore = player.score();
    var bankerScore = banker.score();
    if (playerScore > bankerScore) {
      displayGameStatus();
      console.log('P');
      //game.emit('input', handleInput);
    } else if (bankerScore > playerScore) {
      displayGameStatus();
      console.log('B');
      //game.emit('input', handleInput);
    } else {
      displayGameStatus();
      console.log('T');
      //game.emit('input', handleInput);
    }
  }

  function displayGameStatus() {
    console.log('Player: %s (%d)', player.toString(), player.score());
    console.log('Banker: %s (%d)', banker.toString(), banker.score());
    console.log("Deck Size : " + shoe.length);
  }
}

util.inherits(Game, EventEmitter);
module.exports = Game;
<commit_msg>Code clean up.<commit_after>var shuffle = require('../../lib/index'),
    baccaratHand = require('./baccarat-hand'),
    EventEmitter = require('events').EventEmitter,
    util = require('util');
var pThirdCard = -1;
var playerThirdCard;

var shoe = shuffle.shuffle({numberOfDecks: 8}),
    player, banker;

function Game() {
  EventEmitter.call(this);

  var game = this;
  this.onPlayerInputNeeded;
  this.onEnd;

  var handsPlayed = 0;

  //this.begin = function() {
  //  while(shoe.length >= 14) {
  //    console.log("-----------------");
  //    handsPlayed++;
  //    banker = new baccaratHand();
  //    player = new baccaratHand();
  //    shoe.deal(2, [player, banker]);
  //    displayGameStatus();
  //    checkNaturals();
  //    console.log("-----------------");
  //  }
  //
  //  console.log("Hands Played : " + handsPlayed);
  //  game.emit('end');
  //};

  this.begin = function() {
    var handleInput = function(command) {
      if(command.toLocaleLowerCase() === 'n') {
        console.log("Hands Played : " + handsPlayed);
        game.emit('end');
      } else {
        playHand();
        console.log("Deal? (y)");
        game.emit('input', handleInput);
      }
    };

    console.log("========================================");
    console.log("Starting New Shoe.");
    var burnCard = shoe.draw();
    var burnCardValue = 0;

    if(burnCard.description.toLowerCase() === 'ace')
      burnCardValue = 1;
    else if(burnCard.sort >= 10)
      burnCardValue = 10;
    else
      burnCardValue = burnCard.sort;

    console.log("Burn Card : " + burnCard.toShortDisplayString() + ". Burning " + (burnCardValue + 1) + " for " + burnCardValue);
    for(var i = 1 ; i <= burnCardValue ; i++)
      shoe.draw();
    console.log("Shoe length : " + shoe.length);
    console.log("========================================");

    console.log("Deal? (y)");
    game.emit('input', handleInput);
  };

  function playHand() {
    console.log("-----------------");
    handsPlayed++;
    banker = new baccaratHand();
    player = new baccaratHand();
    shoe.deal(2, [player, banker]);
    displayGameStatus();
    checkNaturals();
    console.log("-----------------");
  }

  function checkNaturals() {
    var playerScore = player.score();
    var bankerScore = banker.score();

    if (playerScore === 8 && bankerScore < 8) {
      console.log('P');
      return;
    } else if (playerScore === 9 && bankerScore < 9) {
      console.log('P');
      return;
    } else if (bankerScore === 8 && playerScore < 8) {
      console.log('B');
      return;
    } else if (bankerScore === 9 && playerScore < 9) {
      console.log('B');
      return;
    } else if (bankerScore === 8 && playerScore === 8) {
      console.log('T');
      return;
    } else if (bankerScore === 9 && playerScore === 9) {
      console.log('T');
      return;
    } else {
      thirdCardDraw();
    }
  }

  function thirdCardDraw() {
    var playerScore = player.score();
    var bankerScore = banker.score();

    // When player score is < 6
    if (playerScore < 6 && playerScore >= 0) {
      console.log("Drawing third card for player");
      playerThirdCard = shoe.draw();
      player.push(playerThirdCard);

      // Check banker drawing rules if third card between 0 and 9...
      pThirdCard = playerThirdCard.sort;
      if(pThirdCard >= 0 && pThirdCard <= 9) {
        if (bankerScore === 3 && pThirdCard != 8 ) {
          console.log("Banker 3 and player third Card is not 8");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        } else if (bankerScore === 4 && (
            pThirdCard >= 2 && pThirdCard <= 7 )) {
          console.log("Banker 4 and player third card between 2 and 7");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        } else if (bankerScore === 5 && (
            pThirdCard >= 4 && pThirdCard <= 7 )) {
          console.log("Banker 5 and player third card between 4 and 7");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        } else if (bankerScore === 6 && (
            pThirdCard >= 6 && pThirdCard <= 7 )) {
          console.log("Banker 6 and player 3rd card between 6 and 7");
          var bankerThirdCard = shoe.draw();
          banker.push(bankerThirdCard);
          return checkWinner();
        }
      }
    }

    if(bankerScore >= 0 && bankerScore <= 5) {
      console.log("bankerscore between 0 and 5");
      var bankerThirdCard = shoe.draw();
      banker.push(bankerThirdCard);
      return checkWinner();
    } else {
      // None of the condition satisfied
      console.log("None of the conditions satisfied.");
      return checkWinner();
    }
  }

  function checkWinner() {
    var playerScore = player.score();
    var bankerScore = banker.score();
    if (playerScore > bankerScore) {
      displayGameStatus();
      console.log('P');
      //game.emit('input', handleInput);
    } else if (bankerScore > playerScore) {
      displayGameStatus();
      console.log('B');
      //game.emit('input', handleInput);
    } else {
      displayGameStatus();
      console.log('T');
      //game.emit('input', handleInput);
    }
  }

  function displayGameStatus() {
    console.log('Player: %s (%d)', player.toString(), player.score());
    console.log('Banker: %s (%d)', banker.toString(), banker.score());
    console.log("Deck Size : " + shoe.length);
  }
}

util.inherits(Game, EventEmitter);
module.exports = Game;
<|endoftext|>


<commit_before>
<commit_msg>Update Facade.js<commit_after>/**
 * A facade class to attach to a Phaser game.
 *
 * TODO: Extract a CollisionHandler/CollisionResolver class that stores solvers
 *       and defaultSolver that the facade can just forward calls to.
 *
 * @class Phaser.Plugin.ArcadeSlopes.Facade
 * @constructor
 * @param {Phaser.Plugin.ArcadeSlopes.TileSlopeFactory} factory       - A tile slope factory.
 * @param {object}                                      solvers       - A set of collision solvers.
 * @param {integer}                                     defaultSolver - The default collision solver type to use for sloped tiles.
 */
Phaser.Plugin.ArcadePolygons.Facade = function (factory, solvers, defaultSolver) {
	/**
	 * A tile slope factory.
	 *
	 * @property {Phaser.Plugin.ArcadeSlopes.TileSlopeFactory} factory
	 */
	this.factory = factory;

	/**
	 * A set of collision solvers.
	 *
	 * Maps solver constants to their respective instances.
	 *
	 * @property {object} solvers
	 */
	this.solvers = solvers;

	/**
	 * The default collision solver type to use for sloped tiles.
	 *
	 * @property {string} defaultSolver
	 * @default
	 */
	this.defaultSolver = defaultSolver || Phaser.Plugin.ArcadePolygons.SAT;
}

/**
 * Enable the physics body of the given object for sloped tile interaction.
 *
 * @method Phaser.Plugin.ArcadeSlopes.Facade#enable
 * @param {Phaser.Sprite|Phaser.Group} object - The object to enable sloped tile physics for.
 */
Phaser.Plugin.ArcadePolygons.Facade.prototype.enable = function (object) {
	if (Array.isArray(object)) {
		for (var i = 0; i < object.length; i++) {
			this.enable(object[i]);
		}
	} else {
		if (object instanceof Phaser.Group) {
			this.enable(object.children);
		} else {
			if (object.hasOwnProperty('body')) {
				this.enableBody(object.body);
			}

			if (object.hasOwnProperty('children') && object.children.length > 0) {
				this.enable(object.children);
			}
		}
	}
};

/**
 * Enable the given physics body for sloped tile interaction.
 *
 * TODO: Circle body support, when it's released.
 *
 * @method Phaser.Plugin.ArcadeSlopes.Facade#enableBody
 * @param {Phaser.Physics.Arcade.Body} body - The physics body to enable.
 */
Phaser.Plugin.ArcadePolygons.Facade.prototype.enableBody = function (body) {

  // Conveniently add it to the player body and convert it to a
  // polygon while we're at it
  // body.sat = {
  //   polygon: new window.SAT.Box(
  //     new window.SAT.Vector(body.x, body.y),
  //     body.width,
  //     body.height
  //   ).toPolygon()
  // }

};

/**
 * Collides a physics body against a tile.
 *
 * @method Phaser.Plugin.ArcadeSlopes.Facade#collide
 * @param  {integer}                    i            - The tile index.
 * @param  {Phaser.Physics.Arcade.Body} body         - The physics body.
 * @param  {Phaser.Tile}                tile         - The tile.
 * @param  {Phaser.TilemapLayer}        tilemapLayer - The tilemap layer.
 * @param  {boolean}                    overlapOnly  - Whether to only check for an overlap.
 * @return {boolean}                                 - Whether the body was separated.
 */
Phaser.Plugin.ArcadePolygons.Facade.prototype.collide = function (sprite, polygons) {

};
<|endoftext|>


<commit_before>import _ from 'lodash';
import jsop from 'jsop';
import path from 'path';

const electron = require('electron');

export const USER_PREFS_PATH = electron.ipcRenderer.sendSync('userPrefsPath');

global.USER_PREFS_PATH = USER_PREFS_PATH;

class Settings {
	constructor(path) {
		this.db = jsop(path);
	}

	destroy() {
		_.forOwn(this.db, this._clearDB);
	}

	load() {
		return this.db;
	}

	val(key, value) {
		var setting;

		var db = this.db;

		var get = (arguments.length === 1 && _.isString(key));
		var objectKey = _.isObject(key);

		if (objectKey || arguments.length > 1) {
			get = false;
		}

		if (get) {
			setting = db[key];
		}
		else if (objectKey) {
			_.extend(db, key);
		}
		else {
			db[key] = value;
		}

		return setting;
	}

	_clearDB(item, index, obj) {
		delete obj[index];
	}
}

var settings = new Settings(path.join(USER_PREFS_PATH || '', 'settings.json'));

settings.USER_PREFS_PATH = USER_PREFS_PATH;

export default settings;<commit_msg>Add ability to remove a property from the settings<commit_after>import _ from 'lodash';
import jsop from 'jsop';
import path from 'path';

const electron = require('electron');

export const USER_PREFS_PATH = electron.ipcRenderer.sendSync('userPrefsPath');

global.USER_PREFS_PATH = USER_PREFS_PATH;

class Settings {
	constructor(path) {
		this.db = jsop(path);
	}

	destroy() {
		_.forOwn(this.db, this._clearDB);
	}

	load() {
		return this.db;
	}

	val(key, value) {
		var setting;

		var db = this.db;

		var get = (arguments.length === 1 && _.isString(key));
		var objectKey = _.isObject(key);

		if (objectKey || arguments.length > 1) {
			get = false;
		}

		if (get) {
			setting = db[key];
		}
		else if (objectKey) {
			_.extend(db, key);

			_.each(
				db,
				function(item, index) {
					if (item === null) {
						delete db[index];
					}
				}
			);
		}
		else if (_.isNull(value)) {
			delete db[key];
		}
		else {
			db[key] = value;
		}

		return setting;
	}

	_clearDB(item, index, obj) {
		delete obj[index];
	}
}

var settings = new Settings(path.join(USER_PREFS_PATH || '', 'settings.json'));

settings.USER_PREFS_PATH = USER_PREFS_PATH;

export default settings;<|endoftext|>


<commit_before>module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readYAML('../config/config.yml'),

        watch: {
            scripts: {
                files: ['js/*.js', 'sass/*.scss'],
                tasks: ['sass'],
                options: {
                    spawn: false,
                    livereload: true
                },
            }
        },

        sass: {
            dist: {
                options: {
                    style: 'nested',
                    loadPath: [
                        'node_modules/bootstrap-sass/vendor/assets/stylesheets/',
                        'node_modules/font-awesome/scss/'
                    ],
                    lineNumbers: true,
                },
                files: {
                    'css/app.css': 'sass/app.scss'
                }
            },

        },

        copy: {
            main: {
                files: [
                    // includes files within path
                    {expand: true, flatten: true, src: ['node_modules/font-awesome/fonts/*'], dest: 'fonts/', filter: 'isFile'}
                ]
            }
        }

    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('default', ['sass', 'watch']);

};
<commit_msg>Update Gruntfile.js<commit_after>module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readYAML('../config/config.yml'),

        watch: {
            scripts: {
                files: ['js/*.js', 'sass/*.scss'],
                tasks: ['sass'],
                options: {
                    spawn: false,
                    livereload: true
                },
            }
        },

        sass: {
            dist: {
                options: {
                    style: 'nested',
                    loadPath: [
                        'node_modules/bootstrap-sass/vendor/assets/stylesheets/',
                        'node_modules/font-awesome/scss/'
                    ],
                    lineNumbers: true
                },
                files: {
                    'css/app.css': 'sass/app.scss'
                }
            },

        },

        copy: {
            main: {
                files: [
                    // includes files within path
                    {expand: true, flatten: true, src: ['node_modules/font-awesome/fonts/*'], dest: 'fonts/', filter: 'isFile'}
                ]
            }
        }

    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('default', ['sass', 'watch']);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
    grunt.util.linefeed = '\n';

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readYAML('../config/config.yml'),

        watch: {
            options: {
                spawn: false,
                livereload: true
            },
            scripts: {
                files: [
                    'sass/*.scss',
                    'sass/nav/*.scss',
                    'sass/modules/*.scss'
                ],
                tasks: [
                    'sass'
                ]
            },
            js: {
                files: [
                    'lib/bolt/*.js'
                ],
                tasks: [
                    'uglify:bolt'
                ]
            }
        },

        sass: {
            dist: {
                options: {
                    outputStyle: 'compressed',
                    includePaths: [
                        'node_modules/bootstrap-sass/assets/stylesheets/',
                        'node_modules/font-awesome/scss/'
                    ],
                    lineNumbers: false,
                    unixNewlines: true,
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED CSS files!\n" +
                            " * Do not edit these files, because all changes will be lost.\n" +
                            " * You can edit ../scss/app.scss & ../scss/app-old-ie.scss, and run 'grunt' to generate this file.\n" +
                            " */\n",
                    precision: 5
                },
                files: {
                    'css/bolt-old-ie.css': 'sass/app-old-ie.scss',
                    'css/bolt.css': 'sass/app.scss'
                }
            }

        },

        copy: {
            main: {
                // Includes files within path
                files: [{
                    expand: true,
                    flatten: true,
                    src: [
                        'node_modules/font-awesome/fonts/*'
                    ],
                    filter: 'isFile',
                    dest: 'fonts/'
                }]
            },
            momentlocales: {
                files: [{
                    expand: true,
                    flatten: true,
                    src: [
                        'node_modules/moment/locale/cs.js',
                        'node_modules/moment/locale/de.js',
                        'node_modules/moment/locale/el.js',
                        'node_modules/moment/locale/en-gb.js',
                        'node_modules/moment/locale/es.js',
                        'node_modules/moment/locale/fi.js',
                        'node_modules/moment/locale/fr.js',
                        'node_modules/moment/locale/hu.js',
                        'node_modules/moment/locale/id.js',
                        'node_modules/moment/locale/it.js',
                        'node_modules/moment/locale/ja.js',
                        'node_modules/moment/locale/nb.js',
                        'node_modules/moment/locale/nl.js',
                        'node_modules/moment/locale/nb.js',
                        'node_modules/moment/locale/nl.js',
                        'node_modules/moment/locale/pt.js',
                        'node_modules/moment/locale/ru.js',
                        'node_modules/moment/locale/zh-cn.js',
                        'node_modules/moment/min/moment.min.js',
                    ],
                    filter: 'isFile',
                    dest: 'lib/moment/'
                }]
            }
        },

        concat: {
            lib: {
                options: {
                    separator: '\n\n'
                },
                nonull: true,
                src: [
                    'lib/jquery-1.11.2/jquery.min.js',                              //  96 kb
                    'lib/jquery-ui-1.10.3/jquery-ui.custom.min.js',                 //  96 kb
                    'lib/bootstrap-file-input/bootstrap-file-input.min.js',         //   1 kb
                    'lib/jquery-tagcloud/jquery-tagcloud.min.js',                   //   1 kb
                    'lib/jquery-hotkeys/jquery-hotkeys.min.js',                     //   2 kb
                    'lib/jquery-watchchanges/jquery-watchchanges.min.js',           //   1 kb
                    'lib/jquery-cookie-1.4.0/jquery-cookie.min.js',                 //   1 kb
                    'lib/jquery-formatdatetime-1.1.4/jquery-formatdatetime.min.js', //   3 kb
                    'lib/jquery-fileupload-5.26/jquery-iframe-transport.min.js',    //   2 kb
                    'lib/jquery-fileupload-5.26/jquery-fileupload.min.js',          //  15 kb
                    'lib/underscore-1.7.0/underscore-min.js',                       //  16 kb
                    'lib/backbone/backbone-min.js',                                 //  20 kb
                    'lib/bootstrap-sass.generated/bootstrap.min.js',                //   2 kb
                    'lib/magnific-popup-0.9.9/magnific-popup.min.js',               //  21 kb
                    'lib/select2-3.5.1/select2.min.js',                             //  66 kb
                    'lib/moment/moment.min.js',                                     //  35 kb
                    'lib/bootbox-4.3.0/bootbox.min.js',                             //   9 kb
                    'lib/modernizr-2.8.3/modernizr.custom.min.js'                   //   5 kb
                ],
                dest: 'js/lib.min.js'
            }
        },

        cssmin: {
            lib: {
                options: {
                    compatibility: 'ie8',
                    relativeTo: './css/',
                    target: './css/'
                },
                files: {
                    'css/lib.css': [
                        'lib/jquery-ui-1.10.3/jquery-ui.custom.min.css',      // 20 kb
                        'lib/magnific-popup-0.9.9/magnific-popup.css',        //  9 kb
                        'lib/select2-3.5.1/select2.css',                      // 19 kb
                        'lib/jquery-fileupload-5.26/jquery-fileupload-ui.css' //  2 kb
                    ]
                }
            }
        },

        uglify: {
            lib: {
                options: {
                    preserveComments: 'some'
                },
                files: [{
                    expand: true,
                    ext: '.min.js',
                    src: [
                        'lib/bootstrap-file-input/bootstrap-file-input.js',
                        'lib/jquery-cookie-1.4.0/jquery-cookie.js',
                        'lib/jquery-fileupload-5.26/jquery-fileupload.js',
                        'lib/jquery-fileupload-5.26/jquery-iframe-transport.js',
                        'lib/jquery-formatdatetime-1.1.4/jquery-formatdatetime.js',
                        'lib/jquery-hotkeys/jquery-hotkeys.js',
                        'lib/jquery-tagcloud/jquery-tagcloud.js',
                        'lib/jquery-watchchanges/jquery-watchchanges.js'
                    ]
                }]
            },
            bootstrap: {
                files: {
                    'lib/bootstrap-sass.generated/bootstrap.min.js': [
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/alert.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/button.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/dropdown.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tab.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/transition.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/modal.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tooltip.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/popover.js'
                    ]
                }
            },
            bolt: {
                options: {
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED JS files!\n" +
                            " * You can edit files in <js/src/*.js> and run 'grunt' to generate this file.\n" +
                            " */",
                    sourceMap: true
                },
                files: {
                    'js/bolt.min.js': [
                        'lib/bolt/console.js',
                        'lib/bolt/fnc-helpers.js',
                        'lib/bolt/activity.js',
                        'lib/bolt/bind-fileupload.js',
                        'lib/bolt/make-uri-slug.js',
                        'lib/bolt/video-embed.js',
                        'lib/bolt/geolocation.js',
                        'lib/bolt/upload-files.js',
                        'lib/bolt/obj-sidebar.js',
                        'lib/bolt/obj-navpopups.js',
                        'lib/bolt/obj-moments.js',
                        'lib/bolt/obj-files.js',
                        'lib/bolt/obj-stack.js',
                        'lib/bolt/obj-folders.js',
                        'lib/bolt/obj-datetime.js',
                        'lib/bolt/extend.js',
                        'lib/bolt/init.js',
                        'lib/bolt/start.js'
                    ]
                }
            }
        },

        jshint: {
            options: {
                browser: true,          // Defines globals exposed by modern browsers
                curly: true,            // Always put curly braces around blocks
                devel: true,            // Defines globals that are usually used for logging/debugging
                immed: true,            // Prohibits the use of immediate function invocations without parentheses
                indent: 4,              // Tab width
                latedef: true,          // Prohibits the use of a variable before it was defined
                maxlen: 120,            // Maximum length of a line
                noarg: true,            // Prohibits the use of arguments.caller and arguments.callee
                nonbsp: true,           // Warns about "non-breaking whitespace" characters
                singleGroups: true,     // Prohibits the use of the grouping operator for single-expression statements
                undef: true,            // Prohibits the use of undeclared variables
                globals: {
                    // Bolt
                    bolt: true,                 // src/console.js
                    FilelistHolder: true,       // src/upload-files.js
                    Files: true,                // src/obj-files.js
                    Folders: true,              // src/obj-folders.js
                    init: true,                 // src/init.js
                    Moments: true,              // src/obj-moments.js
                    Navpopups: true,            // src/obj-navpopups.js
                    Sidebar: true,              // src/obj-sidebar.js
                    Stack: true,                // src/obj-stack.js
                    site: true,                 // src/extend.js/extend.twig
                    baseurl: true,              // src/extend.js/extend.twig
                    rootpath: true,             // src/extend.js/extend.twig
                    // Bolt global functions
                    bindFileUpload: true,       // src/bindfileuploads.js
                    bindGeolocation: true,      // src/geolocation.js
                    bindVideoEmbed: true,       // src/video-embed.js
                    getSelectedItems: true,     // src/fnc-helpers.js
                    makeUri: true,              // src/make-uri-slug.js
                    makeUriAjax: true,          // src/make-uri-slug.js
                    stopMakeUri: true,          // src/make-uri-slug.js
                    updateLatestActivity: true, // src/activity.js
                    validateContent: true,      // src/fnc-helpers.js
                    // Vendor
                    $: true,                    // jQuery
                    _: true,                    // underscore.js
                    Backbone: true,             // backbone.min.js
                    bootbox: true,              // bootbox.min.js
                    CKEDITOR: true,             // ckeditor.js
                    CodeMirror: true,           // ckeditor.js
                    google: true,               // Google
                    jQuery: true,               // jQuery
                    moment: true,               // moment.min.js
                    UAParser: true              // ua-parser.min.js
                }
            },
            src: ['lib/bolt/*.js']
        }

    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', ['sass', 'jshint', 'uglify', 'cssmin', 'concat', 'watch']);

};
<commit_msg>Make grunt generate uglified datepicker locale file and rename them to ease usage<commit_after>module.exports = function(grunt) {
    grunt.util.linefeed = '\n';

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: grunt.file.readYAML('../config/config.yml'),

        watch: {
            options: {
                spawn: false,
                livereload: true
            },
            scripts: {
                files: [
                    'sass/*.scss',
                    'sass/nav/*.scss',
                    'sass/modules/*.scss'
                ],
                tasks: [
                    'sass'
                ]
            },
            js: {
                files: [
                    'lib/bolt/*.js'
                ],
                tasks: [
                    'uglify:bolt'
                ]
            }
        },

        sass: {
            dist: {
                options: {
                    outputStyle: 'compressed',
                    includePaths: [
                        'node_modules/bootstrap-sass/assets/stylesheets/',
                        'node_modules/font-awesome/scss/'
                    ],
                    lineNumbers: false,
                    unixNewlines: true,
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED CSS files!\n" +
                            " * Do not edit these files, because all changes will be lost.\n" +
                            " * You can edit ../scss/app.scss & ../scss/app-old-ie.scss, and run 'grunt' to generate this file.\n" +
                            " */\n",
                    precision: 5
                },
                files: {
                    'css/bolt-old-ie.css': 'sass/app-old-ie.scss',
                    'css/bolt.css': 'sass/app.scss'
                }
            }

        },

        copy: {
            main: {
                // Includes files within path
                files: [{
                    expand: true,
                    flatten: true,
                    src: [
                        'node_modules/font-awesome/fonts/*'
                    ],
                    filter: 'isFile',
                    dest: 'fonts/'
                }]
            },
            momentlocales: {
                files: [{
                    expand: true,
                    flatten: true,
                    src: [
                        'node_modules/moment/locale/cs.js',
                        'node_modules/moment/locale/de.js',
                        'node_modules/moment/locale/el.js',
                        'node_modules/moment/locale/en-gb.js',
                        'node_modules/moment/locale/es.js',
                        'node_modules/moment/locale/fi.js',
                        'node_modules/moment/locale/fr.js',
                        'node_modules/moment/locale/hu.js',
                        'node_modules/moment/locale/id.js',
                        'node_modules/moment/locale/it.js',
                        'node_modules/moment/locale/ja.js',
                        'node_modules/moment/locale/nb.js',
                        'node_modules/moment/locale/nl.js',
                        'node_modules/moment/locale/nb.js',
                        'node_modules/moment/locale/nl.js',
                        'node_modules/moment/locale/pt.js',
                        'node_modules/moment/locale/ru.js',
                        'node_modules/moment/locale/zh-cn.js',
                        'node_modules/moment/min/moment.min.js',
                    ],
                    filter: 'isFile',
                    dest: 'lib/moment/'
                }]
            }
        },

        concat: {
            lib: {
                options: {
                    separator: '\n\n'
                },
                nonull: true,
                src: [
                    'lib/jquery-1.11.2/jquery.min.js',                              //  96 kb
                    'lib/jquery-ui-1.10.3/jquery-ui.custom.min.js',                 //  96 kb
                    'lib/bootstrap-file-input/bootstrap-file-input.min.js',         //   1 kb
                    'lib/jquery-tagcloud/jquery-tagcloud.min.js',                   //   1 kb
                    'lib/jquery-hotkeys/jquery-hotkeys.min.js',                     //   2 kb
                    'lib/jquery-watchchanges/jquery-watchchanges.min.js',           //   1 kb
                    'lib/jquery-cookie-1.4.0/jquery-cookie.min.js',                 //   1 kb
                    'lib/jquery-formatdatetime-1.1.4/jquery-formatdatetime.min.js', //   3 kb
                    'lib/jquery-fileupload-5.26/jquery-iframe-transport.min.js',    //   2 kb
                    'lib/jquery-fileupload-5.26/jquery-fileupload.min.js',          //  15 kb
                    'lib/underscore-1.7.0/underscore-min.js',                       //  16 kb
                    'lib/backbone/backbone-min.js',                                 //  20 kb
                    'lib/bootstrap-sass.generated/bootstrap.min.js',                //   2 kb
                    'lib/magnific-popup-0.9.9/magnific-popup.min.js',               //  21 kb
                    'lib/select2-3.5.1/select2.min.js',                             //  66 kb
                    'lib/moment/moment.min.js',                                     //  35 kb
                    'lib/bootbox-4.3.0/bootbox.min.js',                             //   9 kb
                    'lib/modernizr-2.8.3/modernizr.custom.min.js'                   //   5 kb
                ],
                dest: 'js/lib.min.js'
            }
        },

        cssmin: {
            lib: {
                options: {
                    compatibility: 'ie8',
                    relativeTo: './css/',
                    target: './css/'
                },
                files: {
                    'css/lib.css': [
                        'lib/jquery-ui-1.10.3/jquery-ui.custom.min.css',      // 20 kb
                        'lib/magnific-popup-0.9.9/magnific-popup.css',        //  9 kb
                        'lib/select2-3.5.1/select2.css',                      // 19 kb
                        'lib/jquery-fileupload-5.26/jquery-fileupload-ui.css' //  2 kb
                    ]
                }
            }
        },

        uglify: {
            lib: {
                options: {
                    preserveComments: 'some'
                },
                files: [{
                    expand: true,
                    ext: '.min.js',
                    src: [
                        'lib/bootstrap-file-input/bootstrap-file-input.js',
                        'lib/jquery-cookie-1.4.0/jquery-cookie.js',
                        'lib/jquery-fileupload-5.26/jquery-fileupload.js',
                        'lib/jquery-fileupload-5.26/jquery-iframe-transport.js',
                        'lib/jquery-formatdatetime-1.1.4/jquery-formatdatetime.js',
                        'lib/jquery-hotkeys/jquery-hotkeys.js',
                        'lib/jquery-tagcloud/jquery-tagcloud.js',
                        'lib/jquery-watchchanges/jquery-watchchanges.js'
                    ]
                }]
            },
            locale_datepicker: {
                options: {
                    preserveComments: 'some'
                },
                files: [{
                    expand: true,
                    ext: '.min.js',
                    cwd: 'lib/datepicker',
                    src: '*.js',
                    dest: 'js/locale/datepicker',
                    rename: function(destBase, destPath) {
                        return destBase + '/' + destPath.replace('datepicker-', '').replace('-', '_');
                    }
                }]
            },
            bootstrap: {
                files: {
                    'lib/bootstrap-sass.generated/bootstrap.min.js': [
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/alert.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/button.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/dropdown.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tab.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/transition.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/modal.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/tooltip.js',
                        'node_modules/bootstrap-sass/assets/javascripts/bootstrap/popover.js'
                    ]
                }
            },
            bolt: {
                options: {
                    banner: "/**\n" +
                            " * These are Bolt's COMPILED JS files!\n" +
                            " * You can edit files in <js/src/*.js> and run 'grunt' to generate this file.\n" +
                            " */",
                    sourceMap: true
                },
                files: {
                    'js/bolt.min.js': [
                        'lib/bolt/console.js',
                        'lib/bolt/fnc-helpers.js',
                        'lib/bolt/activity.js',
                        'lib/bolt/bind-fileupload.js',
                        'lib/bolt/make-uri-slug.js',
                        'lib/bolt/video-embed.js',
                        'lib/bolt/geolocation.js',
                        'lib/bolt/upload-files.js',
                        'lib/bolt/obj-sidebar.js',
                        'lib/bolt/obj-navpopups.js',
                        'lib/bolt/obj-moments.js',
                        'lib/bolt/obj-files.js',
                        'lib/bolt/obj-stack.js',
                        'lib/bolt/obj-folders.js',
                        'lib/bolt/obj-datetime.js',
                        'lib/bolt/extend.js',
                        'lib/bolt/init.js',
                        'lib/bolt/start.js'
                    ]
                }
            }
        },

        jshint: {
            options: {
                browser: true,          // Defines globals exposed by modern browsers
                curly: true,            // Always put curly braces around blocks
                devel: true,            // Defines globals that are usually used for logging/debugging
                immed: true,            // Prohibits the use of immediate function invocations without parentheses
                indent: 4,              // Tab width
                latedef: true,          // Prohibits the use of a variable before it was defined
                maxlen: 120,            // Maximum length of a line
                noarg: true,            // Prohibits the use of arguments.caller and arguments.callee
                nonbsp: true,           // Warns about "non-breaking whitespace" characters
                singleGroups: true,     // Prohibits the use of the grouping operator for single-expression statements
                undef: true,            // Prohibits the use of undeclared variables
                globals: {
                    // Bolt
                    bolt: true,                 // src/console.js
                    FilelistHolder: true,       // src/upload-files.js
                    Files: true,                // src/obj-files.js
                    Folders: true,              // src/obj-folders.js
                    init: true,                 // src/init.js
                    Moments: true,              // src/obj-moments.js
                    Navpopups: true,            // src/obj-navpopups.js
                    Sidebar: true,              // src/obj-sidebar.js
                    Stack: true,                // src/obj-stack.js
                    site: true,                 // src/extend.js/extend.twig
                    baseurl: true,              // src/extend.js/extend.twig
                    rootpath: true,             // src/extend.js/extend.twig
                    // Bolt global functions
                    bindFileUpload: true,       // src/bindfileuploads.js
                    bindGeolocation: true,      // src/geolocation.js
                    bindVideoEmbed: true,       // src/video-embed.js
                    getSelectedItems: true,     // src/fnc-helpers.js
                    makeUri: true,              // src/make-uri-slug.js
                    makeUriAjax: true,          // src/make-uri-slug.js
                    stopMakeUri: true,          // src/make-uri-slug.js
                    updateLatestActivity: true, // src/activity.js
                    validateContent: true,      // src/fnc-helpers.js
                    // Vendor
                    $: true,                    // jQuery
                    _: true,                    // underscore.js
                    Backbone: true,             // backbone.min.js
                    bootbox: true,              // bootbox.min.js
                    CKEDITOR: true,             // ckeditor.js
                    CodeMirror: true,           // ckeditor.js
                    google: true,               // Google
                    jQuery: true,               // jQuery
                    moment: true,               // moment.min.js
                    UAParser: true              // ua-parser.min.js
                }
            },
            src: ['lib/bolt/*.js']
        }

    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', ['sass', 'jshint', 'uglify', 'cssmin', 'concat', 'watch']);

};
<|endoftext|>


<commit_before>define("views/ChatView", ["backbone", "underscore", "cocktail", "mixins/storage"], function(Backbone, _, Cocktail, storage){

    var ChatView = Backbone.View.extend({

        tagName: 'div',

        mixins: ["storage"],

        template: _.template($("#appTemplate").html()),

        initialize: function(){
            console.log(12345);
        },

        render: function(){
            this.setItem("viewParam", {});
            this.$el.html(this.template({}));
            return this;
        }
    });

    Cocktail.mixin(ChatView, window.appMixins.storage);

    return ChatView;
});<commit_msg>another one<commit_after>define("views/ChatView", ["backbone", "underscore", "cocktail", "mixins/storage"], function(Backbone, _, Cocktail, storage){

    var ChatView = Backbone.View.extend({

        tagName: 'div',

        mixins: ["storage"],

        template: _.template($("#appTemplate").html()),

        initialize: function(){
            console.log(123456789);
        },

        render: function(){
            this.setItem("viewParam", {});
            this.$el.html(this.template({}));
            return this;
        }
    });

    Cocktail.mixin(ChatView, window.appMixins.storage);

    return ChatView;
});<|endoftext|>


<commit_before>/*
* @Author: dmyang
* @Date:   2015-08-02 14:16:41
* @Last Modified by:   dmyang
* @Last Modified time: 2016-03-28 10:31:25
*/

'use strict';

let path = require('path')
let fs = require('fs')

let webpack = require('webpack')
let _ = require('lodash')
let glob = require('glob')

let ExtractTextPlugin = require('extract-text-webpack-plugin')
let HtmlWebpackPlugin = require('html-webpack-plugin')

let UglifyJsPlugin = webpack.optimize.UglifyJsPlugin
let CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin

let srcDir = path.resolve(process.cwd(), 'src')
let assets = path.resolve(process.cwd(), 'assets')
let nodeModPath = path.resolve(__dirname, './node_modules')
let pathMap = Object.assign({
    'react': path.join(nodeModPath, '/react/dist/react.js'),
    'react-with-addons': path.join(nodeModPath, '/react/dist/react-with-addons.js'),
    'react-dom': path.join(nodeModPath, '/react-dom/dist/react-dom.js'),
    'jquery': path.join(nodeModPath, '/jquery/dist/jquery.js'),
    'zepto': path.join(nodeModPath, '/zepto/zepto.min.js'),
}, require('./src/pathmap.json'))

let entries = (() => {
    let jsDir = path.resolve(srcDir, 'js')
    let entryFiles = glob.sync(jsDir + '/*.{js,jsx}')
    let map = {}

    entryFiles.forEach((filePath) => {
        let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
        map[filename] = filePath
    })

    return map
}())
let chunks = Object.keys(entries)

module.exports = (options) => {
    options = options || {}

    let debug = options.debug !== undefined ? options.debug : true
    // 这里publicPath要使用绝对路径，不然scss/css最终生成的css图片引用路径是错误的，应该是scss-loader的bug
    let publicPath = '/'
    let extractCSS
    let cssLoader
    let sassLoader

    // generate entry html files
    // 自动生成入口文件，入口js名必须和入口文件名相同
    // 例如，a页的入口文件是a.html，那么在js目录下必须有一个a.js作为入口文件
    let plugins = () => {
        let entryHtml = glob.sync(srcDir + '/*.html')
        let r = []

        entryHtml.forEach((filePath) => {
            let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
            let conf = {
                template: 'html!' + filePath,
                filename: filename + '.html'
            }

            if(filename in entries) {
                conf.inject = 'body'
                conf.chunks = ['vender', 'common', filename]
            }

            if(/b|c/.test(filename)) conf.chunks.splice(2, 0, 'common-b-c')

            r.push(new HtmlWebpackPlugin(conf))
        })

        return r
    }()

    if(debug) {
        extractCSS = new ExtractTextPlugin('css/[name].css?[contenthash]')
        cssLoader = extractCSS.extract(['css'])
        sassLoader = extractCSS.extract(['css', 'sass'])
        plugins.push(extractCSS, new webpack.HotModuleReplacementPlugin())
    } else {
        extractCSS = new ExtractTextPlugin('css/[contenthash:8].[name].min.css', {
            // 当allChunks指定为false时，css loader必须指定怎么处理
            // additional chunk所依赖的css，即指定`ExtractTextPlugin.extract()`
            // 第一个参数`notExtractLoader`，一般是使用style-loader
            // @see https://github.com/webpack/extract-text-webpack-plugin
            allChunks: false
        })
        cssLoader = extractCSS.extract(['css?minimize'])
        sassLoader = extractCSS.extract(['css?minimize', 'sass'])

        plugins.push(
            extractCSS,
            new UglifyJsPlugin({
                compress: {
                    warnings: false
                },
                output: {
                    comments: false
                },
                mangle: {
                    except: ['$', 'exports', 'require']
                }
            }),
            // new AssetsPlugin({
            //     filename: path.resolve(assets, 'source-map.json')
            // }),
            new webpack.optimize.DedupePlugin(),
            new webpack.NoErrorsPlugin()
        )

        plugins.push(new UglifyJsPlugin())
    }

    let config = {
        entry: Object.assign(entries, {
            // 用到什么公共lib（例如React.js），就把它加进vender去，目的是将公用库单独提取打包
            'vender': ['zepto']
        }),

        output: {
            path: assets,
            filename: debug ? '[name].js' : 'js/[chunkhash:8].[name].min.js',
            chunkFilename: debug ? '[chunkhash:8].chunk.js' : 'js/[chunkhash:8].chunk.min.js',
            hotUpdateChunkFilename: debug ? '[id].js' : 'js/[id].[chunkhash:8].min.js',
            publicPath: publicPath
        },

        resolve: {
            root: [srcDir, './node_modules'],
            alias: pathMap,
            extensions: ['', '.js', '.css', '.scss', '.tpl', '.png', '.jpg']
        },

        resolveLoader: {
            root: path.join(__dirname, 'node_modules')
        },

        module: {
            loaders: [
                {
                    test: /\.((woff2?|svg)(\?v=[0-9]\.[0-9]\.[0-9]))|(woff2?|svg|jpe?g|png|gif|ico)$/,
                    loaders: [
                        // url-loader更好用，小于10KB的图片会自动转成dataUrl，
                        // 否则则调用file-loader，参数直接传入
                        'url?limit=10000&name=img/[hash:8].[name].[ext]',
                        'image?{bypassOnDebug:true, progressive:true,optimizationLevel:3,pngquant:{quality:"65-80",speed:4}}'
                    ]
                },
                {
                    test: /\.((ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9]))|(ttf|eot)$/,
                    loader: 'url?limit=10000&name=fonts/[hash:8].[name].[ext]'
                },
                {test: /\.(tpl|ejs)$/, loader: 'ejs'},
                {test: /\.css$/, loader: cssLoader},
                {test: /\.scss$/, loader: sassLoader},
                {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel?presets[]=react,presets[]=es2015'}
            ]
        },

        plugins: [
            new CommonsChunkPlugin({
                name: 'common-b-c',
                chunks: ['b', 'c']
            }),
            new CommonsChunkPlugin({
                name: 'common',
                chunks: ['common-b-c', 'a']
            }),
            new CommonsChunkPlugin({
                name: 'vender',
                chunks: ['common']
            })
        ].concat(plugins),

        devServer: {
            hot: true,
            noInfo: false,
            inline: true,
            publicPath: publicPath,
            stats: {
                cached: false,
                colors: true
            }
        }
    }

    if (debug) {
        // 为实现webpack-hot-middleware做相关配置
        // @see https://github.com/glenjamin/webpack-hot-middleware
        ((entry) => {
            for (let key of Object.keys(entry)) {
                if (! Array.isArray(entry[key])) {
                    entry[key] = Array.of(entry[key])
                }
                entry[key].push('webpack-hot-middleware/client?reload=true')
            }
        })(config.entry)

        config.plugins.push( new webpack.HotModuleReplacementPlugin() )
        config.plugins.push( new webpack.NoErrorsPlugin() )
    }

    return config
}
<commit_msg>add ProvidePlugin config<commit_after>/*
* @Author: dmyang
* @Date:   2015-08-02 14:16:41
* @Last Modified by:   dmyang
* @Last Modified time: 2016-03-31 19:10:23
*/

'use strict';

let path = require('path')
let fs = require('fs')

let webpack = require('webpack')
let _ = require('lodash')
let glob = require('glob')

let ExtractTextPlugin = require('extract-text-webpack-plugin')
let HtmlWebpackPlugin = require('html-webpack-plugin')

let UglifyJsPlugin = webpack.optimize.UglifyJsPlugin
let CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin

let srcDir = path.resolve(process.cwd(), 'src')
let assets = path.resolve(process.cwd(), 'assets')
let nodeModPath = path.resolve(__dirname, './node_modules')
let pathMap = Object.assign({
    'react': path.join(nodeModPath, '/react/dist/react.js'),
    'react-with-addons': path.join(nodeModPath, '/react/dist/react-with-addons.js'),
    'react-dom': path.join(nodeModPath, '/react-dom/dist/react-dom.js'),
    'jquery': path.join(nodeModPath, '/jquery/dist/jquery.js'),
    'zepto': path.join(nodeModPath, '/zepto/zepto.min.js'),
}, require('./src/pathmap.json'))

let entries = (() => {
    let jsDir = path.resolve(srcDir, 'js')
    let entryFiles = glob.sync(jsDir + '/*.{js,jsx}')
    let map = {}

    entryFiles.forEach((filePath) => {
        let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
        map[filename] = filePath
    })

    return map
}())
let chunks = Object.keys(entries)

module.exports = (options) => {
    options = options || {}

    let debug = options.debug !== undefined ? options.debug : true
    // 这里publicPath要使用绝对路径，不然scss/css最终生成的css图片引用路径是错误的，应该是scss-loader的bug
    let publicPath = '/'
    let extractCSS
    let cssLoader
    let sassLoader

    // generate entry html files
    // 自动生成入口文件，入口js名必须和入口文件名相同
    // 例如，a页的入口文件是a.html，那么在js目录下必须有一个a.js作为入口文件
    let plugins = () => {
        let entryHtml = glob.sync(srcDir + '/*.html')
        let r = []

        entryHtml.forEach((filePath) => {
            let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
            let conf = {
                template: 'html!' + filePath,
                filename: filename + '.html'
            }

            if(filename in entries) {
                conf.inject = 'body'
                conf.chunks = ['vender', 'common', filename]
            }

            if(/b|c/.test(filename)) conf.chunks.splice(2, 0, 'common-b-c')

            r.push(new HtmlWebpackPlugin(conf))
        })

        return r
    }()

    plugins.push(
        new webpack.ProvidePlugin({
            React: 'react',
            ReactDOM: 'react-dom',
            _: 'lodash',
            $: 'jquery'
        })
    )

    if(debug) {
        extractCSS = new ExtractTextPlugin('css/[name].css?[contenthash]')
        cssLoader = extractCSS.extract(['css'])
        sassLoader = extractCSS.extract(['css', 'sass'])
        plugins.push(extractCSS, new webpack.HotModuleReplacementPlugin())
    } else {
        extractCSS = new ExtractTextPlugin('css/[contenthash:8].[name].min.css', {
            // 当allChunks指定为false时，css loader必须指定怎么处理
            // additional chunk所依赖的css，即指定`ExtractTextPlugin.extract()`
            // 第一个参数`notExtractLoader`，一般是使用style-loader
            // @see https://github.com/webpack/extract-text-webpack-plugin
            allChunks: false
        })
        cssLoader = extractCSS.extract(['css?minimize'])
        sassLoader = extractCSS.extract(['css?minimize', 'sass'])

        plugins.push(
            extractCSS,
            new UglifyJsPlugin({
                compress: {
                    warnings: false
                },
                output: {
                    comments: false
                },
                mangle: {
                    except: ['$', 'exports', 'require']
                }
            }),
            // new AssetsPlugin({
            //     filename: path.resolve(assets, 'source-map.json')
            // }),
            new webpack.optimize.DedupePlugin(),
            new webpack.NoErrorsPlugin()
        )

        plugins.push(new UglifyJsPlugin())
    }

    let config = {
        entry: Object.assign(entries, {
            // 用到什么公共lib（例如React.js），就把它加进vender去，目的是将公用库单独提取打包
            'vender': ['zepto']
        }),

        output: {
            path: assets,
            filename: debug ? '[name].js' : 'js/[chunkhash:8].[name].min.js',
            chunkFilename: debug ? '[chunkhash:8].chunk.js' : 'js/[chunkhash:8].chunk.min.js',
            hotUpdateChunkFilename: debug ? '[id].js' : 'js/[id].[chunkhash:8].min.js',
            publicPath: publicPath
        },

        resolve: {
            root: [srcDir, './node_modules'],
            alias: pathMap,
            extensions: ['', '.js', '.css', '.scss', '.tpl', '.png', '.jpg']
        },

        resolveLoader: {
            root: path.join(__dirname, 'node_modules')
        },

        module: {
            loaders: [
                {
                    test: /\.((woff2?|svg)(\?v=[0-9]\.[0-9]\.[0-9]))|(woff2?|svg|jpe?g|png|gif|ico)$/,
                    loaders: [
                        // url-loader更好用，小于10KB的图片会自动转成dataUrl，
                        // 否则则调用file-loader，参数直接传入
                        'url?limit=10000&name=img/[hash:8].[name].[ext]',
                        'image?{bypassOnDebug:true, progressive:true,optimizationLevel:3,pngquant:{quality:"65-80",speed:4}}'
                    ]
                },
                {
                    test: /\.((ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9]))|(ttf|eot)$/,
                    loader: 'url?limit=10000&name=fonts/[hash:8].[name].[ext]'
                },
                {test: /\.(tpl|ejs)$/, loader: 'ejs'},
                {test: /\.css$/, loader: cssLoader},
                {test: /\.scss$/, loader: sassLoader},
                {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel?presets[]=react,presets[]=es2015'}
            ]
        },

        plugins: [
            new CommonsChunkPlugin({
                name: 'common-b-c',
                chunks: ['b', 'c']
            }),
            new CommonsChunkPlugin({
                name: 'common',
                chunks: ['common-b-c', 'a']
            }),
            new CommonsChunkPlugin({
                name: 'vender',
                chunks: ['common']
            })
        ].concat(plugins),

        devServer: {
            hot: true,
            noInfo: false,
            inline: true,
            publicPath: publicPath,
            stats: {
                cached: false,
                colors: true
            }
        }
    }

    if (debug) {
        // 为实现webpack-hot-middleware做相关配置
        // @see https://github.com/glenjamin/webpack-hot-middleware
        ((entry) => {
            for (let key of Object.keys(entry)) {
                if (! Array.isArray(entry[key])) {
                    entry[key] = Array.of(entry[key])
                }
                entry[key].push('webpack-hot-middleware/client?reload=true')
            }
        })(config.entry)

        config.plugins.push( new webpack.HotModuleReplacementPlugin() )
        config.plugins.push( new webpack.NoErrorsPlugin() )
    }

    return config
}
<|endoftext|>


<commit_before>const html = require('choo/html')
const css = require('sheetify')

const horizontalFlip = css`
  :host {
    transform: scale(-1, 1);
  }
`

const Divider = (flip) => {
  var classes = 'nowrap overflow-hidden tc'
  if (flip) classes += ' ' + horizontalFlip
  return html`

📌📌📌📌📌

  `
}

module.exports = (state, prev, send) => {
  if (!state.token) {
    send('location:set', '/')
    return html`<div></div>`
  }
  // TODO: action to reset the URL/token
  return html`

          Your push notification URL is:

          ${window.location.origin + '/' + state.token + '/notify'}

          You can receive notifications when you send a request to that URL, even when this page isn't open.

      ${Divider(false)}

          Try it out! Run this command to see if it works

          TODO: put a curl command here

      ${Divider(true)}

          API

          TODO: api docs

  `
}
<commit_msg>Add api docs<commit_after>const html = require('choo/html')
const css = require('sheetify')

const horizontalFlip = css`
  :host {
    transform: scale(-1, 1);
  }
`

const Divider = (flip) => {
  var classes = 'nowrap overflow-hidden tc'
  if (flip) classes += ' ' + horizontalFlip
  return html`

📌📌📌📌📌

  `
}

module.exports = (state, prev, send) => {
  if (!state.token) {
    send('location:set', '/')
    return html`<div></div>`
  }
  // TODO: action to reset the URL/token
  return html`

          Your push notification URL is:

          ${window.location.origin + '/' + state.token + '/notify'}

          You can receive notifications when you send a request to that URL, even when this page isn't open.

      ${Divider(false)}

          Try it out! Run this command to see if it works

          curl 'http://localhost:3000/01365a23-26cd-4846-a75b-24d930d5c802/notify?title=nanopush&body=This%20is%20a%20test'

      ${Divider(true)}

          API

          GET /${state.token}/notify

          Takes parameters by query string.

          POST /${state.token}/notify

          Takes parameters by JSON body.

          Parameters

            title: The title text of the notification.

            body: The body text of the notification.

            icon: A URL to an icon for the notification.

  `
}
<|endoftext|>


<commit_before>Template.product.events({
	'click #product-bid': function() {
		$('#modal-container').css('display', 'block');
		$('#modal-bid').css('display', 'block');
	}
});

/*
Template.pageItemInbox.user = function() {
	return Meteor.user().profile.name;
}

Template.pageItemInbox.items = function() {
	return Items.find({
		sellerId: Meteor.userId()
	}).fetch();
}
*/
Template.itemsRow.helpers({
	offers: function() {
		return Offers.find({
			sellerId: Meteor.userId(),
			postId: this._id
		}).fetch();
	}
});

Template.itemsRow.test = function(e) {
	return e;
}

Template.bidding.sendMsg = function(item, message) {
	message.type = 1;
	message.text = $('#message').val();
	message.postId = item._id;
	console.log(this);
	message.public = false;
	Meteor.call('addBid', message, function(e, r) {
		if (e) {
			console.log(e);
		} else {
			if (r == -1)
				console.log('error!');
			else
				console.log('your message has been sent');
		}
	});
}

Template.bidding.events({
	'click #sendMsg': function() {
		var itemObj = Items.findOne({_id: this.itemId});
		console.log("bidding item:");
		console.log(itemObj);
		console.log();

		/*
        if (itemObj.seller._id == Meteor.userId()) {
            alert('You cannot bid for your own item!');
        }
        */

		var msg = {};
		msg.toId = itemObj.sellerId;
		msg.to = itemObj.seller;

		/*
        msg.offer=$('#offer').val();
        msg.location = $('#location').val();
        */
		Template.bidding.sendMsg(itemObj, msg);
		alert('your message has been sent');
	}
});

Template.pageNego.events({
	'click #sendMsg': function() {
		var itemObj = Router.current().data();

		var msg = {};
		msg.toId = itemObj.item.sellerId;
		msg.to = itemObj.item.seller;

		Template.bidding.sendMsg(itemObj.item, msg);
	},
	'keyup #message': function(e) {
		var $message = $("#message");
		if ($message.val() && e.which === 13) {
			var itemObj = Router.current().data();

			var msg = {};
			msg.toId = itemObj.item.sellerId;
			msg.to = itemObj.item.seller;

			Template.bidding.sendMsg(itemObj.item, msg);

			$message.val("");
		}
		return true;
	}
});

Template.pageNego.rendered = function() {
	$("textarea").autosize();
}

Template.message.img = function() {
	var fbId = Meteor.users.findOne({_id: "Ztg5NuWnTrzsBM8Qu"}).services.facebook.id;
	return $.getJSON("https://graph.facebook.com/" + fbId + "?fields=picture.width(100).height(100)").responseJSON;
}

Template.message.text = function() {
	return new Handlebars.SafeString(this.text);
}
<commit_msg>Removed click #sendMsg on messaging page<commit_after>Template.product.events({
	'click #product-bid': function() {
		$('#modal-container').css('display', 'block');
		$('#modal-bid').css('display', 'block');
	}
});

/*
Template.pageItemInbox.user = function() {
	return Meteor.user().profile.name;
}

Template.pageItemInbox.items = function() {
	return Items.find({
		sellerId: Meteor.userId()
	}).fetch();
}
*/
Template.itemsRow.helpers({
	offers: function() {
		return Offers.find({
			sellerId: Meteor.userId(),
			postId: this._id
		}).fetch();
	}
});

Template.itemsRow.test = function(e) {
	return e;
}

Template.bidding.sendMsg = function(item, message) {
	message.type = 1;
	message.text = $('#message').val();
	message.postId = item._id;
	console.log(this);
	message.public = false;
	Meteor.call('addBid', message, function(e, r) {
		if (e) {
			console.log(e);
		} else {
			if (r == -1)
				console.log('error!');
			else
				console.log('your message has been sent');
		}
	});
}

Template.bidding.events({
	'click #sendMsg': function() {
		var itemObj = Items.findOne({_id: this.itemId});
		console.log("bidding item:");
		console.log(itemObj);
		console.log();

		/*
        if (itemObj.seller._id == Meteor.userId()) {
            alert('You cannot bid for your own item!');
        }
        */

		var msg = {};
		msg.toId = itemObj.sellerId;
		msg.to = itemObj.seller;

		/*
        msg.offer=$('#offer').val();
        msg.location = $('#location').val();
        */
		Template.bidding.sendMsg(itemObj, msg);
		alert('your message has been sent');
	}
});

Template.pageNego.events({
	'keyup #message': function(e) {
		var $message = $("#message");
		if ($message.val() && e.which === 13) {
			var itemObj = Router.current().data();

			var msg = {};
			msg.toId = itemObj.item.sellerId;
			msg.to = itemObj.item.seller;

			Template.bidding.sendMsg(itemObj.item, msg);

			$message.val("");
		}
		return true;
	}
});

Template.pageNego.rendered = function() {
	$("textarea").autosize();
}

Template.message.img = function() {
	var fbId = Meteor.users.findOne({_id: "Ztg5NuWnTrzsBM8Qu"}).services.facebook.id;
	return $.getJSON("https://graph.facebook.com/" + fbId + "?fields=picture.width(100).height(100)").responseJSON;
}

Template.message.text = function() {
	return new Handlebars.SafeString(this.text);
}
<|endoftext|>


<commit_before>var m = require('mithril');
var throttle = require('common').throttle;

function editable(tag, submit) {
  return m('input', {
    spellcheck: false,
    value: tag[1],
    config: function(el, isUpdate, ctx) {
      if (isUpdate) return;
      el.onblur = function() {
        submit(el.value);
      };
      el.onkeypress = function(e) {
        if ((e.keyCode || e.which) == '13') el.blur();
      }
    }
  });
}

function fixed(text) {
  return m('span', text);
}

var selectedType;

function renderPgnTags(chapter, submit, node, types) {
  var rows = [
    ['Fen', m('pre#study_fen', node.fen)]
  ];
  if (chapter.setup.variant.key !== 'standard')
    rows.push(['Variant', fixed(chapter.setup.variant.name)]);
  rows = rows.concat(chapter.tags.map(function(tag) {
    return [
      tag[0],
      submit ? editable(tag, submit(tag[0])) : fixed(tag[1])
    ];
  }));
  if (submit) {
    var existingTypes = chapter.tags.map(function(t) {
      return t[0];
    });
    rows.push([
      m('select', {
        config: function(el) {
          selectedType = el.value;
        },
        onchange: function(e) {
          selectedType = e.target.value;
          $(e.target).parents('tr').find('input').focus();
        }
      }, [
        m('option', 'New tag'),
        types.map(function(t) {
          if (!$.fp.contains(existingTypes, t)) return m('option', {
            value: t
          }, t);
        })
      ]),
      editable(['', ''], function(value) {
        if (selectedType) submit(selectedType)(value);
      })
    ]);
  }

  return m('table.tags.slist', m('tbody', rows.map(function(r) {
    return m('tr', {
      key: r[0]
    }, [
      m('th', r[0]),
      m('td', r[1])
    ]);
  })));
}

module.exports = {
  ctrl: function(root, getChapter, members, types) {

    var submit = throttle(500, false, function(name, value) {
      root.study.contribute('setTag', {
        chapterId: getChapter().id,
        name: name,
        value: value.substr(0, 140)
      });
    });

    return {
      submit: function(name) {
        return function(value) {
          submit(name, value);
        }
      },
      getChapter: getChapter,
      members: members,
      types: types,
      cacheKey: m.prop('')
    }
  },
  view: function(root) {
    var ctrl = root.tags,
      node = root.currentNode(),
      chapter = ctrl.getChapter(),
      canContribute = ctrl.members.canContribute();
    var key = [chapter.id, root.data.name, chapter.name, root.data.likes, chapter.tags, canContribute].join('|');
    if (key === ctrl.cacheKey() && m.redraw.strategy() === 'diff') {
      lichess.raf(function() {
        document.getElementById('study_fen').textContent = node.fen;
      });
      return {
        subtree: 'retain'
      };
    }
    ctrl.cacheKey(key);
    return m('div.undertable_inner', renderPgnTags(
      chapter,
      canContribute && ctrl.submit,
      node,
      ctrl.types))
  }
};
<commit_msg>can't change study tags while unsynced<commit_after>var m = require('mithril');
var throttle = require('common').throttle;

function editable(tag, submit) {
  return m('input', {
    spellcheck: false,
    value: tag[1],
    config: function(el, isUpdate, ctx) {
      if (isUpdate) return;
      el.onblur = function() {
        submit(el.value);
      };
      el.onkeypress = function(e) {
        if ((e.keyCode || e.which) == '13') el.blur();
      }
    }
  });
}

function fixed(text) {
  return m('span', text);
}

var selectedType;

function renderPgnTags(chapter, submit, node, types) {
  var rows = [
    ['Fen', m('pre#study_fen', node.fen)]
  ];
  if (chapter.setup.variant.key !== 'standard')
    rows.push(['Variant', fixed(chapter.setup.variant.name)]);
  rows = rows.concat(chapter.tags.map(function(tag) {
    return [
      tag[0],
      submit ? editable(tag, submit(tag[0])) : fixed(tag[1])
    ];
  }));
  if (submit) {
    var existingTypes = chapter.tags.map(function(t) {
      return t[0];
    });
    rows.push([
      m('select', {
        config: function(el) {
          selectedType = el.value;
        },
        onchange: function(e) {
          selectedType = e.target.value;
          $(e.target).parents('tr').find('input').focus();
        }
      }, [
        m('option', 'New tag'),
        types.map(function(t) {
          if (!$.fp.contains(existingTypes, t)) return m('option', {
            value: t
          }, t);
        })
      ]),
      editable(['', ''], function(value) {
        if (selectedType) submit(selectedType)(value);
      })
    ]);
  }

  return m('table.tags.slist', m('tbody', rows.map(function(r) {
    return m('tr', {
      key: r[0]
    }, [
      m('th', r[0]),
      m('td', r[1])
    ]);
  })));
}

module.exports = {
  ctrl: function(root, getChapter, members, types) {

    var submit = throttle(500, false, function(name, value) {
      root.study.contribute('setTag', {
        chapterId: getChapter().id,
        name: name,
        value: value.substr(0, 140)
      });
    });

    return {
      submit: function(name) {
        return function(value) {
          submit(name, value);
        }
      },
      getChapter: getChapter,
      members: members,
      types: types,
      cacheKey: m.prop('')
    }
  },
  view: function(root) {
    var ctrl = root.tags,
      node = root.currentNode(),
      chapter = ctrl.getChapter(),
      canContribute = ctrl.members.canContribute() && root.vm.behind === false;
    var key = [chapter.id, root.data.name, chapter.name, root.data.likes, chapter.tags, canContribute].join('|');
    if (key === ctrl.cacheKey() && m.redraw.strategy() === 'diff') {
      lichess.raf(function() {
        document.getElementById('study_fen').textContent = node.fen;
      });
      return {
        subtree: 'retain'
      };
    }
    ctrl.cacheKey(key);
    return m('div.undertable_inner', renderPgnTags(
      chapter,
      canContribute && ctrl.submit,
      node,
      ctrl.types))
  }
};
<|endoftext|>


<commit_before>/* eslint-disable no-underscore-dangle */

import { avoidWarnForRequire } from './utils';
import { toggleNetworkInspect } from './networkInspect';

let availableDevMenuMethods = {};

export const checkAvailableDevMenuMethods = async (enableNetworkInspect = false) => {
  const done = await avoidWarnForRequire('NativeModules', 'AsyncStorage');
  const NativeModules = window.__DEV__ ? window.require('NativeModules') : {};
  const AsyncStorage = window.__DEV__ ? window.require('AsyncStorage') : {};
  done();

  // RN 0.43 use DevSettings, DevMenu will be deprecated
  const DevSettings = NativeModules.DevSettings || NativeModules.DevMenu;
  // Currently `show dev menu` is only on DevMenu
  const showDevMenu =
    (DevSettings && DevSettings.show) || NativeModules.DevMenu
      ? NativeModules.DevMenu.show
      : undefined;

  const methods = {
    ...DevSettings,
    show: showDevMenu,
    networkInspect: toggleNetworkInspect,
    clearAsyncStorage: () => AsyncStorage.clear().catch(f => f),
  };
  const result = Object.keys(methods).filter(key => !!methods[key]);
  availableDevMenuMethods = methods;

  toggleNetworkInspect(enableNetworkInspect);
  postMessage({ __AVAILABLE_METHODS_CAN_CALL_BY_RNDEBUGGER__: result });
};

export const invokeDevMenuMethod = (name, args = []) => {
  const method = availableDevMenuMethods[name];
  if (method) method(...args);
};
<commit_msg>Fix get showDevMenu on worker<commit_after>/* eslint-disable no-underscore-dangle */

import { avoidWarnForRequire } from './utils';
import { toggleNetworkInspect } from './networkInspect';

let availableDevMenuMethods = {};

export const checkAvailableDevMenuMethods = async (enableNetworkInspect = false) => {
  const done = await avoidWarnForRequire('NativeModules', 'AsyncStorage');
  const NativeModules = window.__DEV__ ? window.require('NativeModules') : {};
  const AsyncStorage = window.__DEV__ ? window.require('AsyncStorage') : {};
  done();

  // RN 0.43 use DevSettings, DevMenu will be deprecated
  const DevSettings = NativeModules.DevSettings || NativeModules.DevMenu;
  // Currently `show dev menu` is only on DevMenu
  const showDevMenu =
    (DevSettings && DevSettings.show) ||
    (NativeModules.DevMenu && NativeModules.DevMenu.show) ||
    undefined;

  const methods = {
    ...DevSettings,
    show: showDevMenu,
    networkInspect: toggleNetworkInspect,
    clearAsyncStorage: () => AsyncStorage.clear().catch(f => f),
  };
  const result = Object.keys(methods).filter(key => !!methods[key]);
  availableDevMenuMethods = methods;

  toggleNetworkInspect(enableNetworkInspect);
  postMessage({ __AVAILABLE_METHODS_CAN_CALL_BY_RNDEBUGGER__: result });
};

export const invokeDevMenuMethod = (name, args = []) => {
  const method = availableDevMenuMethods[name];
  if (method) method(...args);
};
<|endoftext|>


<commit_before>require({

  // libraries dependencies with fallback
  paths: {

    jquery: [
      'vendor/jquery/1.10.2/jquery.min'
    ],

    bootstrap: [
      'vendor/bootstrap/3.0.2/js/bootstrap.min'
    ],

    angular: [
      'vendor/angular.js/1.2.1/angular.min'
    ],

    angular_route: [
      'vendor/angular.js/1.2.1/angular-route.min'
    ],

    angular_resource: [
      'vendor/angular.js/1.2.1/angular-resource.min'
    ],

    angular_animate: [
      'vendor/angular.js/1.2.1/angular-animate.min'
    ],

    ngProgress: [
      'vendor/ngProgress/1.0.3/ngProgress.min'
    ],

    toaster: [
      'vendor/toaster/0.3.0/toaster'
    ]

  },

  // define js scripts dependencies
  shim: {

    'bootstrap': {
      deps: ['jquery']
    },

    'angular': {
      deps: ['bootstrap']
    },

    'angular_route': {
      deps: ['angular']
    },

    'angular_resource': {
      deps: ['angular']
    },

    'angular_animate': {
      deps: ['angular']
    },

    'ngProgress': {
      deps: ['angular']
    },

    'toaster': {
      deps:['angular_animate']
    },

    //--- @begin: require config deps

    // require mock dependencies
    'require.mock.config': {
      deps: ['global']
    }

    //--- @end: require config deps

  }

},

['require'], function(require) {

  console.debug('project require.js config');

  require([
    'shared/components/progressbar/loading/require.config',
    'shared/components/input/utils/require.config',
    'shared/components/pagination/require.config',

    'require.mock.config', // call require mock config

    'app/bookmarks/require.config',
    'app/require.config'
  ]);

});<commit_msg>update root require config<commit_after>require({

  // libraries dependencies with fallback
  paths: {

    jquery: [
      'vendor/jquery/1.10.2/jquery.min'
    ],

    bootstrap: [
      'vendor/bootstrap/3.0.2/js/bootstrap.min'
    ],

    angular: [
      'vendor/angular.js/1.2.1/angular.min'
    ],

    angular_route: [
      'vendor/angular.js/1.2.1/angular-route.min'
    ],

    angular_resource: [
      'vendor/angular.js/1.2.1/angular-resource.min'
    ],

    angular_animate: [
      'vendor/angular.js/1.2.1/angular-animate.min'
    ],

    ngProgress: [
      'vendor/ngProgress/1.0.3/ngProgress.min'
    ],

    toaster: [
      'vendor/toaster/0.3.0/toaster'
    ]

  },

  // define js scripts dependencies
  shim: {

    'bootstrap': {
      deps: ['jquery']
    },

    'angular': {
      deps: ['bootstrap']
    },

    'angular_route': {
      deps: ['angular']
    },

    'angular_resource': {
      deps: ['angular']
    },

    'angular_animate': {
      deps: ['angular']
    },

    'ngProgress': {
      deps: ['angular']
    },

    'toaster': {
      deps:['angular_animate']
    },

    'global': {
      deps: ['angular']
    },

    //--- @begin: require config deps

      //--- shared

    'shared/components/progressbar/loading/require.config': {
      deps: ['global']
    },

    'shared/components/input/utils/require.config': {
      deps: ['global']
    },

    'shared/components/pagination/require.config': {
      deps: ['global']
    },

      //--- app

    'app/bookmarks/require.config': {
      deps: ['global']
    },

    'app/require.config': {
      deps: ['global']
    },

    // require mock dependencies
    'require.mock.config': {
      deps: ['global']
    }

    //--- @end: require config deps

  }

},

['require'], function(require) {

  console.debug('project require.js config');

  require([
    'shared/components/progressbar/loading/require.config',
    'shared/components/input/utils/require.config',
    'shared/components/pagination/require.config',

    'require.mock.config', // call require mock config

    'app/bookmarks/require.config',
    'app/require.config'
  ]);

});<|endoftext|>