<commit_before>const Asteroid = require("./asteroid");
const Keyboard = require("./keyboard");
const SpaceShip = require("./spaceship");

function Game(context) {
  this.context = context;
  this.level = 1;
  this.asteroids = []
  this.keyboard = new Keyboard
  this.createShip();
  this.started = false
  this.time = 0
  this.introTime = 0
  this.lives =  3
  this.lifeChars = ["", "A", "A A", "A A A"]
  this.deadTime = 0
  this.spawnTime = 0
  this.asteroidsToRemove = []
  this.asteroidsDestroyed = 0
  this.gameOver = false
}

Game.prototype.createShip = function() {
  this.ship = new SpaceShip(-1000, -1000, this.context, this.keyboard);
}

Game.prototype.createAsteroid = function(level, asteroid, asteroidCount) {
  if (asteroidCount) {
    var i = 0
    while (i < asteroidCount) {
      this.asteroids.push(new Asteroid(this.context, {x: (asteroid.center.x + i), y: (asteroid.center.y + i)}, (asteroid.radius / 3)))
      i++
    }
    var length = this.asteroids.length - 1
  }
  if (this.asteroids.length < level + 7) {
    this.asteroids.push(new Asteroid(this.context));
  }
}

Game.prototype.startGame = function() {
  this.started = true;
  this.ship.hidden = false;
  this.ship.point = {x: 350, y: 300};
  this.dead = false;
}

Game.prototype.removeAsteroids = function() {
  var thisGame = this
  this.asteroidsToRemove.forEach(function(asteroidIndex){
    thisGame.asteroids.splice(asteroidIndex, 1)
  })
  this.asteroidsToRemove = []
}

Game.prototype.update = function() {
  this.checkTime();
  this.ship.update()
  this.removeAsteroids()
  if (this.keyboard.isDown(this.keyboard.KEYS.ENTER) && this.started === false) {
    this.startGame()
  }
  if (this.keyboard.isDown(this.keyboard.KEYS.ENTER) && this.gameOver === true) {
    this.startGame();
    this.resetGame();
  }
  if (this.dead === true) {
    this.respawnShip();
  }
}

Game.prototype.resetGame = function(){
  this.gameOver = false
  this.lives = 3
  this.asteroidsDestroyed = 0
  this.level = 1
}

Game.prototype.checkTime = function(){
  if (this.started === true && this.gameOver === false) { this.time += 1 }
  if (this.time > 1000){
    this.time = 0
    this.level += 1
  }
}

Game.prototype.checkShipCollision = function(){
  var shipCoordinates = [this.ship.point, this.ship.rightSide, this.ship.leftSide]
  var thisGame = this
  this.asteroids.forEach(function(asteroid){
    shipCoordinates.forEach(function(coordinate){
      if ((coordinate.x > asteroid.center.x - asteroid.radius + 5) &&
      (coordinate.x < asteroid.center.x + asteroid.radius - 5) &&
      (coordinate.y > asteroid.center.y - asteroid.radius + 5) &&
      (coordinate.y < asteroid.center.y + asteroid.radius - 5)) {
        if (thisGame.dead === false) {
          thisGame.killShip();
          console.log(thisGame.dead)
          console.log("hit")
        }
      }
    })
  })
}

Game.prototype.checkBulletCollision = function() {
  var bulletCoordinates = []
  this.ship.bullets.forEach(function(bullet) {
    bulletCoordinates.push(bullet.center);
  })
  var thisGame = this
  if (thisGame.ship.bullets.length > 0) {
    thisGame.asteroids.forEach(function(asteroid, asteroidIndex){
      thisGame.ship.bullets.forEach(function(bullet, bulletIndex){
        if ((bullet.center.x > asteroid.center.x - asteroid.radius + 5) &&
        (bullet.center.x < asteroid.center.x + asteroid.radius - 5) &&
        (bullet.center.y > asteroid.center.y - asteroid.radius + 5) &&
        (bullet.center.y < asteroid.center.y + asteroid.radius - 5)) {
          thisGame.ship.bullets.splice(bulletIndex, 1)
          thisGame.explodeAsteroid(asteroid)
          thisGame.asteroidsToRemove.push(asteroidIndex)
        }
      })
    })
  }
}

Game.prototype.explodeAsteroid = function(asteroid) {
  this.asteroidsDestroyed += 1
  this.calculateScore();
  if (asteroid.radius > 60) {
    this.createAsteroid(this.level, asteroid, 3)
  } else if (asteroid.radius > 30) {
    this.createAsteroid(this.level, asteroid, 2)
  }
}

Game.prototype.killShip = function(){
  this.lives -=1
  this.dead = true
  this.ship.hidden = true
  this.ship.point = {x: -1000, y: -1000}
  this.ship.orientation = 4.7123;
  this.deadTime = this.time
}

Game.prototype.blinkShip = function() {
  this.spawnTime += 1
  if (this.spawnTime < 10 ){
    this.ship.hidden = true
    this.ship.point = {x: -1000, y: -1000}
  }
  else if (this.spawnTime > 20){
    this.spawnTime = 0
    this.ship.point = {x: 350, y: 300}
  }
}

Game.prototype.respawnShip = function(){
  if (this.lives < 1) {
    this.ship.hidden = true
    this.ship.center = {x: -1000, y: -1000}
  }
  else if (this.time > this.deadTime + 60) {
    this.ship.hidden = false
    this.ship.point = {x: 350, y: 300}
    this.blinkShip();
  }
  if (this.time > this.deadTime + 300) {
    this.dead = false
    this.ship.hidden = false
    this.deadTime = 0
  }
}

Game.prototype.endGame = function() {
  this.context.font="55px Verdana"
  this.context.fillText("Game Over", 350, 215)
  this.context.font="20px Verdana"
  this.context.fillText("Press Enter to Play Again", 350, 450)
  this.context.fillText("Asteroids Destroyed: " + this.asteroidsDestroyed, 350, 275)
  this.context.fillText("Score: " + this.score, 350, 310)
  this.gameOver = true
}

Game.prototype.gameText = function() {
  this.context.textAlign = "center";
  if (this.started === false) {
    this.intro()
  }
  if (this.lives < 1){
    this.endGame();
  }
  this.calculateScore();
  this.context.font="15px Verdana"
  this.context.fillText("Level: " + this.level, 45, 25)
  this.context.fillText("Score: " + this.score, 635, 25)
  this.context.textAlign = "left";
  this.context.fillText(this.lifeChars[this.lives], 15, 45)
}

Game.prototype.calculateScore = function() {
  this.score = (this.level * this.asteroidsDestroyed * 10)
}

Game.prototype.intro = function() {
  this.context.font="45px Impact"
  this.context.fillText("ASTEROIDS", 350, 220)
  this.introTime += 1
  if (this.introTime < 25 ){
    this.context.font="20px Verdana"
    this.context.fillText("Hit Enter to Start!", 350, 250)
  }
  else if (this.introTime > 50){
    this.introTime = 0
  }
}

module.exports = Game;
<commit_msg>Refactor game<commit_after>const Asteroid = require("./asteroid");
const Keyboard = require("./keyboard");
const SpaceShip = require("./spaceship");

function Game(context) {
  this.context = context;
  this.level = 1;
  this.asteroids = [];
  this.keyboard = new Keyboard;
  this.createShip();
  this.started = false;
  this.introTime = 0;
  this.lives =  3;
  this.lifeChars = ["", "A", "A A", "A A A"];
  this.deadTime = 0
  this.spawnTime = 0
  this.asteroidsToRemove = []
  this.asteroidsDestroyed = 0
  this.gameOver = false
}

Game.prototype.createShip = function() {
  this.ship = new SpaceShip(-1000, -1000, this.context, this.keyboard);
}

Game.prototype.createAsteroid = function(level, asteroid, asteroidCount) {
  if (asteroidCount) {
    var i = 0
    while (i < asteroidCount) {
      this.asteroids.push(new Asteroid(this.context, {x: (asteroid.center.x + i), y: (asteroid.center.y + i)}, (asteroid.radius / 3)))
      i++
    }
  }
  if (this.asteroids.length -1 < level + 7) {
    this.asteroids.push(new Asteroid(this.context));
  }
}

Game.prototype.startGame = function() {
  this.started = true;
  this.unHideShip()
  this.dead = false;

  this.gameOver = false
  this.lives = 3
  this.asteroidsDestroyed = 0
  this.level = 1
  this.ship.speed = 0
  this.time = 0
}

Game.prototype.removeAsteroids = function() {
  var thisGame = this
  this.asteroidsToRemove.forEach(function(asteroidIndex){
    thisGame.asteroids.splice(asteroidIndex, 1)
  })
  this.asteroidsToRemove = []
}

Game.prototype.update = function() {
  this.checkTime();
  this.removeAsteroids()
  if (this.dead === false) {
    this.ship.update()
  }
  if (this.keyboard.isDown(this.keyboard.KEYS.ENTER) && this.started === false) {
    this.startGame()
  }
  if (this.keyboard.isDown(this.keyboard.KEYS.ENTER) && this.gameOver === true) {
    this.startGame();
  }
  if (this.dead === true && this.gameOver === false) {
    this.respawnShip();
  }
}

Game.prototype.checkTime = function(){
  if (this.started === true && this.gameOver === false) { this.time += 1 }
  if (this.time > 1000){
    this.time = 0
    this.level += 1
  }
}

Game.prototype.checkShipCollision = function(){
  var shipCoordinates = [this.ship.point, this.ship.rightSide, this.ship.leftSide]
  var thisGame = this
  this.asteroids.forEach(function(asteroid){
    shipCoordinates.forEach(function(coordinate){
      if ((coordinate.x > asteroid.center.x - asteroid.radius + 5) &&
      (coordinate.x < asteroid.center.x + asteroid.radius - 5) &&
      (coordinate.y > asteroid.center.y - asteroid.radius + 5) &&
      (coordinate.y < asteroid.center.y + asteroid.radius - 5)) {
        if (thisGame.dead === false) {
          thisGame.killShip();
          console.log(thisGame.dead)
          console.log("hit")
        }
      }
    })
  })
}

