<commit_before>(function(){
  var module = angular.module('multi-transclude', []);

  var Ctrl = ['$scope', '$element', '$transclude', function($scope, $element, $transclude){
    // Ensure we're transcluding or nothing will work.
    if(!$transclude){
      throw new Error(
        'Illegal use of ngMultiTransclude controller. No directive ' +
        'that requires a transclusion found.'
      );
    }

    // There's not a good way to ask Angular to give you the closest
    // controller from a list of controllers, we get all multi-transclude
    // controllers and select the one that is the child of the other.
    this.$element = $element;
    this.isChildOf = function(otherCtrl){
      return otherCtrl.$element[0].contains(this.$element[0]);
    };

    // Destination for transcluded content.
    var toTransclude;
    $scope.$on('$destroy', function(){
      if(toTransclude){
        toTransclude.remove();
        toTransclude = null;
      }
    });

    // A temporary container for transcluded content, so that content will not
    // be detached from the DOM during link. This ensures that controllers and
    // other data parent nodes are accessible within the transcluded content.
    var transcludeContainer = angular.element('

');

    // Transclude content that matches name into element.
    this.transclude = function(name, element){
      for(var i = 0; i < toTransclude.length; ++i){
        // Uses the argument as the `name` attribute directly, but we could
        // evaluate it or interpolate it or whatever.
        var el = angular.element(toTransclude[i]);
        if(el.attr('name') === name){
          element.empty();
          element.append(el);
          return;
        }
      }
    };

    // Should be called after all transclusions are complete to clean up the
    // temporary container.
    this.transcluded = function(){
      if(transcludeContainer){
        transcludeContainer.remove();
        transcludeContainer = null;
      }
    };

    // Transclude content and keep track of it; be sure to keep it in the DOM
    // by attaching it to `$element`.
    $transclude(function(clone){
      toTransclude = clone;

      transcludeContainer.append(clone);
      $element.append(transcludeContainer);
    });
  }];

  module.directive('ngMultiTemplate', function(){
    return {
      transclude: true,
      templateUrl: function(element, attrs){
        return attrs.ngMultiTemplate;
      },
      controller: Ctrl,
      link: function(scope, element, attrs, ctrl){
        scope.$evalAsync(ctrl.transcluded);
      }
    };
  });

  module.directive('ngMultiTranscludeController', function(){
    return {
      controller: Ctrl,
      link: function(scope, element, attrs, ctrl){
        scope.$evalAsync(ctrl.transcluded);
      }
    };
  });

  module.directive('ngMultiTransclude', function(){
    return {
      require: ['?^ngMultiTranscludeController', '?^ngMultiTemplate'],
      link: function(scope, element, attrs, ctrls){
        // Find the deepest controller (closes to this element).
        var ctrl1 = ctrls[0];
        var ctrl2 = ctrls[1];
        var ctrl;
        if(ctrl1 && ctrl2){
          ctrl = ctrl1.isChildOf(ctrl2) ? ctrl1 : ctrl2;
        }
        else {
          ctrl = ctrl1 || ctrl2;
        }

        // A multi-transclude parent directive must be present.
        if(!ctrl){
          throw new Error('Illegal use of ngMultiTransclude. No wrapping controller.')
        }

        // Receive transcluded content.
        ctrl.transclude(attrs.ngMultiTransclude, element);
      }
    };
  });
})();
<commit_msg>Fix scoping confusion.<commit_after>(function(){
  var module = angular.module('multi-transclude', []);

  var Ctrl = ['$scope', '$element', '$transclude', function($scope, $element, $transclude){
    // Ensure we're transcluding or nothing will work.
    if(!$transclude){
      throw new Error(
        'Illegal use of ngMultiTransclude controller. No directive ' +
        'that requires a transclusion found.'
      );
    }

    // There's not a good way to ask Angular to give you the closest
    // controller from a list of controllers, we get all multi-transclude
    // controllers and select the one that is the child of the other.
    this.$element = $element;
    this.isChildOf = function(otherCtrl){
      return otherCtrl.$element[0].contains(this.$element[0]);
    };

    // Destination for transcluded content.
    var toTransclude;
    $scope.$on('$destroy', function(){
      if(toTransclude){
        toTransclude.remove();
        toTransclude = null;
      }
    });

    // A temporary container for transcluded content, so that content will not
    // be detached from the DOM during link. This ensures that controllers and
    // other data parent nodes are accessible within the transcluded content.
    var transcludeContainer = angular.element('

');

    // Transclude content that matches name into element.
    this.transclude = function(name, element){
      for(var i = 0; i < toTransclude.length; ++i){
        // Uses the argument as the `name` attribute directly, but we could
        // evaluate it or interpolate it or whatever.
        var el = angular.element(toTransclude[i]);
        if(el.attr('name') === name){
          element.empty();
          element.append(el);
          return;
        }
      }
    };

    // Should be called after all transclusions are complete to clean up the
    // temporary container.
    this.transcluded = function(){
      if(transcludeContainer){
        transcludeContainer.remove();
        transcludeContainer = null;
      }
    };

    // Transclude content and keep track of it; be sure to keep it in the DOM
    // by attaching it to `$element`.
    var childScope = $scope.$new();
    $transclude(childScope, function(clone){
      toTransclude = clone;

      transcludeContainer.append(clone);
      $element.append(transcludeContainer);
    });
  }];

  module.directive('ngMultiTemplate', function(){
    return {
      transclude: true,
      templateUrl: function(element, attrs){
        return attrs.ngMultiTemplate;
      },
      controller: Ctrl,
      link: function(scope, element, attrs, ctrl){
        ctrl.transcluded();
      }
    };
  });

  module.directive('ngMultiTranscludeController', function(){
    return {
      controller: Ctrl,
      link: function(scope, element, attrs, ctrl){
        ctrl.transcluded();
      }
    };
  });

  module.directive('ngMultiTransclude', function(){
    return {
      require: ['?^ngMultiTranscludeController', '?^ngMultiTemplate'],
      link: function(scope, element, attrs, ctrls){
        // Find the deepest controller (closes to this element).
        var ctrl1 = ctrls[0];
        var ctrl2 = ctrls[1];
        var ctrl;
        if(ctrl1 && ctrl2){
          ctrl = ctrl1.isChildOf(ctrl2) ? ctrl1 : ctrl2;
        }
        else {
          ctrl = ctrl1 || ctrl2;
        }

        // A multi-transclude parent directive must be present.
        if(!ctrl){
          throw new Error('Illegal use of ngMultiTransclude. No wrapping controller.')
        }

        // Receive transcluded content.
        ctrl.transclude(attrs.ngMultiTransclude, element);
      }
    };
  });
})();
<|endoftext|>


<commit_before>var _ = require('lodash');

var Argument = require('../arguments/argument');
var ClosureArgument = require('../arguments/closure');
var ObjectArgument = require('../arguments/object');
var ArrayArgument = require('../arguments/array');
var ClassArgument = require('../arguments/class');
var NumberArgument = require('../arguments/number');

module.exports = (function() {
  function GremlinFunction(name, args) {
    this.name = name;
    this.arguments = args;
    this.closures = [];
    this.parenthesizedArguments = [];
    this.buildArguments();
  }

  GremlinFunction.prototype.toGroovy = function() {
    return this.name + this.groovifyArguments();
  };

  GremlinFunction.prototype.groovifyArguments = function() {
    var args = [];

    // Append arguments between parentheses, if any
    groovy = '(' + _.map(this.parenthesizedArguments, function(argument) {
      return argument.toGroovy();
    }).join(',') + ')';

    // Append closures, if any
    groovy += _.map(this.closures, function(closure) {
      return closure.toGroovy();
    }).join(',');

    return groovy;
  };

  GremlinFunction.prototype.buildArguments = function() {
    _.each(this.arguments, function(argument) {
      if (this.isClosure(argument)) {
        built = new ClosureArgument(argument, this);
        this.closures.push(built);
      } else if (_.isArray(argument)) {
        built = new ArrayArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else if (_.isFunction(argument)) {
        built = new ClassArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else if (_.isObject(argument)) {
        built = new ObjectArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else if (_.isNumber(argument)) {
        built = new NumberArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else {
        built = new Argument(argument, this);
        this.parenthesizedArguments.push(built);
      }
    }, this);
  };

  GremlinFunction.prototype.isClosure = function(val) {
    var closureRegex = /^\{.*\}$/;

    return _.isString(val) && closureRegex.test(val);
  };

  GremlinFunction.prototype.stringifyArgument = function(argument) {
    return JSON.stringify(argument).replace('{', '[').replace('}', ']');
  };

  return GremlinFunction;
})();<commit_msg>Add GremlinFunction.isClass() method<commit_after>var _ = require('lodash');

var Argument = require('../arguments/argument');
var ClosureArgument = require('../arguments/closure');
var ObjectArgument = require('../arguments/object');
var ArrayArgument = require('../arguments/array');
var ClassArgument = require('../arguments/class');
var NumberArgument = require('../arguments/number');

module.exports = (function() {
  function GremlinFunction(name, args) {
    this.name = name;
    this.arguments = args;
    this.closures = [];
    this.parenthesizedArguments = [];
    this.buildArguments();
  }

  GremlinFunction.prototype.toGroovy = function() {
    return this.name + this.groovifyArguments();
  };

  GremlinFunction.prototype.groovifyArguments = function() {
    var args = [];

    // Append arguments between parentheses, if any
    groovy = '(' + _.map(this.parenthesizedArguments, function(argument) {
      return argument.toGroovy();
    }).join(',') + ')';

    // Append closures, if any
    groovy += _.map(this.closures, function(closure) {
      return closure.toGroovy();
    }).join(',');

    return groovy;
  };

  GremlinFunction.prototype.buildArguments = function() {
    _.each(this.arguments, function(argument) {
      if (this.isClosure(argument)) {
        built = new ClosureArgument(argument, this);
        this.closures.push(built);
      } else if (_.isArray(argument)) {
        built = new ArrayArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else if (this.isClass(argument)) {
        built = new ClassArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else if (_.isObject(argument)) {
        built = new ObjectArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else if (_.isNumber(argument)) {
        built = new NumberArgument(argument, this);
        this.parenthesizedArguments.push(built);
      } else {
        built = new Argument(argument, this);
        this.parenthesizedArguments.push(built);
      }
    }, this);
  };

  GremlinFunction.prototype.isClosure = function(val) {
    var closureRegex = /^\{.*\}$/;

    return _.isString(val) && closureRegex.test(val);
  };

  GremlinFunction.prototype.isClass = function(argument) {
    return !!argument.class;
  };

  GremlinFunction.prototype.stringifyArgument = function(argument) {
    return JSON.stringify(argument).replace('{', '[').replace('}', ']');
  };

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


<commit_before>/**
 * @module Math
 * @submodule Random
 * @for p5
 * @requires core
 */
define(function (require) {

  'use strict';

  var p5 = require('core');

  var seeded = false;

  // Linear Congruential Generator
  // Variant of a Lehman Generator
  var lcg = (function() {
    // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
        // m is basically chosen to be large (as it is the max period)
        // and for its relationships to a and c
    var m = 4294967296,
        // a - 1 should be divisible by m's prime factors
        a = 1664525,
        // c and m should be co-prime
        c = 1013904223,
        seed, z;
    return {
      setSeed : function(val) {
        z = seed = val || Math.round(Math.random() * m);
      },
      getSeed : function() {
        return seed;
      },
      rand : function() {
        // define the recurrence relationship
        z = (a * z + c) % m;
        // return a float in [0, 1)
        // if z = m then z / m = 0 therefore (z % m) / m < 1 always
        return z / m;
      }
    };
  }());

  /**
   * Sets the seed value for random().
   *
   * By default, random() produces different results each time the program
   * is run. Set the seed parameter to a constant to return the same
   * pseudo-random numbers each time the software is run.
   *
   * @method randomSeed
   * @param {Number} seed value
   * @example
   *

   *
   * randomSeed(99);
   * for (var i=0; i < 100; i++) {
   *   var r = random(0, 255);
   *   stroke(r);
   *   line(i, 0, i, 100);
   * }
   *
   *

   */
  p5.prototype.randomSeed = function(seed) {
    lcg.setSeed(seed);
    seeded = true;
  };

  /**
   * Return a random number.
   *
   * Takes either 0, 1 or 2 arguments.
   * If no argument is given, returns a random number between 0 and 1.
   * If one argument is given, returns a random number between 0 and the number.
   * If two arguments are given, returns a random number between them,
   * inclusive.
   *
   * @method random
   * @param  {x}      min the lower bound
   * @param  {y}      max the upper bound
   * @return {Number}     the random number
   */
  p5.prototype.random = function (min, max) {

    var rand;

    if (seeded) {
      rand  = lcg.rand();
    } else {
      rand = Math.random();
    }

    if (arguments.length === 0) {
      return rand;
    } else
    if (arguments.length === 1) {
      return rand * min;
    } else {
      if (min > max) {
        var tmp = min;
        min = max;
        max = tmp;
      }

      return rand * (max-min) + min;
    }
  };

  /**
   *
   * Returns a random number fitting a Gaussian, or
   * normal, distribution. There is theoretically no minimum or maximum
   * value that randomGaussian() might return. Rather, there is
   * just a very low probability that values far from the mean will be
   * returned; and a higher probability that numbers near the mean will
   * be returned.
   * Takes either 0, 1 or 2 arguments.
   * If no args, returns a mean of 0 and standard deviation of 1
   * If one arg, that arg is the mean (standard deviation is 1)
   * If two args, first is mean, second is standard deviation
   *
   * @method randomGaussian
   * @param  {mean}       mean
   * @param  {sd}         standard deviation
   * @return {Number}     the random number
   */
  var y2;
  var previous = false;
  p5.prototype.randomGaussian = function(mean, sd)  {
    var y1,x1,x2,w;
    if (previous) {
      y1 = y2;
      previous = false;
    } else {
      do {
        x1 = this.random(2) - 1;
        x2 = this.random(2) - 1;
        w = x1 * x1 + x2 * x2;
      } while (w >= 1);
      w = Math.sqrt((-2 * Math.log(w))/w);
      y1 = x1 * w;
      y2 = x2 * w;
      previous = true;
    }

    var m = mean || 0;
    var s = sd || 1;
    return y1*s + m;
  };

  return p5;

});

<commit_msg>random inline examples #252<commit_after>/**
 * @module Math
 * @submodule Random
 * @for p5
 * @requires core
 */
define(function (require) {

  'use strict';

  var p5 = require('core');

  var seeded = false;

  // Linear Congruential Generator
  // Variant of a Lehman Generator
  var lcg = (function() {
    // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
        // m is basically chosen to be large (as it is the max period)
        // and for its relationships to a and c
    var m = 4294967296,
        // a - 1 should be divisible by m's prime factors
        a = 1664525,
        // c and m should be co-prime
        c = 1013904223,
        seed, z;
    return {
      setSeed : function(val) {
        z = seed = val || Math.round(Math.random() * m);
      },
      getSeed : function() {
        return seed;
      },
      rand : function() {
        // define the recurrence relationship
        z = (a * z + c) % m;
        // return a float in [0, 1)
        // if z = m then z / m = 0 therefore (z % m) / m < 1 always
        return z / m;
      }
    };
  }());

  /**
   * Sets the seed value for random().
   *
   * By default, random() produces different results each time the program
   * is run. Set the seed parameter to a constant to return the same
   * pseudo-random numbers each time the software is run.
   *
   * @method randomSeed
   * @param {Number} seed value
   * @example
   *

   *
   * randomSeed(99);
   * for (var i=0; i < 100; i++) {
   *   var r = random(0, 255);
   *   stroke(r);
   *   line(i, 0, i, 100);
   * }
   *
   *

   */
  p5.prototype.randomSeed = function(seed) {
    lcg.setSeed(seed);
    seeded = true;
  };

  /**
   * Return a random number.
   *
   * Takes either 0, 1 or 2 arguments.
   * If no argument is given, returns a random number between 0 and 1.
   * If one argument is given, returns a random number between 0 and the number.
   * If two arguments are given, returns a random number between them,
   * inclusive.
   *
   * @method random
   * @param  {x}      min the lower bound
   * @param  {y}      max the upper bound
   * @return {Number}     the random number
   * @example
   *

   *
   * for (var i = 0; i < 100; i++) {
   *   var r = random(50);
   *   stroke(r*5);
   *   line(50, i, 50+r, i);
   * }
   *
   *

   *

   *
   * for (var i = 0; i < 100; i++) {
   *   var r = random(-50, 50);
   *   line(50,i,50+r,i);
   * }
   *
   *

   *

   *
   * // Get a random element from an array
   * var words = [ "apple", "bear", "cat", "dog" ];
   * var index = floor(random(words.length));  // Convert to integer
   * text(words[index],10,50);  // Displays one of the four words
   *
   *

   */
  p5.prototype.random = function (min, max) {

    var rand;

    if (seeded) {
      rand  = lcg.rand();
    } else {
      rand = Math.random();
    }

    if (arguments.length === 0) {
      return rand;
    } else
    if (arguments.length === 1) {
      return rand * min;
    } else {
      if (min > max) {
        var tmp = min;
        min = max;
        max = tmp;
      }

      return rand * (max-min) + min;
    }
  };

  /**
   *
   * Returns a random number fitting a Gaussian, or
   * normal, distribution. There is theoretically no minimum or maximum
   * value that randomGaussian() might return. Rather, there is
   * just a very low probability that values far from the mean will be
   * returned; and a higher probability that numbers near the mean will
   * be returned.
   * Takes either 0, 1 or 2 arguments.
   * If no args, returns a mean of 0 and standard deviation of 1
   * If one arg, that arg is the mean (standard deviation is 1)
   * If two args, first is mean, second is standard deviation
   *
   * @method randomGaussian
   * @param  {mean}       mean
   * @param  {sd}         standard deviation
   * @return {Number}     the random number
   */
  var y2;
  var previous = false;
  p5.prototype.randomGaussian = function(mean, sd)  {
    var y1,x1,x2,w;
    if (previous) {
      y1 = y2;
      previous = false;
    } else {
      do {
        x1 = this.random(2) - 1;
        x2 = this.random(2) - 1;
        w = x1 * x1 + x2 * x2;
      } while (w >= 1);
      w = Math.sqrt((-2 * Math.log(w))/w);
      y1 = x1 * w;
      y2 = x2 * w;
      previous = true;
    }

    var m = mean || 0;
    var s = sd || 1;
    return y1*s + m;
  };

  return p5;

});

<|endoftext|>


<commit_before>/**
* directive.diPiece Module
*
* Description
*/
angular.module('directive.diPiece', [
    'service.GameManager',
    'resource.GameData'
])
.controller('PieceCtrl', [
    '$scope',
    'GameManager',
    'GameData',
function (
    $scope,
    GameManager,
    GameData
){
    var getX = _.memoize(function(x) {
           return x * GameData.gameBoard.pieceWidthInPixel + GameData.gameBoard.borderWidth;
        }),
        getY = _.memoize(function (y) {
            return y * GameData.gameBoard.pieceWidthInPixel;
        }),
        memCheckPattern = _.memoize(function (pattern, piece) {
            var res = _.find(getPattern(), function (p) {
                return piece === p;
            });
            return _.isNumber(res);
        }, function (pattern, piece) {
            return pattern.toString() + ',' + piece;
        });

    function getPattern() {
        return GameManager.getCurrentPattern();
    }

    function getPiece() {
        return GameManager.getCurrentPiece();
    }

    function getPositionX () {
        return GameManager.getPositionX();
    }

    function getPositionY() {
        return GameManager.getPositionY();
    }

    $scope.pieces = _.range(16);

    // if sequence is match, then highlight the DOM ele
    $scope.checkPattern = function checkPattern(piece) {
        if (!GameManager.isGameStart()) {
            return;
        }
        return memCheckPattern(getPattern(), piece);
    };

    $scope.getClassForShape = function getClassForShape() {
        if (!GameManager.isGameStart() ||
            _.isNull(GameManager.getCurrentPiece())) {
            return;
        }
        var pieceClass = '';
        switch(GameManager.getCurrentShape()) {
            case 0: pieceClass = 'dy-L';
                break;
            case 1: pieceClass = 'dy-O';
                break;
            case 2: pieceClass = 'dy-I';
                break;
            case 3: pieceClass = 'dy-T';
                break;
            case 4: pieceClass = 'dy-J';
                break;
            case 5: pieceClass = 'dy-S';
                break;
            case 6: pieceClass = 'dy-Z';
                break;
            default: pieceClass = 'dy-X';
                break;
        }
        return pieceClass;
    };

    this.getLeft = function getLeft() {
        return getX(getPositionX());
    };

    this.getTop = function getTop() {
        return getY(getPositionY());
    };
}])
.directive('diPiece', [
    'GameManager',
    'GameData',
function(
    GameManager,
    GameData
){
    var Piece = {};

    Piece.controller = 'PieceCtrl';

    Piece.templateUrl = 'directives/diPiece/diPiece.tpl.html';

    Piece.restrict = 'A';

    Piece.replace = true;

    Piece.scope = true;

    Piece.link = function link(scope, element, attrs, controller) {
        scope.$on('home.GameOn', function () {
            var top = controller.getTop(),
                left = controller.getLeft();
            element.css({
                'left': left + 'px',
                'top': Math.round(top) + 'px'
            });
        });

        scope.getColor = function getColor() {
            var ul = element.children(),
                li = ul.children();
            if (ul.hasClass('dy-X')) {
                if (this.checkPattern(this.i)) {
                    return {
                        'background-color': GameData.getColor()
                    };
                }
            }
        };

        // can't separate the digest loop with class update and
        // create a new piece, so manually update the dy-piece-ready class
        scope.isPieceReady = function isPieceReady() {
            var isReady = !_.isNull(GameManager.getCurrentPiece());
            if (!isReady) {
                element.removeClass('dy-piece-ready');
                scope.$emit('Piece.createNewPiece');
            } else {
                if (!element.hasClass('dy-piece-ready')) {
                    // wait for the animation complete in 0.3 seconds
                    // if modify the timeout time, it need to update
                    // the variables in the variables.less
                    window.setTimeout(function() {
                        element.addClass('dy-piece-ready');
                    }, GameData.cssAnimateTimeout);
                }
            }
            return isReady;
        };
    };

    return Piece;
}]);<commit_msg>use transform instead of top and left, because it will use the GPU to reduce the repaint in DOM<commit_after>/**
* directive.diPiece Module
*
* Description
*/
angular.module('directive.diPiece', [
    'service.GameManager',
    'resource.GameData'
])
.controller('PieceCtrl', [
    '$scope',
    'GameManager',
    'GameData',
function (
    $scope,
    GameManager,
    GameData
){
    var getX = _.memoize(function(x) {
           return x * GameData.gameBoard.pieceWidthInPixel + GameData.gameBoard.borderWidth;
        }),
        getY = _.memoize(function (y) {
            return y * GameData.gameBoard.pieceWidthInPixel;
        }),
        memCheckPattern = _.memoize(function (pattern, piece) {
            var res = _.find(getPattern(), function (p) {
                return piece === p;
            });
            return _.isNumber(res);
        }, function (pattern, piece) {
            return pattern.toString() + ',' + piece;
        });

    function getPattern() {
        return GameManager.getCurrentPattern();
    }

    function getPiece() {
        return GameManager.getCurrentPiece();
    }

    function getPositionX () {
        return GameManager.getPositionX();
    }

    function getPositionY() {
        return GameManager.getPositionY();
    }

    $scope.pieces = _.range(16);

    // if sequence is match, then highlight the DOM ele
    $scope.checkPattern = function checkPattern(piece) {
        if (!GameManager.isGameStart()) {
            return;
        }
        return memCheckPattern(getPattern(), piece);
    };

    $scope.getClassForShape = function getClassForShape() {
        if (!GameManager.isGameStart() ||
            _.isNull(GameManager.getCurrentPiece())) {
            return;
        }
        var pieceClass = '';
        switch(GameManager.getCurrentShape()) {
            case 0: pieceClass = 'dy-L';
                break;
            case 1: pieceClass = 'dy-O';
                break;
            case 2: pieceClass = 'dy-I';
                break;
            case 3: pieceClass = 'dy-T';
                break;
            case 4: pieceClass = 'dy-J';
                break;
            case 5: pieceClass = 'dy-S';
                break;
            case 6: pieceClass = 'dy-Z';
                break;
            default: pieceClass = 'dy-X';
                break;
        }
        return pieceClass;
    };

    this.getLeft = function getLeft() {
        return getX(getPositionX());
    };

    this.getTop = function getTop() {
        return getY(getPositionY());
    };
}])
.directive('diPiece', [
    'GameManager',
    'GameData',
function(
    GameManager,
    GameData
){
    var Piece = {};

    Piece.controller = 'PieceCtrl';

    Piece.templateUrl = 'directives/diPiece/diPiece.tpl.html';

    Piece.restrict = 'A';

    Piece.replace = true;

    Piece.scope = true;

    Piece.link = function link(scope, element, attrs, controller) {
        scope.$on('home.GameOn', function () {
            var top = controller.getTop(),
                left = controller.getLeft(),
                translatePos = 'translate(' + left + 'px,' + Math.round(top) + 'px)';
            element.css({
                'transform': translatePos,
                '-webkit-transform': translatePos,
                '-ms-transform': translatePos,
                '-moz-transform': translatePos
            });
        });

        scope.getColor = function getColor() {
            var ul = element.children(),
                li = ul.children();
            if (ul.hasClass('dy-X')) {
                if (this.checkPattern(this.i)) {
                    return {
                        'background-color': GameData.getColor()
                    };
                }
            }
        };

        // can't separate the digest loop with class update and
        // create a new piece, so manually update the dy-piece-ready class
        scope.isPieceReady = function isPieceReady() {
            var isReady = !_.isNull(GameManager.getCurrentPiece());
            if (!isReady) {
                element.removeClass('dy-piece-ready');
                scope.$emit('Piece.createNewPiece');
            } else {
                if (!element.hasClass('dy-piece-ready')) {
                    // wait for the animation complete in 0.3 seconds
                    // if modify the timeout time, it need to update
                    // the variables in the variables.less
                    window.setTimeout(function() {
                        element.addClass('dy-piece-ready');
                    }, GameData.cssAnimateTimeout);
                }
            }
            return isReady;
        };
    };

    return Piece;
}]);<|endoftext|>


<commit_before>'use strict';

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import baseStyles from './baseStyles';
import BurgerIcon from './BurgerIcon';
import CrossIcon from './CrossIcon';

export default styles => {
  class Menu extends Component {
    constructor(props) {
      super(props);
      this.state = {
        isOpen: false
      };

      if (!styles) {
        throw new Error('No styles supplied');
      }
    }

    toggleMenu(options = {}) {
      const { isOpen, noStateChange } = options;
      const newState = {
        isOpen: typeof isOpen !== 'undefined' ? isOpen : !this.state.isOpen
      };

      this.applyWrapperStyles();

      this.setState(newState, () => {
        !noStateChange && this.props.onStateChange(newState);

        if (!this.props.disableAutoFocus) {
          // For accessibility reasons, ensures that when we toggle open,
          // we focus the first menu item if one exists.
          if (newState.isOpen) {
            const firstItem = document.querySelector('.bm-item');
            if (firstItem) {
              firstItem.focus();
            }
          } else {
            if (document.activeElement) {
              document.activeElement.blur();
            } else {
              document.body.blur(); // Needed for IE
            }
          }
        }

        // Timeout ensures wrappers are cleared after animation finishes.
        this.timeoutId && clearTimeout(this.timeoutId);
        this.timeoutId = setTimeout(() => {
          this.timeoutId = null;
          if (!newState.isOpen) {
            this.applyWrapperStyles(false);
          }
        }, 500);
      });
    }

    // Applies component-specific styles to external wrapper elements.
    applyWrapperStyles(set = true) {
      const applyClass = (el, className) =>
        el.classList[set ? 'add' : 'remove'](className);

      if (this.props.htmlClassName) {
        applyClass(document.querySelector('html'), this.props.htmlClassName);
      }
      if (this.props.bodyClassName) {
        applyClass(document.querySelector('body'), this.props.bodyClassName);
      }

      if (styles.pageWrap && this.props.pageWrapId) {
        this.handleExternalWrapper(this.props.pageWrapId, styles.pageWrap, set);
      }

      if (styles.outerContainer && this.props.outerContainerId) {
        this.handleExternalWrapper(
          this.props.outerContainerId,
          styles.outerContainer,
          set
        );
      }
    }

    // Sets or unsets styles on DOM elements outside the menu component.
    // This is necessary for correct page interaction with some of the menus.
    // Throws and returns if the required external elements don't exist,
    // which means any external page animations won't be applied.
    handleExternalWrapper(id, wrapperStyles, set) {
      const wrapper = document.getElementById(id);

      if (!wrapper) {
        console.error("Element with ID '" + id + "' not found");
        return;
      }

      const builtStyles = this.getStyle(wrapperStyles);

      for (const prop in builtStyles) {
        if (builtStyles.hasOwnProperty(prop)) {
          wrapper.style[prop] = set ? builtStyles[prop] : '';
        }
      }

      // Prevent any horizontal scroll.
      // Only set overflow-x as an inline style if htmlClassName or
      // bodyClassName is not passed in. Otherwise, it is up to the caller to
      // decide if they want to set the overflow style in CSS using the custom
      // class names.
      const applyOverflow = el =>
        (el.style['overflow-x'] = set ? 'hidden' : '');
      if (!this.props.htmlClassName) {
        applyOverflow(document.querySelector('html'));
      }
      if (!this.props.bodyClassName) {
        applyOverflow(document.querySelector('body'));
      }
    }

    // Builds styles incrementally for a given element.
    getStyles(el, index, inline) {
      const propName =
        'bm' + el.replace(el.charAt(0), el.charAt(0).toUpperCase());

      // Set base styles.
      let output = baseStyles[el] ? this.getStyle(baseStyles[el]) : {};

      // Add animation-specific styles.
      if (styles[el]) {
        output = {
          ...output,
          ...this.getStyle(styles[el], index + 1)
        };
      }

      // Add custom styles.
      if (this.props.styles[propName]) {
        output = {
          ...output,
          ...this.props.styles[propName]
        };
      }

      // Add element inline styles.
      if (inline) {
        output = {
          ...output,
          ...inline
        };
      }

      return output;
    }

    getStyle(style, index) {
      const { width } = this.props;
      const formattedWidth = typeof width !== 'string' ? `${width}px` : width;
      return style(this.state.isOpen, formattedWidth, this.props.right, index);
    }

    listenForClose(e) {
      e = e || window.event;

      if (this.state.isOpen && (e.key === 'Escape' || e.keyCode === 27)) {
        this.toggleMenu();
      }
    }

    shouldDisableOverlayClick() {
      if (typeof this.props.disableOverlayClick === 'function') {
        return this.props.disableOverlayClick();
      } else {
        return this.props.disableOverlayClick;
      }
    }

    componentDidMount() {
      // Bind ESC key handler (unless disabled or custom function supplied).
      if (this.props.customOnKeyDown) {
        window.onkeydown = this.props.customOnKeyDown;
      } else if (!this.props.disableCloseOnEsc) {
        window.onkeydown = this.listenForClose.bind(this);
      }

      // Allow initial open state to be set by props.
      if (this.props.isOpen) {
        this.toggleMenu({ isOpen: true, noStateChange: true });
      }
    }

    componentWillUnmount() {
      window.onkeydown = null;

      this.applyWrapperStyles(false);
    }

    componentDidUpdate(prevProps) {
      const wasToggled =
        typeof this.props.isOpen !== 'undefined' &&
        this.props.isOpen !== this.state.isOpen &&
        this.props.isOpen !== prevProps.isOpen;
      if (wasToggled) {
        this.toggleMenu();
        // Toggling changes SVG animation requirements, so we defer these until the next componentDidUpdate
        return;
      }

      if (styles.svg) {
        const morphShape = ReactDOM.findDOMNode(this, 'bm-morph-shape');
        const path = styles.svg.lib(morphShape).select('path');

        if (this.state.isOpen) {
          // Animate SVG path.
          styles.svg.animate(path);
        } else {
          // Reset path (timeout ensures animation happens off screen).
          setTimeout(() => {
            path.attr('d', styles.svg.pathInitial);
          }, 300);
        }
      }
    }

    render() {
      return (

          {!this.props.noOverlay && (
            <div
              className={`bm-overlay ${this.props.overlayClassName}`.trim()}
              onClick={() =>
                !this.shouldDisableOverlayClick() && this.toggleMenu()
              }
              style={this.getStyles('overlay')}
            />
          )}
          <div
            id={this.props.id}
            className={`bm-menu-wrap ${this.props.className}`.trim()}
            style={this.getStyles('menuWrap')}
          >
            {styles.svg && (

                <svg
                  width="100%"
                  height="100%"
                  viewBox="0 0 100 800"
                  preserveAspectRatio="none"
                >
                  <path d={styles.svg.pathInitial} />
                </svg>

            )}
            <div
              className={`bm-menu ${this.props.menuClassName}`.trim()}
              style={this.getStyles('menu')}
            >

                {React.Children.map(this.props.children, (item, index) => {
                  if (item) {
                    const classList = [
                      'bm-item',
                      this.props.itemClassName,
                      item.props.className
                    ]
                      .filter(className => !!className)
                      .join(' ');
                    const extraProps = {
                      key: index,
                      className: classList,
                      style: this.getStyles('item', index, item.props.style),
                      tabIndex: this.state.isOpen ? 0 : -1
                    };
                    return React.cloneElement(item, extraProps);
                  }
                })}

            {this.props.customCrossIcon !== false && (

                <CrossIcon
                  onClick={() => this.toggleMenu()}
                  styles={this.props.styles}
                  customIcon={this.props.customCrossIcon}
                  className={this.props.crossButtonClassName}
                  crossClassName={this.props.crossClassName}
                  tabIndex={this.state.isOpen ? 0 : -1}
                />

            )}

          {this.props.customBurgerIcon !== false && (

              <BurgerIcon
                onClick={() => this.toggleMenu()}
                styles={this.props.styles}
                customIcon={this.props.customBurgerIcon}
                className={this.props.burgerButtonClassName}
                barClassName={this.props.burgerBarClassName}
              />

          )}

      );
    }
  }

  Menu.propTypes = {
    bodyClassName: PropTypes.string,
    burgerBarClassName: PropTypes.string,
    burgerButtonClassName: PropTypes.string,
    className: PropTypes.string,
    crossButtonClassName: PropTypes.string,
    crossClassName: PropTypes.string,
    customBurgerIcon: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.oneOf([false])
    ]),
    customCrossIcon: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.oneOf([false])
    ]),
    customOnKeyDown: PropTypes.func,
    disableAutoFocus: PropTypes.bool,
    disableCloseOnEsc: PropTypes.bool,
    disableOverlayClick: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
    htmlClassName: PropTypes.string,
    id: PropTypes.string,
    isOpen: PropTypes.bool,
    itemClassName: PropTypes.string,
    itemListClassName: PropTypes.string,
    menuClassName: PropTypes.string,
    morphShapeClassName: PropTypes.string,
    noOverlay: PropTypes.bool,
    onStateChange: PropTypes.func,
    outerContainerId:
      styles && styles.outerContainer
        ? PropTypes.string.isRequired
        : PropTypes.string,
    overlayClassName: PropTypes.string,
    pageWrapId:
      styles && styles.pageWrap
        ? PropTypes.string.isRequired
        : PropTypes.string,
    right: PropTypes.bool,
    styles: PropTypes.object,
    width: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
  };

  Menu.defaultProps = {
    bodyClassName: '',
    burgerBarClassName: '',
    burgerButtonClassName: '',
    className: '',
    crossButtonClassName: '',
    crossClassName: '',
    disableAutoFocus: false,
    disableCloseOnEsc: false,
    htmlClassName: '',
    id: '',
    itemClassName: '',
    itemListClassName: '',
    menuClassName: '',
    morphShapeClassName: '',
    noOverlay: false,
    onStateChange: () => {},
    outerContainerId: '',
    overlayClassName: '',
    pageWrapId: '',
    styles: {},
    width: 300
  };

  return Menu;
};
<commit_msg>Check `disableCloseOnEsc` prop dynamically<commit_after>'use strict';

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import baseStyles from './baseStyles';
import BurgerIcon from './BurgerIcon';
import CrossIcon from './CrossIcon';

export default styles => {
  class Menu extends Component {
    constructor(props) {
      super(props);
      this.state = {
        isOpen: false
      };

      if (!styles) {
        throw new Error('No styles supplied');
      }
    }

    toggleMenu(options = {}) {
      const { isOpen, noStateChange } = options;
      const newState = {
        isOpen: typeof isOpen !== 'undefined' ? isOpen : !this.state.isOpen
      };

      this.applyWrapperStyles();

      this.setState(newState, () => {
        !noStateChange && this.props.onStateChange(newState);

        if (!this.props.disableAutoFocus) {
          // For accessibility reasons, ensures that when we toggle open,
          // we focus the first menu item if one exists.
          if (newState.isOpen) {
            const firstItem = document.querySelector('.bm-item');
            if (firstItem) {
              firstItem.focus();
            }
          } else {
            if (document.activeElement) {
              document.activeElement.blur();
            } else {
              document.body.blur(); // Needed for IE
            }
          }
        }

        // Timeout ensures wrappers are cleared after animation finishes.
        this.timeoutId && clearTimeout(this.timeoutId);
        this.timeoutId = setTimeout(() => {
          this.timeoutId = null;
          if (!newState.isOpen) {
            this.applyWrapperStyles(false);
          }
        }, 500);
      });
    }

    // Applies component-specific styles to external wrapper elements.
    applyWrapperStyles(set = true) {
      const applyClass = (el, className) =>
        el.classList[set ? 'add' : 'remove'](className);

      if (this.props.htmlClassName) {
        applyClass(document.querySelector('html'), this.props.htmlClassName);
      }
      if (this.props.bodyClassName) {
        applyClass(document.querySelector('body'), this.props.bodyClassName);
      }

      if (styles.pageWrap && this.props.pageWrapId) {
        this.handleExternalWrapper(this.props.pageWrapId, styles.pageWrap, set);
      }

      if (styles.outerContainer && this.props.outerContainerId) {
        this.handleExternalWrapper(
          this.props.outerContainerId,
          styles.outerContainer,
          set
        );
      }
    }

    // Sets or unsets styles on DOM elements outside the menu component.
    // This is necessary for correct page interaction with some of the menus.
    // Throws and returns if the required external elements don't exist,
    // which means any external page animations won't be applied.
    handleExternalWrapper(id, wrapperStyles, set) {
      const wrapper = document.getElementById(id);

      if (!wrapper) {
        console.error("Element with ID '" + id + "' not found");
        return;
      }

      const builtStyles = this.getStyle(wrapperStyles);

      for (const prop in builtStyles) {
        if (builtStyles.hasOwnProperty(prop)) {
          wrapper.style[prop] = set ? builtStyles[prop] : '';
        }
      }

      // Prevent any horizontal scroll.
      // Only set overflow-x as an inline style if htmlClassName or
      // bodyClassName is not passed in. Otherwise, it is up to the caller to
      // decide if they want to set the overflow style in CSS using the custom
      // class names.
      const applyOverflow = el =>
        (el.style['overflow-x'] = set ? 'hidden' : '');
      if (!this.props.htmlClassName) {
        applyOverflow(document.querySelector('html'));
      }
      if (!this.props.bodyClassName) {
        applyOverflow(document.querySelector('body'));
      }
    }

    // Builds styles incrementally for a given element.
    getStyles(el, index, inline) {
      const propName =
        'bm' + el.replace(el.charAt(0), el.charAt(0).toUpperCase());

      // Set base styles.
      let output = baseStyles[el] ? this.getStyle(baseStyles[el]) : {};

      // Add animation-specific styles.
      if (styles[el]) {
        output = {
          ...output,
          ...this.getStyle(styles[el], index + 1)
        };
      }

      // Add custom styles.
      if (this.props.styles[propName]) {
        output = {
          ...output,
          ...this.props.styles[propName]
        };
      }

      // Add element inline styles.
      if (inline) {
        output = {
          ...output,
          ...inline
        };
      }

      return output;
    }

    getStyle(style, index) {
      const { width } = this.props;
      const formattedWidth = typeof width !== 'string' ? `${width}px` : width;
      return style(this.state.isOpen, formattedWidth, this.props.right, index);
    }

    listenForClose(e) {
      e = e || window.event;

      // Close on ESC, unless disabled
      if (
        !this.props.disableCloseOnEsc &&
        this.state.isOpen &&
        (e.key === 'Escape' || e.keyCode === 27)
      ) {
        this.toggleMenu();
      }
    }

    shouldDisableOverlayClick() {
      if (typeof this.props.disableOverlayClick === 'function') {
        return this.props.disableOverlayClick();
      } else {
        return this.props.disableOverlayClick;
      }
    }

    componentDidMount() {
      // Bind ESC key handler (unless custom function supplied).
      if (this.props.customOnKeyDown) {
        window.onkeydown = this.props.customOnKeyDown;
      } else {
        window.onkeydown = this.listenForClose.bind(this);
      }

      // Allow initial open state to be set by props.
      if (this.props.isOpen) {
        this.toggleMenu({ isOpen: true, noStateChange: true });
      }
    }

    componentWillUnmount() {
      window.onkeydown = null;

      this.applyWrapperStyles(false);
    }

    componentDidUpdate(prevProps) {
      const wasToggled =
        typeof this.props.isOpen !== 'undefined' &&
        this.props.isOpen !== this.state.isOpen &&
        this.props.isOpen !== prevProps.isOpen;
      if (wasToggled) {
        this.toggleMenu();
        // Toggling changes SVG animation requirements, so we defer these until the next componentDidUpdate
        return;
      }

      if (styles.svg) {
        const morphShape = ReactDOM.findDOMNode(this, 'bm-morph-shape');
        const path = styles.svg.lib(morphShape).select('path');

        if (this.state.isOpen) {
          // Animate SVG path.
          styles.svg.animate(path);
        } else {
          // Reset path (timeout ensures animation happens off screen).
          setTimeout(() => {
            path.attr('d', styles.svg.pathInitial);
          }, 300);
        }
      }
    }

    render() {
      return (

          {!this.props.noOverlay && (
            <div
              className={`bm-overlay ${this.props.overlayClassName}`.trim()}
              onClick={() =>
                !this.shouldDisableOverlayClick() && this.toggleMenu()
              }
              style={this.getStyles('overlay')}
            />
          )}
          <div
            id={this.props.id}
            className={`bm-menu-wrap ${this.props.className}`.trim()}
            style={this.getStyles('menuWrap')}
          >
            {styles.svg && (

                <svg
                  width="100%"
                  height="100%"
                  viewBox="0 0 100 800"
                  preserveAspectRatio="none"
                >
                  <path d={styles.svg.pathInitial} />
                </svg>

            )}
            <div
              className={`bm-menu ${this.props.menuClassName}`.trim()}
              style={this.getStyles('menu')}
            >

                {React.Children.map(this.props.children, (item, index) => {
                  if (item) {
                    const classList = [
                      'bm-item',
                      this.props.itemClassName,
                      item.props.className
                    ]
                      .filter(className => !!className)
                      .join(' ');
                    const extraProps = {
                      key: index,
                      className: classList,
                      style: this.getStyles('item', index, item.props.style),
                      tabIndex: this.state.isOpen ? 0 : -1
                    };
                    return React.cloneElement(item, extraProps);
                  }
                })}

            {this.props.customCrossIcon !== false && (

                <CrossIcon
                  onClick={() => this.toggleMenu()}
                  styles={this.props.styles}
                  customIcon={this.props.customCrossIcon}
                  className={this.props.crossButtonClassName}
                  crossClassName={this.props.crossClassName}
                  tabIndex={this.state.isOpen ? 0 : -1}
                />

            )}

          {this.props.customBurgerIcon !== false && (

              <BurgerIcon
                onClick={() => this.toggleMenu()}
                styles={this.props.styles}
                customIcon={this.props.customBurgerIcon}
                className={this.props.burgerButtonClassName}
                barClassName={this.props.burgerBarClassName}
              />

          )}

      );
    }
  }

  Menu.propTypes = {
    bodyClassName: PropTypes.string,
    burgerBarClassName: PropTypes.string,
    burgerButtonClassName: PropTypes.string,
    className: PropTypes.string,
    crossButtonClassName: PropTypes.string,
    crossClassName: PropTypes.string,
    customBurgerIcon: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.oneOf([false])
    ]),
    customCrossIcon: PropTypes.oneOfType([
      PropTypes.element,
      PropTypes.oneOf([false])
    ]),
    customOnKeyDown: PropTypes.func,
    disableAutoFocus: PropTypes.bool,
    disableCloseOnEsc: PropTypes.bool,
    disableOverlayClick: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
    htmlClassName: PropTypes.string,
    id: PropTypes.string,
    isOpen: PropTypes.bool,
    itemClassName: PropTypes.string,
    itemListClassName: PropTypes.string,
    menuClassName: PropTypes.string,
    morphShapeClassName: PropTypes.string,
    noOverlay: PropTypes.bool,
    onStateChange: PropTypes.func,
    outerContainerId:
      styles && styles.outerContainer
        ? PropTypes.string.isRequired
        : PropTypes.string,
    overlayClassName: PropTypes.string,
    pageWrapId:
      styles && styles.pageWrap
        ? PropTypes.string.isRequired
        : PropTypes.string,
    right: PropTypes.bool,
    styles: PropTypes.object,
    width: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
  };

  Menu.defaultProps = {
    bodyClassName: '',
    burgerBarClassName: '',
    burgerButtonClassName: '',
    className: '',
    crossButtonClassName: '',
    crossClassName: '',
    disableAutoFocus: false,
    disableCloseOnEsc: false,
    htmlClassName: '',
    id: '',
    itemClassName: '',
    itemListClassName: '',
    menuClassName: '',
    morphShapeClassName: '',
    noOverlay: false,
    onStateChange: () => {},
    outerContainerId: '',
    overlayClassName: '',
    pageWrapId: '',
    styles: {},
    width: 300
  };

  return Menu;
};
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';

class EnterpriseMapComponent extends React.Component {

  render() {
    let enterprise = this.props.enterprise;
    if (enterprise.locations == null ||
        enterprise.locations.coordinates == null ||
        enterprise.locations.coordinates.length === 0) {
      return null;
    }

    let popupMarkers = this.generatePopupMarkers(enterprise);
    let tileLayer = this.generateTileLayer();

    if (enterprise.locations.coordinates.length === 1) {
      return (

          <Map center={enterprise.locations.coordinates[0]} zoom={15}>
            {tileLayer}
            {popupMarkers}
          </Map>

      );
    }

    return (

        <Map bounds={enterprise.locations.coordinates}>
          {tileLayer}
          {popupMarkers}
        </Map>

    );
  }

  generateTileLayer() {
    return (
      <TileLayer
        attribution='© OpenStreetMap contributors'
        url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
      />
    );
  }

  generatePopupMarkers(enterprise) {
    let jsx = [];
    enterprise.locations.coordinates.map(coordinates => {
      let coordsStr = coordinates[0] + ',' + coordinates[1];
      jsx.push(
        <Marker key={coordsStr} position={coordinates}>
          <Popup>
            {enterprise.name}
          </Popup>
        </Marker>
      );
    });
    return jsx;
  }
}

EnterpriseMapComponent.displayName = 'EnterpriseMapComponent';

// Uncomment properties you need
// EnterpriseMapComponent.propTypes = {};
// EnterpriseMapComponent.defaultProps = {};

export default EnterpriseMapComponent;
<commit_msg>one more lat long place to fix<commit_after>'use strict';

import React from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';

class EnterpriseMapComponent extends React.Component {

  render() {
    let enterprise = this.props.enterprise;
    if (enterprise.locations == null ||
        enterprise.locations.coordinates == null ||
        enterprise.locations.coordinates.length === 0) {
      return null;
    }

    let popupMarkers = this.generatePopupMarkers(enterprise);
    let tileLayer = this.generateTileLayer();

    if (enterprise.locations.coordinates.length === 1) {
      let latLng = [enterprise.locations.coordinates[0][1], enterprise.locations.coordinates[0][0]];
      return (

          <Map center={latLng} zoom={15}>
            {tileLayer}
            {popupMarkers}
          </Map>

      );
    }

    return (

        <Map bounds={this.generateAllCoords(enterprise)}>
          {tileLayer}
          {popupMarkers}
        </Map>

    );
  }

  generateTileLayer() {
    return (
      <TileLayer
        attribution='© OpenStreetMap contributors'
        url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
      />
    );
  }

  generatePopupMarkers(enterprise) {
    let jsx = [];
    enterprise.locations.coordinates.map(coordinates => {
      let latLng = [coordinates[1], coordinates[0]];
      let coordsStr = latLng[0] + ',' + latLng[1];
      jsx.push(
        <Marker key={coordsStr} position={latLng}>
          <Popup>
            {enterprise.name}
          </Popup>
        </Marker>
      );
    });
    return jsx;
  }

  generateAllCoords(enterprise) {
    let allCoords = [];
    enterprise.locations.coordinates.map(coordinates => {
      let latLng = [coordinates[1], coordinates[0]];
      allCoords.push(latLng);
    });
    return allCoords;
  }
}

EnterpriseMapComponent.displayName = 'EnterpriseMapComponent';

// Uncomment properties you need
// EnterpriseMapComponent.propTypes = {};
// EnterpriseMapComponent.defaultProps = {};

export default EnterpriseMapComponent;
<|endoftext|>


<commit_before>/**
 *  @module   Amount Model
 *
 *  @access   public
 *  @author   TAurelien
 *  @date     2015-05-02
 *  @version  1.0.0
 */
'use strict';

// Module dependencies ========================================================
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = function (options, imports) {

	var logger = imports.logger.get('Amount Model');

	var nomenclatures = imports.nomenclatures;
	var currencies = nomenclatures.getIds('currencies');

	// TODO Deal with nomenclatures update

	var defaultCurrency = options.defaultCurrency || currencies[0];
	var defaultScale = options.defaultScale || 100;

	// Schema definition ======================================================

	var AmountSchema = new Schema({

		quantity: {
			type: Number,
			default: 1
		},

		unitary: {
			type: Number
		},

		value: {
			type: Number,
			required: true,
			default: 0
		},

		scale: {
			type: Number,
			required: true,
			default: defaultScale
		},

		currency: {
			type: String,
			trim: true,
			default: defaultCurrency,
			enum: currencies
		}

	});

	// Pre processing =========================================================

	AmountSchema.pre('save', function (next) {

		if (this.quantity === 0) {
			this.unitary = 0;
			this.value = 0;
		} else {
			if (!this.unitary) {
				this.unitary = this.value / this.quantity;
			}
		}

		next();

	});

	// Model export ===========================================================

	return AmountSchema;

};<commit_msg>set options on Amount schema<commit_after>/**
 *  @module   Amount Model
 *
 *  @access   public
 *  @author   TAurelien
 *  @date     2015-05-02
 *  @version  1.0.0
 */
'use strict';

// Module dependencies ========================================================
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = function (options, imports) {

	var logger = imports.logger.get('Amount Model');

	var nomenclatures = imports.nomenclatures;
	var currencies = nomenclatures.getIds('currencies');

	// TODO Deal with nomenclatures update

	var defaultCurrency = options.defaultCurrency || currencies[0];
	var defaultScale = options.defaultScale || 100;

	// Schema definition ======================================================

	var AmountSchema = new Schema({

		quantity: {
			type: Number,
			default: 1
		},

		unitary: {
			type: Number
		},

		value: {
			type: Number,
			required: true,
			default: 0
		},

		scale: {
			type: Number,
			required: true,
			default: defaultScale
		},

		currency: {
			type: String,
			trim: true,
			default: defaultCurrency,
			enum: currencies
		}

	}, {
		id: false,
		_id: false,
		versionKey: false
	});

	// Pre processing =========================================================

	AmountSchema.pre('save', function (next) {

		if (this.quantity === 0) {
			this.unitary = 0;
			this.value = 0;
		} else {
			if (!this.unitary) {
				this.unitary = this.value / this.quantity;
			}
		}

		next();

	});

	// Model export ===========================================================

	return AmountSchema;

};<|endoftext|>


<commit_before>/* eslint-disable jsx-a11y/no-static-element-interactions */
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { Link } from 'react-router'
import ImageAsset from '../assets/ImageAsset'
import VideoAsset from '../assets/VideoAsset'
import { isGif } from '../../helpers/file_helper'
import { before, css, media, modifier, select } from '../../styles/jss'
import * as s from '../../styles/jso'

const STATUS = {
  PENDING: 'isPending',
  REQUEST: 'isRequesting',
  SUCCESS: null,
  FAILURE: 'isFailing',
}

export function getSource(props) {
  const { dpi, sources, useGif } = props
  if (!sources) {
    return ''
  } else if (sources.getIn(['tmp', 'url'])) {
    return sources.getIn(['tmp', 'url'])
  } else if (useGif && isGif(sources.getIn(['video', 'url']))) {
    return sources.getIn(['video', 'url'])
  }
  return sources.getIn([dpi, 'url'], null)
}

const baseStyle = css(
  s.absolute,
  s.flood,
  s.zIndex0,
  s.overflowHidden,
  {
    background: 'rgba(0, 0, 0, 0.2) no-repeat 50% 50%',
    backgroundSize: 'cover',
    transition: 'background-color 0.2s ease, opacity 0.4s ease',
  },
  modifier('.isRequesting', { animation: 'animateLavaLamp 3s infinite linear' }),
  modifier('.isFailing', s.bgcRed),
  modifier('.inOnboarding', { height: 220 }),
  modifier('.inSettings', { height: 220 }),
  modifier('.inUserProfileCard', { height: 260 }),
  before(s.absolute, s.flood, s.zIndex1, s.bgcTransparent, s.transitionBgColor, { content: '""' }),
  modifier('.hasOverlay3', before({ backgroundColor: 'rgba(0, 0, 0, 0.3)' })),
  modifier('.hasOverlay4', before({ backgroundColor: 'rgba(0, 0, 0, 0.4)' })),
  modifier('.hasOverlay5', before({ backgroundColor: 'rgba(0, 0, 0, 0.5)' })),
  modifier('.hasOverlay6', before({ backgroundColor: 'rgba(0, 0, 0, 0.6)' })),
  select('.no-touch &.isLink:hover::before', { backgroundColor: 'rgba(0, 0, 0, 0.4)' }),
  media(s.maxBreak2, modifier('.inHeroProfile', { height: 220 })),
  media(s.minBreak2, modifier('.inSettings', { minHeight: 330 })),
  media(s.minBreak2, modifier('.inUserProfileCard:not(.isMiniProfileCard)', { minHeight: 540 })),
)

const editorialVideoStyle = css(
  {
    width: '100%',
    height: '100%',
    objectFit: 'cover',
    minWidth: '100%',
    minHeight: '100%',
  },
)

export default class BackgroundImage extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    onClick: PropTypes.func,
    to: PropTypes.string,
  }

  static defaultProps = {
    className: null,
    onClick: null,
    to: null,
  }

  componentWillMount() {
    this.state = {
      status: STATUS.REQUEST,
    }
  }

  componentWillReceiveProps(nextProps) {
    const thisSource = getSource(this.props)
    const nextSource = getSource(nextProps)
    if (thisSource !== nextSource) {
      this.setState({
        status: nextSource ? STATUS.REQUEST : STATUS.PENDING,
      })
    }
  }

  onLoadSuccess = () => {
    this.setState({ status: STATUS.SUCCESS })
  }

  onLoadFailure = () => {
    this.setState({ status: STATUS.FAILURE })
  }

  render() {
    const { className, onClick, to } = this.props
    const { status } = this.state
    const classList = classNames(`BackgroundImage ${baseStyle}`, status, className)
    const src = getSource(this.props)
    const isVideo = !!src && src.substr(-3) === 'mp4'
    const imageAssetProps = {
      isBackgroundImage: true,
      onLoadFailure: this.onLoadFailure,
      onLoadSuccess: this.onLoadSuccess,
      src,
    }
    const videoAssetProps = {
      src,
    }

    if (isVideo) {
      return (<Link className={classNames(classList, 'isLink')} onClick={onClick} to={to}>
        <VideoAsset {...videoAssetProps} className={editorialVideoStyle} />
      </Link>)
    }

    return to ?
      <Link className={classNames(classList, 'isLink')} onClick={onClick} to={to}>
        <ImageAsset {...imageAssetProps} />
      </Link> :

        <ImageAsset {...imageAssetProps} />

  }
}

<commit_msg>If useGif is true, use original as fallback if video isn’t available<commit_after>/* eslint-disable jsx-a11y/no-static-element-interactions */
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { Link } from 'react-router'
import ImageAsset from '../assets/ImageAsset'
import VideoAsset from '../assets/VideoAsset'
import { isGif } from '../../helpers/file_helper'
import { before, css, media, modifier, select } from '../../styles/jss'
import * as s from '../../styles/jso'

const STATUS = {
  PENDING: 'isPending',
  REQUEST: 'isRequesting',
  SUCCESS: null,
  FAILURE: 'isFailing',
}

export function getSource(props) {
  const { dpi, sources, useGif } = props
  if (!sources) {
    return ''
  } else if (sources.getIn(['tmp', 'url'])) {
    return sources.getIn(['tmp', 'url'])
  } else if (useGif && isGif(sources.getIn(['video', 'url']))) {
    return sources.getIn(['video', 'url'])
  } else if (useGif && isGif(sources.getIn(['original', 'url']))) {
    return sources.getIn(['original', 'url'])
  }
  return sources.getIn([dpi, 'url'], null)
}

const baseStyle = css(
  s.absolute,
  s.flood,
  s.zIndex0,
  s.overflowHidden,
  {
    background: 'rgba(0, 0, 0, 0.2) no-repeat 50% 50%',
    backgroundSize: 'cover',
    transition: 'background-color 0.2s ease, opacity 0.4s ease',
  },
  modifier('.isRequesting', { animation: 'animateLavaLamp 3s infinite linear' }),
  modifier('.isFailing', s.bgcRed),
  modifier('.inOnboarding', { height: 220 }),
  modifier('.inSettings', { height: 220 }),
  modifier('.inUserProfileCard', { height: 260 }),
  before(s.absolute, s.flood, s.zIndex1, s.bgcTransparent, s.transitionBgColor, { content: '""' }),
  modifier('.hasOverlay3', before({ backgroundColor: 'rgba(0, 0, 0, 0.3)' })),
  modifier('.hasOverlay4', before({ backgroundColor: 'rgba(0, 0, 0, 0.4)' })),
  modifier('.hasOverlay5', before({ backgroundColor: 'rgba(0, 0, 0, 0.5)' })),
  modifier('.hasOverlay6', before({ backgroundColor: 'rgba(0, 0, 0, 0.6)' })),
  select('.no-touch &.isLink:hover::before', { backgroundColor: 'rgba(0, 0, 0, 0.4)' }),
  media(s.maxBreak2, modifier('.inHeroProfile', { height: 220 })),
  media(s.minBreak2, modifier('.inSettings', { minHeight: 330 })),
  media(s.minBreak2, modifier('.inUserProfileCard:not(.isMiniProfileCard)', { minHeight: 540 })),
)

const editorialVideoStyle = css(
  {
    width: '100%',
    height: '100%',
    objectFit: 'cover',
    minWidth: '100%',
    minHeight: '100%',
  },
)

export default class BackgroundImage extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    onClick: PropTypes.func,
    to: PropTypes.string,
  }

  static defaultProps = {
    className: null,
    onClick: null,
    to: null,
  }

  componentWillMount() {
    this.state = {
      status: STATUS.REQUEST,
    }
  }

  componentWillReceiveProps(nextProps) {
    const thisSource = getSource(this.props)
    const nextSource = getSource(nextProps)
    if (thisSource !== nextSource) {
      this.setState({
        status: nextSource ? STATUS.REQUEST : STATUS.PENDING,
      })
    }
  }

  onLoadSuccess = () => {
    this.setState({ status: STATUS.SUCCESS })
  }

  onLoadFailure = () => {
    this.setState({ status: STATUS.FAILURE })
  }

  render() {
    const { className, onClick, to } = this.props
    const { status } = this.state
    const classList = classNames(`BackgroundImage ${baseStyle}`, status, className)
    const src = getSource(this.props)
    const isVideo = !!src && src.substr(-3) === 'mp4'
    const imageAssetProps = {
      isBackgroundImage: true,
      onLoadFailure: this.onLoadFailure,
      onLoadSuccess: this.onLoadSuccess,
      src,
    }
    const videoAssetProps = {
      src,
    }

    if (isVideo) {
      return (<Link className={classNames(classList, 'isLink')} onClick={onClick} to={to}>
        <VideoAsset {...videoAssetProps} className={editorialVideoStyle} />
      </Link>)
    }

    return to ?
      <Link className={classNames(classList, 'isLink')} onClick={onClick} to={to}>
        <ImageAsset {...imageAssetProps} />
      </Link> :

        <ImageAsset {...imageAssetProps} />

  }
}

<|endoftext|>


<commit_before>import { DateTime, Info } from 'luxon';

const defaultLocale = 'en-GB';
const firstDayOfWeek = {
  'da-DK': 1,
  'de-DE': 1,
  'fr-FR': 1,
  'en-GB': 1,
  'en-US': 0,
  'es-ES': 1,
  'fi-FI': 1,
  'it-IT': 1,
  'nl-BE': 1,
  'pt-PT': 1,
  'pl-PL': 1,
  'sv-SE': 1,
};

export const formatDay = (day, locale = defaultLocale) =>
  DateTime.fromJSDate(day)
    .setLocale(locale)
    .toLocaleString(DateTime.DATE_HUGE);

export const formatMonthTitle = (date, locale = defaultLocale) =>
  DateTime.fromJSDate(date)
    .setLocale(locale)
    .toLocaleString({ month: 'long', year: 'numeric' });

export const formatWeekdayShort = (dayOfWeekNumber, locale = defaultLocale) =>
  Info.weekdays('short', { locale })[dayOfWeekNumber];

export const formatWeekdayLong = (dayOfWeekNumber, locale = defaultLocale) =>
  Info.weekdays('long', { locale })[dayOfWeekNumber];

export const getFirstDayOfWeek = (locale = defaultLocale) => {
  return firstDayOfWeek[locale];
};

export const getMonths = (locale = defaultLocale) => Info.months('long', { locale });

export const formatDate = (date, locale = defaultLocale, format = DateTime.DATE_SHORT) =>
  DateTime.fromJSDate(date)
    .setLocale(locale)
    .toLocaleString(format);

export const parseDate = (string, format = DateTime.DATE_SHORT, locale = defaultLocale) =>
  DateTime.fromFormat(string, format, { locale }).toJSDate();

export default {
  getFirstDayOfWeek,
  formatDate,
  formatDay,
  formatMonthTitle,
  formatWeekdayShort,
  formatWeekdayLong,
  getMonths,
  parseDate,
};
<commit_msg>:bug: the weekdays array starts on monday, so we need to calculate the correct index, because sunday should be 0.<commit_after>import { DateTime, Info } from 'luxon';

const defaultLocale = 'en-GB';
const firstDayOfWeek = {
  'da-DK': 1,
  'de-DE': 1,
  'fr-FR': 1,
  'en-GB': 1,
  'en-US': 0,
  'es-ES': 1,
  'fi-FI': 1,
  'it-IT': 1,
  'nl-BE': 1,
  'pt-PT': 1,
  'pl-PL': 1,
  'sv-SE': 1,
};

export const formatDay = (day, locale = defaultLocale) =>
  DateTime.fromJSDate(day)
    .setLocale(locale)
    .toLocaleString(DateTime.DATE_HUGE);

export const formatMonthTitle = (date, locale = defaultLocale) =>
  DateTime.fromJSDate(date)
    .setLocale(locale)
    .toLocaleString({ month: 'long', year: 'numeric' });

export const formatWeekdayShort = (dayOfWeekNumber, locale = defaultLocale) => {
  const dayIndex = (7 + dayOfWeekNumber - getFirstDayOfWeek(locale)) % 7;
  return Info.weekdays('short', { locale })[dayIndex];
};

export const formatWeekdayLong = (dayOfWeekNumber, locale = defaultLocale) => {
  const dayIndex = (7 + dayOfWeekNumber - 1) % 7;
  return Info.weekdays('long', { locale })[dayIndex];
};

export const getFirstDayOfWeek = (locale = defaultLocale) => {
  return firstDayOfWeek[locale];
};

export const getMonths = (locale = defaultLocale) => Info.months('long', { locale });

export const formatDate = (date, locale = defaultLocale, format = DateTime.DATE_SHORT) =>
  DateTime.fromJSDate(date)
    .setLocale(locale)
    .toLocaleString(format);

export const parseDate = (string, format = DateTime.DATE_SHORT, locale = defaultLocale) =>
  DateTime.fromFormat(string, format, { locale }).toJSDate();

export default {
  getFirstDayOfWeek,
  formatDate,
  formatDay,
  formatMonthTitle,
  formatWeekdayShort,
  formatWeekdayLong,
  getMonths,
  parseDate,
};
<|endoftext|>


<commit_before>/* global AFRAME, NAF, THREE */
var naf = require('../NafIndex');

AFRAME.registerComponent('networked-video-source', {

  schema: {
  },

  dependencies: ['material'],

  init: function () {
    this.videoTexture = null;
    this.video = null;
    this.stream = null;

    this._setMediaStream = this._setMediaStream.bind(this);

    NAF.utils.getNetworkedEntity(this.el).then((networkedEl) => {
      const ownerId = networkedEl.components.networked.data.owner;

      if (ownerId) {
        NAF.connection.adapter.getMediaStream(ownerId, "video")
          .then(this._setMediaStream)
          .catch((e) => naf.log.error(`Error getting media stream for ${ownerId}`, e));
      } else {
        // Correctly configured local entity, perhaps do something here for enabling debug audio loopback
      }
    });
  },

  _setMediaStream(newStream) {

    if(!this.video) {
      this.setupVideo();
    }

    if(newStream != this.stream) {
      if (this.stream) {
        this._clearMediaStream();
      }

      if (newStream) {
        this.video.srcObject = newStream;

        var playResult = this.video.play();
        if (playResult instanceof Promise) {
          playResult.catch((e) => naf.log.error(`Error play video stream`, e));
        }

        const mesh = this.el.getObject3D('mesh');
        mesh.material.map = new THREE.VideoTexture(this.video);
        mesh.material.needsUpdate = true;
      }

      this.stream = newStream;
    }
  },

  _clearMediaStream() {
    if (this.video) {
      this.video.srcObject = null;
      this.video = null;
      this.stream = null;
    }
  },

  remove: function() {
    if (!this.videoTexture) return;

    if (this.stream) {
        this._clearMediaStream();
    }
  },

  setupVideo: function() {
    var el = this.el;

    if (!this.video) {
      var video = document.createElement('video');
      video.setAttribute('autoplay', true);
      video.setAttribute('playsinline', true);
      video.setAttribute('muted', true);
    }

    this.video = video;
  }
});<commit_msg>improve networked-video-source component videoTexture cleanup and reuse video<commit_after>/* global AFRAME, NAF, THREE */
var naf = require('../NafIndex');

AFRAME.registerComponent('networked-video-source', {

  schema: {
  },

  dependencies: ['material'],

  init: function () {
    this.videoTexture = null;
    this.video = null;
    this.stream = null;

    this._setMediaStream = this._setMediaStream.bind(this);

    NAF.utils.getNetworkedEntity(this.el).then((networkedEl) => {
      const ownerId = networkedEl.components.networked.data.owner;

      if (ownerId) {
        NAF.connection.adapter.getMediaStream(ownerId, "video")
          .then(this._setMediaStream)
          .catch((e) => naf.log.error(`Error getting media stream for ${ownerId}`, e));
      } else {
        // Correctly configured local entity, perhaps do something here for enabling debug audio loopback
      }
    });
  },

  _setMediaStream(newStream) {

    if(!this.video) {
      this.setupVideo();
    }

    if(newStream != this.stream) {
      if (this.stream) {
        this._clearMediaStream();
      }

      if (newStream) {
        this.video.srcObject = newStream;

        const playResult = this.video.play();
        if (playResult instanceof Promise) {
          playResult.catch((e) => naf.log.error(`Error play video stream`, e));
        }

        if (this.videoTexture) {
          this.videoTexture.dispose();
        }

        this.videoTexture = new THREE.VideoTexture(this.video);

        const mesh = this.el.getObject3D('mesh');
        mesh.material.map = this.videoTexture;
        mesh.material.needsUpdate = true;
      }

      this.stream = newStream;
    }
  },

  _clearMediaStream() {

    this.stream = null;

    if (this.videoTexture) {

      if (this.videoTexture.image instanceof HTMLVideoElement) {
        // Note: this.videoTexture.image === this.video
        const video = this.videoTexture.image;
        video.pause();
        video.srcObject = null;
        video.load();
      }

      this.videoTexture.dispose();
      this.videoTexture = null;
    }
  },

  remove: function() {
      this._clearMediaStream();
  },

  setupVideo: function() {
    if (!this.video) {
      const video = document.createElement('video');
      video.setAttribute('autoplay', true);
      video.setAttribute('playsinline', true);
      video.setAttribute('muted', true);
      this.video = video;
    }
  }
});<|endoftext|>