<commit_before>import R from 'ramda';
import { DOM } from './util';

const ENTER = 13;          // (enter)
const SHIFT_KEY = 16;      // (shift)
const SQUARE_KEY = 83;     // (s)
const MARKER_KEY = 77;     // (m)
const POLYGON_KEY = 80;    // (p)
const ESCAPE_KEY = 27;  // (esc)
const LINESTRING_KEY = 76; // (l)

export default function(ctx) {
  var isMouseDown = false;
  var dragStartPoint = null;
  var isShiftDown = false;
  var newFeature = null;
  var activeVertex = null;
  var activeDrawId = null;

  var cleanupNewFeatureIfNeeded = function() {
     if (newFeature.created) {
        ctx._handleDrawFinished();
        newFeature = null;
      }
      else if (newFeature.toRemove) {
        ctx._destroy();
        newFeature = null;
      }
  };

  var api = {
    setNewFeature: function(value) {
      newFeature = value;
    },
    destroyNewFeature: function() {
      if(newFeature) {
        newFeature.toRemove = true;
        newFeature = null;
        ctx._destroy();
      }
    },
    onMouseDown: function(e) {
      isMouseDown = true;
      if (newFeature) {
        newFeature.onMouseDown(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
      else {
        dragStartPoint = DOM.mousePos(e, ctx._map._container);

        var drawIds = ctx._store.getSelectedIds();
        if (newFeature === null && drawIds.length > 0) {
          var coords = DOM.mousePos(e, ctx._map._container);
          ctx._map.featuresAt([coords.x, coords.y], { radius: 20 }, (err, features) => {
            if(err) throw err;
            features = features.filter(feature => drawIds.indexOf(feature.properties.drawId || feature.properties.parent) > -1);
            if (features.length > 0) {
              var tempVertex = R.find(feat => feat.properties.meta === 'midpoint')(features);
              activeVertex = R.find(feat => feat.properties.meta === 'vertex')(features) || null;

              if(tempVertex && activeVertex === null) {
                ctx._store.get(tempVertex.properties.parent)
                  .addVertex([tempVertex.properties.lng, tempVertex.properties.lat], tempVertex.properties.index);
                activeVertex = tempVertex;
                ctx._store._render();
              }

              if (activeVertex === null) {
                activeDrawId = R.find(feat => feat.properties.drawId)(features).properties.drawId;
              }
            }
          });
        }
      }
    },
    onMouseUp: function(e) {
      isMouseDown = false;
      if (newFeature) {
        newFeature.onMouseUp(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
      else {

        var end = DOM.mousePos(e, ctx._map.getContainer());
        if(isShiftDown && activeVertex === null && activeDrawId === null && dragStartPoint.x !== end.x && dragStartPoint.y !== end.y) {
          ctx._store.selectFeaturesIn(dragStartPoint, end);
        }

        if (activeVertex) {
          ctx._store.get(activeVertex.properties.parent).movingVertex = false;
        }

        activeVertex = null;

        if (activeDrawId) {
          ctx._store.get(activeDrawId).translating = false;
        }

        activeDrawId = null;
      }

      dragStartPoint = null;
    },
    onMouseMove: function(e) {
      if(isMouseDown) {
        return api.onMouseDrag(e);
      }
      else if (newFeature) {
        e.originalEvent.stopPropagation();
        newFeature.onMouseMove(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
    },
    onMouseDrag: function(e) {
      var curr = DOM.mousePos(e.originalEvent, ctx._map.getContainer());
      if (activeVertex) {
        e.originalEvent.stopPropagation();
        ctx._store.get(activeVertex.properties.parent)
          .moveVertex(dragStartPoint, curr, activeVertex.properties.index);
        ctx._store._render();
      }
      else if (activeDrawId) {
        e.originalEvent.stopPropagation();
        ctx._store.get(activeDrawId).translate(dragStartPoint, curr);
        ctx._store._render();
      }
    },
    onClick: function(e) {
      if (newFeature) {
        newFeature.onClick(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
      else {
        ctx._map.featuresAt(e.point, {
          radius: 10,
          layer: [ 'gl-draw-polygon', 'gl-draw-line', 'gl-draw-point',
          'gl-draw-selected-polygon', 'gl-draw-selected-line', 'gl-draw-selected-point' ]
        }, (err, results) => {
          if (err) {
            throw err;
          }

          var features = [];
          var vertices = [];

          results.forEach(result => {
            var featureId = result.properties.drawId || result.properties.parent;
            var feature = ctx._store.get(featureId);

            if (feature && result.properties.meta === 'vertex') {
              vertices.push([feature, result.properties.index]);
            }
            else if (feature
              && result.properties.drawId
              && feature.getOptions().permanent !== true
              && !feature.selected) {
              features.push(feature);
            }
          });

          if(features.length > 0) {
            if(isShiftDown === false) {
              ctx._handleDrawFinished();
            }
            ctx.select(features[0].drawId);
          }
          else if(vertices.length > 0) {
            if (vertices[0][0].removeVertex(vertices[0][1])) {
              ctx._store.delete(vertices[0][0].drawId);
            }
            ctx._store._render();
          }
          else {
            ctx._handleDrawFinished();
          }
        });
      }
    },
    onDoubleClick: function(e) {
      if (newFeature) {
        newFeature.onDoubleClick(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
    },
    onKeyUp: function(e) {
      if (e.keyCode === SHIFT_KEY) {
        isShiftDown = false;
      }

      if (newFeature === null) {
        switch (e.keyCode) {
          case LINESTRING_KEY:
            ctx.startDrawing(ctx.types.LINE);
            break;
          case MARKER_KEY:
            ctx.startDrawing(ctx.types.POINT);
            break;
          case POLYGON_KEY:
            ctx.startDrawing(ctx.types.POLYGON);
            break;
          case SQUARE_KEY:
            ctx.startDrawing(ctx.types.SQUARE);
            break;
          case ESCAPE_KEY:
            ctx._store.revertSelected();
            e.preventDefault();
            break;
          case ENTER:
            ctx._handleDrawFinished();
            break;
        }
      }
      else {
        switch(e.keyCode) {
          case ENTER:
            newFeature.onStopDrawing(e);
            cleanupNewFeatureIfNeeded();
            break;
          case ESCAPE_KEY:
            newFeature.toRemove = true;
            ctx._destroy();
            newFeature = null;
            break;
        }
      }
    },
    onKeyDown: function(e) {
      if (e.keyCode === SHIFT_KEY) {
        isShiftDown = true;
      }
    }
  };

  return api;
}
<commit_msg>Fix for issue when you drag a shape and instead of a shape map is dragged<commit_after>import R from 'ramda';
import { DOM } from './util';

const ENTER = 13;          // (enter)
const SHIFT_KEY = 16;      // (shift)
const SQUARE_KEY = 83;     // (s)
const MARKER_KEY = 77;     // (m)
const POLYGON_KEY = 80;    // (p)
const ESCAPE_KEY = 27;  // (esc)
const LINESTRING_KEY = 76; // (l)

export default function(ctx) {
  var isMouseDown = false;
  var dragStartPoint = null;
  var isShiftDown = false;
  var newFeature = null;
  var activeVertex = null;
  var activeDrawId = null;
  var featuresAtProgress = false;

  var cleanupNewFeatureIfNeeded = function() {
     if (newFeature.created) {
        ctx._handleDrawFinished();
        newFeature = null;
      }
      else if (newFeature.toRemove) {
        ctx._destroy();
        newFeature = null;
      }
  };

  var api = {
    setNewFeature: function(value) {
      newFeature = value;
    },
    destroyNewFeature: function() {
      if(newFeature) {
        newFeature.toRemove = true;
        newFeature = null;
        ctx._destroy();
      }
    },
    onMouseDown: function(e) {
      isMouseDown = true;
      if (newFeature) {
        newFeature.onMouseDown(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
      else {
        dragStartPoint = DOM.mousePos(e, ctx._map._container);

        var drawIds = ctx._store.getSelectedIds();
        if (newFeature === null && drawIds.length > 0) {
          var coords = DOM.mousePos(e, ctx._map._container);
          featuresAtProgress = true;
          ctx._map.featuresAt([coords.x, coords.y], { radius: 20 }, (err, features) => {
            if(err) throw err;
            features = features.filter(feature => drawIds.indexOf(feature.properties.drawId || feature.properties.parent) > -1);
            if (features.length > 0) {
              var tempVertex = R.find(feat => feat.properties.meta === 'midpoint')(features);
              activeVertex = R.find(feat => feat.properties.meta === 'vertex')(features) || null;

              if(tempVertex && activeVertex === null) {
                ctx._store.get(tempVertex.properties.parent)
                  .addVertex([tempVertex.properties.lng, tempVertex.properties.lat], tempVertex.properties.index);
                activeVertex = tempVertex;
                ctx._store._render();
              }

              if (activeVertex === null) {
                activeDrawId = R.find(feat => feat.properties.drawId)(features).properties.drawId;
              }
            }
            featuresAtProgress = false;
          });
        }
      }
    },
    onMouseUp: function(e) {
      isMouseDown = false;
      if (newFeature) {
        newFeature.onMouseUp(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
      else {

        var end = DOM.mousePos(e, ctx._map.getContainer());
        if(isShiftDown && activeVertex === null && activeDrawId === null && dragStartPoint.x !== end.x && dragStartPoint.y !== end.y) {
          ctx._store.selectFeaturesIn(dragStartPoint, end);
        }

        if (activeVertex) {
          ctx._store.get(activeVertex.properties.parent).movingVertex = false;
        }

        activeVertex = null;

        if (activeDrawId) {
          ctx._store.get(activeDrawId).translating = false;
        }

        activeDrawId = null;
      }

      dragStartPoint = null;
    },
    onMouseMove: function(e) {
      if (isMouseDown) {
        featuresAtProgress && e.originalEvent.stopPropagation();
        return api.onMouseDrag(e);
      }
      else if (newFeature) {
        e.originalEvent.stopPropagation();
        newFeature.onMouseMove(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
    },
    onMouseDrag: function(e) {
      var curr = DOM.mousePos(e.originalEvent, ctx._map.getContainer());
      if (activeVertex) {
        e.originalEvent.stopPropagation();
        ctx._store.get(activeVertex.properties.parent)
          .moveVertex(dragStartPoint, curr, activeVertex.properties.index);
        ctx._store._render();
      }
      else if (activeDrawId) {
        e.originalEvent.stopPropagation();
        ctx._store.get(activeDrawId).translate(dragStartPoint, curr);
        ctx._store._render();
      }
    },
    onClick: function(e) {
      if (newFeature) {
        newFeature.onClick(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
      else {
        ctx._map.featuresAt(e.point, {
          radius: 10,
          layer: [ 'gl-draw-polygon', 'gl-draw-line', 'gl-draw-point',
          'gl-draw-selected-polygon', 'gl-draw-selected-line', 'gl-draw-selected-point' ]
        }, (err, results) => {
          if (err) {
            throw err;
          }

          var features = [];
          var vertices = [];

          results.forEach(result => {
            var featureId = result.properties.drawId || result.properties.parent;
            var feature = ctx._store.get(featureId);

            if (feature && result.properties.meta === 'vertex') {
              vertices.push([feature, result.properties.index]);
            }
            else if (feature
              && result.properties.drawId
              && feature.getOptions().permanent !== true
              && !feature.selected) {
              features.push(feature);
            }
          });

          if(features.length > 0) {
            if(isShiftDown === false) {
              ctx._handleDrawFinished();
            }
            ctx.select(features[0].drawId);
          }
          else if(vertices.length > 0) {
            if (vertices[0][0].removeVertex(vertices[0][1])) {
              ctx._store.delete(vertices[0][0].drawId);
            }
            ctx._store._render();
          }
          else {
            ctx._handleDrawFinished();
          }
        });
      }
    },
    onDoubleClick: function(e) {
      if (newFeature) {
        newFeature.onDoubleClick(e);
        ctx._store._render();
        cleanupNewFeatureIfNeeded();
      }
    },
    onKeyUp: function(e) {
      if (e.keyCode === SHIFT_KEY) {
        isShiftDown = false;
      }

      if (newFeature === null) {
        switch (e.keyCode) {
          case LINESTRING_KEY:
            ctx.startDrawing(ctx.types.LINE);
            break;
          case MARKER_KEY:
            ctx.startDrawing(ctx.types.POINT);
            break;
          case POLYGON_KEY:
            ctx.startDrawing(ctx.types.POLYGON);
            break;
          case SQUARE_KEY:
            ctx.startDrawing(ctx.types.SQUARE);
            break;
          case ESCAPE_KEY:
            ctx._store.revertSelected();
            e.preventDefault();
            break;
          case ENTER:
            ctx._handleDrawFinished();
            break;
        }
      }
      else {
        switch(e.keyCode) {
          case ENTER:
            newFeature.onStopDrawing(e);
            cleanupNewFeatureIfNeeded();
            break;
          case ESCAPE_KEY:
            newFeature.toRemove = true;
            ctx._destroy();
            newFeature = null;
            break;
        }
      }
    },
    onKeyDown: function(e) {
      if (e.keyCode === SHIFT_KEY) {
        isShiftDown = true;
      }
    }
  };

  return api;
}
<|endoftext|>


<commit_before>'use strict';
var util = require('util'),
path = require('path'),
yeoman = require('yeoman-generator'),
childProcess = require('child_process'),
chalk = require('chalk'),
_s = require('underscore.string'),
scriptBase = require('../script-base');

var exec = childProcess.exec;
var spawn = childProcess.spawn;

var OpenshiftGenerator = module.exports = function OpenshiftGenerator() {
    yeoman.generators.Base.apply(this, arguments);
    console.log(chalk.bold('Openshift configuration is starting'));
    this.env.options.appPath = this.config.get('appPath') || 'src/main/webapp';
    this.baseName = this.config.get('baseName');
    this.packageName = this.config.get('packageName');
    this.packageFolder = this.config.get('packageFolder');
    this.javaVersion = this.config.get('javaVersion');
    this.hibernateCache = this.config.get('hibernateCache');
    this.databaseType = this.config.get('databaseType');
    this.angularAppName = _s.camelize(_s.slugify(this.baseName)) + 'App';
};

util.inherits(OpenshiftGenerator, yeoman.generators.Base);
util.inherits(OpenshiftGenerator, scriptBase);

OpenshiftGenerator.prototype.askForName = function askForName() {
    var done = this.async();

    var prompts = [{
        name: 'openShiftDeployedName',
        message: 'Name to deploy as:',
        default: this.baseName
    }];

    this.prompt(prompts, function (props) {
        this.openShiftDeployedName = this._.slugify(props.openShiftDeployedName).split('-').join('');
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.checkInstallation = function checkInstallation() {
    if(this.abort) return;
    var done = this.async();

    exec('rhc --version', function (err) {
        if (err) {
            this.log.error('Openshift\'s rhc command line interface is not available. ' +
            'You can install it via RubyGems with: gem install rhc');
            this.abort = true;
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.dirInit = function dirInit() {
    if(this.abort) return;
    var done = this.async();

    this.log(chalk.bold('Initializing deployment repo'));
    this.mkdir('deploy/openshift');
    done();
};

OpenshiftGenerator.prototype.gitRemoteCheck = function gitRemoteCheck() {
    this.openshift_remote_exists = false;
    if(this.abort || typeof this.dist_repo_url !== 'undefined') return;
    var done = this.async();

    this.log(chalk.bold("\nChecking for an existing git remote named '"+'openshift'+"'..."));
    exec('git remote -v', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        var lines = stdout.split('\n');
        var dist_repo = '';
        if (err && stderr.search('DL is deprecated') === -1) {
            this.log.error(err);
        } else {
            var repo_url_finder = new RegExp('openshift'+"[  ]*");
            lines.forEach(function(line) {
                if(line.search(repo_url_finder) === 0 && dist_repo === '') {
                    var dist_repo_detailed = line.slice(line.match(repo_url_finder)[0].length);
                    dist_repo = dist_repo_detailed.slice(0, dist_repo_detailed.length - 7);
                }
            });
            if (dist_repo !== ''){
                console.log("Found an existing git remote for this app: "+dist_repo);
                this.dist_repo_url = dist_repo;
                this.openshift_remote_exists = true;
            } else {
                console.log('No existing remote found.');
            }
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.rhcAppShow = function rhcAppShow() {
    if(this.abort || typeof this.dist_repo_url !== 'undefined') return;
    var done = this.async();

    this.log(chalk.bold("\nChecking for an existing Openshift hosting environment..."));
    var child = exec('rhc app show '+this.openShiftDeployedName+' --noprompt', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        var lines = stdout.split('\n');
        var dist_repo = '';
        // Unauthenticated
        if (stdout.search('Not authenticated') >= 0 || stdout.search('Invalid characters found in login') >= 0) {
            this.log.error('Error: Not authenticated. Run "rhc setup" to login to your Openshift account and try again.');
            this.abort = true;
        }
        // No remote found
        else if (stderr.search('not found.') < 0) {
            console.log('No existing app found.');
        }
        // Error
        else if (err && stderr.search('DL is deprecated') === -1) {
            this.log.error(err);
        } else {   // Remote found
            this.log(stdout);
            var repo_url_finder = / *Git URL: */;
            lines.forEach(function(line) {
                if(line.search(repo_url_finder) === 0) {
                    dist_repo = line.slice(line.match(repo_url_finder)[0].length);
                    console.log("Found an existing git remote for this app: "+dist_repo);
                }
            });
            if (dist_repo !== '') this.dist_repo_url = dist_repo;
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.rhcAppCreate = function rhcAppCreate() {
    if(this.abort || typeof this.dist_repo_url !== 'undefined') return;
    var done = this.async();

    this.log(chalk.bold("\nCreating your Openshift hosting environment, this may take a couple minutes..."));
    var child = exec('rhc app create ' + this.openShiftDeployedName + ' diy-0.1 mysql-5.5 ', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        var lines = stdout.split('\n');
        this.log(stdout);
        if (stdout.search('Not authenticated') >= 0 || stdout.search('Invalid characters found in login') >= 0) {
            this.log.error('Error: Not authenticated. Run "rhc setup" to login to your Openshift account and try again.');
            this.abort = true;
        } else if (err && stderr.search('DL is deprecated') === -1) {
            this.log.error(err);
        } else {
            var dist_repo = '';
            var repo_url_finder = / *Git remote: */;
            lines.forEach(function(line) {
                if(line.search(repo_url_finder) === 0) {
                    dist_repo = line.slice(line.match(repo_url_finder)[0].length);
                }
            });

            if (dist_repo !== '') this.dist_repo_url = dist_repo;
            if(this.dist_repo_url !== undefined) {
                this.log("New remote git repo at: "+this.dist_repo_url);
            }
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.gitRemoteAdd = function gitRemoteAdd() {
    if(this.abort || typeof this.dist_repo_url === 'undefined' || this.openshift_remote_exists) return;
    var done = this.async();
    this.log(chalk.bold("\nAdding remote repo url: "+this.dist_repo_url));

    var child = exec('git remote add '+'openshift'+' '+this.dist_repo_url, { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        if (err) {
            this.log.error(err);
        } else {
            this.openshift_remote_exists = true;
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.copyOpenshiftFiles = function copyOpenshiftFiles() {
    if(this.abort || !this.openshift_remote_exists ) return;
    var done = this.async();
    this.log(chalk.bold('\nCreating Openshift deployment files'));

    this.copy('openshift/action_hooks/build', 'deploy/openshift/.openshift/action_hooks/build');
    this.copy('openshift/action_hooks/start', 'deploy/openshift/.openshift/action_hooks/start');
    this.copy('openshift/action_hooks/stop', 'deploy/openshift/.openshift/action_hooks/stop');
    this.conflicter.resolve(function (err) {
        done();
    });
};

OpenshiftGenerator.prototype.productionBuild = function productionBuild() {
    if(this.abort || !this.openshift_remote_exists ) return;
    var done = this.async();

    this.log(chalk.bold('\nBuilding deploy/openshift folder, please wait...'));
    var child = exec('grunt buildOpenshift', function (err, stdout) {
        if (err) {
            this.log.error(err);
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.gitCommit = function gitInit() {
    if(this.abort || !this.openshift_remote_exists ) return;
    var done = this.async();

    this.log(chalk.bold('\nAdding files for initial commit'));
    var child = exec('git add -A && git commit -m "Initial commit"', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        if (stdout.search('nothing to commit') >= 0) {
            this.log('Re-pushing the existing "deploy/openshift" build...');
        } else if (err) {
            this.log.error(err);
        } else {
            this.log(chalk.green('Done, without errors.'));
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.gitForcePush = function gitForcePush() {
    if (this.abort || !this.openshift_remote_exists) return;
    var done = this.async();
    this.log(chalk.bold("\nUploading your initial application code.\n This may take " + chalk.cyan('several minutes') + " depending on your connection speed..."));

    var push = spawn('git', ['push', '-f', 'openshift', 'master'], {cwd: 'deploy/openshift'});
    var error = null;

    push.stderr.on('data', function (data) {
        var output = data.toString();
        this.log.error(output);
    }.bind(this));

    push.stdout.on('data', function (data) {
        var output = data.toString();
        this.log.stdin(output);
    }.bind(this));

    push.on('exit', function (code) {
        if (code !== 0) {
            this.abort = true;
            return done();
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.restartApp = function restartApp() {
    if(this.abort || !this.openshift_remote_exists ) return;
    this.log(chalk.bold("\nRestarting your Openshift app.\n"));

    var child = exec('rhc app restart -a ' + this.openShiftDeployedName, function(err, stdout, stderr) {

        var host_url = '';
        var hasWarning = false;
        var before_hostname = this.dist_repo_url.indexOf('@') + 1;
        var after_hostname = this.dist_repo_url.length - ( 'openshift'.length + 12 );
        host_url = 'http://' + this.dist_repo_url.slice(before_hostname, after_hostname) + 'com';

        this.log(chalk.green('\nYour app should now be live at \n\t' + chalk.bold(host_url)));
        if(hasWarning) {
            this.log(chalk.green('\nYou may need to address the issues mentioned above and restart the server for the app to work correctly \n\t' +
            'rhc app-restart -a ' + this.openShiftDeployedName));
        }
        this.log(chalk.yellow('After application modification, re-deploy it with\n\t' + chalk.bold('grunt deployOpenshift') +
        ' and then do a \n\t' + chalk.bold('git push') + ' on your Openshift repository.'));
    }.bind(this));
};
<commit_msg>Rename method<commit_after>'use strict';
var util = require('util'),
path = require('path'),
yeoman = require('yeoman-generator'),
childProcess = require('child_process'),
chalk = require('chalk'),
_s = require('underscore.string'),
scriptBase = require('../script-base');

var exec = childProcess.exec;
var spawn = childProcess.spawn;

var OpenshiftGenerator = module.exports = function OpenshiftGenerator() {
    yeoman.generators.Base.apply(this, arguments);
    console.log(chalk.bold('Openshift configuration is starting'));
    this.env.options.appPath = this.config.get('appPath') || 'src/main/webapp';
    this.baseName = this.config.get('baseName');
    this.packageName = this.config.get('packageName');
    this.packageFolder = this.config.get('packageFolder');
    this.javaVersion = this.config.get('javaVersion');
    this.hibernateCache = this.config.get('hibernateCache');
    this.databaseType = this.config.get('databaseType');
    this.angularAppName = _s.camelize(_s.slugify(this.baseName)) + 'App';
};

util.inherits(OpenshiftGenerator, yeoman.generators.Base);
util.inherits(OpenshiftGenerator, scriptBase);

OpenshiftGenerator.prototype.askForName = function askForName() {
    var done = this.async();

    var prompts = [{
        name: 'openShiftDeployedName',
        message: 'Name to deploy as:',
        default: this.baseName
    }];

    this.prompt(prompts, function (props) {
        this.openShiftDeployedName = this._.slugify(props.openShiftDeployedName).split('-').join('');
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.checkInstallation = function checkInstallation() {
    if(this.abort) return;
    var done = this.async();

    exec('rhc --version', function (err) {
        if (err) {
            this.log.error('Openshift\'s rhc command line interface is not available. ' +
            'You can install it via RubyGems with: gem install rhc');
            this.abort = true;
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.dirInit = function dirInit() {
    if(this.abort) return;
    var done = this.async();

    this.log(chalk.bold('Initializing deployment repo'));
    this.mkdir('deploy/openshift');
    done();
};

OpenshiftGenerator.prototype.gitRemoteCheck = function gitRemoteCheck() {
    this.openshift_remote_exists = false;
    if(this.abort || typeof this.dist_repo_url !== 'undefined') return;
    var done = this.async();

    this.log(chalk.bold("\nChecking for an existing git remote named '"+'openshift'+"'..."));
    exec('git remote -v', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        var lines = stdout.split('\n');
        var dist_repo = '';
        if (err && stderr.search('DL is deprecated') === -1) {
            this.log.error(err);
        } else {
            var repo_url_finder = new RegExp('openshift'+"[  ]*");
            lines.forEach(function(line) {
                if(line.search(repo_url_finder) === 0 && dist_repo === '') {
                    var dist_repo_detailed = line.slice(line.match(repo_url_finder)[0].length);
                    dist_repo = dist_repo_detailed.slice(0, dist_repo_detailed.length - 7);
                }
            });
            if (dist_repo !== ''){
                console.log("Found an existing git remote for this app: "+dist_repo);
                this.dist_repo_url = dist_repo;
                this.openshift_remote_exists = true;
            } else {
                console.log('No existing remote found.');
            }
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.rhcAppShow = function rhcAppShow() {
    if(this.abort || typeof this.dist_repo_url !== 'undefined') return;
    var done = this.async();

    this.log(chalk.bold("\nChecking for an existing Openshift hosting environment..."));
    var child = exec('rhc app show '+this.openShiftDeployedName+' --noprompt', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        var lines = stdout.split('\n');
        var dist_repo = '';
        // Unauthenticated
        if (stdout.search('Not authenticated') >= 0 || stdout.search('Invalid characters found in login') >= 0) {
            this.log.error('Error: Not authenticated. Run "rhc setup" to login to your Openshift account and try again.');
            this.abort = true;
        }
        // No remote found
        else if (stderr.search('not found.') < 0) {
            console.log('No existing app found.');
        }
        // Error
        else if (err && stderr.search('DL is deprecated') === -1) {
            this.log.error(err);
        } else {   // Remote found
            this.log(stdout);
            var repo_url_finder = / *Git URL: */;
            lines.forEach(function(line) {
                if(line.search(repo_url_finder) === 0) {
                    dist_repo = line.slice(line.match(repo_url_finder)[0].length);
                    console.log("Found an existing git remote for this app: "+dist_repo);
                }
            });
            if (dist_repo !== '') this.dist_repo_url = dist_repo;
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.rhcAppCreate = function rhcAppCreate() {
    if(this.abort || typeof this.dist_repo_url !== 'undefined') return;
    var done = this.async();

    this.log(chalk.bold("\nCreating your Openshift hosting environment, this may take a couple minutes..."));
    var child = exec('rhc app create ' + this.openShiftDeployedName + ' diy-0.1 mysql-5.5 ', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        var lines = stdout.split('\n');
        this.log(stdout);
        if (stdout.search('Not authenticated') >= 0 || stdout.search('Invalid characters found in login') >= 0) {
            this.log.error('Error: Not authenticated. Run "rhc setup" to login to your Openshift account and try again.');
            this.abort = true;
        } else if (err && stderr.search('DL is deprecated') === -1) {
            this.log.error(err);
        } else {
            var dist_repo = '';
            var repo_url_finder = / *Git remote: */;
            lines.forEach(function(line) {
                if(line.search(repo_url_finder) === 0) {
                    dist_repo = line.slice(line.match(repo_url_finder)[0].length);
                }
            });

            if (dist_repo !== '') this.dist_repo_url = dist_repo;
            if(this.dist_repo_url !== undefined) {
                this.log("New remote git repo at: "+this.dist_repo_url);
            }
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.gitRemoteAdd = function gitRemoteAdd() {
    if(this.abort || typeof this.dist_repo_url === 'undefined' || this.openshift_remote_exists) return;
    var done = this.async();
    this.log(chalk.bold("\nAdding remote repo url: "+this.dist_repo_url));

    var child = exec('git remote add '+'openshift'+' '+this.dist_repo_url, { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        if (err) {
            this.log.error(err);
        } else {
            this.openshift_remote_exists = true;
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.copyOpenshiftFiles = function copyOpenshiftFiles() {
    if(this.abort || !this.openshift_remote_exists ) return;
    var done = this.async();
    this.log(chalk.bold('\nCreating Openshift deployment files'));

    this.copy('openshift/action_hooks/build', 'deploy/openshift/.openshift/action_hooks/build');
    this.copy('openshift/action_hooks/start', 'deploy/openshift/.openshift/action_hooks/start');
    this.copy('openshift/action_hooks/stop', 'deploy/openshift/.openshift/action_hooks/stop');
    this.conflicter.resolve(function (err) {
        done();
    });
};

OpenshiftGenerator.prototype.productionBuild = function productionBuild() {
    if(this.abort || !this.openshift_remote_exists ) return;
    var done = this.async();

    this.log(chalk.bold('\nBuilding deploy/openshift folder, please wait...'));
    var child = exec('grunt buildOpenshift', function (err, stdout) {
        if (err) {
            this.log.error(err);
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.gitCommit = function gitCommit() {
    if(this.abort || !this.openshift_remote_exists ) return;
    var done = this.async();

    this.log(chalk.bold('\nAdding files for initial commit'));
    var child = exec('git add -A && git commit -m "Initial commit"', { cwd: 'deploy/openshift' }, function (err, stdout, stderr) {
        if (stdout.search('nothing to commit') >= 0) {
            this.log('Re-pushing the existing "deploy/openshift" build...');
        } else if (err) {
            this.log.error(err);
        } else {
            this.log(chalk.green('Done, without errors.'));
        }
        done();
    }.bind(this));

    child.stdout.on('data', function(data) {
        this.log(data.toString());
    }.bind(this));
};

OpenshiftGenerator.prototype.gitForcePush = function gitForcePush() {
    if (this.abort || !this.openshift_remote_exists) return;
    var done = this.async();
    this.log(chalk.bold("\nUploading your initial application code.\n This may take " + chalk.cyan('several minutes') + " depending on your connection speed..."));

    var push = spawn('git', ['push', '-f', 'openshift', 'master'], {cwd: 'deploy/openshift'});
    var error = null;

    push.stderr.on('data', function (data) {
        var output = data.toString();
        this.log.error(output);
    }.bind(this));

    push.stdout.on('data', function (data) {
        var output = data.toString();
        this.log.stdin(output);
    }.bind(this));

    push.on('exit', function (code) {
        if (code !== 0) {
            this.abort = true;
            return done();
        }
        done();
    }.bind(this));
};

OpenshiftGenerator.prototype.restartApp = function restartApp() {
    if(this.abort || !this.openshift_remote_exists ) return;
    this.log(chalk.bold("\nRestarting your Openshift app.\n"));

    var child = exec('rhc app restart -a ' + this.openShiftDeployedName, function(err, stdout, stderr) {

        var host_url = '';
        var hasWarning = false;
        var before_hostname = this.dist_repo_url.indexOf('@') + 1;
        var after_hostname = this.dist_repo_url.length - ( 'openshift'.length + 12 );
        host_url = 'http://' + this.dist_repo_url.slice(before_hostname, after_hostname) + 'com';

        this.log(chalk.green('\nYour app should now be live at \n\t' + chalk.bold(host_url)));
        if(hasWarning) {
            this.log(chalk.green('\nYou may need to address the issues mentioned above and restart the server for the app to work correctly \n\t' +
            'rhc app-restart -a ' + this.openShiftDeployedName));
        }
        this.log(chalk.yellow('After application modification, re-deploy it with\n\t' + chalk.bold('grunt deployOpenshift') +
        ' and then do a \n\t' + chalk.bold('git push') + ' on your Openshift repository.'));
    }.bind(this));
};
<|endoftext|>


<commit_before><commit_msg>editor<commit_after><|endoftext|>


<commit_before>fillPlayersInfos();
var HORIZONTAL = 'h';
var VERTICAL = 'v';

var playerCanvas = document.getElementById('player-canvas');
var boatsContainer = document.getElementById('boats-container');
var canvasWrapper = document.getElementById('canvas-wrapper');
var randomGenerator = document.getElementById('random');
var boatSelecters = document.getElementsByClassName('boat-selector');
var timer = document.getElementById('timer');
var otherPlayersCanvasContainer = document.getElementById('other-players-canvas');
var fireCanvasContainer = document.getElementById('fire-canvas-wrapper');
var rankList = document.getElementById('rank-list');
var phaseTitle = document.getElementById('phase-title');

var grids = [];
var shooterGrid;

var previousMouseCoords = undefined;
// images
var boatsSprite = new Image();
var grid;
boatsSprite.src = "/images/sprites.png";
socket.emit('game-init');
socket.on('init', function (playerId, playersInfos) {
    grid = new Grid(playerCanvas, "viewer");
    grids.push(grid);

    manageRankList(playersInfos);
});

function findGridByPlayerId(playerId) {
    for (var i = 0; i < grids.length; i++) {
        if (grids[i].playerId == playerId) {
            return grids[i];
        }
    }
    return null;
}

function manageRankList(playersInfos) {
    rankList.removeChildren();
    var position = 1;
    for (var i = playersInfos.length - 1; i >= 0; i--, position++) {
        var infos = playersInfos[i];
        var newLi = document.createElement('li');
        var pPosition = document.createElement('p');
        var pPseudo = document.createElement('p');
        var pPoints = document.createElement('p');

        pPosition.className = 'rank-position';
        pPosition.innerHTML = position;
        pPseudo.className = 'rank-username';
        pPseudo.innerHTML = infos.name;
        pPoints.className = 'rank-points';
        pPoints.id = infos.id + '-points';
        pPoints.innerHTML = infos.points;

        newLi.appendChild(pPosition);
        newLi.appendChild(pPseudo);
        newLi.appendChild(pPoints);
        rankList.appendChild(newLi);
    }
}

function cloneGrid(from, to) {
    var g;
    if (typeof from == 'string') {
        g = findGridByPlayerId(from);
    } else if (typeof from == 'object') {
        if (from instanceof Grid) {
            g = from;
        } else {
            console.error('Bad param');
            return;
        }
    }
    to.cells = JSON.parse(JSON.stringify(g.cells));
    to.cellsContainingBoats = JSON.parse(JSON.stringify(g.cellsContainingBoats));
    to.shootedCells = JSON.parse(JSON.stringify(g.shootedCells));
}
var selectedBoat = null;
var gameHandlers = {
    placementStage: {
        click: function (e) {
            if (selectedBoat != null) {
                var possibleToPlace = grid.canPlaceBoat(e.gridInfo.coords, selectedBoat);
                if (possibleToPlace) {
                    var boatSelector = document.getElementById(selectedBoat.id);
                    boatSelector.setAttribute('data-placed', 'true');
                    boatSelector.setAttribute('class', 'boat-selector placed');
                    grid.placeBoat(selectedBoat, e.gridInfo.coords);
                    selectedBoat = null;
                    grid.clearCanvas();
                    grid.drawPlacedBoats(boatsSprite);
                    grid.drawCoords();
                    grid.renderGrid();
                }
            } else {
                if (e.gridInfo.cell.containBoat) {
                    var boatId = e.gridInfo.cell.boatId;
                    var boatOrientation = e.gridInfo.cell.boatOrientation;
                    grid.removePlacedBoat(boatId);

                    var removedBoat = grid.getDefaultBoats(boatId);
                    selectedBoat = new Boat(removedBoat.name, removedBoat.size, boatOrientation, removedBoat.id);
                    document.getElementById(boatId).setAttribute('class', 'boat-selector');

                    grid.clearCanvas();
                    grid.drawPlacedBoats(boatsSprite);
                    grid.drawPreviewBoat(boatsSprite, selectedBoat, e.gridInfo, .5);
                    grid.renderGrid();
                }
            }
        },
        mousemove: function (e) {
            console.log(e.gridInfo);
            var pos = {
                x: e.offsetX || e.layerX,
                y: e.offsetY || e.layerY
            };
            if (!previousMouseCoords) {
                previousMouseCoords = grid.getMouseCoord(pos);
            }

            if (selectedBoat != null) {
                var currentCoords = e.gridInfo.coords;
                if (currentCoords.x >= 0 && currentCoords.y >= 0) {
                    if (previousMouseCoords.x != currentCoords.x ||
                        previousMouseCoords.y != currentCoords.y) { // still in the same place
                        var possible = grid.canPlaceBoat(e.gridInfo.coords, selectedBoat);
                        var alpha = possible ? 1 : .5;
                        grid.clearCanvas();
                        grid.drawPlacedBoats(boatsSprite);
                        grid.drawPreviewBoat(boatsSprite, selectedBoat, e.gridInfo, alpha);
                        grid.drawCoords();
                        grid.renderGrid();
                    }
                    previousMouseCoords = grid.getMouseCoord(pos);
                }
            }
        },
        contextmenu: function (e) {
            e.preventDefault();
            if (selectedBoat) {
                selectedBoat.orientation = selectedBoat.orientation == HORIZONTAL ? VERTICAL : HORIZONTAL;
                var possibleToPlace = grid.canPlaceBoat(e.gridInfo.coords, selectedBoat);
                var alpha = possibleToPlace ? 1 : .5;
                grid.clearCanvas();
                grid.drawPlacedBoats(boatsSprite);
                grid.drawPreviewBoat(boatsSprite, selectedBoat, e.gridInfo, alpha);
                grid.drawCoords();
                grid.renderGrid();
            }
        },
        selectBoat: function (e) {
            var placed = this.getAttribute('data-placed').toBool();
            if (!placed) {
                var boatSelecters = document.getElementsByClassName('boat-selector');
                var previousBoatOrientation = HORIZONTAL;

                var name = this.innerHTML,
                    size = this.getAttribute('data-boat-size'),
                    id = this.id;
                selectedBoat = new Boat(name, size, previousBoatOrientation, id);
            }
        },
        random: function (e) {
            grid.randomBoatsPosition();
            grid.drawPlacedBoats(boatsSprite);
            grid.renderGrid();
            selectedBoat = null;

            var selectors = document.getElementsByClassName('boat-selector');
            for (var i = 0; i < selectors.length; i++) {
                selectors[i].className = 'boat-selector placed';
            }

            randomGenerator.removeEventListener('click', random);
            randomGenerator.remove();
        }
    },
    battleStage: {
        otherPlayersGrid: {
            click: function (e) {
                var gridId = this.getAttribute('data-player-id');
                cloneGrid(gridId, grid);
                grid.clearCanvas();
                grid.renderGrid();
                grid.drawPlacedBoats(boatsSprite);
                grid.drawShoots(boatsSprite);
            }
        },
        shooterGrid: {
            click: function (e) {
                if (shooterGrid.highlightedSelected.x != null &&
                    shooterGrid.highlightedSelected.y != null) {
                    grids.forEach(function (g) {
                        shooterGrid.clearHighlightCell(shooterGrid.highlightedSelected);
                    });
                }

                grids.forEach(function (g) {
                    g.clearHighlightCell(shooterGrid.highlightedSelected);
                    g.highlightedSelected = e.gridInfo.coords
                    g.highlightCell(e.gridInfo.coords);
                });
                if (!shooterGrid.cellIsShooted(e.gridInfo.coords)) {
                    socket.emit('game-shoot', e.gridInfo.coords);
                }
            },
            mousemove: function (e) {
                grids.forEach(function (g) {
                    g.highlightCell(e.gridInfo.coords);
                    g.highlightedOver = e.gridInfo.coords;
                });
            }
        }
    },
    gameover: {
        replay: function (e) {
            ajax.get('/wait', function (data) {
                socket.emit('game-replay');
                socket.on('replay-init-done', function () {
                    handlers.onComplete(data);
                });
            });
        },
        quit: function (e) {
            window.location.href = '/rooms';
        }
    }
};

boatsSprite.onload = function () {
    console.log('obj');
    // PLACEMENT STAGE
    playerCanvas.addEventListener('mousemove', gameHandlers.placementStage.mousemove);
    playerCanvas.addEventListener('click', gameHandlers.placementStage.click);
    playerCanvas.addEventListener('contextmenu', gameHandlers.placementStage.contextmenu);

    for (var i = 0; i < boatSelecters.length; i++) {
        boatSelecters[i].addEventListener('click', gameHandlers.placementStage.selectBoat);
    }
    randomGenerator.addEventListener('click', gameHandlers.placementStage.random);
}

window.addEventListener('resize', function (e) {
    grids.forEach(function (g) {
        var newWidth = parseInt(getComputedStyle(g.container).width);
        g.rescaleCanvas(newWidth, boatsSprite);
    });
});

socket.on('game-timer-update', function (timeRemaining) {
    timer.innerHTML = timeRemaining + 's';
});
socket.on('game-check-grid', function () {
    if (!grid.allBoatsArePlaced()) {
        gameHandlers.placementStage.random();
        grid.drawPlacedBoats(boatsSprite);
    }
    playerCanvas.removeEventListener('click', gameHandlers.placementStage.click);
    playerCanvas.removeEventListener('mousemove', gameHandlers.placementStage.mousemove);
    playerCanvas.removeEventListener('contextmenu', gameHandlers.placementStage.contextmenu);

    socket.emit('game-set-ready', grid.cells);
});
socket.on('game-init-players-grids', function (players) {
    document.getElementById('boats-container').addClass('hidden')
    document.getElementById('other-players-canvas').removeClass('hidden');
    /*    canvasWrapper.removeClass('placement-phase');
        canvasWrapper.addClass('fire-phase');*/
    phaseTitle.innerHTML = 'Phases de tir';
    players.forEach(function (player) {
        var div = document.createElement('div');
        var playerName = document.createElement('p');
        var otherCanvasWrapper = document.createElement('div');
        var otherPlayerCanvas = document.createElement('canvas');

        playerName.className = 'player-username';
        playerName.innerHTML = player.name;
        otherCanvasWrapper.className = 'canvas-wrapper';
        otherPlayerCanvas.setAttribute('data-player-id', player.id);

        div.appendChild(playerName);
        otherCanvasWrapper.appendChild(otherPlayerCanvas);
        div.appendChild(otherCanvasWrapper);
        otherPlayersCanvasContainer.appendChild(div);

        var otherPlayerGrid = new Grid(otherPlayerCanvas, player.id);
        grids.push(otherPlayerGrid);
        otherPlayerCanvas.addEventListener('click', gameHandlers.battleStage.otherPlayersGrid.click);
        if (playerInfos.id == player.id) {
            cloneGrid(grid, otherPlayerGrid);
            otherPlayerGrid.cells = JSON.parse(JSON.stringify(grid.cells));
            otherPlayerGrid.cellsContainingBoats = JSON.parse(JSON.stringify(grid.cellsContainingBoats));
            otherPlayerGrid.shootedCells = JSON.parse(JSON.stringify(grid.shootedCells));
            otherPlayerGrid.drawPlacedBoats(boatsSprite);
        }
    });

    // grid shooter
    var shooterCanvas = document.createElement('canvas');
    shooterCanvas.id = 'shooter-canvas';
    fireCanvasContainer.appendChild(shooterCanvas);
    document.getElementById('fire-canvas').removeClass('hidden');
    shooterGrid = new Grid(shooterCanvas, 'shooter');
    grids.push(shooterGrid);
    shooterCanvas.addEventListener('click', gameHandlers.battleStage.shooterGrid.click);
    shooterCanvas.addEventListener('mousemove', gameHandlers.battleStage.shooterGrid.mousemove);
});

socket.on('update-after-turn', function (touchedPlayers, playersInfos) {
    // TEST to implement (almost right)
    /*
    var playerHasTouched = false;
    var playerShootCoord = null;
    for (var player in touchedPlayers) {
        var currentGrid = findGridByPlayerId(player);
        touchedPlayers[player].touchedAt.forEach(function (data) {
            currentGrid.cells[data.coords.x][data.coords.x].shooted = true;
            currentGrid.cells[data.coords.x][data.coords.x].shootedBy = data.by;
            currentGrid.shootedCells.push({
                coords: JSON.parse(JSON.stringify(data.coords)),
                touched: data.touched
            });

            // can enter here many times if player shooted many other players
            if (data.byId == playerInfos.id) {
                if (playerShootCoord == null) {
                    playerShootCoord = JSON.parse(JSON.stringify(data.coords));
                }

                if (data.touched) {
                    playerHasTouched = true;
                }
            }
        });

        shooterGrid.shootedCells.push({
            coords: playerShootCoord,
            touched: playerHasTouched
        });

        if (player == playerInfos.id) {
            cloneGrid(currentGrid, grid);
            grid.clearCanvas();
            grid.renderGrid();
            grid.drawPlacedBoats(boatsSprite);
            grid.drawShoots(boatsSprite);
        }
    }
    */

    // OLD VERSION (bugged but needed for demo...)
    for (var player in touchedPlayers) {
        var currentGrid = findGridByPlayerId(player);
        touchedPlayers[player].touchedAt.forEach(function (data) {
            currentGrid.cells[data.coords.x][data.coords.x].shooted = true;
            currentGrid.cells[data.coords.x][data.coords.x].shootedBy = data.by;
            currentGrid.shootedCells.push({
                coords: JSON.parse(JSON.stringify(data.coords)),
                touched: data.touched
            });
            if (data.byId == playerInfos.id) {
                shooterGrid.shootedCells.push({
                    coords: JSON.parse(JSON.stringify(data.coords)),
                    touched: data.touched
                });
            }

        });

        if (player == playerInfos.id) {
            cloneGrid(currentGrid, grid);
            grid.clearCanvas();
            grid.renderGrid();
            grid.drawPlacedBoats(boatsSprite);
            grid.drawShoots(boatsSprite);
        }
    }

    grids.forEach(function (g) {
        g.drawShoots(boatsSprite);
    });
    manageRankList(playersInfos);
});

socket.on('gameover', function (winners) {
    if (winners.length > 1) {
        var text = 'Winners are ';
        winners.forEach(function (winner, i) {
            if (i == 0) {
                text += winner.name;
            } else {
                text = +', ' + winner.name;
            }
        });
    } else {
        var text = 'The winner is ' + winners[0].name;
    }
    var shooterCan = document.getElementById('shooter-canvas');
    shooterCan.removeEventListener('click', gameHandlers.battleStage.shooterGrid.click);
    shooterCan.removeEventListener('mousemove', gameHandlers.battleStage.shooterGrid.mousemove);
    document.getElementById('replay-modal').style.display = 'block';
    document.getElementById('winner').innerHTML = text;

    document.getElementById('button-replay').addEventListener('click', gameHandlers.gameover.replay);
    document.getElementById('button-quit').addEventListener('click', gameHandlers.gameover.quit);
});<commit_msg>placement boats bug fixed<commit_after>fillPlayersInfos();
var HORIZONTAL = 'h';
var VERTICAL = 'v';

var playerCanvas = document.getElementById('player-canvas');
var boatsContainer = document.getElementById('boats-container');
var canvasWrapper = document.getElementById('canvas-wrapper');
var randomGenerator = document.getElementById('random');
var boatSelecters = document.getElementsByClassName('boat-selector');
var timer = document.getElementById('timer');
var otherPlayersCanvasContainer = document.getElementById('other-players-canvas');
var fireCanvasContainer = document.getElementById('fire-canvas-wrapper');
var rankList = document.getElementById('rank-list');
var phaseTitle = document.getElementById('phase-title');

var grids = [];
var shooterGrid;
var selectedBoat = null;
var gameHandlers = {
	placementStage: {
		click: function (e) {
			if (selectedBoat != null) {
				var possibleToPlace = grid.canPlaceBoat(e.gridInfo.coords, selectedBoat);
				if (possibleToPlace) {
					var boatSelector = document.getElementById(selectedBoat.id);
					boatSelector.setAttribute('data-placed', 'true');
					boatSelector.setAttribute('class', 'boat-selector placed');
					grid.placeBoat(selectedBoat, e.gridInfo.coords);
					selectedBoat = null;
					grid.clearCanvas();
					grid.drawPlacedBoats(boatsSprite);
					grid.drawCoords();
					grid.renderGrid();
				}
			} else {
				if (e.gridInfo.cell.containBoat) {
					var boatId = e.gridInfo.cell.boatId;
					var boatOrientation = e.gridInfo.cell.boatOrientation;
					grid.removePlacedBoat(boatId);

					var removedBoat = grid.getDefaultBoats(boatId);
					selectedBoat = new Boat(removedBoat.name, removedBoat.size, boatOrientation, removedBoat.id);
					document.getElementById(boatId).setAttribute('class', 'boat-selector');

					grid.clearCanvas();
					grid.drawPlacedBoats(boatsSprite);
					grid.drawPreviewBoat(boatsSprite, selectedBoat, e.gridInfo, .5);
					grid.renderGrid();
				}
			}
		},
		mousemove: function (e) {
			var pos = {
				x: e.offsetX || e.layerX,
				y: e.offsetY || e.layerY
			};
			if (!previousMouseCoords) {
				previousMouseCoords = grid.getMouseCoord(pos);
			}

			if (selectedBoat != null) {
				var currentCoords = e.gridInfo.coords;
				if (currentCoords.x >= 0 && currentCoords.y >= 0) {
					if (previousMouseCoords.x != currentCoords.x ||
						previousMouseCoords.y != currentCoords.y) { // still in the same place
						var possible = grid.canPlaceBoat(e.gridInfo.coords, selectedBoat);
						var alpha = possible ? 1 : .5;
						grid.clearCanvas();
						grid.drawPlacedBoats(boatsSprite);
						grid.drawPreviewBoat(boatsSprite, selectedBoat, e.gridInfo, alpha);
						grid.drawCoords();
						grid.renderGrid();
					}
					previousMouseCoords = grid.getMouseCoord(pos);
				}
			}
		},
		contextmenu: function (e) {
			e.preventDefault();
			if (selectedBoat) {
				selectedBoat.orientation = selectedBoat.orientation == HORIZONTAL ? VERTICAL : HORIZONTAL;
				var possibleToPlace = grid.canPlaceBoat(e.gridInfo.coords, selectedBoat);
				var alpha = possibleToPlace ? 1 : .5;
				grid.clearCanvas();
				grid.drawPlacedBoats(boatsSprite);
				grid.drawPreviewBoat(boatsSprite, selectedBoat, e.gridInfo, alpha);
				grid.drawCoords();
				grid.renderGrid();
			}
		},
		selectBoat: function (e) {
			var placed = this.getAttribute('data-placed').toBool();
			if (!placed) {
				var boatSelecters = document.getElementsByClassName('boat-selector');
				var previousBoatOrientation = HORIZONTAL;

				var name = this.innerHTML,
					size = this.getAttribute('data-boat-size'),
					id = this.id;
				selectedBoat = new Boat(name, size, previousBoatOrientation, id);
			}
		},
		random: function (e) {
			grid.randomBoatsPosition();
			grid.drawPlacedBoats(boatsSprite);
			grid.renderGrid();
			selectedBoat = null;

			var selectors = document.getElementsByClassName('boat-selector');
			for (var i = 0; i < selectors.length; i++) {
				selectors[i].className = 'boat-selector placed';
			}

			randomGenerator.removeEventListener('click', random);
			randomGenerator.remove();
		}
	},
	battleStage: {
		otherPlayersGrid: {
			click: function (e) {
				var gridId = this.getAttribute('data-player-id');
				cloneGrid(gridId, grid);
				grid.clearCanvas();
				grid.renderGrid();
				grid.drawPlacedBoats(boatsSprite);
				grid.drawShoots(boatsSprite);
			}
		},
		shooterGrid: {
			click: function (e) {
				if (shooterGrid.highlightedSelected.x != null &&
					shooterGrid.highlightedSelected.y != null) {
					grids.forEach(function (g) {
						shooterGrid.clearHighlightCell(shooterGrid.highlightedSelected);
					});
				}

				grids.forEach(function (g) {
					g.clearHighlightCell(shooterGrid.highlightedSelected);
					g.highlightedSelected = e.gridInfo.coords
					g.highlightCell(e.gridInfo.coords);
				});
				if (!shooterGrid.cellIsShooted(e.gridInfo.coords)) {
					socket.emit('game-shoot', e.gridInfo.coords);
				}
			},
			mousemove: function (e) {
				grids.forEach(function (g) {
					g.highlightCell(e.gridInfo.coords);
					g.highlightedOver = e.gridInfo.coords;
				});
			}
		}
	},
	gameover: {
		replay: function (e) {
			ajax.get('/wait', function (data) {
				socket.emit('game-replay');
				socket.on('replay-init-done', function () {
					handlers.onComplete(data);
				});
			});
		},
		quit: function (e) {
			window.location.href = '/rooms';
		}
	}
};
var previousMouseCoords = undefined;
var boatsSprite = new Image();
var grid;

function findGridByPlayerId(playerId) {
	for (var i = 0; i < grids.length; i++) {
		if (grids[i].playerId == playerId) {
			return grids[i];
		}
	}
	return null;
}
function manageRankList(playersInfos) {
	rankList.removeChildren();
	var position = 1;
	for (var i = playersInfos.length - 1; i >= 0; i--, position++) {
		var infos = playersInfos[i];
		var newLi = document.createElement('li');
		var pPosition = document.createElement('p');
		var pPseudo = document.createElement('p');
		var pPoints = document.createElement('p');

		pPosition.className = 'rank-position';
		pPosition.innerHTML = position;
		pPseudo.className = 'rank-username';
		pPseudo.innerHTML = infos.name;
		pPoints.className = 'rank-points';
		pPoints.id = infos.id + '-points';
		pPoints.innerHTML = infos.points;

		newLi.appendChild(pPosition);
		newLi.appendChild(pPseudo);
		newLi.appendChild(pPoints);
		rankList.appendChild(newLi);
	}
}
function cloneGrid(from, to) {
	var g;
	if (typeof from == 'string') {
		g = findGridByPlayerId(from);
	} else if (typeof from == 'object') {
		if (from instanceof Grid) {
			g = from;
		} else {
			console.error('Bad param');
			return;
		}
	}
	to.cells = JSON.parse(JSON.stringify(g.cells));
	to.cellsContainingBoats = JSON.parse(JSON.stringify(g.cellsContainingBoats));
	to.shootedCells = JSON.parse(JSON.stringify(g.shootedCells));
}

socket.emit('game-init');
socket.on('init', function (playerId, playersInfos) {
	console.log(1);
	grid = new Grid(playerCanvas, "viewer");
	grids.push(grid);
	manageRankList(playersInfos);

	boatsSprite.src = "/images/sprites.png";
	boatsSprite.onload = function () {
		console.log(2);
		// PLACEMENT STAGE
		playerCanvas.addEventListener('mousemove', gameHandlers.placementStage.mousemove);
		playerCanvas.addEventListener('click', gameHandlers.placementStage.click);
		playerCanvas.addEventListener('contextmenu', gameHandlers.placementStage.contextmenu);

		for (var i = 0; i < boatSelecters.length; i++) {
			boatSelecters[i].addEventListener('click', gameHandlers.placementStage.selectBoat);
		}
		randomGenerator.addEventListener('click', gameHandlers.placementStage.random);
	}

	window.addEventListener('resize', function (e) {
		grids.forEach(function (g) {
			var newWidth = parseInt(getComputedStyle(g.container).width);
			g.rescaleCanvas(newWidth, boatsSprite);
		});
	});
});
socket.on('game-timer-update', function (timeRemaining) {
	timer.innerHTML = timeRemaining + 's';
});
socket.on('game-check-grid', function () {
	if (!grid.allBoatsArePlaced()) {
		gameHandlers.placementStage.random();
		grid.drawPlacedBoats(boatsSprite);
	}
	playerCanvas.removeEventListener('click', gameHandlers.placementStage.click);
	playerCanvas.removeEventListener('mousemove', gameHandlers.placementStage.mousemove);
	playerCanvas.removeEventListener('contextmenu', gameHandlers.placementStage.contextmenu);

	socket.emit('game-set-ready', grid.cells);
});
socket.on('game-init-players-grids', function (players) {
	document.getElementById('boats-container').addClass('hidden')
	document.getElementById('other-players-canvas').removeClass('hidden');
	/*    canvasWrapper.removeClass('placement-phase');
	    canvasWrapper.addClass('fire-phase');*/
	phaseTitle.innerHTML = 'Phases de tir';
	players.forEach(function (player) {
		var div = document.createElement('div');
		var playerName = document.createElement('p');
		var otherCanvasWrapper = document.createElement('div');
		var otherPlayerCanvas = document.createElement('canvas');

		playerName.className = 'player-username';
		playerName.innerHTML = player.name;
		otherCanvasWrapper.className = 'canvas-wrapper';
		otherPlayerCanvas.setAttribute('data-player-id', player.id);

		div.appendChild(playerName);
		otherCanvasWrapper.appendChild(otherPlayerCanvas);
		div.appendChild(otherCanvasWrapper);
		otherPlayersCanvasContainer.appendChild(div);

		var otherPlayerGrid = new Grid(otherPlayerCanvas, player.id);
		grids.push(otherPlayerGrid);
		otherPlayerCanvas.addEventListener('click', gameHandlers.battleStage.otherPlayersGrid.click);
		if (playerInfos.id == player.id) {
			cloneGrid(grid, otherPlayerGrid);
			otherPlayerGrid.cells = JSON.parse(JSON.stringify(grid.cells));
			otherPlayerGrid.cellsContainingBoats = JSON.parse(JSON.stringify(grid.cellsContainingBoats));
			otherPlayerGrid.shootedCells = JSON.parse(JSON.stringify(grid.shootedCells));
			otherPlayerGrid.drawPlacedBoats(boatsSprite);
		}
	});

	// grid shooter
	var shooterCanvas = document.createElement('canvas');
	shooterCanvas.id = 'shooter-canvas';
	fireCanvasContainer.appendChild(shooterCanvas);
	document.getElementById('fire-canvas').removeClass('hidden');
	shooterGrid = new Grid(shooterCanvas, 'shooter');
	grids.push(shooterGrid);
	shooterCanvas.addEventListener('click', gameHandlers.battleStage.shooterGrid.click);
	shooterCanvas.addEventListener('mousemove', gameHandlers.battleStage.shooterGrid.mousemove);
});
socket.on('update-after-turn', function (touchedPlayers, playersInfos) {
	// TEST to implement (almost right)
	/*
	var playerHasTouched = false;
	var playerShootCoord = null;
	for (var player in touchedPlayers) {
	    var currentGrid = findGridByPlayerId(player);
	    touchedPlayers[player].touchedAt.forEach(function (data) {
	        currentGrid.cells[data.coords.x][data.coords.x].shooted = true;
	        currentGrid.cells[data.coords.x][data.coords.x].shootedBy = data.by;
	        currentGrid.shootedCells.push({
	            coords: JSON.parse(JSON.stringify(data.coords)),
	            touched: data.touched
	        });

	        // can enter here many times if player shooted many other players
	        if (data.byId == playerInfos.id) {
	            if (playerShootCoord == null) {
	                playerShootCoord = JSON.parse(JSON.stringify(data.coords));
	            }

	            if (data.touched) {
	                playerHasTouched = true;
	            }
	        }
	    });

	    shooterGrid.shootedCells.push({
	        coords: playerShootCoord,
	        touched: playerHasTouched
	    });

	    if (player == playerInfos.id) {
	        cloneGrid(currentGrid, grid);
	        grid.clearCanvas();
	        grid.renderGrid();
	        grid.drawPlacedBoats(boatsSprite);
	        grid.drawShoots(boatsSprite);
	    }
	}
	*/

	// OLD VERSION (bugged but needed for demo...)
	for (var player in touchedPlayers) {
		var currentGrid = findGridByPlayerId(player);
		touchedPlayers[player].touchedAt.forEach(function (data) {
			currentGrid.cells[data.coords.x][data.coords.x].shooted = true;
			currentGrid.cells[data.coords.x][data.coords.x].shootedBy = data.by;
			currentGrid.shootedCells.push({
				coords: JSON.parse(JSON.stringify(data.coords)),
				touched: data.touched
			});
			if (data.byId == playerInfos.id) {
				shooterGrid.shootedCells.push({
					coords: JSON.parse(JSON.stringify(data.coords)),
					touched: data.touched
				});
			}

		});

		if (player == playerInfos.id) {
			cloneGrid(currentGrid, grid);
			grid.clearCanvas();
			grid.renderGrid();
			grid.drawPlacedBoats(boatsSprite);
			grid.drawShoots(boatsSprite);
		}
	}

	grids.forEach(function (g) {
		g.drawShoots(boatsSprite);
	});
	manageRankList(playersInfos);
});
socket.on('gameover', function (winners) {
	if (winners.length > 1) {
		var text = 'Winners are ';
		winners.forEach(function (winner, i) {
			if (i == 0) {
				text += winner.name;
			} else {
				text = +', ' + winner.name;
			}
		});
	} else {
		var text = 'The winner is ' + winners[0].name;
	}
	var shooterCan = document.getElementById('shooter-canvas');
	shooterCan.removeEventListener('click', gameHandlers.battleStage.shooterGrid.click);
	shooterCan.removeEventListener('mousemove', gameHandlers.battleStage.shooterGrid.mousemove);
	document.getElementById('replay-modal').style.display = 'block';
	document.getElementById('winner').innerHTML = text;

	document.getElementById('button-replay').addEventListener('click', gameHandlers.gameover.replay);
	document.getElementById('button-quit').addEventListener('click', gameHandlers.gameover.quit);
});<|endoftext|>


<commit_before>var rpcRequest = require('./rpc-request');
require('./polyfills');

var DropboxApi = function (options) {
  this.accessToken = options && options.accessToken || '';
};

DropboxApi.prototype.setAccessToken = function (accessToken) {
  this.accessToken = accessToken;
};

DropboxApi.prototype.getAccessToken = function () {
  return this.accessToken;
};

DropboxApi.prototype.listFolder = function (path) {
  return rpcRequest('files/list_folder', { path: path }, this.getAccessToken());
};

module.exports = DropboxApi;
<commit_msg>Add JSDocs populated from website documentation<commit_after>var rpcRequest = require('./rpc-request');
require('./polyfills');

var DropboxApi = function (options) {
  this.accessToken = options && options.accessToken || '';
};

DropboxApi.prototype.setAccessToken = function (accessToken) {
  this.accessToken = accessToken;
};

DropboxApi.prototype.getAccessToken = function () {
  return this.accessToken;
};

/**
 * Returns the contents of a folder.
 * @param {Object} params - The requests parameters
 * @param {string} params.path - The path to the folder you want to see the contents of.
 * @param {boolean} [params.recursive=false] - If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.
 * @param {boolean} [params.include_media_info=false] - If true, FileMetadata.media_info is set for photo and video.
 * @param {boolean} [params.include_deleted=false] - If true, the results will include entries for files and folders that used to exist but were deleted.
 * @returns {Object}
 * */
DropboxApi.prototype.listFolder = function (params) {
  return rpcRequest('files/list_folder', params, this.getAccessToken());
};

module.exports = DropboxApi;
<|endoftext|>


<commit_before>Molecule(320, 320, function (game, require) {

    game.assets = require('assets');

    // Create sprite
    var sprite = game.assets.sprites.flappy;

    // Change friction
    game.physics.friction.x = 0;
    game.physics.friction.y = 0.05;

    // Change gravity (pixels per frame)
    game.physics.gravity.x = 0;
    game.physics.gravity.y = 9.78 / 60;

    game.init(function () {

        // Change sprite position
        sprite.position.x = game.width / 2;
        sprite.position.y = game.width / 2;

        // Change sprite anchor
        sprite.anchor.x = sprite.width / 2;
        sprite.anchor.y = sprite.height / 2;

        // Add animation with parameters: animation name, animation frames, speed
        sprite.animation.add('fly', [0, 1, 0, 2], 0.5);

        // Stop current animation
        sprite.animation.stop();

        // Run animation with parameters: animation name, loop, reverse
        sprite.animation.run('fly', true, false);

    });

    game.update(function () {

        if(sprite.position.y < 50) {
            game.physics.gravity.y = 9.78 / 60;
        } else if(sprite.position.y + sprite.frame.height > game.width - 50) {
            game.physics.gravity.y = -9.78 / 60;
        }

    });

});<commit_msg>Fixed examples<commit_after>Molecule(320, 320, function (game, require) {

    game.assets = require('assets');

    // Create sprite
    var sprite = game.assets.sprites.flappy;

    // Change friction
    game.physics.friction.x = 0;
    game.physics.friction.y = 0.025;

    // Change gravity (pixels per frame)
    game.physics.gravity.x = 0;
    game.physics.gravity.y = 9.78 / 60;

    game.init(function () {

        // Change sprite position
        sprite.position.x = game.width / 2;
        sprite.position.y = game.width / 2;

        // Change sprite anchor
        sprite.anchor.x = sprite.width / 2;
        sprite.anchor.y = sprite.height / 2;

        // Add animation with parameters: animation name, animation frames, speed
        sprite.animation.add('fly', [0, 1, 0, 2], 0.5);

        // Run animation with parameters: animation name, loop, reverse (loop and reverse parameters are optional)
        sprite.animation.run('fly');

    });

    game.update(function () {

        if(sprite.position.y - sprite.anchor.y < 70) {
            game.physics.gravity.y = 9.78 / 60;
        } else if(sprite.position.y - sprite.anchor.y + sprite.frame.height > game.width - 70) {
            game.physics.gravity.y = -9.78 / 60;
        }

    });

});<|endoftext|>


<commit_before>
define(['build/Objects/Abstract/form_item'], function(FormItem) {

    var Trumbowyg = function(data) {

        //Call the parent constructor
        FormItem.call(this, data);

        //Set type of this object
        this.setType('trumbowyg');

        /**
         * Buttons for the editor
         * @type {string[]}
         */
        this.buttons = ['header', 'bold', 'italic', '|', 'unorderedList', 'orderedList', '|', 'insertImage', 'link', '|', 'viewHTML', 'fullscreen'];

        /**
         * Get attributes for this input
         * @return Object
         */
        this.getAttributes = function() {
            return {
                type: this.getType(),
                value: this.getValue(),
                name: this.getName()
            }
        };

        /**
         * Setter of buttons
         * @param buttons
         */
        this.setButtons = function(buttons) {
            this.buttons = buttons;
        };

        /**
         * Getter for buttons
         */
        this.getButtons = function() {
            return this.buttons;
        };

    };

    // Inherit Panel
    Trumbowyg.prototype = FormItem;

    // Fix constructor
    Trumbowyg.prototype.constructor = Trumbowyg;

    return Trumbowyg;
});<commit_msg>Actually setting buttons from server response in Trumbowyg RTE<commit_after>
define(['build/Objects/Abstract/form_item'], function(FormItem) {

    var Trumbowyg = function(data) {

        //Call the parent constructor
        FormItem.call(this, data);

        //Set type of this object
        this.setType('trumbowyg');

        /**
         * Buttons for the editor
         * @type {string[]}
         */
        this.buttons = data.buttons || ['header', 'bold', 'italic', '|', 'unorderedList', 'orderedList', '|', 'insertImage', 'link', '|', 'viewHTML', 'fullscreen'];

        /**
         * Get attributes for this input
         * @return Object
         */
        this.getAttributes = function() {
            return {
                type: this.getType(),
                value: this.getValue(),
                name: this.getName()
            }
        };

        /**
         * Setter of buttons
         * @param buttons
         */
        this.setButtons = function(buttons) {
            this.buttons = buttons;
        };

        /**
         * Getter for buttons
         */
        this.getButtons = function() {
            return this.buttons;
        };

    };

    // Inherit Panel
    Trumbowyg.prototype = FormItem;

    // Fix constructor
    Trumbowyg.prototype.constructor = Trumbowyg;

    return Trumbowyg;
});<|endoftext|>


<commit_before>
/**
 * Module dependencies
 */

var express = require('express'),
  routes = require('./routes'),
  api = require('./routes/api'),
  http = require('http'),
  path = require('path');

var app = module.exports = express();

/**
 * Configuration
 */

// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

// development only
if (app.get('env') === 'development') {
  app.use(express.errorHandler());
}

// production only
if (app.get('env') === 'production') {
  // TODO
};

/**
 * Routes
 */

// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);

// JSON API
app.get('/laws/:id', api.law); //to be done

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

/**
 * Start Server
 */

http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>fixed port<commit_after>/**
 * Module dependencies
 */

var express = require('express'),
  routes = require('./routes'),
  api = require('./routes/api'),
  http = require('http'),
  path = require('path');

var app = module.exports = express();

/**
 * Configuration
 */

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

// development only
if (app.get('env') === 'development') {
  app.use(express.errorHandler());
}

// production only
if (app.get('env') === 'production') {
  // TODO
};

/**
 * Routes
 */

// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);

// JSON API
app.get('/laws/:id', api.law); //to be done

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

/**
 * Start Server
 */

http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@folio/stripes-components/lib/Button';
import Paneset from '@folio/stripes-components/lib/Paneset';
import Pane from '@folio/stripes-components/lib/Pane';
import PaneMenu from '@folio/stripes-components/lib/PaneMenu';
import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList';
import dateFormat from 'dateformat';
import loanHistoryMap from './data/loanHistoryMap';
import { formatDate, formatDateTime } from './util';

class LoansHistory extends React.Component {

  static propTypes = {
    stripes: PropTypes.shape({
      locale: PropTypes.string.isRequired,
    }).isRequired,
    resources: PropTypes.shape({
      loansHistory: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
    }),
    mutator: PropTypes.shape({
      loanId: PropTypes.shape({
        replace: PropTypes.func,
      }),
      loansHistory: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
      }),
    }).isRequired,
    onCancel: PropTypes.func.isRequired,
    openLoans: PropTypes.bool,
    onClickViewLoanActionsHistory: PropTypes.func.isRequired,
    onClickViewOpenLoans: PropTypes.func.isRequired,
    onClickViewClosedLoans: PropTypes.func.isRequired,
  };

  static manifest = Object.freeze({
    loanId: {},
    loansHistory: {
      type: 'okapi',
      records: 'loans',
      path: 'circulation/loans?query=(userId=!{userid}) sortby id',
      PUT: {
        path: 'circulation/loans/%{loanId}',
      },
    },
  });

  constructor(props) {
    super(props);

    this.handleOptionsChange = this.handleOptionsChange.bind(this);
    this.handleOptionsClick = this.handleOptionsClick.bind(this);
  }

  /**
   * change handler for the options-menu prevents the event from bubbling
   * up to the event handler attached to the row.
   */
   // eslint-disable-next-line class-methods-use-this
  handleOptionsChange(e, loan) {
    const action = e.target.value;

    if (action && this[action]) {
      this[action](loan);
    }

    e.preventDefault();
    e.stopPropagation();
  }

  renew(loan) {
    const loanDate = new Date();
    const dueDate = new Date();
    dueDate.setDate(loanDate.getDate() + 30);

    Object.assign(loan, {
      renewalCount: (loan.renewalCount || 0) + 1,
      loanDate: dateFormat(loanDate, "yyyy-mm-dd'T'HH:MM:ss'Z'"),
      dueDate: dateFormat(dueDate, "yyyy-mm-dd'T'HH:MM:ss'Z'"),
      action: 'renewed',
    });

    this.props.mutator.loanId.replace(loan.id);
    this.props.mutator.loansHistory.PUT(_.omit(loan, ['item', 'rowIndex']));
  }

  /**
   * click handler for the options-menu prevents the event from bubbling
   * up to the event handler attached to the row.
   */
   // eslint-disable-next-line class-methods-use-this
  handleOptionsClick(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  renderActions(loan) {
    return (
      <select onChange={e => this.handleOptionsChange(e, loan)} onClick={this.handleOptionsClick}>
        <option value="">•••</option>
        <option value="renew">Renew</option>
      </select>
    );
  }

  render() {
    const loansHistory = _.get(this.props.resources, ['loansHistory', 'records']);
    const loanStatus = this.props.openLoans ? 'Open' : 'Closed';
    const loans = _.filter(loansHistory, loan => loanStatus === _.get(loan, ['status', 'name']));
    if (!loans) return
;

    const historyLastMenu = (<PaneMenu>
      <Button title="Open Loans" aria-label="Open Loans" onClick={this.props.onClickViewOpenLoans}>Open Loans</Button>
      <Button title="Closed Loans" aria-label="Closed Loans" onClick={this.props.onClickViewClosedLoans}>Closed Loans</Button>
    </PaneMenu>);

    /*
     * loanTitleFormatter isn't currently in use, but apparently there's a use
     * case for having the cell content link to a different location than the
     * cell background. On a scale from 1 to WTF, I give this a 10, but I digress.
     * Note that both e.preventDefault() and e.stopPropagation() are required to
     * achieve this behavior.
     *
    const loanTitleFormatter = loan => (
       {
          e.preventDefault();
          e.stopPropagation();
          this.props.doSomethingWithThisClick(e, loan);
        }}
      >{_.get(loan, ['item', 'title'], '')}
    );

    const loansFormatter = {
      title: loanTitleFormatter,
      ...
    };
    */

    const loansFormatter = {
      title: loan => `${_.get(loan, ['item', 'title'], '')}`,
      barcode: loan => `${_.get(loan, ['item', 'barcode'], '')}`,
      itemStatus: loan => `${_.get(loan, ['item', 'status', 'name'], '')}`,
      loanDate: loan => formatDate(loan.loanDate, this.props.stripes.locale),
      dueDate: loan => (loan.dueDate ? formatDateTime(loan.dueDate, this.props.stripes.locale) : ''),
      renewals: loan => loan.renewalCount || 0,
      returnDate: loan => (loan.returnDate ? formatDateTime(loan.returnDate, this.props.stripes.locale) : ''),
      ' ': (loan) => {
        const status = _.get(loan, ['status', 'name'], '');
        return (status === 'Closed') ? (
) : this.renderActions(loan);
      },
    };

    return (
      <Paneset isRoot>
        <Pane id="pane-loanshistory" defaultWidth="100%" lastMenu={historyLastMenu} dismissible onClose={this.props.onCancel} paneTitle="Loans">
          <MultiColumnList
            id="list-loanshistory"
            fullWidth
            formatter={loansFormatter}
            visibleColumns={['title', 'itemStatus', 'barcode', 'loanDate', 'dueDate', 'returnDate', 'renewals', ' ']}
            columnMapping={loanHistoryMap}
            contentData={loans}
            onRowClick={this.props.onClickViewLoanActionsHistory}
          />
        </Pane>
      </Paneset>);
  }
}

export default LoansHistory;
<commit_msg>format actions menu. Refs UIU-128<commit_after>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { DropdownButton, MenuItem } from 'react-bootstrap';
import dateFormat from 'dateformat';
import Button from '@folio/stripes-components/lib/Button';
import Paneset from '@folio/stripes-components/lib/Paneset';
import Pane from '@folio/stripes-components/lib/Pane';
import PaneMenu from '@folio/stripes-components/lib/PaneMenu';
import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList';
import loanHistoryMap from './data/loanHistoryMap';
import { formatDate, formatDateTime } from './util';

class LoansHistory extends React.Component {

  static propTypes = {
    stripes: PropTypes.shape({
      locale: PropTypes.string.isRequired,
    }).isRequired,
    resources: PropTypes.shape({
      loansHistory: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
    }),
    mutator: PropTypes.shape({
      loanId: PropTypes.shape({
        replace: PropTypes.func,
      }),
      loansHistory: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
      }),
    }).isRequired,
    onCancel: PropTypes.func.isRequired,
    openLoans: PropTypes.bool,
    onClickViewLoanActionsHistory: PropTypes.func.isRequired,
    onClickViewOpenLoans: PropTypes.func.isRequired,
    onClickViewClosedLoans: PropTypes.func.isRequired,
  };

  static manifest = Object.freeze({
    loanId: {},
    loansHistory: {
      type: 'okapi',
      records: 'loans',
      path: 'circulation/loans?query=(userId=!{userid}) sortby id',
      PUT: {
        path: 'circulation/loans/%{loanId}',
      },
    },
  });

  constructor(props) {
    super(props);

    this.handleOptionsChange = this.handleOptionsChange.bind(this);
    this.handleOptionsClick = this.handleOptionsClick.bind(this);
  }

  /**
   * change handler for the options-menu prevents the event from bubbling
   * up to the event handler attached to the row.
   */
  handleOptionsChange(key, e) {
    e.preventDefault();
    e.stopPropagation();

    if (key.action && this[key.action]) {
      this[key.action](key.loan);
    }
  }

  renew(loan) {
    const loanDate = new Date();
    const dueDate = new Date();
    dueDate.setDate(loanDate.getDate() + 30);

    Object.assign(loan, {
      renewalCount: (loan.renewalCount || 0) + 1,
      loanDate: dateFormat(loanDate, "yyyy-mm-dd'T'HH:MM:ss'Z'"),
      dueDate: dateFormat(dueDate, "yyyy-mm-dd'T'HH:MM:ss'Z'"),
      action: 'renewed',
    });

    this.props.mutator.loanId.replace(loan.id);
    this.props.mutator.loansHistory.PUT(_.omit(loan, ['item', 'rowIndex']));
  }

  /**
   * click handler for the options-menu prevents the event from bubbling
   * up to the event handler attached to the row.
   */
   // eslint-disable-next-line class-methods-use-this
  handleOptionsClick(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  renderActions(loan) {
    return (
      <DropdownButton
        title="•••"
        id={`bg-nested-dropdown-${loan.id}`}
        noCaret
        pullRight onClick={this.handleOptionsClick}
        onSelect={this.handleOptionsChange}
      >
        <MenuItem eventKey={{ loan, action: 'renew' }}>Renew</MenuItem>
      </DropdownButton>
    );
  }

  render() {
    const loansHistory = _.get(this.props.resources, ['loansHistory', 'records']);
    const loanStatus = this.props.openLoans ? 'Open' : 'Closed';
    const loans = _.filter(loansHistory, loan => loanStatus === _.get(loan, ['status', 'name']));
    if (!loans) return
;

    const historyLastMenu = (<PaneMenu>
      <Button title="Open Loans" aria-label="Open Loans" onClick={this.props.onClickViewOpenLoans}>Open Loans</Button>
      <Button title="Closed Loans" aria-label="Closed Loans" onClick={this.props.onClickViewClosedLoans}>Closed Loans</Button>
    </PaneMenu>);

    /*
     * loanTitleFormatter isn't currently in use, but apparently there's a use
     * case for having the cell content link to a different location than the
     * cell background. On a scale from 1 to WTF, I give this a 10, but I digress.
     * Note that both e.preventDefault() and e.stopPropagation() are required to
     * achieve this behavior.
     *
    const loanTitleFormatter = loan => (
       {
          e.preventDefault();
          e.stopPropagation();
          this.props.doSomethingWithThisClick(e, loan);
        }}
      >{_.get(loan, ['item', 'title'], '')}
    );

    const loansFormatter = {
      title: loanTitleFormatter,
      ...
    };
    */

    const loansFormatter = {
      title: loan => `${_.get(loan, ['item', 'title'], '')}`,
      barcode: loan => `${_.get(loan, ['item', 'barcode'], '')}`,
      itemStatus: loan => `${_.get(loan, ['item', 'status', 'name'], '')}`,
      loanDate: loan => formatDate(loan.loanDate, this.props.stripes.locale),
      dueDate: loan => (loan.dueDate ? formatDateTime(loan.dueDate, this.props.stripes.locale) : ''),
      renewals: loan => loan.renewalCount || 0,
      returnDate: loan => (loan.returnDate ? formatDateTime(loan.returnDate, this.props.stripes.locale) : ''),
      ' ': (loan) => {
        const status = _.get(loan, ['status', 'name'], '');
        return (status === 'Closed') ? (
) : this.renderActions(loan);
      },
    };

    return (
      <Paneset isRoot>
        <Pane id="pane-loanshistory" defaultWidth="100%" lastMenu={historyLastMenu} dismissible onClose={this.props.onCancel} paneTitle="Loans">
          <MultiColumnList
            id="list-loanshistory"
            fullWidth
            formatter={loansFormatter}
            visibleColumns={['title', 'itemStatus', 'barcode', 'loanDate', 'dueDate', 'returnDate', 'renewals', ' ']}
            columnMapping={loanHistoryMap}
            columnOverflow={{ ' ': true }}
            contentData={loans}
            onRowClick={this.props.onClickViewLoanActionsHistory}
          />
        </Pane>
      </Paneset>);
  }
}

export default LoansHistory;
<|endoftext|>