Game.prototype.checkBulletCollision = function() {
  var bulletCoordinates = []
  this.ship.bullets.forEach(function(bullet) {
    bulletCoordinates.push(bullet.center);
  })
  var thisGame = this
  if (thisGame.ship.bullets.length > 0) {
    thisGame.asteroids.forEach(function(asteroid, asteroidIndex){
      thisGame.ship.bullets.forEach(function(bullet, bulletIndex){
        if ((bullet.center.x > asteroid.center.x - asteroid.radius + 5) &&
        (bullet.center.x < asteroid.center.x + asteroid.radius - 5) &&
        (bullet.center.y > asteroid.center.y - asteroid.radius + 5) &&
        (bullet.center.y < asteroid.center.y + asteroid.radius - 5)) {
          thisGame.ship.bullets.splice(bulletIndex, 1)
          thisGame.explodeAsteroid(asteroid)
          thisGame.asteroidsToRemove.push(asteroidIndex)
        }
      })
    })
  }
}

Game.prototype.explodeAsteroid = function(asteroid) {
  this.asteroidsDestroyed += 1
  this.calculateScore();
  if (asteroid.radius > 60) {
    this.createAsteroid(this.level, asteroid, 3)
  } else if (asteroid.radius > 30) {
    this.createAsteroid(this.level, asteroid, 2)
  }
}

Game.prototype.killShip = function(){
  this.lives -=1
  this.dead = true
  this.hideShip()
  this.ship.orientation = 4.7123;
  this.deadTime = this.time
  if (this.lives === 0) {
    this.gameOver = true
  }
}

Game.prototype.hideShip = function() {
  this.ship.hidden = true
  this.ship.point = {x: -1000, y: -1000}
}

Game.prototype.unHideShip = function() {
  this.ship.hidden = false
  this.ship.point = {x: 350, y: 300}
}

Game.prototype.blinkShip = function() {
  this.spawnTime += 1
  if (this.spawnTime < 10 ){
    this.hideShip()
  }
  else if (this.spawnTime > 20) {
    this.spawnTime = 0
    this.unHideShip()
  }
}

Game.prototype.respawnShip = function(){
  this.ship.speed = 0
  if (this.time > this.deadTime + 60) {
    this.unHideShip();
    this.blinkShip();
  }
  if (this.time > this.deadTime + 240) {
    this.dead = false
    this.unHideShip();
    this.deadTime = 0;
  }
}

Game.prototype.endGame = function() {
  this.context.font="55px Verdana"
  this.context.fillText("Game Over", 350, 215)
  this.context.font="20px Verdana"
  this.context.fillText("Press Enter to Play Again", 350, 450)
  this.context.fillText("Asteroids Destroyed: " + this.asteroidsDestroyed, 350, 275)
  this.context.fillText("Score: " + this.score, 350, 310)
  this.gameOver = true
}

Game.prototype.gameText = function() {
  this.context.textAlign = "center";
  if (this.started === false) {
    this.intro()
  }
  if (this.lives < 1){
    this.endGame();
  }
  this.calculateScore();
  this.context.font="15px Verdana"
  this.context.fillText("Level: " + this.level, 45, 25)
  this.context.fillText("Score: " + this.score, 635, 25)
  this.context.textAlign = "left";
  this.context.fillText(this.lifeChars[this.lives], 15, 45)
}

Game.prototype.calculateScore = function() {
  this.score = (this.level * this.asteroidsDestroyed * 10)
}

Game.prototype.intro = function() {
  this.context.font="45px Impact"
  this.context.fillText("ASTEROIDS", 350, 220)
  this.introTime += 1
  if (this.introTime < 25 ){
    this.context.font="20px Verdana"
    this.context.fillText("Hit Enter to Start!", 350, 250)
  }
  else if (this.introTime > 50){
    this.introTime = 0
  }
}

module.exports = Game;
<|endoftext|>


<commit_before>import path from 'path';
import _ from 'lodash';
import express from 'express';
import bodyParser from 'body-parser';
import compression from 'compression';
import * as reactRouter from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import DocumentTitle from 'react-document-title';
import fs from 'fs-extra';
import mime from 'mime';
import React from 'react';
import reactDomServer from 'react-dom/server';
import { Provider } from 'react-redux';
import { RouterContext } from 'react-router';
import controllerRoutes from './config/routes';
import reactAsync from './helpers/reactAsync';
import routes from './routes';
import createStore from './redux/createStore';

// Create a new Express app
const app = express();

const distDir = path.resolve(__dirname, '..', 'dist');

// Use gzipped version of assets if they are available and acceptable
app.use('/assets/bundle', (req, res, next) => {
  // Do nothing if client doesn't accept gzip encoding
  const accepts = req.headers['accept-encoding'];
  if(!(accepts && accepts.search(/[^\w]gzip[^\w]/))) {
    next();
    return;
  }

  const gzPath = `${req.url}.gz`;
  fs.access(path.join(distDir, gzPath), fs.constants.R_OK)
    .then(() => {
      res.set('Content-Type', mime.lookup(req.url));
      res.set('Content-Encoding', 'gzip');
      req.url = gzPath;
    })
    .catch(() => {})
    .then(() => next());
});

// Serve up our static assets from 'dist'
app.use('/assets/bundle', express.static(distDir));

const shouldCompress = (req, res) =>
  (req.headers['x-no-compression'] ? false : compression.filter(req, res));

app.use(compression({ filter: shouldCompress }));

app.use(bodyParser.json({ limit: '50mb' }));

controllerRoutes.connect(app);

app.use((req, res) => {
  const store = createStore();
  const history = syncHistoryWithStore(reactRouter.createMemoryHistory(), store);

  const matchOpts = { history, routes, location: req.url };
  reactRouter.match(matchOpts, (matchError, redirectLocation, renderProps) => {
    if(matchError) {
      res.status(500).send(matchError.message);
    } else if(redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if(!renderProps) {
      res.status(404).send('Not found');
    } else {
      const Root = () => (
        <Provider store={store}>
          <RouterContext {...renderProps} />
        </Provider>
      );

      // First render will kick off asynchronous calls
      reactDomServer.renderToString(<Root />);

      // Try to complete all asynchronous calls on the server
      Promise.race([
        Promise.all(reactAsync.promises),
        new Promise((resolve) => setTimeout(resolve, 200)) // Timeout after 200ms
      ]).then(() => {
        // Render a second time, but hopefully this time including the data
        // returned from asynchronous calls
        const reactHtml = reactDomServer.renderToString(<Root />);

        const title = DocumentTitle.rewind();

        // The HTML is pretty barebones, it just provides a mount point
        // for React and links to our styles and scripts.
        const htmlContent = `
          <!DOCTYPE html>

              <title>${title}</title>
              <link rel="stylesheet" type="text/css" href="/assets/bundle/vendor.css">
              <link rel="stylesheet" type="text/css" href="/assets/bundle/app.css">

${reactHtml}

          `;

        // Respond with the HTML
        res.send(htmlContent);
      }).catch((error) => {
        console.error(error);
        res.status(500).send(error.message);
      });
    }
  });
});

// Export the Express app
export default app;
<commit_msg>Serve files as subpaths from notebooks<commit_after>import path from 'path';
import _ from 'lodash';
import express from 'express';
import bodyParser from 'body-parser';
import compression from 'compression';
import * as reactRouter from 'react-router';
import { RouterContext } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import DocumentTitle from 'react-document-title';
import fs from 'fs-extra';
import mime from 'mime';
import React from 'react';
import reactDomServer from 'react-dom/server';
import { Provider } from 'react-redux';

import controllerRoutes from './config/routes';
import reactAsync from './helpers/reactAsync';
import routes from './routes';
import createStore from './redux/createStore';
import showoffConfig from './config/showoff';

const { uploadDir } = showoffConfig;

// Create a new Express app
const app = express();

const distDir = path.resolve(__dirname, '..', 'dist');

// Use gzipped version of assets if they are available and acceptable
app.use('/assets/bundle', (req, res, next) => {
  // Do nothing if client doesn't accept gzip encoding
  const accepts = req.headers['accept-encoding'];
  if(!(accepts && accepts.search(/[^\w]gzip[^\w]/))) {
    next();
    return;
  }

  const gzPath = `${req.url}.gz`;
  fs.access(path.join(distDir, gzPath), fs.constants.R_OK)
    .then(() => {
      res.set('Content-Type', mime.lookup(req.url));
      res.set('Content-Encoding', 'gzip');
      req.url = gzPath;
    })
    .catch(() => {})
    .then(() => next());
});

// Serve up our static assets from 'dist'
app.use('/assets/bundle', express.static(distDir));

// Serve uploaded static files for notebooks
app.use('/notebooks', express.static(path.join(uploadDir, 'notebooks')));

const shouldCompress = (req, res) =>
  (req.headers['x-no-compression'] ? false : compression.filter(req, res));

app.use(compression({ filter: shouldCompress }));

app.use(bodyParser.json({ limit: '50mb' }));

controllerRoutes.connect(app);

app.use((req, res) => {
  const store = createStore();
  const history = syncHistoryWithStore(reactRouter.createMemoryHistory(), store);

  const matchOpts = { history, routes, location: req.url };
  reactRouter.match(matchOpts, (matchError, redirectLocation, renderProps) => {
    if(matchError) {
      res.status(500).send(matchError.message);
    } else if(redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if(!renderProps) {
      res.status(404).send('Not found');
    } else {
      const Root = () => (
        <Provider store={store}>
          <RouterContext {...renderProps} />
        </Provider>
      );

      // First render will kick off asynchronous calls
      reactDomServer.renderToString(<Root />);

      // Try to complete all asynchronous calls on the server
      Promise.race([
        Promise.all(reactAsync.promises),
        new Promise((resolve) => setTimeout(resolve, 200)) // Timeout after 200ms
      ]).then(() => {
        // Render a second time, but hopefully this time including the data
        // returned from asynchronous calls
        const reactHtml = reactDomServer.renderToString(<Root />);

        const title = DocumentTitle.rewind();

        // The HTML is pretty barebones, it just provides a mount point
        // for React and links to our styles and scripts.
        const htmlContent = `
          <!DOCTYPE html>

              <title>${title}</title>
              <link rel="stylesheet" type="text/css" href="/assets/bundle/vendor.css">
              <link rel="stylesheet" type="text/css" href="/assets/bundle/app.css">

${reactHtml}

          `;

        // Respond with the HTML
        res.send(htmlContent);
      }).catch((error) => {
        console.error(error);
        res.status(500).send(error.message);
      });
    }
  });
});

// Export the Express app
export default app;
<|endoftext|>


<commit_before>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require("./enemies.js");
var Bluecifer = require('./bluecifer');

var themeSong = document.getElementById("theme-song");
var celebration = document.getElementById("celebration");

var scoreCounter = 0;
var enemies = [];

function Game() {
  this.canvas = canvas;
  this.ctx = this.canvas.getContext('2d');
  this.bluecifer = new Bluecifer (150, 150, 50, 41);
  this.enemy = new Enemy();
  this.active = true;
  this.enemies = enemies;
}

Game.prototype.repeat = function() {
    this.clearCanvas();
    this.bluecifer.draw(this.ctx);
    this.bluecifer.gravity();
    this.detectFloorCollision();
    this.createNewEnemies();
    this.drawEnemiesFromArray(this.ctx);
    // this.keepScore();
}

Game.prototype.clearCanvas = function() {
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}

Game.prototype.bluecifer = function() {
  this.bluecifer.draw(this.ctx);
}

Game.prototype.blueciferGravity = function() {
  this.bluecifer.gravity();
}

Game.prototype.createNewEnemies = function() {
this.enemy
if (scoreCounter % 50 === 0){
  if (this.enemies.length < 5){
    this.enemies.push(this.enemy, this.ctx);
  }
}
}

Game.prototype.drawEnemiesFromArray = function() {
  enemies.forEach(function(enemy) {
    enemy.draw(canvas.getContext("2d"));
    enemy.moveLeftRandom();
    this.collision(enemy, this.bluecifer);
  });
}

//collision functions below. Refactor these late to be in their own file
//airplane collistion
Game.prototype.collision = function(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width)) || collisionCanHappen === false) {
  //if there is no collision
  }
  else {
    // themeSong.pause();
    $('#game-over').css('visibility', 'visible')
    youAreDead();
    this.resetGame();
  }
}

//ceiling collision
Game.prototype.detectCeilingCollision = function() {
  if (this.bluecifer.y < 0) {
    this.bluecifer.y = this.bluecifer.y + 20;
  }
}

Game.prototype.detectFloorCollision = function() {
  if (this.bluecifer.y > 350) {
    // console.log('game over!')
    // themeSong.pause();
    this.resetGame();
    this.youAreDead();
    this.bluecifer.y = 300;
  }
}

Game.prototype.airportCollision = function(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    // themeSong.pause();
    // celebration.play();
    $("#message-center").text("You win! Your score was " + scoreCounter);
    bluecifer.y = 1000;
    setTimeout(function() {
      resetGame();
    }, 3000);
  }
};

Game.prototype.resetGame = function() {
  location.reload();
  $('start-game').css('visibility', 'hidden');
  $('game-over').css('visibility', 'hidden');
  this.repeat();
}

Game.prototype.keepScore = function() {
  var currentScore = scoreCounter++;
  if (currentScore <= 100){
    $('#game-score').text("000" + currentScore);
  } else if (currentScore <= 1000){
    $('#game-score').text("00" + currentScore);
  } else if (currentScore <= 10000){
    $('#game-score').text("0" + currentScore);
    // drawAirport();
  } else {
    $('#game-score').text(currentScore);
  }
}

Game.prototype.youAreDead = function() {
  $('#game-over').css('visibility', 'visible');
  this.stop();
}

module.exports = Game;
<commit_msg>plane collision reading in cosole, but not staggering items inside the array<commit_after>var $ = require('jquery');

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var Enemy = require("./enemies.js");
var Bluecifer = require('./bluecifer');

var themeSong = document.getElementById("theme-song");
var celebration = document.getElementById("celebration");

var scoreCounter = 0;
var enemies = [];

function Game() {
  this.canvas = canvas;
  this.ctx = this.canvas.getContext('2d');
  this.bluecifer = new Bluecifer (150, 150, 50, 41);
  this.enemy = new Enemy();
  this.active = true;
  this.enemies = enemies;
}

Game.prototype.repeat = function() {
    this.clearCanvas();
    this.bluecifer.draw(this.ctx);
    this.bluecifer.gravity();
    this.detectFloorCollision();
    this.createNewEnemies();
    this.drawEnemiesFromArray(this.ctx);
    // this.keepScore();
}

Game.prototype.clearCanvas = function() {
  this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}

Game.prototype.bluecifer = function() {
  this.bluecifer.draw(this.ctx);
}

Game.prototype.blueciferGravity = function() {
  this.bluecifer.gravity();
}

Game.prototype.createNewEnemies = function() {
this.enemy
if (scoreCounter % 50 === 0){
  if (this.enemies.length < 5){
    this.enemies.push(this.enemy);
  }
}
}

Game.prototype.drawEnemiesFromArray = function() {
  var game = new Game();
  enemies.forEach(function(enemy) {
    enemy.draw(canvas.getContext("2d"));
    game.collision(enemy, game.bluecifer);
    enemy.moveLeftRandom();
  });
}

//collision functions below. Refactor these late to be in their own file
//airplane collistion
Game.prototype.collision = function(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    console.log('youre dead')
    // themeSong.pause();
    $('#game-over').css('visibility', 'visible')
    youAreDead();
    this.resetGame();
  }
}

//ceiling collision
Game.prototype.detectCeilingCollision = function() {
  if (this.bluecifer.y < 0) {
    this.bluecifer.y = this.bluecifer.y + 20;
  }
}

Game.prototype.detectFloorCollision = function() {
  if (this.bluecifer.y > 350) {
    // console.log('game over!')
    // themeSong.pause();
    this.resetGame();
    this.youAreDead();
    this.bluecifer.y = 300;
  }
}

Game.prototype.airportCollision = function(a, b) {
  if (((a.y + a.height) < (b.y)) || (a.y > (b.y + b.height)) || ((a.x + a.width) < b.x) || (a.x > (b.x + b.width))) {
  //if there is no collision
  }
  else {
    // themeSong.pause();
    // celebration.play();
    $("#message-center").text("You win! Your score was " + scoreCounter);
    bluecifer.y = 1000;
    setTimeout(function() {
      resetGame();
    }, 3000);
  }
};

Game.prototype.resetGame = function() {
  location.reload();
  $('start-game').css('visibility', 'hidden');
  $('game-over').css('visibility', 'hidden');
  this.repeat();
}

Game.prototype.keepScore = function() {
  var currentScore = scoreCounter++;
  if (currentScore <= 100){
    $('#game-score').text("000" + currentScore);
  } else if (currentScore <= 1000){
    $('#game-score').text("00" + currentScore);
  } else if (currentScore <= 10000){
    $('#game-score').text("0" + currentScore);
    // drawAirport();
  } else {
    $('#game-score').text(currentScore);
  }
}

Game.prototype.youAreDead = function() {
  $('#game-over').css('visibility', 'visible');
  this.stop();
}

module.exports = Game;
<|endoftext|>


<commit_before>const $ = require('jquery');

const Playfield = require('./playfield');
const Face = require('./face');
const Tomato = require('./tomato');

function Game(canvas, context) {
  this.context = context;
  this.tomatoes = [];
  this.playfield = new Playfield(context, canvas.width, canvas.height);
  this.face = new Face(context, {x: (canvas.width - 100), y: (canvas.height - 300)});
  this.tomatoCounter = 5;
}

Game.prototype = {
  start: function() {
    $(document).keydown(onKeyDown.bind(this));

    function onKeyDown(event) {
      var face = this.face;

      var keys = {
        37: face.moveLeft,
        38: face.moveUp,
        39: face.moveRight,
        40: face.moveDown
      };

      //keys[event.which] = true;
      keys[event.keyCode].bind(face)()
    }
    //add listeners for collision and board edges on face
    // add listener for each tomato as it is created
    // remove listener for each tomato as it is popped off

    // var counter = Time.now (when time is one second from now, throw tomato
    // once counter hits, add tomato to array, throw tomato, tomatocounter +=1
    // OR once counter hits, go faster so one tomato is being thrown faster and faster
    // check which key is pressed, and tell the face to move depending
    // check if face and any tomato has any collisions and respond accordingly
  }
};

Game.prototype.addTomato = function() {
  var tomato = new Tomato(this.context, {x: (Math.floor(Math.random() * (775 - 20 + 1)) + 1), y: (Math.floor(Math.random() * (575 - 20 + 1)) + 1)});
  this.tomatoes.push(tomato)
};

Game.prototype.renderUniverse = function() {
  this.playfield.draw();
  this.face.draw();
  this.tomatoes.forEach(function (tomato) {
    tomato.draw()
  });
};

Game.prototype.updateTomatoPositions = function() {
  this.tomatoes.forEach(function (tomato) {
    tomato.updatePosition();
  });
};

Game.prototype.detectCollisions = function() {
  this.tomatoes.forEach(function (tomato) {
    if (this.distanceBetweenTomatoAndFace(tomato) < (tomato.size + this.face.size)) {
      this.face.handleCollision();
    }
  }, this);
};

Game.prototype.distanceBetweenTomatoAndFace = function (tomato) {
  var xDistance = tomato.center.x - this.face.center.x;
  var yDistance = tomato.center.y - this.face.center.y;
  return (Math.sqrt((xDistance * xDistance) + (yDistance * yDistance)));
};

Game.prototype.loadTomatoes = function () {
  for (var i = 0; i < this.tomatoCounter; i++) {
    this.addTomato();
  }
  this.tomatoCounter += 1
};

module.exports = Game;
<commit_msg>updated tomato array to start off-screen on x axis<commit_after>const $ = require('jquery');

const Playfield = require('./playfield');
const Face = require('./face');
const Tomato = require('./tomato');

function Game(canvas, context) {
  this.context = context;
  this.tomatoes = [];
  this.playfield = new Playfield(context, canvas.width, canvas.height);
  this.face = new Face(context, {x: (canvas.width - 100), y: (canvas.height - 300)});
  this.tomatoCounter = 5;
}

Game.prototype = {
  start: function() {
    $(document).keydown(onKeyDown.bind(this));

    function onKeyDown(event) {
      var face = this.face;

      var keys = {
        37: face.moveLeft,
        38: face.moveUp,
        39: face.moveRight,
        40: face.moveDown
      };

      //keys[event.which] = true;
      keys[event.keyCode].bind(face)()
    }
    //add listeners for collision and board edges on face
    // add listener for each tomato as it is created
    // remove listener for each tomato as it is popped off

    // var counter = Time.now (when time is one second from now, throw tomato
    // once counter hits, add tomato to array, throw tomato, tomatocounter +=1
    // OR once counter hits, go faster so one tomato is being thrown faster and faster
    // check which key is pressed, and tell the face to move depending
    // check if face and any tomato has any collisions and respond accordingly
  }
};

Game.prototype.addTomato = function() {
  var tomato = new Tomato(this.context, {x: -15, y: (Math.floor(Math.random() * (575 - 20 + 1)) + 1)});
  this.tomatoes.push(tomato)
};

Game.prototype.renderUniverse = function() {
  this.playfield.draw();
  this.face.draw();
  this.tomatoes.forEach(function (tomato) {
    tomato.draw()
  });
};

Game.prototype.updateTomatoPositions = function() {
  this.tomatoes.forEach(function (tomato) {
    tomato.updatePosition();
  });
};

Game.prototype.detectCollisions = function() {
  this.tomatoes.forEach(function (tomato) {
    if (this.distanceBetweenTomatoAndFace(tomato) < (tomato.size + this.face.size)) {
      this.face.handleCollision();
    }
  }, this);
};

Game.prototype.distanceBetweenTomatoAndFace = function (tomato) {
  var xDistance = tomato.center.x - this.face.center.x;
  var yDistance = tomato.center.y - this.face.center.y;
  return (Math.sqrt((xDistance * xDistance) + (yDistance * yDistance)));
};

Game.prototype.loadTomatoes = function () {
  for (var i = 0; i < this.tomatoCounter; i++) {
    this.addTomato();
  }
  this.tomatoCounter += 1
};

module.exports = Game;
<|endoftext|>


<commit_before>import {Rx} from '@cycle/core';
import {h} from '@cycle/dom';

export default function main ({DOM}) {
  return {
    DOM: Rx.Observable.just(h('.hi', 'Hello world'))
  };
}

<commit_msg>Display todos<commit_after>import {Rx} from '@cycle/core';
import {h} from '@cycle/dom';

function todoView ({todo, complete}) {
  return (
    h('.todo', [
      h('span.title', todo),
      h('input.complete', {type: 'checkbox', checked: complete})
    ])
  );
}

function todosView (todos) {
  return (
    h('.todos', todos.map(todoView))
  );
}

export default function main ({DOM}) {
  const todos$ = Rx.Observable.just([
    {todo: 'Display todos', complete: true},
    {todo: 'Add todos', complete: false}
  ]);

  return {
    DOM: todos$.map(todosView)
  };
}

<|endoftext|>


<commit_before>import 'bootstrap';
import 'bootstrap/css/bootstrap.css!';

export class App {
  configureRouter(config, router){
    config.title = 'Snipperino';
    config.map([
      { route: ['','welcome'], name: 'welcome',      moduleId: './welcome',      nav: true, title:'Welcome' },
      { route: 'flickr',       name: 'flickr',       moduleId: './flickr',       nav: true, title:'Flickr' },
      { route: 'child-router', name: 'child-router', moduleId: './child-router', nav: true, title:'Child Router' }
    ]);

    this.router = router;
  }
}
<commit_msg>update routes to include just our snippets module<commit_after>import 'bootstrap';
import 'bootstrap/css/bootstrap.css!';

export class App {
  configureRouter(config, router){
    config.title = 'Snipperino';
    config.map([
      {
        route: ['','welcome'],
        name: 'welcome',
        moduleId: './welcome',
        nav: true,
        title: 'Welcome'
      },
      {
        route: 'snippets',
        name: 'snippets',
        moduleId: './snippets',
        nav: true,
        title: 'Snippets'
      }
    ]);

    this.router = router;
  }
}
<|endoftext|>


<commit_before>const $ = require('jquery');

const Player = require('./player');

function Game(board) {
    this.board = board;
    this.players = [new Player('player1', 'black'), new Player('player2', 'white')];
    this.currentPlayer = null;
    this.turn = 0;
    this.over = false;
}

Game.prototype.welcome = function() {
    $('#welcome').prepend(`<h1>Welcome to Othello</h1>`);
};

module.exports = Game;

//if (this.turn % 2 === 0) {
//    //$('#turn').prepend(`<h1>${this.players[1].name} turn</h1>`);
//    //} else {
//    //$('#turn').prepend(`<h1>${this.players[0].name} turn</h1>`);
//    //}

//Game.prototype.start = function(){
//    welcomePlayers(this.players);
//    placeFirstFourPieces(this);
//};
//
//Game.prototype.respondToClick = function(x, y) {
//    //if (this.turn % 2 === 0) {
//    //$('#turn').prepend(`<h1>${this.players[1].name} turn</h1>`);
//    //} else {
//    //$('#turn').prepend(`<h1>${this.players[0].name} turn</h1>`);
//    //}
//    var selectedSquareArray = this.board.squares.filter(function(square){
//        var xMatch = (x >= square.x) && (x <= square.x + square.width);
//        var yMatch = (y >= square.y) && (y <= square.y + square.width);
//        return xMatch && yMatch;
//    });
//    if (selectedSquareArray[0].piece){
//        console.log('cannot do that');
//    } else {
//        $('#turn').html('');
//        if (this.turn % 2 === 0){
//            $('#turn').prepend(`<h1>${this.players[1].name} turn</h1>`);
//            selectedSquareArray[0].placePiece(this.players[0].color);
//        } else {
//            selectedSquareArray[0].placePiece(this.players[1].color);
//            $('#turn').prepend(`<h1>${this.players[0].name} turn</h1>`);
//        }
//        this.turn ++;
//        console.log(this.turn);
//    }
//};
//
//function placeFirstFourPieces(game) {
//    var square0 = game.board.squares[27];
//    var square1 = game.board.squares[28];
//    var square2 = game.board.squares[36];
//    var square3 = game.board.squares[35];
//
//    var squares = [square0, square1, square2, square3];
//
//    squares.forEach(function(square,index){
//        if (index % 2 == 0){
//            square.placePiece(game.players[0].color);
//        } else {
//            square.placePiece(game.players[1].color);
//        }
//    });
//};
//
//function welcomePlayers(players) {
//    var first = players[0];
//    var second = players[1];
//    $('#title').prepend(`<h1>Welcome ${first.name}(${first.color}) and ${second.name}(${second.color})!</h1>`)
//}
<commit_msg>Add player1 name form<commit_after>const $ = require('jquery');

const Player = require('./player');

function Game(board) {
    this.board = board;
    this.players = [new Player('player1', 'black'), new Player('player2', 'white')];
    this.currentPlayer = null;
    this.turn = 0;
    this.over = false;
}

Game.prototype.welcome = function() {
    $('#welcome').prepend(`<h1>Welcome to Othello</h1> ${createForm()}`);
};

function createForm(){
    return `Player1:
            <input type="text" id="player1">
`;
}

module.exports = Game;

//Title:
//<input type="text" id="edit-title" value="<%= @idea.title %>">

//Body:
//<input type="text" id="edit-body" value="<%= @idea.body %>">

//<input id="edit-id" type="hidden" value="<%= @idea.id %>">
//<input type="submit" value="Save" id="edit">
//if (this.turn % 2 === 0) {
//    //$('#turn').prepend(`<h1>${this.players[1].name} turn</h1>`);
//    //} else {
//    //$('#turn').prepend(`<h1>${this.players[0].name} turn</h1>`);
//    //}

//Game.prototype.start = function(){
//    welcomePlayers(this.players);
//    placeFirstFourPieces(this);
//};
//
//Game.prototype.respondToClick = function(x, y) {
//    //if (this.turn % 2 === 0) {
//    //$('#turn').prepend(`<h1>${this.players[1].name} turn</h1>`);
//    //} else {
//    //$('#turn').prepend(`<h1>${this.players[0].name} turn</h1>`);
//    //}
//    var selectedSquareArray = this.board.squares.filter(function(square){
//        var xMatch = (x >= square.x) && (x <= square.x + square.width);
//        var yMatch = (y >= square.y) && (y <= square.y + square.width);
//        return xMatch && yMatch;
//    });
//    if (selectedSquareArray[0].piece){
//        console.log('cannot do that');
//    } else {
//        $('#turn').html('');
//        if (this.turn % 2 === 0){
//            $('#turn').prepend(`<h1>${this.players[1].name} turn</h1>`);
//            selectedSquareArray[0].placePiece(this.players[0].color);
//        } else {
//            selectedSquareArray[0].placePiece(this.players[1].color);
//            $('#turn').prepend(`<h1>${this.players[0].name} turn</h1>`);
//        }
//        this.turn ++;
//        console.log(this.turn);
//    }
//};
//
//function placeFirstFourPieces(game) {
//    var square0 = game.board.squares[27];
//    var square1 = game.board.squares[28];
//    var square2 = game.board.squares[36];
//    var square3 = game.board.squares[35];
//
//    var squares = [square0, square1, square2, square3];
//
//    squares.forEach(function(square,index){
//        if (index % 2 == 0){
//            square.placePiece(game.players[0].color);
//        } else {
//            square.placePiece(game.players[1].color);
//        }
//    });
//};
//
//function welcomePlayers(players) {
//    var first = players[0];
//    var second = players[1];
//    $('#title').prepend(`<h1>Welcome ${first.name}(${first.color}) and ${second.name}(${second.color})!</h1>`)
//}
<|endoftext|>


<commit_before>import * as d3 from 'd3';
import Codeck from './Codeck';

const { floor } = Math;
const codeck = new Codeck();

const svg = d3.select('#cards svg')
  .attr('width', '600px')
  .attr('height', '400px');

const messageInput = d3.select('#message');
const cleanedMessageSpan = d3.select('.cleanednotification');

messageInput.node().maxLength = codeck.maxLength;
messageInput.node().size = codeck.maxLength;

const cards = {};
codeck.deck.forEach((key, idx) => {
  cards[key] = { key, idx, dragging: false, dx: 0, dy: 0 };
});

const cardOrder = codeck.deck.slice(); // copy of deck.

let debounceInputId = -1;
messageInput.on('keyup', () => {
  clearTimeout(debounceInputId);
  debounceInputId = setTimeout(updateMessage, 300);
});

function cleanMessage(text) {
  return text.toUpperCase().trim()
    .replace(/['"]/g, ',')
    .replace(/[!?]/g, '.')
    .replace(/[^A-Z0-9,. ]/g, '');
}

function updateMessage() {
  const typedMessage = messageInput.node().value;
  const cleanedMessage = cleanMessage(messageInput.node().value);
  const newOrder = codeck.encode(cleanedMessage.toLowerCase());
  newOrder.forEach((cardKey, i) => {
    cardOrder[i] = cardKey;
    cards[cardKey].idx = i;
  });
  if (typedMessage === cleanedMessage) {
    cleanedMessageSpan.classed('hide', true);
  } else {
    cleanedMessageSpan
      .classed('hide', false)
      .select('span')
        .text(cleanedMessage);
  }
  renderCards();
}

function moveCard(card, di) {
  if (card + di > cardOrder.length || card + di < 0) return;

  if (di > 0) {
    for (let i = card.idx; i < card.idx + di; i++) {
      cardOrder[i] = cardOrder[i + 1];
      cards[cardOrder[i]].idx = i;
    }
  } else if (di < 0) {
    for (let i = card.idx; i > card.idx + di; i--) {
      cardOrder[i] = cardOrder[i - 1];
      cards[cardOrder[i]].idx = i;
    }
  }
  cardOrder[card.idx + di] = card.key;
  card.idx += di;
  renderCards();
}

function renderCards() {
  svg.selectAll('.card').transition()
    .delay(d => d.idx * 5)
    .filter(d => !d.dragging)
    .attr('transform', d =>
      `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragstarted(d) {
  d.dragging = true;
  d3.select(this).style('filter', 'url(#shadow)');
}

function dragged(d) {
  d.dx += d3.event.dx;
  d.dy += d3.event.dy;
  if (d.dx > 28) {
    d.dx -= 48;
    moveCard(d, 1);
  } else if (d.dx < -28) {
    d.dx += 48;
    moveCard(d, -1);
  }
  if (d.dy > 34) {
    d.dy -= 60;
    moveCard(d, 9);
  } else if (d.dy < -34) {
    d.dy += 60;
    moveCard(d, -9);
  }
  d3.select(this).attr('transform', d =>
    `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragended(d) {
  d.dx = 0;
  d.dy = 0;
  d.dragging = false;
  d3.select(this).style('filter', null);
  renderCards();
  const message = codeck.decode(cardOrder);
  messageInput.node().value = message.trim().toUpperCase();
  cleanedMessageSpan.classed('hide', true);
}

function showCardsInit() {
  svg.selectAll('.card')
    .data(Object.values(cards), card => card.key)
    .enter().append('text')
      .attr('class', 'card')
      .attr('transform', 'translate(0, 0)')
      .text(card => card.key)
      .attr('y', 60)
      .attr('fill', d => (floor(d.idx / 13) % 2 !== 0) ? 'red' : 'black')
      .call(d3.drag()
        .on('start', dragstarted)
        .on('drag', dragged)
        .on('end', dragended));
  renderCards();
}

setTimeout(showCardsInit, 300);
<commit_msg>Change debounce interval from 300ms to 25ms<commit_after>import * as d3 from 'd3';
import Codeck from './Codeck';

const { floor } = Math;
const codeck = new Codeck();

const svg = d3.select('#cards svg')
  .attr('width', '600px')
  .attr('height', '400px');

const messageInput = d3.select('#message');
const cleanedMessageSpan = d3.select('.cleanednotification');

messageInput.node().maxLength = codeck.maxLength;
messageInput.node().size = codeck.maxLength;

const cards = {};
codeck.deck.forEach((key, idx) => {
  cards[key] = { key, idx, dragging: false, dx: 0, dy: 0 };
});

const cardOrder = codeck.deck.slice(); // copy of deck.

let debounceInputId = -1;
messageInput.on('keyup', () => {
  clearTimeout(debounceInputId);
  debounceInputId = setTimeout(updateMessage, 25);
});

function cleanMessage(text) {
  return text.toUpperCase().trim()
    .replace(/['"]/g, ',')
    .replace(/[!?]/g, '.')
    .replace(/[^A-Z0-9,. ]/g, '');
}

function updateMessage() {
  const typedMessage = messageInput.node().value;
  const cleanedMessage = cleanMessage(messageInput.node().value);
  const newOrder = codeck.encode(cleanedMessage.toLowerCase());
  newOrder.forEach((cardKey, i) => {
    cardOrder[i] = cardKey;
    cards[cardKey].idx = i;
  });
  if (typedMessage === cleanedMessage) {
    cleanedMessageSpan.classed('hide', true);
  } else {
    cleanedMessageSpan
      .classed('hide', false)
      .select('span')
        .text(cleanedMessage);
  }
  renderCards();
}

function moveCard(card, di) {
  if (card + di > cardOrder.length || card + di < 0) return;

  if (di > 0) {
    for (let i = card.idx; i < card.idx + di; i++) {
      cardOrder[i] = cardOrder[i + 1];
      cards[cardOrder[i]].idx = i;
    }
  } else if (di < 0) {
    for (let i = card.idx; i > card.idx + di; i--) {
      cardOrder[i] = cardOrder[i - 1];
      cards[cardOrder[i]].idx = i;
    }
  }
  cardOrder[card.idx + di] = card.key;
  card.idx += di;
  renderCards();
}

function renderCards() {
  svg.selectAll('.card').transition()
    .delay(d => d.idx * 5)
    .filter(d => !d.dragging)
    .attr('transform', d =>
      `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragstarted(d) {
  d.dragging = true;
  d3.select(this).style('filter', 'url(#shadow)');
}

function dragged(d) {
  d.dx += d3.event.dx;
  d.dy += d3.event.dy;
  if (d.dx > 28) {
    d.dx -= 48;
    moveCard(d, 1);
  } else if (d.dx < -28) {
    d.dx += 48;
    moveCard(d, -1);
  }
  if (d.dy > 34) {
    d.dy -= 60;
    moveCard(d, 9);
  } else if (d.dy < -34) {
    d.dy += 60;
    moveCard(d, -9);
  }
  d3.select(this).attr('transform', d =>
    `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`);
}

function dragended(d) {
  d.dx = 0;
  d.dy = 0;
  d.dragging = false;
  d3.select(this).style('filter', null);
  renderCards();
  const message = codeck.decode(cardOrder);
  messageInput.node().value = message.trim().toUpperCase();
  cleanedMessageSpan.classed('hide', true);
}

function showCardsInit() {
  svg.selectAll('.card')
    .data(Object.values(cards), card => card.key)
    .enter().append('text')
      .attr('class', 'card')
      .attr('transform', 'translate(0, 0)')
      .text(card => card.key)
      .attr('y', 60)
      .attr('fill', d => (floor(d.idx / 13) % 2 !== 0) ? 'red' : 'black')
      .call(d3.drag()
        .on('start', dragstarted)
        .on('drag', dragged)
        .on('end', dragended));
  renderCards();
}

setTimeout(showCardsInit, 25);
<|endoftext|>


<commit_before>function pasteHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}

function addToObject(object, otherObject){
    for(let prop in otherObject){
        if(otherObject.hasOwnProperty(prop)){
            object[prop] = otherObject[prop];
        }
    }
    return object
}

let makeIterable = function(object){
    object[Symbol.iterator] = function *(){
        let names = Object.getOwnPropertyNames(this);
        let i = 0;
        while(i < names.length){
            yield this[names[i]];
            i++;
        }
    }
    return object
}

let mapEmojis = function(matches, html){
    matches = matches ? matches : [];
    for(let match of matches){
        let matchWithoutColons = match.slice(1, -1);
        matchEmoji = matchMap[matchWithoutColons];
        if(matchEmoji){
            html = html.replace(match, matchEmoji);
        }
    }
    return html
}

let searchForMatch = function(match, matchMap){
    let searchResult = "";
    for(let emoji in matchMap){
        if(emoji.indexOf(match) == 0){
            searchResult = emoji;
            break;
        }
    }
    return searchResult
}

let searchHandler = function(matches, $emoji){
    if(matches){
        let match = matches[0]
        match = match.slice(1, match.length);
        $emoji.html(searchForMatch(match, matchMap));
    } else {
        $emoji.html("");
    }
}

let emojis = require('discord-emoji');
emojis = makeIterable(emojis);

let matchMap = {};
for(let object of emojis){
    matchMap = addToObject(matchMap, object);
}
matchMap = makeIterable(matchMap);

$('body').on('DOMNodeInserted', '[contenteditable="true"]', function(){
    let reCommand = /:[a-zA-Z0-9-_]+:/;
    let reSearch = /:[a-zA-Z0-9-_]+$/;
    let $self = $(this);
    let $parent = $self.parent();
    if($parent.find('.emoji').length == 0){
        let $div = $('<div/>').addClass('emoji').css('color', 'gray');
        let $predictionSpan = $('<span/>').addClass('emoji-prediction');
        $div.insertAfter($self);
        $div.append($predictionSpan);
    }
    let $emoji = $parent.find('.emoji-prediction');
    $self.off('keypress');
    $self.off('keydown');
    $self.keydown(function(event){
        if(event.which == 8 || event.which == 13){
            let $this = $(this);
            let $span = $this.find('[data-text="true"]');
            let html = $span.html();
            if(event.which == 8){
                html = html.slice(0, -1)
            }
            let matches = reSearch.exec(html);
            searchHandler(matches, $emoji);
        }
    })
    $self.keypress(function(event){
        let character = String.fromCharCode(event.which);
        let $this = $(this);
        let $span = $this.find('[data-text="true"]');
        let textObj = $span[0].firstChild;
        let html = $span.html();
        let matches = reCommand.exec(html);
        let newHtml = mapEmojis(matches, html);
        if(newHtml != html){
            pasteHtmlAtCaret(newHtml);
            $emoji.html("");
        } else {
            html = html + character;
            matches = reSearch.exec(html)
            searchHandler(matches, $emoji);
        }
    })
})
<commit_msg>Fixed for enter too.<commit_after>function pasteHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}

function addToObject(object, otherObject){
    for(let prop in otherObject){
        if(otherObject.hasOwnProperty(prop)){
            object[prop] = otherObject[prop];
        }
    }
    return object
}

let makeIterable = function(object){
    object[Symbol.iterator] = function *(){
        let names = Object.getOwnPropertyNames(this);
        let i = 0;
        while(i < names.length){
            yield this[names[i]];
            i++;
        }
    }
    return object
}

let mapEmojis = function(matches, html){
    matches = matches ? matches : [];
    for(let match of matches){
        let matchWithoutColons = match.slice(1, -1);
        matchEmoji = matchMap[matchWithoutColons];
        if(matchEmoji){
            html = html.replace(match, matchEmoji);
        }
    }
    return html
}

let searchForMatch = function(match, matchMap){
    let searchResult = "";
    for(let emoji in matchMap){
        if(emoji.indexOf(match) == 0){
            searchResult = emoji;
            break;
        }
    }
    return searchResult
}

let searchHandler = function(matches, $emoji){
    if(matches){
        let match = matches[0]
        match = match.slice(1, match.length);
        $emoji.html(searchForMatch(match, matchMap));
    } else {
        $emoji.html("");
    }
}

let emojis = require('discord-emoji');
emojis = makeIterable(emojis);

let matchMap = {};
for(let object of emojis){
    matchMap = addToObject(matchMap, object);
}
matchMap = makeIterable(matchMap);

$('body').on('DOMNodeInserted', '[contenteditable="true"]', function(){
    let reCommand = /:[a-zA-Z0-9-_]+:/;
    let reSearch = /:[a-zA-Z0-9-_]+$/;
    let $self = $(this);
    let $parent = $self.parent();
    if($parent.find('.emoji').length == 0){
        let $div = $('<div/>').addClass('emoji').css('color', 'gray');
        let $predictionSpan = $('<span/>').addClass('emoji-prediction');
        $div.insertAfter($self);
        $div.append($predictionSpan);
    }
    let $emoji = $parent.find('.emoji-prediction');
    $self.off('keypress');
    $self.off('keydown');
    $self.keydown(function(event){
        let $this = $(this);
        let $span = $this.find('[data-text="true"]');
        let html = $span.html();
        if(event.which == 8){
            html = html.slice(0, -1)
            let matches = reSearch.exec(html);
            searchHandler(matches, $emoji);
        } else if(event.which == 13) {
            searchHandler(null, $emoji);
        }
    })
    $self.keypress(function(event){
        let character = String.fromCharCode(event.which);
        let $this = $(this);
        let $span = $this.find('[data-text="true"]');
        let textObj = $span[0].firstChild;
        let html = $span.html();
        let matches = reCommand.exec(html);
        let newHtml = mapEmojis(matches, html);
        if(newHtml != html){
            pasteHtmlAtCaret(newHtml);
            $emoji.html("");
        } else {
            html = html + character;
            matches = reSearch.exec(html)
            searchHandler(matches, $emoji);
        }
    })
})
<|endoftext|>


<commit_before>var env = 'local';
var api_url;
var admin_url;

if (env == 'local') {
    admin_url = "http://admin.forum.dev/";
    api_url = './data/';
} else {
    admin_url = 'http://admin.forum.dev/';
    api_url = 'http://api.forum.dev/';
}

var app = angular.module('app', ['ngResource',
    'oc.lazyLoad',
    'app.config',
    'ui.router',
    'ngSanitize',
    'angular-bind-html-compile',
    'localytics.directives',
    'ngTouch',
    'underscore',
    'ngMessages',
    'angularMoment',
    'commons',
    'accueil',
    'authentification',
    'biensePreparer',
    'exposants',
    'infosPratique'
]).constant('urls', {
    API: api_url,
    ADMIN: admin_url
});

app.config(
    function ($stateProvider, $httpProvider, $urlRouterProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = undefined;
        $httpProvider.defaults.headers.put['Content-Type'] = undefined;
        $httpProvider.defaults.transformRequest = angular.identity;

        $urlRouterProvider.otherwise("accueil");
        $stateProvider
            .state('index', {
                abstract: true,
                url: "/", // root route
                templateUrl: 'index.html'
            })
            .state('accueil', {
                url: "/accueil?target_area",
                templateUrl: 'src/accueil/accueil.html',
                controller: 'accueilController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'accueil',
                            files: [
                                'src/accueil/accueilController.js',
                                'src/accueil/accueilService.js'
                            ]
                        });
                    }]
                }
            })
            .state('actualites', {
                url: '/actualites/{id:[0-9]*}',
                templateUrl: 'src/accueil/accueil.html',
                controller: 'accueilController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'actualites',
                            files: [
                                'src/accueil/accueilController.js',
                                'src/accueil/accueilService.js'
                            ]
                        });
                    }]
                }
            })
            .state('connexion', {
                url: "/connexion",
                templateUrl: 'src/authentification/authentification.html',
                controller: 'authentificationController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'authentification',
                            files: [
                                'src/authentification/authentificationController.js',
                                'src/authentification/authentificationService.js'
                            ]
                        });
                    }]
                }
            })
            .state('inscription', {
                url: "/inscription",
                templateUrl: 'src/authentification/authentification.html',
                controller: 'authentificationController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'authentification',
                            files: [
                                'src/authentification/authentificationController.js',
                                'src/authentification/authentificationService.js'
                            ]
                        });
                    }]
                }
            })
            .state('biensepreparer', {
                url: "/biensepreparer",
                templateUrl: 'src/bien_se_preparer/bien_se_preparer.html',
                controller: 'biensePreparerController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'biensePreparer',
                            files: [
                                'src/bien_se_preparer/biensePreparerController.js',
                                'src/bien_se_preparer/biensePreparerService.js'
                            ]
                        });
                    }]
                }
            })
            .state('listeExposants', {
                url: "/exposants",
                templateUrl: 'src/exposants/exposants.html',
                controller: 'exposantsController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'listeExposants',
                            files: [
                                'src/exposants/exposantsController.js',
                                'src/exposants/exposantsService.js'
                            ]
                        });
                    }]
                }
            })
            .state('exposants', {
                url: "/exposants/{id:[0-9]*}",
                templateUrl: 'src/exposants/exposants.html',
                controller: 'exposantsController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'exposants',
                            files: [
                                'src/exposants/exposantsController.js',
                                'src/exposants/exposantsService.js'
                            ]
                        });
                    }]
                }
            })
            .state('infospratiques', {
                url: "/infospratiques",
                templateUrl: 'src/infos_pratique/infos_pratique.html',
                controller: 'infosPratiqueController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'infosPratique',
                            files: [
                                'src/infos_pratique/infosPratiqueController.js',
                                'src/infos_pratique/infosPratiqueService.js',
                                'src/exposants/exposantsService.js'
                            ]
                        });
                    }]
                }
            });
        $httpProvider.interceptors.push('app.httpinterceptor');
    });

app.run(function ($rootScope, $location, $http) {
    console.log("app run ");
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
    });
});

//Intercepteur HTTP
app.factory('app.httpinterceptor', function ($q, $rootScope, $location) {
    return {
        // optional method
        'request': function (config) {
            return config || $q.when(config);
        },
        // optional method
        'requestError': function (rejection) {
            return $q.reject(rejection);
        },
        // optional method
        'response': function (response) {
            return response || $q.when(response);
        },
        // optional method
        'responseError': function (rejection) {
            if (rejection.status === 403) {
                $location.path('/accueil');
            }
            return $q.reject(rejection);
        }
    };
});

<commit_msg>Modification pour api et mep<commit_after>var env = 'local';
var api_url;
var admin_url;

if (env == 'local') {
    admin_url = "http://admin.forum.dev/";
    api_url = './data/';
} else if (env == 'test') {
    admin_url = 'http://admin.forum.dev/';
    api_url = 'http://api.forum.dev/';
} else if (env == 'pprod') {
    admin_url = 'http://admin.forum-am.neoxia-forge.com/';
    api_url = 'http://admin.forum-am.neoxia-forge.com/';
} else {
    admin_url = 'http://admin.forum-am.fr/';
    api_url = 'http://api.forum-am.fr/';
}

var app = angular.module('app', ['ngResource',
    'oc.lazyLoad',
    'app.config',
    'ui.router',
    'ngSanitize',
    'angular-bind-html-compile',
    'localytics.directives',
    'ngTouch',
    'underscore',
    'ngMessages',
    'angularMoment',
    'commons',
    'accueil',
    'authentification',
    'biensePreparer',
    'exposants',
    'infosPratique'
]).constant('urls', {
    API: api_url,
    ADMIN: admin_url
});

app.config(
    function ($stateProvider, $httpProvider, $urlRouterProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = undefined;
        $httpProvider.defaults.headers.put['Content-Type'] = undefined;
        $httpProvider.defaults.transformRequest = angular.identity;

        $urlRouterProvider.otherwise("accueil");
        $stateProvider
            .state('index', {
                abstract: true,
                url: "/", // root route
                templateUrl: 'index.html'
            })
            .state('accueil', {
                url: "/accueil?target_area",
                templateUrl: 'src/accueil/accueil.html',
                controller: 'accueilController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'accueil',
                            files: [
                                'src/accueil/accueilController.js',
                                'src/accueil/accueilService.js'
                            ]
                        });
                    }]
                }
            })
            .state('actualites', {
                url: '/actualites/{id:[0-9]*}',
                templateUrl: 'src/accueil/accueil.html',
                controller: 'accueilController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'actualites',
                            files: [
                                'src/accueil/accueilController.js',
                                'src/accueil/accueilService.js'
                            ]
                        });
                    }]
                }
            })
            .state('connexion', {
                url: "/connexion",
                templateUrl: 'src/authentification/authentification.html',
                controller: 'authentificationController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'authentification',
                            files: [
                                'src/authentification/authentificationController.js',
                                'src/authentification/authentificationService.js'
                            ]
                        });
                    }]
                }
            })
            .state('inscription', {
                url: "/inscription",
                templateUrl: 'src/authentification/authentification.html',
                controller: 'authentificationController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'authentification',
                            files: [
                                'src/authentification/authentificationController.js',
                                'src/authentification/authentificationService.js'
                            ]
                        });
                    }]
                }
            })
            .state('biensepreparer', {
                url: "/biensepreparer",
                templateUrl: 'src/bien_se_preparer/bien_se_preparer.html',
                controller: 'biensePreparerController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'biensePreparer',
                            files: [
                                'src/bien_se_preparer/biensePreparerController.js',
                                'src/bien_se_preparer/biensePreparerService.js'
                            ]
                        });
                    }]
                }
            })
            .state('listeExposants', {
                url: "/exposants",
                templateUrl: 'src/exposants/exposants.html',
                controller: 'exposantsController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'listeExposants',
                            files: [
                                'src/exposants/exposantsController.js',
                                'src/exposants/exposantsService.js'
                            ]
                        });
                    }]
                }
            })
            .state('exposants', {
                url: "/exposants/{id:[0-9]*}",
                templateUrl: 'src/exposants/exposants.html',
                controller: 'exposantsController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'exposants',
                            files: [
                                'src/exposants/exposantsController.js',
                                'src/exposants/exposantsService.js'
                            ]
                        });
                    }]
                }
            })
            .state('infospratiques', {
                url: "/infospratiques",
                templateUrl: 'src/infos_pratique/infos_pratique.html',
                controller: 'infosPratiqueController',
                resolve: {
                    lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'infosPratique',
                            files: [
                                'src/infos_pratique/infosPratiqueController.js',
                                'src/infos_pratique/infosPratiqueService.js',
                                'src/exposants/exposantsService.js'
                            ]
                        });
                    }]
                }
            });
        $httpProvider.interceptors.push('app.httpinterceptor');
    });

app.run(function ($rootScope, $location, $http) {
    console.log("app run ");
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
    });
});

//Intercepteur HTTP
app.factory('app.httpinterceptor', function ($q, $rootScope, $location) {
    return {
        // optional method
        'request': function (config) {
            return config || $q.when(config);
        },
        // optional method
        'requestError': function (rejection) {
            return $q.reject(rejection);
        },
        // optional method
        'response': function (response) {
            return response || $q.when(response);
        },
        // optional method
        'responseError': function (rejection) {
            if (rejection.status === 403) {
                $location.path('/accueil');
            }
            return $q.reject(rejection);
        }
    };
});

<|endoftext|>


<commit_before>module.exports = {
	html: function(el, value, previousValue) {
		$(el).html(value);
	},

	value: function(el, value, previousValue) {
		var $el = $(el);

		if($el[0].type === 'radio' || $el[0].type === 'checkbox') {
			if($el.length === 1) {
				$el.prop('checked', !!value);
			} else {
				$el.prop('checked', false);

				if(value)
					$el.filter((_.isArray(value) ? value : [ value ]).map(function(value) {
						return '[value="' + value + '"]';
					}).join(',')).prop('checked', true);
			}
		} else {
			if(value != null) value = value.toString();

			$(el).val(value);
		}

		$el.trigger('change', { internalUpdate: true });
	},

	published: function(el, value) {
		$el = $(this).closest('[data-published]');

		$el.attr('data-published', (!!value).toString());
	},

	parts: function(el, value) {
		if(!_.isDate(value)) ref = new Date(value);

		ref = ref.toLocaleString('se-SV').split(' ');

		$(el).find('[data-part]').toArray().forEach(function(part, index) {
			$(part).val(ref[index]);
		});
	},

	src: function(el, value) {
		$(el).attr('src', value);
	},

	selectMultiple: function(el, value) {
		if(!value) $(el).val(null);
		else
			value.forEach(function(value) {
				$(el).find('[value="' + value + '"]').prop('selected', true);
			});
	}
};
<commit_msg>el > , and trigger change html setter.<commit_after>module.exports = {
	html: function($el, value, previousValue) {
		$el.html(value);

		$el.trigger('change', { internalUpdate: true });
	},

	value: function($el, value, previousValue) {
		if($el[0].type === 'radio' || $el[0].type === 'checkbox') {
			if($el.length === 1) {
				$el.prop('checked', !!value);
			} else {
				$el.prop('checked', false);

				if(value)
					$el.filter((_.isArray(value) ? value : [ value ]).map(function(value) {
						return '[value="' + value + '"]';
					}).join(',')).prop('checked', true);
			}
		} else {
			if(value != null) value = value.toString();

			$el.val(value);
		}

		$el.trigger('change', { internalUpdate: true });
	},

	published: function($el, value) {
		$el = $el.closest('[data-published]');

		$el.attr('data-published', (!!value).toString());
	},

	parts: function($el, value) {
		if(!_.isDate(value)) ref = new Date(value);

		ref = ref.toLocaleString('se-SV').split(' ');

		$el.find('[data-part]').toArray().forEach(function(part, index) {
			$(part).val(ref[index]);
		});
	},

	src: function($el, value) {
		$el.attr('src', value);
	},

	selectMultiple: function($el, value) {
		if(!value) $el.val(null);
		else
			value.forEach(function(value) {
				$el.find('[value="' + value + '"]').prop('selected', true);
			});
	}
};
<|endoftext|>


<commit_before>// here is where it begins
'use strict'

const cytoscape = require('cytoscape')

const nodeInfo = require('./src/nodeInfo.js')
const hoverNodeInfo = require('./src/hoverNodeInfo.js')
// const searchAttribute = require('./src/searchAttribute.js')
const flagNodes = require('./src/flagNodes.js')
const moduleSelection = require('./src/moduleSelection.js')
const nodeSelection = require('./src/nodeSelection.js')
const threatVerification = require('./src/threatVerification.js')
const keybindings = require('./src/keybindings.js')
const addEdge = require('./src/addEdge.js')
const totalNodes = require('./src/totalNodes.js')
const save = require('./src/save.js')
const load = require('./src/load.js')

// reguire implementation functions
const impModuleValidation = require('./src/implementation/impModuleValidation.js')
const vulnVerification = require('./src/implementation/vulnVerification.js')
const findVulns = require('./src/implementation/findVulns.js')
const impOverview = require('./src/implementation/impOverview.js')
const addImpComponent = require('./src/implementation/addImpComponent.js')

// require design functions
const dgnModuleValidation = require('./src/design/dgnModuleValidation.js')
const dgnOverview = require('./src/design/dgnOverview.js')
const addDgnComponent = require('./src/design/addDgnComponent.js')

// require design-state functions
const dgnStateModuleValidation = require('./src/design-state/dgnStateModuleValidation.js')
const dgnStateOverview = require('./src/design-state/dgnStateOverview.js')
const addDgnStateComponent = require('./src/design-state/addDgnStateComponent.js')

const config = require('./style/config.js')

// save the path
const path = `${__dirname}`
// require the graph file
let system = require(`${path}/graphs/implementation/smartHome.js`)

// graphs style
const graphStyle = require(`${path}/style/graphStyle.js`)

// setting up the graph container
let cy = cytoscape({
  container: document.getElementById('graph-container'),
  autounselectify: true,
  elements: system.elements,
  style: graphStyle.style
})

// graph layout
cy.layout({
  name: 'cose'
})

let selectedNode = ''
let selectedEdge = ''
let sourceNode = ''
let targetNode = ''

cy.on('tap', 'node', (selection) => {
  // removes previous selections
  cy.elements().removeClass('selection')
  cy.elements().removeClass('attention')
  cy.elements().removeClass('protect')
  selectedNode = selection.target[0]
  // const neighborhood = selectedNode.neighborhood().add(selectedNode)
  // cy.elements().addClass('faded')
  // neighborhood.removeClass('faded')
  nodeInfo(selectedNode)
  selectedNode.addClass('selection')
  sourceNode = targetNode // second selection
  targetNode = selectedNode.data().id
  totalNodes(cy)
})
cy.on('tap', 'edge', (selection) => {
  // removes previous selections
  cy.elements().removeClass('selection')
  cy.elements().removeClass('attention')
  cy.elements().removeClass('protect')
  selection.target.addClass('selection')
  selectedEdge = selection.target[0]
  totalNodes(cy)
})
// when tapping the stage
cy.on('tap', (selection) => {
  if (selection.target === cy) {
    // removes previous selections
    cy.elements().removeClass('faded')
    cy.elements().removeClass('selection')
    cy.elements().removeClass('attention')
    cy.elements().removeClass('protect')
    document.getElementById('module-group').selectedIndex = ''
    document.getElementById('selection-id').selectedIndex = ''
    totalNodes(cy)
  }
})
// hover over a node
cy.on('mouseover', 'node', (event) => {
  hoverNodeInfo(event.target[0])
})
// hover out of a node
cy.on('mouseout', 'node', (event) => {
  document.getElementById('container-node-id').style.display = 'none'
})

// load implementation specific buttons
if (window.location.pathname === `${path}/implementation.html`) {
  // verify vulnerabilities
  const buttonVulnVefiry = document.getElementById('vuln-verify-button')
  buttonVulnVefiry.addEventListener('click', () => {
    vulnVerification(cy) // module
  })
  // find vulnerabilities
  const buttonFindVuln = document.getElementById('find-vuln-button')
  buttonFindVuln.addEventListener('click', () => {
    findVulns(cy) // module
  })
}
const buttonModuleValidate = document.getElementById('module-validate-button')
buttonModuleValidate.addEventListener('click', () => {
  if (window.location.pathname === `${path}/implementation.html`) {
    impModuleValidation(cy) // imp module
  } else if (window.location.pathname === `${path}/design.html`) {
    dgnModuleValidation(cy) // dgn module
  } else if (window.location.pathname === `${path}/design-state.html`) {
    dgnStateModuleValidation(cy) // dgn-state module
  }
})
const buttonOverview = document.getElementById('overview-button')
buttonOverview.addEventListener('click', () => {
  if (window.location.pathname === `${path}/implementation.html`) {
    impOverview(cy) // imp module
  } else if (window.location.pathname === `${path}/design.html`) {
    dgnOverview(cy) // dgn module
  } else if (window.location.pathname === `${path}/design-state.html`) {
    dgnStateOverview(cy) // dgn-state module
  }
})
// flag nodes
const buttonFlag = document.getElementById('flag-button')
buttonFlag.addEventListener('click', () => {
  flagNodes(cy, config.flag) // module
})
// save graph
const buttonSave = document.getElementById('save-button')
buttonSave.addEventListener('click', () => {
  save(cy, path) // module
})
// load graph
const buttonLoad = document.getElementById('load-button')
buttonLoad.addEventListener('click', () => {
  load(cy, system, cytoscape, graphStyle) // module
})
// delele selected node
const buttonDeleteNode = document.getElementById('delete-node')
buttonDeleteNode.addEventListener('click', () => {
  selectedNode.remove()
  totalNodes(cy)
})
const buttonAddEdge = document.getElementById('add-edge')
buttonAddEdge.addEventListener('click', () => {
  addEdge(cy, sourceNode, targetNode) // module
  totalNodes(cy)
})
const buttonDeleteEdge = document.getElementById('delete-edge')
buttonDeleteEdge.addEventListener('click', () => {
  selectedEdge.remove()
  totalNodes(cy)
})
const buttonThreatVefiry = document.getElementById('threat-verify-button')
buttonThreatVefiry.addEventListener('click', () => {
  threatVerification(cy) // module
})
const buttonNeighbor = document.getElementById('neighbors-button')
buttonNeighbor.addEventListener('click', () => {
  // selectedNode from cy.on tap node function
  const neighborhood = selectedNode.neighborhood().add(selectedNode)
  cy.elements().addClass('faded')
  neighborhood.removeClass('faded')
})
// test function
const buttonTest = document.getElementById('test-button')
buttonTest.addEventListener('click', () => {

})

// selections
const moduleGroup = document.getElementById('module-group')
moduleGroup.addEventListener('change', (input) => {
  moduleSelection(input, cy) // module
  // reset selection selection
  // document.getElementById('module-group').selectedIndex = ''
})
// for the filter selection
const select = document.getElementById('selection-id')
select.addEventListener('change', (e) => {
  nodeSelection(cy, e.target.value) // module
  // reset moduleGroup selection
  // document.getElementById('selection-id').selectedIndex = ''
})
// adding component
const add = document.getElementById('add-component-id')
add.addEventListener('change', (e) => {
  if (window.location.pathname === `${path}/implementation.html`) {
    addImpComponent(cy, e.target.value) // imp module
  } else if (window.location.pathname === `${path}/design.html`) {
    addDgnComponent(cy, e.target.value) // dgn module
  } else if (window.location.pathname === `${path}/design-state.html`) {
    addDgnStateComponent(cy, e.target.value) // dgn-state module
  }
  // reset moduleGroup selection
  document.getElementById('add-component-id').selectedIndex = ''
  totalNodes(cy)
})

// toggles side divs
const toggleUI = () => {
  const sidebarStatus = document.getElementById('sidebar-id')
  const actionBarStatus = document.getElementById('action-bar-id')
  if (sidebarStatus.style.display === 'block') {
    sidebarStatus.style.display = 'none'
    actionBarStatus.style.display = 'none'
  } else {
    sidebarStatus.style.display = 'block'
    actionBarStatus.style.display = 'block'
  }
}

totalNodes(cy)
// enable keyboard shortcuts
keybindings(cy, toggleUI)
<commit_msg>:art:<commit_after>// here is where it begins
'use strict'

const cytoscape = require('cytoscape')

const nodeInfo = require('./src/nodeInfo.js')
const hoverNodeInfo = require('./src/hoverNodeInfo.js')
// const searchAttribute = require('./src/searchAttribute.js')
const flagNodes = require('./src/flagNodes.js')
const moduleSelection = require('./src/moduleSelection.js')
const nodeSelection = require('./src/nodeSelection.js')
const threatVerification = require('./src/threatVerification.js')
const keybindings = require('./src/keybindings.js')
const addEdge = require('./src/addEdge.js')
const totalNodes = require('./src/totalNodes.js')
const save = require('./src/save.js')
const load = require('./src/load.js')

// reguire implementation functions
const impModuleValidation = require('./src/implementation/impModuleValidation.js')
const vulnVerification = require('./src/implementation/vulnVerification.js')
const findVulns = require('./src/implementation/findVulns.js')
const impOverview = require('./src/implementation/impOverview.js')
const addImpComponent = require('./src/implementation/addImpComponent.js')

// require design functions
const dgnModuleValidation = require('./src/design/dgnModuleValidation.js')
const dgnOverview = require('./src/design/dgnOverview.js')
const addDgnComponent = require('./src/design/addDgnComponent.js')

// require design-state functions
const dgnStateModuleValidation = require('./src/design-state/dgnStateModuleValidation.js')
const dgnStateOverview = require('./src/design-state/dgnStateOverview.js')
const addDgnStateComponent = require('./src/design-state/addDgnStateComponent.js')

const config = require('./style/config.js')

// save the path
const path = `${__dirname}`
// require the graph file
let system = require(`${path}/graphs/implementation/smartHome.js`)

// graphs style
const graphStyle = require(`${path}/style/graphStyle.js`)

// setting up the graph container
let cy = cytoscape({
  container: document.getElementById('graph-container'),
  autounselectify: true,
  elements: system.elements,
  style: graphStyle.style
})

// graph layout
cy.layout({
  name: 'cose'
})

let selectedNode = ''
let selectedEdge = ''
let sourceNode = ''
let targetNode = ''

cy.on('tap', 'node', (selection) => {
  // removes previous selections
  cy.elements().removeClass('selection')
  cy.elements().removeClass('attention')
  cy.elements().removeClass('protect')
  selectedNode = selection.target[0]
  // const neighborhood = selectedNode.neighborhood().add(selectedNode)
  // cy.elements().addClass('faded')
  // neighborhood.removeClass('faded')
  nodeInfo(selectedNode)
  selectedNode.addClass('selection')
  sourceNode = targetNode // second selection
  targetNode = selectedNode.data().id
  totalNodes(cy)
})
cy.on('tap', 'edge', (selection) => {
  // removes previous selections
  cy.elements().removeClass('selection')
  cy.elements().removeClass('attention')
  cy.elements().removeClass('protect')
  selection.target.addClass('selection')
  selectedEdge = selection.target[0]
  totalNodes(cy)
})
// when tapping the stage
cy.on('tap', (selection) => {
  if (selection.target === cy) {
    // removes previous selections
    cy.elements().removeClass('faded')
    cy.elements().removeClass('selection')
    cy.elements().removeClass('attention')
    cy.elements().removeClass('protect')
    document.getElementById('module-group').selectedIndex = ''
    document.getElementById('selection-id').selectedIndex = ''
    totalNodes(cy)
  }
})
// hover over a node
cy.on('mouseover', 'node', (event) => {
  hoverNodeInfo(event.target[0])
})
// hover out of a node
cy.on('mouseout', 'node', (event) => {
  document.getElementById('container-node-id').style.display = 'none'
})

// load implementation specific buttons
if (window.location.pathname === `${path}/implementation.html`) {
  // verify vulnerabilities
  const buttonVulnVefiry = document.getElementById('vuln-verify-button')
  buttonVulnVefiry.addEventListener('click', () => {
    vulnVerification(cy) // module
  })
  // find vulnerabilities
  const buttonFindVuln = document.getElementById('find-vuln-button')
  buttonFindVuln.addEventListener('click', () => {
    findVulns(cy) // module
  })
}
const buttonModuleValidate = document.getElementById('module-validate-button')
buttonModuleValidate.addEventListener('click', () => {
  if (window.location.pathname === `${path}/implementation.html`) {
    impModuleValidation(cy) // imp module
  } else if (window.location.pathname === `${path}/design.html`) {
    dgnModuleValidation(cy) // dgn module
  } else if (window.location.pathname === `${path}/design-state.html`) {
    dgnStateModuleValidation(cy) // dgn-state module
  }
})
const buttonOverview = document.getElementById('overview-button')
buttonOverview.addEventListener('click', () => {
  if (window.location.pathname === `${path}/implementation.html`) {
    impOverview(cy) // imp module
  } else if (window.location.pathname === `${path}/design.html`) {
    dgnOverview(cy) // dgn module
  } else if (window.location.pathname === `${path}/design-state.html`) {
    dgnStateOverview(cy) // dgn-state module
  }
})
// flag nodes
const buttonFlag = document.getElementById('flag-button')
buttonFlag.addEventListener('click', () => {
  flagNodes(cy, config.flag) // module
})
// save graph
const buttonSave = document.getElementById('save-button')
buttonSave.addEventListener('click', () => {
  save(cy, path) // module
})
// load graph
const buttonLoad = document.getElementById('load-button')
buttonLoad.addEventListener('click', () => {
  load(cy, system, cytoscape, graphStyle) // module
})
// delele selected node
const buttonDeleteNode = document.getElementById('delete-node')
buttonDeleteNode.addEventListener('click', () => {
  selectedNode.remove()
  totalNodes(cy)
})
const buttonAddEdge = document.getElementById('add-edge')
buttonAddEdge.addEventListener('click', () => {
  addEdge(cy, sourceNode, targetNode) // module
  totalNodes(cy)
})
const buttonDeleteEdge = document.getElementById('delete-edge')
buttonDeleteEdge.addEventListener('click', () => {
  selectedEdge.remove()
  totalNodes(cy)
})
const buttonThreatVefiry = document.getElementById('threat-verify-button')
buttonThreatVefiry.addEventListener('click', () => {
  threatVerification(cy) // module
})
const buttonNeighbor = document.getElementById('neighbors-button')
buttonNeighbor.addEventListener('click', () => {
  // selectedNode from cy.on tap node function
  const neighborhood = selectedNode.neighborhood().add(selectedNode)
  cy.elements().addClass('faded')
  neighborhood.removeClass('faded')
})
// test function
const buttonTest = document.getElementById('test-button')
buttonTest.addEventListener('click', () => {
  // test code goes here
})

// add component
const add = document.getElementById('add-component-id')
add.addEventListener('change', (e) => {
  if (window.location.pathname === `${path}/implementation.html`) {
    addImpComponent(cy, e.target.value) // imp module
  } else if (window.location.pathname === `${path}/design.html`) {
    addDgnComponent(cy, e.target.value) // dgn module
  } else if (window.location.pathname === `${path}/design-state.html`) {
    addDgnStateComponent(cy, e.target.value) // dgn-state module
  }
  // reset moduleGroup selection
  document.getElementById('add-component-id').selectedIndex = ''
  totalNodes(cy)
})

// selections
const moduleGroup = document.getElementById('module-group')
moduleGroup.addEventListener('change', (input) => {
  moduleSelection(input, cy) // module
  // reset selection selection
  // document.getElementById('module-group').selectedIndex = ''
})
// for the filter selection
const select = document.getElementById('selection-id')
select.addEventListener('change', (e) => {
  nodeSelection(cy, e.target.value) // module
  // reset moduleGroup selection
  // document.getElementById('selection-id').selectedIndex = ''
})

// toggles side divs
const toggleUI = () => {
  const sidebarStatus = document.getElementById('sidebar-id')
  const actionBarStatus = document.getElementById('action-bar-id')
  if (sidebarStatus.style.display === 'block') {
    sidebarStatus.style.display = 'none'
    actionBarStatus.style.display = 'none'
  } else {
    sidebarStatus.style.display = 'block'
    actionBarStatus.style.display = 'block'
  }
}

totalNodes(cy)
// enable keyboard shortcuts
keybindings(cy, toggleUI)
<|endoftext|>