<commit_before>const path = require('path');
const program = require('commander');
const fs = require('fs-extra');
const inquirer = require('inquirer');
const chalk = require('chalk');

const VirtualModulesPlugin = require('webpack-virtual-modules');
const HTMLWebpackPlugin = require('html-webpack-plugin');

const { getPackagesMap } = require('../utils');
const start = require('../utils/start');
const clean = require('../utils/clean');

const getEntryCode = packagePath => {
  return `
import React from 'react'
import ReactDOM from 'react-dom'
import App from '${packagePath}'

ReactDOM.render(<App />,document.getElementById('app'))
  `;
};

const startDev = packagePath => {
  const distPath = path.join(packagePath, 'dist');
  const testPath = path.join(packagePath, '__tests__');

  const entryPath = path.join(testPath, 'entry.tsx');
  const virtualModules = new VirtualModulesPlugin({
    [entryPath]: getEntryCode(
      path.join(testPath, 'index.tsx').replace(/\\/g, '/')
    )
  });

  const config = {};
  const webpackConfig = {
    entry: {
      index: entryPath
    },
    output: {
      path: distPath
    },
    plugins: [
      virtualModules,
      new HTMLWebpackPlugin({
        template: path.join(__dirname, 'index.ejs')
      })
    ]
  };

  start(config, webpackConfig);
};

async function main() {
  clean();

  const packagesMap = getPackagesMap();

  program.parse(process.argv);
  const args = program.args;
  if (args.length === 1) {
    const currentPackage = packagesMap[args[0]];
    if (!currentPackage) {
      console.log(chalk.red(`component ${args[0]} not found`));
    }
    startDev(currentPackage.path);
  } else {
    inquirer
      .prompt([
        {
          type: 'list',
          name: 'package',
          message: 'Please select the component for development testing',
          choices: Object.keys(packagesMap).map(key => {
            const package = packagesMap[key];
            return {
              name: `${package.name} (${package.description || '-'})`,
              value: package.path
            };
          })
        }
      ])
      .then(answers => {
        if (!answers.package) {
          return;
        }

        startDev(answers.package);
      });
  }
}

main();
<commit_msg>update: dev命令调整<commit_after>const path = require('path');
const program = require('commander');
const fs = require('fs-extra');
const inquirer = require('inquirer');
const chalk = require('chalk');

const VirtualModulesPlugin = require('webpack-virtual-modules');
const HTMLWebpackPlugin = require('html-webpack-plugin');

const { getPackagesMap } = require('../utils');
const start = require('../utils/start');
const clean = require('../utils/clean');

const getEntryCode = packagePath => {
  return `
import React from 'react'
import ReactDOM from 'react-dom'
import App from '${packagePath}'

ReactDOM.render(<App />,document.getElementById('app'))
  `;
};

const startDev = packagePath => {
  const distPath = path.join(packagePath, 'dist');
  const testPath = path.join(packagePath, '__tests__');

  const entryPath = path.join(testPath, 'entry.tsx');
  const virtualModules = new VirtualModulesPlugin({
    [entryPath]: getEntryCode(
      path.join(testPath, 'index.tsx').replace(/\\/g, '/')
    )
  });

  const config = {};
  const webpackConfig = {
    entry: {
      index: entryPath
    },
    output: {
      path: distPath
    },
    plugins: [
      virtualModules,
      new HTMLWebpackPlugin({
        template: path.join(__dirname, 'index.ejs')
      })
    ]
  };

  start(config, webpackConfig);
};

async function main() {
  clean();

  const packagesMap = getPackagesMap();

  program.parse(process.argv);
  const args = program.args;
  if (args.length === 1) {
    const currentPackage = packagesMap[args[0]];
    if (!currentPackage) {
      console.log(chalk.red(`component ${args[0]} not found`));
      return;
    }
    startDev(currentPackage.path);
  } else {
    inquirer
      .prompt([
        {
          type: 'list',
          name: 'package',
          message: 'Please select the component for development testing',
          choices: Object.keys(packagesMap).map(key => {
            const package = packagesMap[key];
            return {
              name: `${package.name} (${package.description || '-'})`,
              value: package.path
            };
          })
        }
      ])
      .then(answers => {
        if (!answers.package) {
          return;
        }

        startDev(answers.package);
      });
  }
}

main();
<|endoftext|>


<commit_before>//########################################################
//###############   STATE OBJECT and CONSTANTS  ##########
//########################################################
const state = {
  guns: []
}

const rootURL = 'http://localhost:8080/guns';

//const rootURL = 'https://firearmbase.herokuapp.com/guns';

//#########################################################
//#################  STATE MODIFICATION METHODS  ##########
//#########################################################

function getAllGuns() {
  return new Promise(function (res, rej) {
    $.ajax({
      url: rootURL,
      type: "GET",
      headers: {
        "accept": "application/jsonp;odata=verbose",
      },
      success: function(gundata) {
        var num=0;
        gundata.forEach( gun => {
          //state.guns[gun.fullName] = gun;
          state.guns[num] = gun;
          num++;
        });
        console.log('StateObject: ',state.guns);
        res();
      },
      error: function(error){
        console.log('error: ',error);
      }
    })
  })
  return state;
}

getAllGuns()
.then(showMenu);

//#########################################################
//#################  DOM MODIFICATION METHODS  ############
//#########################################################

function outputGunsReport() {
  // return new Promise( (res, rej) => {
    var template = '
';
    state.guns.forEach( gun => {
      console.log('ONE: ', typeof gun);
      template += '
'+gun.fullName+'
';
    })
    template += '<button id="home_page">Home</button>';
    template += '
';
    console.log('state.guns object ', state.guns);
    $("#output").html(template);
    $("#home_page").click(function(){
      showMenu();
    })
  // });
}

//#########################################################
//#################  DATABASE METHODS      ################
//#########################################################

function gunDbTalk(gunData, http_method){
  console.log('gunTalk ', gunData);
  if (gunData.id) myURL = rootURL + "/" + gunData.id;
  else myURL = rootURL;
    $.ajax({
      url: myURL,
      type: http_method,
      headers: {
        "accept": "application/json;odata=verbose",
      },
      data: JSON.stringify(gunData),
      contentType: "application/json; charset=utf-8",
      dataType: 'json',
      success: function(gundata) {

        //console.log('StateObject: ',state.guns);
        console.log('HEY!  Object: ',gundata);
        // res();
      },
      error: function(error){
        console.log('error: ',error);
      }
    })
  getAllGuns();
  showMenu();
}

//GET single gun from db
//From here the user can either update or delete the record or go to home menu
function getOneGun(gunId){
  //console.log('UPDATE: You want to update: ',gunId)
  var myURL = rootURL + '/' + gunId;
  $.ajax({
    url: myURL,
    type: 'GET',
    headers: {
      "accept": "application/json;odata=verbose",
    },
    //data: JSON.stringify(gunId),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function(gundata) {
      console.log('HEY!  Object: ',gundata);
      var template = '
<form id="update_gun_form">';
      template += `<input id="manufacturer" type="text" placeholder="${gundata.manufacturer}" name="manufacturer">`;
      template += `<input id="model"  type="text" placeholder="${gundata.model}" name="model">`;
      template += `<input id="chambering"  type="text" placeholder="${gundata.chambering}" name="chambering">`;
      template += `<input id="type" type="text" placeholder="${gundata.type}" name="type">`;
      template += `<input  id="serial_number" type="text" placeholder="${gundata.serial_number}" name="serial_number">`;
      template += `<input id="image" type="text" placeholder="${gundata.image}" name="image">`;
      template += `<input id="value" type="text" placeholder="${gundata.value}" name="value">`;
      template += `<input id="sold" type="text" placeholder="${gundata.sold}" name="sold">`;
      template += `<input id="buyer" type="text" placeholder="${gundata.buyer}" name="buyer">`;
      template += '<button type="submit" id="update_gun_submit">Submit</submit> ';
      template += '<button type="submit" id="delete_gun_submit">Delete?</submit>';
      template += '<button type="submit" id="load_home_page">Home</submit>';
      template += '</form>
';
      $("#output").html(template);

      $("#load_home_page").click(function(){
        showMenu();
      })

      $("#update_gun_submit").click(function(ev){
        ev.preventDefault();
        let fields = ['manufacturer', 'model', 'chambering', 'type', 'serial_number', 'image', 'value', 'sold', 'buyer'];

        let updateData = {};
        updateData.id = `${gunId}`;

        //Modify this so you can update more than one field!!!
        fields.forEach(function(field){
          if ($('#'+field).val()) {
            let thevalue = $('#'+field).val();
            updateData[field] = `${thevalue}`
          }
        })

        console.log('TYPEOF:  ',typeof updateData, ' DATA: ',updateData);
        updateGun(updateData, gunId);
      })

      //If the delete button gets pressed...
      $("#delete_gun_submit").click(function(ev){
        ev.preventDefault();
        console.log('Deleting gun with id: ', gunId);

        deleteGun(gunId);
      })
    },
    error: function(error){
      console.log('error *getting* the record: ',error);
    }
  })
}  // End of getOneGun()  (Includes calls to deleteGun() and updateGun() and showMenu()! )

// Update a single gun record
function updateGun(updateData, gunId){
  var myURL = rootURL + '/' + gunId;
  $.ajax({
    url: myURL,
    type: 'PUT',
    headers: {
      "accept": "application/json;odata=verbose",
    },
    data: JSON.stringify(updateData),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function(gundata) {

      //console.log('StateObject: ',state.guns);
      console.log('Gun updated!  Object: ',gundata);
      // res();
    },
    error: function(error){
      console.log('Update failed.  Error: ',error);
    }
  })
  getAllGuns()
  .then(showMenu);
}

//Delete a single gun from db
function deleteGun(gunId){
  console.log('Do you really want to delete this gun: ', gunId);
  var myURL = rootURL + '/' + gunId;
  $.ajax({
    url: myURL,
    type: 'DELETE',
    headers: {
      "accept": "application/json;odata=verbose",
    },
    //data: JSON.stringify(updateData),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function() {

      console.log(`Gun ${gunId} deleted!`);
      // res();
    },
    error: function(error){
      console.log('Update failed.  Error: ',error);
    }
  })
  getAllGuns().then(showMenu);
}

//#########################################################
//#################  PROGRAM CONTROL FLOW  ################
//#########################################################

//This function shows the opening menu
function showMenu(){
  var template = '
'
  template += '<button id="list_all">List All Guns</button>';
  template += '<button id="create_gun">Add Gun</button>';
  template += '<button id="read_gun">Find Gun</button>';
  template += '
';

  $("#output").html(template);

  // List all guns
  $("#list_all").click(function(){
    outputGunsReport();
  })

  // Add a gun to database
  $("#create_gun").click(function(){

    var template = `<div><form>`;
    template += '<input id="manufacturer" type="text" placeholder="manufacturer" name="manufacturer">';
    template += '<input id="model"  type="text" placeholder="model" name="model">';
    template += '<input id="chambering"  type="text" placeholder="chambering" name="chambering">';
    template += '<input id="type" type="text" placeholder="type" name="type">';
    template += '<input  id="serial_number" type="text" placeholder="serial_number" name="serial_number">';
    template += '<input id="image" type="text" placeholder="image" name="image">'
    template += '<input id="value" type="text" placeholder="value" name="value">';
    template += '<input id="sold" type="text" placeholder="sold" name="sold">';
    template += '<input id="buyer" type="text" placeholder="buyer" name="buyer">';
    template += '<button type="submit" id="create_gun_submit">Submit</submit> ';
    template += '</form>
';

    $("#output").html(template);

    $("#create_gun_submit").click(function(e){
      e.preventDefault();
      gunObj = {
        manufacturer: $("#manufacturer").val(),
        model: $("#model").val(),
        chambering: $("#chambering").val(),
        type: $("#type").val(),
        serial_number: $("#serial_number").val(),
        image: $("#image").val(),
        value: $("#value").val(),
        sold: $("#sold").val(),
        buyer: $("#buyer").val()
      }

      console.log("From showmenu() ",gunObj);
      gunDbTalk(gunObj, "POST");
    })
  })  //end of #create_gun listener

  //Search for a gun in the state.guns object
  $("#read_gun").click(function(){
    console.log('Find gun clicked')
    var template = '

Search for Gun
<form>';
    template += '<input id="manufacturer" type="text" placeholder="manufacturer" name="manufacturer">';
    template += '<input id="model"  type="text" placeholder="model" name="model">';
    template += '<input id="chambering"  type="text" placeholder="chambering" name="chambering">';
    template += '<input id="type" type="text" placeholder="type" name="type">';
    template += '<input  id="serial_number" type="text" placeholder="serial_number" name="serial_number">';
    template += '<input id="image" type="text" placeholder="image" name="image">'
    template += '<input id="value" type="text" placeholder="value" name="value">';
    template += '<input id="sold" type="text" placeholder="sold" name="sold">';
    template += '<input id="buyer" type="text" placeholder="buyer" name="buyer">';
    template += '<button type="submit" id="search_gun_submit">Submit</submit> ';
    template += '</form>
';

    $("#output").html(template);

    // Collect info from the search fields
    $("#search_gun_submit").click(function(e){
      e.preventDefault();
      gunObj = {
        manufacturer: $("#manufacturer").val(),
        model: $("#model").val(),
        chambering: $("#chambering").val(),
        type: $("#type").val(),
        serial_number: $("#serial_number").val(),
        image: $("#image").val(),
        value: $("#value").val(),
        sold: $("#sold").val(),
        buyer: $("#buyer").val()
      }

      //searchKeys are the fields the user is looking for
      var searchKeys = {};
      //searchList is a big list to be whittled down...
      var searchList = state.guns;
      for (var [key, value] of Object.entries(gunObj)) {
        if (value) { searchKeys[key] = value; }
      }

      //Why are some guns not being returned?
      console.log('Looking for: ', searchKeys);

      // newArray will contain only matching guns to be returned to user
      let newArray = searchList.filter(function(gun, index, array) {
        Object.keys(searchKeys).forEach(function(key) {
          // if(searchKeys[key] !== gun[key]) {
          if (!gun[key].includes(searchKeys[key])) {
            gun['delete'] = true;
          }
        });
        return !gun.delete;
      });

      let returnTemplate = '
';
      newArray.forEach(function(gun){
        console.log('newArray size: ', newArray.length);
        returnTemplate += '
'+gun.fullName+
        `<button class="update_gun" data-gunobj="${gun.id}">Update or Delete</button>`;
      })

      if (newArray.length === 0) returnTemplate += "No Guns Found.";

      // put the 'home' button on the page
      returnTemplate += '<button id="home_page">Home</button>';
      returnTemplate += '
';

      $("#output").html(returnTemplate);

      $("#home_page").click(function(){
        showMenu();
      })

      $("#edit_guns").click('.update_gun', function(ev) {
        var targetId = $(ev.target).data('gunobj');
        console.log('ClickHandler!  target id:', targetId);

        getOneGun(targetId);
      })

      console.log('NewArray returned: ', newArray);
    })
  })  //end of searchgun menu pick

  // $("#update_gun").click(function(){
  //   console.log('Update gun clicked')
  // })

  // $("#delete_gun").click(function(){
  //   console.log('Delete gun clicked')
  // })

}  // end of showMenu()
<commit_msg>update for heroku site<commit_after>//########################################################
//###############   STATE OBJECT and CONSTANTS  ##########
//########################################################
const state = {
  guns: []
}

//const rootURL = 'http://localhost:8080/guns';

const rootURL = 'https://firearmbase.herokuapp.com/guns';

//#########################################################
//#################  STATE MODIFICATION METHODS  ##########
//#########################################################

function getAllGuns() {
  return new Promise(function (res, rej) {
    $.ajax({
      url: rootURL,
      type: "GET",
      headers: {
        "accept": "application/jsonp;odata=verbose",
      },
      success: function(gundata) {
        var num=0;
        gundata.forEach( gun => {
          //state.guns[gun.fullName] = gun;
          state.guns[num] = gun;
          num++;
        });
        console.log('StateObject: ',state.guns);
        res();
      },
      error: function(error){
        console.log('error: ',error);
      }
    })
  })
  return state;
}

getAllGuns()
.then(showMenu);

//#########################################################
//#################  DOM MODIFICATION METHODS  ############
//#########################################################

function outputGunsReport() {
  // return new Promise( (res, rej) => {
    var template = '
';
    state.guns.forEach( gun => {
      console.log('ONE: ', typeof gun);
      template += '
'+gun.fullName+'
';
    })
    template += '<button id="home_page">Home</button>';
    template += '
';
    console.log('state.guns object ', state.guns);
    $("#output").html(template);
    $("#home_page").click(function(){
      showMenu();
    })
  // });
}

//#########################################################
//#################  DATABASE METHODS      ################
//#########################################################

function gunDbTalk(gunData, http_method){
  console.log('gunTalk ', gunData);
  if (gunData.id) myURL = rootURL + "/" + gunData.id;
  else myURL = rootURL;
    $.ajax({
      url: myURL,
      type: http_method,
      headers: {
        "accept": "application/json;odata=verbose",
      },
      data: JSON.stringify(gunData),
      contentType: "application/json; charset=utf-8",
      dataType: 'json',
      success: function(gundata) {

        //console.log('StateObject: ',state.guns);
        console.log('HEY!  Object: ',gundata);
        // res();
      },
      error: function(error){
        console.log('error: ',error);
      }
    })
  getAllGuns();
  showMenu();
}

//GET single gun from db
//From here the user can either update or delete the record or go to home menu
function getOneGun(gunId){
  //console.log('UPDATE: You want to update: ',gunId)
  var myURL = rootURL + '/' + gunId;
  $.ajax({
    url: myURL,
    type: 'GET',
    headers: {
      "accept": "application/json;odata=verbose",
    },
    //data: JSON.stringify(gunId),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function(gundata) {
      console.log('HEY!  Object: ',gundata);
      var template = '
<form id="update_gun_form">';
      template += `<input id="manufacturer" type="text" placeholder="${gundata.manufacturer}" name="manufacturer">`;
      template += `<input id="model"  type="text" placeholder="${gundata.model}" name="model">`;
      template += `<input id="chambering"  type="text" placeholder="${gundata.chambering}" name="chambering">`;
      template += `<input id="type" type="text" placeholder="${gundata.type}" name="type">`;
      template += `<input  id="serial_number" type="text" placeholder="${gundata.serial_number}" name="serial_number">`;
      template += `<input id="image" type="text" placeholder="${gundata.image}" name="image">`;
      template += `<input id="value" type="text" placeholder="${gundata.value}" name="value">`;
      template += `<input id="sold" type="text" placeholder="${gundata.sold}" name="sold">`;
      template += `<input id="buyer" type="text" placeholder="${gundata.buyer}" name="buyer">`;
      template += '<button type="submit" id="update_gun_submit">Submit</submit> ';
      template += '<button type="submit" id="delete_gun_submit">Delete?</submit>';
      template += '<button type="submit" id="load_home_page">Home</submit>';
      template += '</form>
';
      $("#output").html(template);

      $("#load_home_page").click(function(){
        showMenu();
      })

      $("#update_gun_submit").click(function(ev){
        ev.preventDefault();
        let fields = ['manufacturer', 'model', 'chambering', 'type', 'serial_number', 'image', 'value', 'sold', 'buyer'];

        let updateData = {};
        updateData.id = `${gunId}`;

        //Modify this so you can update more than one field!!!
        fields.forEach(function(field){
          if ($('#'+field).val()) {
            let thevalue = $('#'+field).val();
            updateData[field] = `${thevalue}`
          }
        })

        console.log('TYPEOF:  ',typeof updateData, ' DATA: ',updateData);
        updateGun(updateData, gunId);
      })

      //If the delete button gets pressed...
      $("#delete_gun_submit").click(function(ev){
        ev.preventDefault();
        console.log('Deleting gun with id: ', gunId);

        deleteGun(gunId);
      })
    },
    error: function(error){
      console.log('error *getting* the record: ',error);
    }
  })
}  // End of getOneGun()  (Includes calls to deleteGun() and updateGun() and showMenu()! )

// Update a single gun record
function updateGun(updateData, gunId){
  var myURL = rootURL + '/' + gunId;
  $.ajax({
    url: myURL,
    type: 'PUT',
    headers: {
      "accept": "application/json;odata=verbose",
    },
    data: JSON.stringify(updateData),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function(gundata) {

      //console.log('StateObject: ',state.guns);
      console.log('Gun updated!  Object: ',gundata);
      // res();
    },
    error: function(error){
      console.log('Update failed.  Error: ',error);
    }
  })
  getAllGuns()
  .then(showMenu);
}

//Delete a single gun from db
function deleteGun(gunId){
  console.log('Do you really want to delete this gun: ', gunId);
  var myURL = rootURL + '/' + gunId;
  $.ajax({
    url: myURL,
    type: 'DELETE',
    headers: {
      "accept": "application/json;odata=verbose",
    },
    //data: JSON.stringify(updateData),
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function() {

      console.log(`Gun ${gunId} deleted!`);
      // res();
    },
    error: function(error){
      console.log('Update failed.  Error: ',error);
    }
  })
  getAllGuns().then(showMenu);
}

//#########################################################
//#################  PROGRAM CONTROL FLOW  ################
//#########################################################

//This function shows the opening menu
function showMenu(){
  var template = '
'
  template += '<button id="list_all">List All Guns</button>';
  template += '<button id="create_gun">Add Gun</button>';
  template += '<button id="read_gun">Find Gun</button>';
  template += '
';

  $("#output").html(template);

  // List all guns
  $("#list_all").click(function(){
    outputGunsReport();
  })

  // Add a gun to database
  $("#create_gun").click(function(){

    var template = `<div><form>`;
    template += '<input id="manufacturer" type="text" placeholder="manufacturer" name="manufacturer">';
    template += '<input id="model"  type="text" placeholder="model" name="model">';
    template += '<input id="chambering"  type="text" placeholder="chambering" name="chambering">';
    template += '<input id="type" type="text" placeholder="type" name="type">';
    template += '<input  id="serial_number" type="text" placeholder="serial_number" name="serial_number">';
    template += '<input id="image" type="text" placeholder="image" name="image">'
    template += '<input id="value" type="text" placeholder="value" name="value">';
    template += '<input id="sold" type="text" placeholder="sold" name="sold">';
    template += '<input id="buyer" type="text" placeholder="buyer" name="buyer">';
    template += '<button type="submit" id="create_gun_submit">Submit</submit> ';
    template += '</form>
';

    $("#output").html(template);

    $("#create_gun_submit").click(function(e){
      e.preventDefault();
      gunObj = {
        manufacturer: $("#manufacturer").val(),
        model: $("#model").val(),
        chambering: $("#chambering").val(),
        type: $("#type").val(),
        serial_number: $("#serial_number").val(),
        image: $("#image").val(),
        value: $("#value").val(),
        sold: $("#sold").val(),
        buyer: $("#buyer").val()
      }

      console.log("From showmenu() ",gunObj);
      gunDbTalk(gunObj, "POST");
    })
  })  //end of #create_gun listener

  //Search for a gun in the state.guns object
  $("#read_gun").click(function(){
    console.log('Find gun clicked')
    var template = '

Search for Gun
<form>';
    template += '<input id="manufacturer" type="text" placeholder="manufacturer" name="manufacturer">';
    template += '<input id="model"  type="text" placeholder="model" name="model">';
    template += '<input id="chambering"  type="text" placeholder="chambering" name="chambering">';
    template += '<input id="type" type="text" placeholder="type" name="type">';
    template += '<input  id="serial_number" type="text" placeholder="serial_number" name="serial_number">';
    template += '<input id="image" type="text" placeholder="image" name="image">'
    template += '<input id="value" type="text" placeholder="value" name="value">';
    template += '<input id="sold" type="text" placeholder="sold" name="sold">';
    template += '<input id="buyer" type="text" placeholder="buyer" name="buyer">';
    template += '<button type="submit" id="search_gun_submit">Submit</submit> ';
    template += '</form>
';

    $("#output").html(template);

    // Collect info from the search fields
    $("#search_gun_submit").click(function(e){
      e.preventDefault();
      gunObj = {
        manufacturer: $("#manufacturer").val(),
        model: $("#model").val(),
        chambering: $("#chambering").val(),
        type: $("#type").val(),
        serial_number: $("#serial_number").val(),
        image: $("#image").val(),
        value: $("#value").val(),
        sold: $("#sold").val(),
        buyer: $("#buyer").val()
      }

      //searchKeys are the fields the user is looking for
      var searchKeys = {};
      //searchList is a big list to be whittled down...
      var searchList = state.guns;
      for (var [key, value] of Object.entries(gunObj)) {
        if (value) { searchKeys[key] = value; }
      }

      //Why are some guns not being returned?
      console.log('Looking for: ', searchKeys);

      // newArray will contain only matching guns to be returned to user
      let newArray = searchList.filter(function(gun, index, array) {
        Object.keys(searchKeys).forEach(function(key) {
          // if(searchKeys[key] !== gun[key]) {
          if (!gun[key].includes(searchKeys[key])) {
            gun['delete'] = true;
          }
        });
        return !gun.delete;
      });

      let returnTemplate = '
';
      newArray.forEach(function(gun){
        console.log('newArray size: ', newArray.length);
        returnTemplate += '
'+gun.fullName+
        `<button class="update_gun" data-gunobj="${gun.id}">Update or Delete</button>`;
      })

      if (newArray.length === 0) returnTemplate += "No Guns Found.";

      // put the 'home' button on the page
      returnTemplate += '<button id="home_page">Home</button>';
      returnTemplate += '
';

      $("#output").html(returnTemplate);

      $("#home_page").click(function(){
        showMenu();
      })

      $("#edit_guns").click('.update_gun', function(ev) {
        var targetId = $(ev.target).data('gunobj');
        console.log('ClickHandler!  target id:', targetId);

        getOneGun(targetId);
      })

      console.log('NewArray returned: ', newArray);
    })
  })  //end of searchgun menu pick

  // $("#update_gun").click(function(){
  //   console.log('Update gun clicked')
  // })

  // $("#delete_gun").click(function(){
  //   console.log('Delete gun clicked')
  // })

}  // end of showMenu()
<|endoftext|>


<commit_before>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */
(function() {
    'use strict';

    // Your custom JavaScript goes here
    var nav = document.getElementById('nav-burger-menu');
    var menuList = document.getElementById('nav-menu-list');
    var overlay = document.getElementById('site-overlay');
    var body = document.getElementsByTagName('body')[0];
    var searchIcon = document.getElementById('nav-search');
    var searchBar = document.getElementById('search-bar');
    var resultsSearchBar = document.getElementById('results-search-bar');
    var pressonhead = document.getElementById('pressonhead');
    var searchField = document.getElementsByClassName('search-field')[0];
    var resultsSearchField = document.getElementsByClassName('search-field')[1];

    nav.onclick = function() {
        if (nav.classList.contains('open')) {
            closeMenu();
        } else {
            openMenu();
        }
    };

    searchIcon.onclick = function() {
        if (searchBar.classList.contains('search-close')) {
            openSearch();
        } else {
            closeSearch();
        }
    };

    searchBar.onclick = function() {
        searchField.focus();
    };

    if (resultsSearchBar != null) {
        resultsSearchBar.onclick = function() {
            resultsSearchField.focus();
        };
    }

    overlay.onclick = closeAll;

    function openMenu() {
        pressonhead.classList.add('opaque');
        nav.classList.add('open');
        menuList.classList.add('slideLeft');
        menuList.classList.remove('slideRight');
        menuList.classList.remove('resting');
        menuList.classList.add('slide');

        if (searchBar.classList.contains('search-open')) {
            closeSearchHelper();
        }
        toggle();
    }

    function closeMenu() {
        closeMenuHelper();
    }

    function openSearch() {
        pressonhead.classList.add('opaque');
        searchBar.classList.add('search-open');
        searchBar.classList.remove('search-close');
        if (nav.classList.contains('open')) {
            closeMenuHelper();
        }
        toggle();
        searchField.focus();
    }

    function closeSearch() {
        closeSearchHelper();
    }

    function closeMenuHelper() {
        nav.classList.remove('open');
        menuList.classList.add('slideRight');
        menuList.classList.remove('slideLeft');
        menuList.classList.add('resting');
        menuList.classList.remove('slide');
        toggle();
    }

    function closeAll() {
        closeMenu();
        closeSearch();
        toggle();
    }

    function closeSearchHelper() {
        searchBar.classList.remove('search-open');
        searchBar.classList.add('search-close');
        toggle();
    }

    function toggle() {
        if (overlay.style.display === 'none')
            overlay.style.display = '';
        else
            overlay.style.display = 'none';

        if (body.classList.contains('stop-scrolling'))
            body.classList.remove('stop-scrolling');
        else
            body.classList.add('stop-scrolling');
    }
})();<commit_msg>[Farzana] adjusting header opacity when closing search and menu<commit_after>/*!
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */
/* eslint-env browser */
(function() {
    'use strict';

    // Your custom JavaScript goes here
    var nav = document.getElementById('nav-burger-menu');
    var menuList = document.getElementById('nav-menu-list');
    var overlay = document.getElementById('site-overlay');
    var body = document.getElementsByTagName('body')[0];
    var searchIcon = document.getElementById('nav-search');
    var searchBar = document.getElementById('search-bar');
    var resultsSearchBar = document.getElementById('results-search-bar');
    var pressonhead = document.getElementById('pressonhead');
    var searchField = document.getElementsByClassName('search-field')[0];
    var resultsSearchField = document.getElementsByClassName('search-field')[1];

    nav.onclick = function() {
        if (nav.classList.contains('open')) {
            closeMenu();
        } else {
            openMenu();
        }
    };

    searchIcon.onclick = function() {
        if (searchBar.classList.contains('search-close')) {
            openSearch();
        } else {
            closeSearch();
        }
    };

    searchBar.onclick = function() {
        searchField.focus();
    };

    if (resultsSearchBar != null) {
        resultsSearchBar.onclick = function() {
            resultsSearchField.focus();
        };
    }

    overlay.onclick = closeAll;

    function openMenu() {
        pressonhead.classList.add('opaque');
        nav.classList.add('open');
        menuList.classList.add('slideLeft');
        menuList.classList.remove('slideRight');
        menuList.classList.remove('resting');
        menuList.classList.add('slide');

        if (searchBar.classList.contains('search-open')) {
            closeSearchHelper();
        }
        toggle();
    }

    function closeMenu() {
        closeMenuHelper();
    }

    function openSearch() {
        pressonhead.classList.add('opaque');
        searchBar.classList.add('search-open');
        searchBar.classList.remove('search-close');
        if (nav.classList.contains('open')) {
            closeMenuHelper();
        }
        toggle();
        searchField.focus();
    }

    function closeSearch() {
        closeSearchHelper();
    }

    function closeMenuHelper() {
        nav.classList.remove('open');
        menuList.classList.add('slideRight');
        menuList.classList.remove('slideLeft');
        menuList.classList.add('resting');
        menuList.classList.remove('slide');
        pressonhead.classList.remove('opaque');
        toggle();
    }

    function closeAll() {
        closeMenu();
        closeSearch();
        toggle();
    }

    function closeSearchHelper() {
        searchBar.classList.remove('search-open');
        searchBar.classList.add('search-close');
        pressonhead.classList.remove('opaque');
        toggle();
    }

    function toggle() {
        if (overlay.style.display === 'none')
            overlay.style.display = '';
        else
            overlay.style.display = 'none';

        if (body.classList.contains('stop-scrolling'))
            body.classList.remove('stop-scrolling');
        else
            body.classList.add('stop-scrolling');
    }
})();<|endoftext|>


<commit_before>"use strict";

var _ = require('lodash'),
    Bacon = require('baconjs'),
    url = require('url'),
    L = require('leaflet'),
    History = require('history'),

    modeNamesForUrl = [
        require('treemap/addTreeMode').name,
        require('treemap/addResourceMode').name,
        'prioritization',
        'scenarios'
    ];

var _state = null,
    _stateChangeBus = new Bacon.Bus(),
    _history = null,
    _window = null;

function HistoryApi() {
    function onStateChange(callback) {
        History.Adapter.bind(window, 'statechange', callback);
        // We use the "History" library for "pushState" etc. capabilities on IE9.
        // If we drop IE9 support we should change "History" to "history" in this
        // module, and replace the above "bind" call with:
        //        window.onpopstate = function(event) {
        //            setStateAndPushToApp(event.state || getStateFromCurrentUrl());
        //        };
    }
    function getState() {
        return History.getState();
    }
    function pushState(state, title, url) {
        History.pushState(state, title, url);
    }
    function replaceState(state, title, url) {
        History.replaceState(state, title, url);
    }
    return {
        onStateChange: onStateChange,
        getState: getState,
        pushState: pushState,
        replaceState: replaceState
    };
}

function WindowApi() {
    return {
        getLocationHref: function() {
            return window.location.href;
        }
    };
}

var serializers = {
    zoomLatLng: function(state, query) {
        if (state.zoomLatLng) {
            var zoom = state.zoomLatLng.zoom,
                precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)),
                lat = state.zoomLatLng.lat.toFixed(precision),
                lng = state.zoomLatLng.lng.toFixed(precision);
            query.z = [zoom, lat, lng].join('/');
        }
    },

    search: function(state, query) {
        if (state.search && state.search.filter && !_.isEmpty(state.search.filter)) {
            query.q = JSON.stringify(state.search.filter);
        }
        if (state.search && state.search.display) {
            query.show = JSON.stringify(state.search.display);
        }
    },

    modeName: function(state, query) {
        if (state.modeName) {
            query.m = state.modeName;
        }
    }
};

var deserializers = {
    z: function(newState, query) {
        var zoomLatLng = query.z;
        newState.zoomLatLng = null;
        if (zoomLatLng) {
            var parts = zoomLatLng.split("/"),
                zoom = parseInt(parts[0], 10),
                lat = parseFloat(parts[1]),
                lng = parseFloat(parts[2]);
            if (!isNaN(zoom) && !isNaN(lat) && !isNaN(lng)) {
                newState.zoomLatLng = makeZoomLatLng(zoom, lat, lng);
            }
        }
    },

    q: function(newState, query) {
        newState.search = newState.search || {};
        newState.search.filter = JSON.parse(query.q || '{}');
    },

    show: function(newState, query) {
        newState.search = newState.search || {};
        newState.search.display = query.show ? JSON.parse(query.show) : undefined;
    },

    m: function(newState, query) {
        newState.modeName = query.m || '';
    }
};

module.exports = {
    init: function (options) {
        options = _.defaults(options, {
            historyApi: new HistoryApi(),
            windowApi: new WindowApi()
        });

        _state = null;
        _history = options.historyApi;
        _window = options.windowApi;

        setStateAndPushToApp(getStateFromCurrentUrl());

        _history.onStateChange(function() {
            setStateAndPushToApp(_history.getState().data || getStateFromCurrentUrl());
        });
    },

    setZoomLatLng: function (zoom, center) {
        var zoomLatLng = makeZoomLatLng(zoom, center.lat, center.lng);
        if (!_.isEqual(zoomLatLng, _state.zoomLatLng)) {
            _state.zoomLatLng = zoomLatLng;
            _history.replaceState(_state, document.title, getUrlFromCurrentState());
        }
    },

    setSearch: function (otmSearch) {
        if (!_.isEqual(otmSearch, _state.search)) {
            _state.search = otmSearch;
            _history.pushState(_state, document.title, getUrlFromCurrentState());
        }
    },

    setModeName: function (modeName) {
        modeName = _.contains(modeNamesForUrl, modeName) ? modeName : '';
        if (modeName !== _state.modeName) {
            _state.modeName = modeName;
            _history.replaceState(_state, document.title, getUrlFromCurrentState());
        }
    },

    getSearch: function() {
        return _state.search;
    },

    get: function(key) {
        return _state[key];
    },

    set: function(key, value) {
        if (!_.isEqual(_state && _state[key], value)) {
            _state[key] = value;
            _history.replaceState(_state, document.title, getUrlFromCurrentState());
        }
    },

    stateChangeStream: _stateChangeBus.map(_.identity)
};

function getStateFromCurrentUrl() {
    var newState = {},
        query = url.parse(_window.getLocationHref(), true).query,
        allKeys = _.union(_.keys(deserializers), _.keys(query));

    _.each(allKeys, function(k) {
        var deserialize = deserializers[k];
        if (deserialize) {
            deserialize(newState, query);
        } else {
            newState[k] = query[k];
        }
    });

    return newState;
}

function makeZoomLatLng(zoom, lat, lng) {
    return { zoom: zoom, lat: lat, lng: lng };
}

function getUrlFromCurrentState() {
    var parsedUrl = url.parse(_window.getLocationHref()),
        query = {};

    _.each(_state, function(v, k) {
        var serialize = serializers[k];
        if (serialize) {
            serialize(_state, query);
        } else {
            query[k] = v;
        }
    });

    parsedUrl.query = query;
    parsedUrl.search = null;
    var urlText = url.format(parsedUrl).replace(/%2F/g, '/');
    return urlText;
}

function setStateAndPushToApp(newState) {
    var changedState = _.omit(newState, function(v, k) {
        return _state && _.isEqual(_state[k], v);
    });
    _state = newState;
    if (!_.isEmpty(changedState)) {
        _stateChangeBus.push(changedState);
    }
}
<commit_msg>Fix undefined error when urlState options is null<commit_after>"use strict";

var _ = require('lodash'),
    Bacon = require('baconjs'),
    url = require('url'),
    L = require('leaflet'),
    History = require('history'),

    modeNamesForUrl = [
        require('treemap/addTreeMode').name,
        require('treemap/addResourceMode').name,
        'prioritization',
        'scenarios'
    ];

var _state = null,
    _stateChangeBus = new Bacon.Bus(),
    _history = null,
    _window = null;

function HistoryApi() {
    function onStateChange(callback) {
        History.Adapter.bind(window, 'statechange', callback);
        // We use the "History" library for "pushState" etc. capabilities on IE9.
        // If we drop IE9 support we should change "History" to "history" in this
        // module, and replace the above "bind" call with:
        //        window.onpopstate = function(event) {
        //            setStateAndPushToApp(event.state || getStateFromCurrentUrl());
        //        };
    }
    function getState() {
        return History.getState();
    }
    function pushState(state, title, url) {
        History.pushState(state, title, url);
    }
    function replaceState(state, title, url) {
        History.replaceState(state, title, url);
    }
    return {
        onStateChange: onStateChange,
        getState: getState,
        pushState: pushState,
        replaceState: replaceState
    };
}

function WindowApi() {
    return {
        getLocationHref: function() {
            return window.location.href;
        }
    };
}

var serializers = {
    zoomLatLng: function(state, query) {
        if (state.zoomLatLng) {
            var zoom = state.zoomLatLng.zoom,
                precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)),
                lat = state.zoomLatLng.lat.toFixed(precision),
                lng = state.zoomLatLng.lng.toFixed(precision);
            query.z = [zoom, lat, lng].join('/');
        }
    },

    search: function(state, query) {
        if (state.search && state.search.filter && !_.isEmpty(state.search.filter)) {
            query.q = JSON.stringify(state.search.filter);
        }
        if (state.search && state.search.display) {
            query.show = JSON.stringify(state.search.display);
        }
    },

    modeName: function(state, query) {
        if (state.modeName) {
            query.m = state.modeName;
        }
    }
};

var deserializers = {
    z: function(newState, query) {
        var zoomLatLng = query.z;
        newState.zoomLatLng = null;
        if (zoomLatLng) {
            var parts = zoomLatLng.split("/"),
                zoom = parseInt(parts[0], 10),
                lat = parseFloat(parts[1]),
                lng = parseFloat(parts[2]);
            if (!isNaN(zoom) && !isNaN(lat) && !isNaN(lng)) {
                newState.zoomLatLng = makeZoomLatLng(zoom, lat, lng);
            }
        }
    },

    q: function(newState, query) {
        newState.search = newState.search || {};
        newState.search.filter = JSON.parse(query.q || '{}');
    },

    show: function(newState, query) {
        newState.search = newState.search || {};
        newState.search.display = query.show ? JSON.parse(query.show) : undefined;
    },

    m: function(newState, query) {
        newState.modeName = query.m || '';
    }
};

module.exports = {
    init: function (options) {
        options = _.defaults({}, options, {
            historyApi: new HistoryApi(),
            windowApi: new WindowApi()
        });

        _state = null;
        _history = options.historyApi;
        _window = options.windowApi;

        setStateAndPushToApp(getStateFromCurrentUrl());

        _history.onStateChange(function() {
            setStateAndPushToApp(_history.getState().data || getStateFromCurrentUrl());
        });
    },

    setZoomLatLng: function (zoom, center) {
        var zoomLatLng = makeZoomLatLng(zoom, center.lat, center.lng);
        if (!_.isEqual(zoomLatLng, _state.zoomLatLng)) {
            _state.zoomLatLng = zoomLatLng;
            _history.replaceState(_state, document.title, getUrlFromCurrentState());
        }
    },

    setSearch: function (otmSearch) {
        if (!_.isEqual(otmSearch, _state.search)) {
            _state.search = otmSearch;
            _history.pushState(_state, document.title, getUrlFromCurrentState());
        }
    },

    setModeName: function (modeName) {
        modeName = _.contains(modeNamesForUrl, modeName) ? modeName : '';
        if (modeName !== _state.modeName) {
            _state.modeName = modeName;
            _history.replaceState(_state, document.title, getUrlFromCurrentState());
        }
    },

    getSearch: function() {
        return _state.search;
    },

    get: function(key) {
        return _state[key];
    },

    set: function(key, value) {
        if (!_.isEqual(_state && _state[key], value)) {
            _state[key] = value;
            _history.replaceState(_state, document.title, getUrlFromCurrentState());
        }
    },

    stateChangeStream: _stateChangeBus.map(_.identity)
};

function getStateFromCurrentUrl() {
    var newState = {},
        query = url.parse(_window.getLocationHref(), true).query,
        allKeys = _.union(_.keys(deserializers), _.keys(query));

    _.each(allKeys, function(k) {
        var deserialize = deserializers[k];
        if (deserialize) {
            deserialize(newState, query);
        } else {
            newState[k] = query[k];
        }
    });

    return newState;
}

function makeZoomLatLng(zoom, lat, lng) {
    return { zoom: zoom, lat: lat, lng: lng };
}

function getUrlFromCurrentState() {
    var parsedUrl = url.parse(_window.getLocationHref()),
        query = {};

    _.each(_state, function(v, k) {
        var serialize = serializers[k];
        if (serialize) {
            serialize(_state, query);
        } else {
            query[k] = v;
        }
    });

    parsedUrl.query = query;
    parsedUrl.search = null;
    var urlText = url.format(parsedUrl).replace(/%2F/g, '/');
    return urlText;
}

function setStateAndPushToApp(newState) {
    var changedState = _.omit(newState, function(v, k) {
        return _state && _.isEqual(_state[k], v);
    });
    _state = newState;
    if (!_.isEmpty(changedState)) {
        _stateChangeBus.push(changedState);
    }
}
<|endoftext|>


<commit_before>/// requires
// var Player = require("./players");

/// object
function Puck(position, board) {
	/// public variables
	this.board = board;

	if (position) {
		this.place(position);
	}
}

Puck.prototype = {
	// return a list of tiles representing the path this puck would take if
	// kicked in the direction of the tile passed in
	calculateTrajectory: function (direction) {
		var crossedBorder = false,
			dx = direction.x - this.x,
			dy = direction.y - this.y,
			lastTile = this.board.tile(this.x, this.y),
			reflectX,
			reflectY,
			tile,
			trajectory = [],
			x = this.x,
			y = this.y;

		while (1) {
			if (tile) {
				lastTile = tile;
			}

			x += dx;
			y += dy;

			tile = this.board.tile(x, y);

			if (!tile || tile.type === "wall") {
				// check if this is an orthagonal collision, in which case the
				// path of the puck needs to end here
				if (dx * dy === 0) {
					break;
				}

				reflectX = x <= 1 || x >= 13;
				reflectY = y === 8 || y === -1;

				// we know that this is a diagonal collision, so we need to
				// reverse the direction and allow the puck to continue
				if (reflectY) {
					x -= dx;
					y -= dy;

					dy *= -1;
				}

				if (reflectX && !reflectY) {
					x -= dx;
					y -= dy;

					dx *= -1;
				}

				continue;
			}

			// check if the owner of this tile does not equal the owner of the
			// original tile, which would indicate that the puck has crossed the
			// border at some point
			if (tile.owner !== lastTile.owner) {
				if (crossedBorder) {
					// if the tile has already crossed the border, then the next
					// tile represents a second crossing of the border, which we
					// won't allow
					break;
				} else {
					// however, if this is the first time crossing the border,
					// then we let the puck continue on its way
					crossedBorder = true;
				}
			}

			// if the tile is occupied by an actor, end the loop
			if (tile.actor) {
				break;
			}

			if (tile && tile.type !== "wall") {
				trajectory.push(tile);
			}

			// if this tile is a goal, then break the loop
			if (tile.inZone("goal")) {
				break;
			}
		}

		return trajectory;
	},

	kick: function (tile) {
		// remove the reference to this puck from the tile it is sitting on
		this.board.tile(this.x, this.y).removeActor();

		// kick to another tile
		this.x = tile.x;
		this.y = tile.y;

		// give the tile this puck is sitting on a reference to it
		this.board.tile(this.x, this.y).addActor(this);
	},

	// calculate the directions this puck can be kicked in, based on the actors
	// surrounding it, and the player that is passed in
	kickDirections: function (player) {
		var directions = [],
			neighborhood,
			self = this,
			puckTile = this.board.tile(this.x, this.y);

		neighborhood = puckTile.neighborhood();

		neighborhood.forEach(function(actorTile) {
			var actorAngle,
				dx,
				dy,
				oppositeTile;

			if (!actorTile.actor || actorTile.actor.owner !== player) {
				return;
			}

			// find relative position of the actor on this tile
			dx = actorTile.x - self.x;
			dy = actorTile.y - self.y;

			// find tile on the other side of the ball based on the actor's
			// position
			oppositeTile = self.board.tile(self.x - dx, self.y - dy);

			// find the relative angle of the player to the puck (atan2's
			// arguments are passed in backwards, counterintuitively)
			actorAngle = Math.atan2(dy, dx);

			// iterate through the neighbors of the puck and find their
			// relative positions to the puck, then compare the atan2 of
			// that relative position to the atan2 of the relative position
			// of the player; if the absolute of resulting value is greater or
			// equal to 1.57 degrees radian, we know that that direction is not
			// "backwards" for the current actor and we will add it to the
			// list of directions; otherwise, we can't add this tile
			neighborhood.forEach(function (tile) {
				var diffAngle,
					tileAngle = Math.atan2(tile.y - self.y, tile.x - self.x);

				diffAngle = Math.abs(actorAngle - tileAngle);

				if (diffAngle > Math.PI) {
					diffAngle = Math.PI * 2 - diffAngle;
				}

				if (// the direction is greater than 45º away from the player
					((diffAngle >= 1.57) ||

					// or the puck is against a wall and the player is facing
					// the wall
					((!oppositeTile || oppositeTile.type === "wall") &&
						dx * dy === 0) ||

					// or the puck is in a corner
					(neighborhood.length < 4)) &&

					// and the tile is not occupied or already in the list
					!tile.actor &&

					// and the tile is not already in the list
					directions.indexOf(tile) < 0) {

					// then we can add this direction to the list
					directions.push(tile);
				}
			});
		});

		return directions;
	},

	// place this puck on the board
	place: function (position) {
		this.x = position.x;
		this.y = position.y;

		this.board.tile(this.x, this.y).addActor(this);
	}
};

/// exports
module.exports = Puck;<commit_msg>Disallow puck to bounce off corners of goal zones<commit_after>/// requires
// var Player = require("./players");

/// object
function Puck(position, board) {
	/// public variables
	this.board = board;

	if (position) {
		this.place(position);
	}
}

Puck.prototype = {
	// return a list of tiles representing the path this puck would take if
	// kicked in the direction of the tile passed in
	calculateTrajectory: function (direction) {
		var crossedBorder = false,
			dx = direction.x - this.x,
			dy = direction.y - this.y,
			lastTile = this.board.tile(this.x, this.y),
			reflectX,
			reflectY,
			tile,
			trajectory = [],
			x = this.x,
			y = this.y;

		while (1) {
			if (tile) {
				lastTile = tile;
			}

			x += dx;
			y += dy;

			tile = this.board.tile(x, y);

			if (!tile || tile.type === "wall") {
				// check if this is an orthagonal collision, in which case the
				// path of the puck needs to end here
				if (dx * dy === 0) {
					break;
				}

				// we must disallow puck to bounce off corners of goal zones
				// so we need to check if this wall is below or above goal zone
				if(this.board.tile(x, y - dy).zones.indexOf('goal') >= 0) {
					break;
				}

				reflectX = x <= 1 || x >= 13;
				reflectY = y === 8 || y === -1;

				// we know that this is a diagonal collision, so we need to
				// reverse the direction and allow the puck to continue
				if (reflectY) {
					x -= dx;
					y -= dy;

					dy *= -1;
				}

				if (reflectX && !reflectY) {
					x -= dx;
					y -= dy;

					dx *= -1;
				}

				continue;
			}

			// check if the owner of this tile does not equal the owner of the
			// original tile, which would indicate that the puck has crossed the
			// border at some point
			if (tile.owner !== lastTile.owner) {
				if (crossedBorder) {
					// if the tile has already crossed the border, then the next
					// tile represents a second crossing of the border, which we
					// won't allow
					break;
				} else {
					// however, if this is the first time crossing the border,
					// then we let the puck continue on its way
					crossedBorder = true;
				}
			}

			// if the tile is occupied by an actor, end the loop
			if (tile.actor) {
				break;
			}

			if (tile && tile.type !== "wall") {
				trajectory.push(tile);
			}

			// if this tile is a goal, then break the loop
			if (tile.inZone("goal")) {
				break;
			}
		}

		return trajectory;
	},

	kick: function (tile) {
		// remove the reference to this puck from the tile it is sitting on
		this.board.tile(this.x, this.y).removeActor();

		// kick to another tile
		this.x = tile.x;
		this.y = tile.y;

		// give the tile this puck is sitting on a reference to it
		this.board.tile(this.x, this.y).addActor(this);
	},

	// calculate the directions this puck can be kicked in, based on the actors
	// surrounding it, and the player that is passed in
	kickDirections: function (player) {
		var directions = [],
			neighborhood,
			self = this,
			puckTile = this.board.tile(this.x, this.y);

		neighborhood = puckTile.neighborhood();

		neighborhood.forEach(function(actorTile) {
			var actorAngle,
				dx,
				dy,
				oppositeTile;

			if (!actorTile.actor || actorTile.actor.owner !== player) {
				return;
			}

			// find relative position of the actor on this tile
			dx = actorTile.x - self.x;
			dy = actorTile.y - self.y;

			// find tile on the other side of the ball based on the actor's
			// position
			oppositeTile = self.board.tile(self.x - dx, self.y - dy);

			// find the relative angle of the player to the puck (atan2's
			// arguments are passed in backwards, counterintuitively)
			actorAngle = Math.atan2(dy, dx);

			// iterate through the neighbors of the puck and find their
			// relative positions to the puck, then compare the atan2 of
			// that relative position to the atan2 of the relative position
			// of the player; if the absolute of resulting value is greater or
			// equal to 1.57 degrees radian, we know that that direction is not
			// "backwards" for the current actor and we will add it to the
			// list of directions; otherwise, we can't add this tile
			neighborhood.forEach(function (tile) {
				var diffAngle,
					tileAngle = Math.atan2(tile.y - self.y, tile.x - self.x);

				diffAngle = Math.abs(actorAngle - tileAngle);

				if (diffAngle > Math.PI) {
					diffAngle = Math.PI * 2 - diffAngle;
				}

				if (// the direction is greater than 45º away from the player
					((diffAngle >= 1.57) ||

					// or the puck is against a wall and the player is facing
					// the wall
					((!oppositeTile || oppositeTile.type === "wall") &&
						dx * dy === 0) ||

					// or the puck is in a corner
					(neighborhood.length < 4)) &&

					// and the tile is not occupied or already in the list
					!tile.actor &&

					// and the tile is not already in the list
					directions.indexOf(tile) < 0) {

					// then we can add this direction to the list
					directions.push(tile);
				}
			});
		});

		return directions;
	},

	// place this puck on the board
	place: function (position) {
		this.x = position.x;
		this.y = position.y;

		this.board.tile(this.x, this.y).addActor(this);
	}
};

/// exports
module.exports = Puck;<|endoftext|>


<commit_before>$( document ).ready (function(){
	$("#save_task").click(save_task);
	chrome.identity.getProfileUserInfo(function(token) {
		var login = {
			username: token.email
		};
		$.ajax({
			type:'GET',
			url:'http://cs180.no-ip.info/GetTask',
			data: login,
			success: function(tasks) {
				$.each (tasks, function (i, tasks) {
					if (tasks.status === 0) {
						var newTaskId = tasks.description.toString();
						$('#tasks').append('
 '+ tasks.description + '
');
						var thisTask = $('#' + newTaskId);
						$(thisTask).click(function() {
							var cross = {
								taskid: tasks.taskid,
								status: tasks.status
							};
							$.ajax({
								type: 'POST',
								url: 'http://cs180.no-ip.info/CheckTask',
								data: cross,
								success: function(cross) {
								    location.reload();
								    // This does not cross it out...
									// $cross.append('
taskid: ' + cross.taskid + ', status: 1
');
								},
								error: function() {
									alert('error task');
								}
							});
						});
						var newButtonId = tasks.taskid.toString();
                        $('#tasks').append ('
 <button id=' + newButtonId + '> Delete </button>
');
						var thisButton = $('#' + newButtonId);
                        $(thisButton).click(function() {
							var deletion = {
								taskid: tasks.taskid
					        };
						    $.ajax({
						        type: 'DELETE',
							    url: 'http://cs180.no-ip.info/DeleteTask',
							    data: deletion,
							    success: function(deletion) {
							        location.reload();
							        // This does not delete it...
							        // $deletion.append('
taskid: ' + deletion.taskid + '
');
							    },
							    error: function() {
							        alert('error task');
							    }
						    });
					    });
					}
					else {
						//strikethrough if status is 1
						var newTaskId = tasks.description.toString();
						$('#tasks').append('
 <s>'+ tasks.description + '</s>
');
						var thisTask = $('#' + newTaskId);
						$(thisTask).click(function(){
							var cross = {
								taskid: tasks.taskid,
								status: tasks.status
							};
							$.ajax({
								type: 'POST',
								url: 'http://cs180.no-ip.info/CheckTask',
								data: cross,
								success: function(cross) {
								    // This does not cross it out...
									// $cross.append('
taskid: ' + cross.taskid + ', status: 0
');
								},
								error: function() {
									alert('error task');
								}
							});
						});

						var newButtonId = tasks.taskid.toString();
                        $('#tasks').append ('
 <button id=' + newButtonId + '> Delete </button>
');
						var thisButton = $('#' + newButtonId);
                        $(thisButton).click(function() {
							var deletion = {
								taskid: tasks.taskid
							};
							$.ajax({
								type: 'DELETE',
								url: 'http://cs180.no-ip.info/DeleteTask',
								data: deletion,
								success: function(deletion) {
								    location.reload();
								    // This does not delete it
									// $deletion.append('
taskid: ' + deletion.taskid + '
');
								},
								error: function() {
									alert('error task');
								}
							});
						});
					}
					$('#tasks').append ('

deadline: '  + tasks.deadline + '

');
					$('#tasks').append ('

');
				});
			}
		});
	});
});

function save_task() {
    chrome.identity.getProfileUserInfo(function(token) {
        if (token.email === '') {
            console.log('lol');
            return;
        }
        else {
	        var input, task, year, month, day, date;
		    input=document.getElementById("form1") ;
		    task=input.elements["task"].value;
		    year=input.elements["year"].value;
		    month=input.elements["month"].value;
		    day=input.elements["day"].value;
		    date= year + "-" + month + "-" + day;
		    var task = {
	            username: token.email,
			    deadline: date,
			    description: task
		    };
		    $.ajax({
	            type: 'POST',
			    url: 'http://cs180.no-ip.info/AddTask',
			    data: task,
			    success: function(data) {
			        location.reload();
			    },
			    error: function() {
		            alert('error task');
			    }
		    });
		}
    });
};

<commit_msg>more last minute changes<commit_after>$( document ).ready (function(){
	$("#save_task").click(save_task);
	chrome.identity.getProfileUserInfo(function(token) {
		var login = {
			username: token.email
		};
		$.ajax({
			type:'GET',
			url:'http://cs180.no-ip.info/GetTask',
			data: login,
			success: function(tasks) {
				$.each (tasks, function (i, tasks) {
					if (tasks.status === 0) {
						var newTaskId = tasks.description.toString();
						$('#tasks').append('
 '+ tasks.description + '
');
						var thisTask = $('#' + newTaskId);
						$(thisTask).click(function() {
							var cross = {
								taskid: tasks.taskid,
								status: tasks.status
							};
							$.ajax({
								type: 'POST',
								url: 'http://cs180.no-ip.info/CheckTask',
								data: cross,
								success: function(cross) {
								    location.reload();
								    // This does not cross it out...
									// $cross.append('
taskid: ' + cross.taskid + ', status: 1
');
								},
								error: function() {
									alert('error task');
								}
							});
						});
						var newButtonId = tasks.taskid.toString();
                        $('#tasks').append ('
 <button id=' + newButtonId + '> Delete </button>
');
						var thisButton = $('#' + newButtonId);
                        $(thisButton).click(function() {
							var deletion = {
								taskid: tasks.taskid
					        };
						    $.ajax({
						        type: 'DELETE',
							    url: 'http://cs180.no-ip.info/DeleteTask',
							    data: deletion,
							    success: function(deletion) {
							        location.reload();
							        // This does not delete it...
							        // $deletion.append('
taskid: ' + deletion.taskid + '
');
							    },
							    error: function() {
							        alert('error task');
							    }
						    });
					    });
					}
					else {
						//strikethrough if status is 1
						var newTaskId = tasks.description.toString();
						$('#tasks').append('
 <s>'+ tasks.description + '</s>
');
						var thisTask = $('#' + newTaskId);
						$(thisTask).click(function(){
							var cross = {
								taskid: tasks.taskid,
								status: tasks.status
							};
							$.ajax({
								type: 'POST',
								url: 'http://cs180.no-ip.info/CheckTask',
								data: cross,
								success: function(cross) {
								    // This does not cross it out...
									// $cross.append('
taskid: ' + cross.taskid + ', status: 0
');
								},
								error: function() {
									alert('error task');
								}
							});
						});

						var newButtonId = tasks.taskid.toString();
                        $('#tasks').append ('
 <button id=' + newButtonId + '> Delete </button>
');
						var thisButton = $('#' + newButtonId);
                        $(thisButton).click(function() {
							var deletion = {
								taskid: tasks.taskid
							};
							$.ajax({
								type: 'DELETE',
								url: 'http://cs180.no-ip.info/DeleteTask',
								data: deletion,
								success: function(deletion) {
								    location.reload();
								    // This does not delete it
									// $deletion.append('
taskid: ' + deletion.taskid + '
');
								},
								error: function() {
									alert('error task');
								}
							});
						});
					}
					$('#tasks').append ('

deadline: '  + tasks.deadline + '

');
					$('#tasks').append ('

');
				});
			}
		});
	});
});

function save_task() {
    chrome.identity.getProfileUserInfo(function(token) {
        if (token.email === '') {
            return;
        }
        else {
	        var input, task, year, month, day, date;
		    input=document.getElementById("form1") ;
		    task=input.elements["task"].value;
		    if (task === '') {
		        return;
		    }
		    year=input.elements["year"].value;
		    month=input.elements["month"].value;
		    day=input.elements["day"].value;
		    date= year + "-" + month + "-" + day;
		    var task = {
	            username: token.email,
			    deadline: date,
			    description: task
		    };
		    $.ajax({
	            type: 'POST',
			    url: 'http://cs180.no-ip.info/AddTask',
			    data: task,
			    success: function(data) {
			        location.reload();
			    },
			    error: function() {
		            alert('error task');
			    }
		    });
		}
    });
};

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Onegini B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = (function () {
  var utils = require('./utils');

  function AuthenticationHandler(options, client, action) {
    var self = this;
    this.callbacks = {};

    this.callbackActions = {
      providePin: function (options) {
        options = utils.getOptionsWithDefaults(options, {}, 'pin');
        if (!options || !options.pin) {
          throw new TypeError('Onegini: missing "pin" argument for providePin');
        }

        utils.callbackExec(client, 'providePin', options, callSuccessCallback, callErrorCallback);
      },

      fallbackToPin: function () {
        utils.onceExec(client, 'fallbackToPin');
      },

      acceptFingerprint: function (options) {
        options = utils.getOptionsWithDefaults(options, {}, 'iosPrompt');
        options.accept = true;
        utils.callbackExec(client, 'respondToFingerprintRequest', options, callSuccessCallback, callErrorCallback);
      },

      denyFingerprint: function () {
        utils.callbackExec(client, 'respondToFingerprintRequest', {accept: false}, callSuccessCallback, callErrorCallback)
      },

      createPin: function (options) {
        options = utils.getOptionsWithDefaults(options, {}, 'pin');
        if (!options || !options.pin) {
          throw new TypeError('Onegini: missing "pin" argument for createPin');
        }

        utils.callbackExec(client, 'createPin', options, callSuccessCallback, callErrorCallback);
      },

      handleRegistrationUrl: function(options) {
        options = utils.getOptionsWithDefaults(options, {}, 'url');
        utils.callbackExec(client, 'respondToRegistrationRequest', options, callSuccessCallback, callErrorCallback);
      },

      cancel: function () {
        utils.callbackExec(client, 'cancelFlow', {}, callSuccessCallback, callErrorCallback);
      }
    };

    function callSuccessCallback(options) {
      var event = options.pluginEvent;
      delete options.pluginEvent;

      if (self.callbacks[event]) {
        self.callbacks[event](self.callbackActions, options);
      }
    }

    function callErrorCallback(err) {
      if (self.callbacks.onError) {
        self.callbacks.onError(err);
      } else {
        console.warn('Onegini: An Error occurred but no error callback was registered');
        console.error('Onegini: ', err);
      }
    }

    utils.callbackExec(client, action, options, callSuccessCallback, callErrorCallback)
  }

  AuthenticationHandler.prototype.onPinRequest = function (cb) {
    this.callbacks.onPinRequest = cb;
    return this;
  };

  AuthenticationHandler.prototype.onCreatePinRequest = function (cb) {
    this.callbacks.onCreatePinRequest = cb;
    return this;
  };

  AuthenticationHandler.prototype.onFingerprintRequest = function (cb) {
    this.callbacks.onFingerprintRequest = cb;
    return this;
  };

  AuthenticationHandler.prototype.onFingerprintCaptured = function (cb) {
    this.callbacks.onFingerprintCaptured = cb;
    return this;
  };

  AuthenticationHandler.prototype.onFingerprintFailed = function (cb) {
    this.callbacks.onFingerprintFailed = cb;
    return this;
  };

  AuthenticationHandler.prototype.onRegistrationRequest = function (cb) {
    this.callbacks.onRegistrationRequest = cb;
    return this;
  };

  AuthenticationHandler.prototype.onError = function (cb) {
    this.callbacks.onError = cb;
    return this;
  };

  AuthenticationHandler.prototype.onSuccess = function (cb) {
    this.callbacks.onSuccess = cb;
    return this;
  };

  function authenticate (profileOptions, authenticatorOptions) {
    profileOptions = utils.getOptionsWithDefaults(profileOptions, {}, 'profileId');
    if (!profileOptions.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for user.authenticate");
    }

    const options = [profileOptions];

    if (authenticatorOptions) {
      authenticatorOptions = utils.getOptionsWithDefaults(authenticatorOptions, {}, 'authenticatorType');
      if (!authenticatorOptions.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for user.authenticate");
      }
      options.push(authenticatorOptions);
    }

    return new AuthenticationHandler(options, 'OneginiUserAuthenticationClient', 'authenticate');
  }

  function authenticateImplicitly (options, successCb, failureCb) {
    options = utils.getOptionsWithDefaults(options, {
      scopes: []
    }, 'profileId');

    if (!options || !options.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for user.authenticateImplicitly");
    }

    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'authenticateImplicitly', options, successCb, failureCb);
  }

  function register (options) {
    options = utils.getOptionsWithDefaults(options, {}, 'scopes');
    return new AuthenticationHandler(options, 'OneginiUserRegistrationClient', 'start');
  }

  function changePin () {
    return new AuthenticationHandler(null, 'OneginiChangePinClient', 'start');
  }

  var authenticators = {
    getAll: function (options, successCb, failureCb) {
      if (!options || !options.profileId) {
        throw new TypeError("Onegini: missing 'profileId' argument for authenticators.getAll");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'getAll', options, successCb, failureCb);
    },

    getRegistered: function (options, successCb, failureCb) {
      if (!options || !options.profileId) {
        throw new TypeError("Onegini: missing 'profileId' argument for authenticators.getRegistered");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'getRegistered', options, successCb, failureCb);
    },

    getNotRegistered: function (options, successCb, failureCb) {
      if (!options || !options.profileId) {
        throw new TypeError("Onegini: missing 'profileId' argument for authenticators.getNotRegistered");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'getNotRegistered', options, successCb, failureCb);
    },

    getPreferred: function (successCb, failureCb) {
      return utils.promiseOrCallbackExec("OneginiAuthenticatorsClient", "getPreferred", [], successCb, failureCb);
    },

    setPreferred: function (options, successCb, failureCb) {
      options = utils.getOptionsWithDefaults(options, {}, 'authenticatorType');
      if (!options || !options.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for authenticators.setPreferred");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'setPreferred', options, successCb, failureCb);
    },

    registerNew: function (options) {
      options = utils.getOptionsWithDefaults(options, {}, 'authenticatorType');
      if (!options || !options.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for authenticators.registerNew");
      }

      return new AuthenticationHandler(options, 'OneginiAuthenticatorRegistrationClient', 'start');
    },

    deregister: function (options, successCb, failureCb) {
      if (!options || !options.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for authenticators.deregister");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorRegistrationClient', 'deregister', options, successCb, failureCb);
    }
  };

  function deregister(options, successCb, failureCb) {
    if (!options || !options.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for deregister");
    }
    return utils.promiseOrCallbackExec('OneginiUserDeregistrationClient', 'deregister', options, successCb, failureCb);
  }

  function isUserRegistered(options, successCb, failureCb) {
    if (!options || !options.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for isUserRegistered");
    }
    return utils.promiseOrCallbackExec('OneginiUserRegistrationClient', 'isUserRegistered', options, successCb, failureCb);
  }

  function getUserProfiles(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserRegistrationClient', 'getUserProfiles', [], successCb, failureCb);
  }

  function getAuthenticatedUserProfile(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'getAuthenticatedUserProfile', [], successCb, failureCb);
  }

  function getImplicitlyAuthenticatedUserProfile(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'getImplicitlyAuthenticatedUserProfile', [], successCb, failureCb);
  }

  function logout(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'logout', [], successCb, failureCb);
  }

  function validatePinWithPolicy(options, successCb, failureCb) {
    if (!options || !options.pin) {
      throw new TypeError("Onegini: missing 'pin' argument for validatePinWithPolicy");
    }
    return utils.promiseOrCallbackExec('OneginiUserClient', 'validatePinWithPolicy', options, successCb, failureCb);
  }

  function getIdentityProviders(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiIdentityProvidersClient', 'getIdentityProviders', [], successCb, failureCb);
  }

  return {
    authenticate: authenticate,
    authenticateImplicitly: authenticateImplicitly,
    register: register,
    changePin: changePin,
    authenticators: authenticators,
    deregister: deregister,
    isUserRegistered: isUserRegistered,
    getUserProfiles: getUserProfiles,
    getAuthenticatedUserProfile: getAuthenticatedUserProfile,
    getImplicitlyAuthenticatedUserProfile: getImplicitlyAuthenticatedUserProfile,
    logout: logout,
    validatePinWithPolicy: validatePinWithPolicy,
    getIdentityProviders: getIdentityProviders
  };
})();
<commit_msg>CORDOPLUG-297 implement custom registration<commit_after>/*
 * Copyright (c) 2017 Onegini B.V.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

module.exports = (function () {
  var utils = require('./utils');

  function UserActionHandler(options, client, action) {
    var self = this;
    this.callbacks = {};

    this.callbackActions = {
      providePin: function (options) {
        options = utils.getOptionsWithDefaults(options, {}, 'pin');
        if (!options || !options.pin) {
          throw new TypeError('Onegini: missing "pin" argument for providePin');
        }

        utils.callbackExec(client, 'providePin', options, callSuccessCallback, callErrorCallback);
      },

      fallbackToPin: function () {
        utils.onceExec(client, 'fallbackToPin');
      },

      acceptFingerprint: function (options) {
        options = utils.getOptionsWithDefaults(options, {}, 'iosPrompt');
        options.accept = true;
        utils.callbackExec(client, 'respondToFingerprintRequest', options, callSuccessCallback, callErrorCallback);
      },

      denyFingerprint: function () {
        utils.callbackExec(client, 'respondToFingerprintRequest', {accept: false}, callSuccessCallback, callErrorCallback)
      },

      createPin: function (options) {
        options = utils.getOptionsWithDefaults(options, {}, 'pin');
        if (!options || !options.pin) {
          throw new TypeError('Onegini: missing "pin" argument for createPin');
        }

        utils.callbackExec(client, 'createPin', options, callSuccessCallback, callErrorCallback);
      },

      handleRegistrationUrl: function (options) {
        options = utils.getOptionsWithDefaults(options, {}, 'url');
        utils.callbackExec(client, 'respondToRegistrationRequest', options, callSuccessCallback, callErrorCallback);
      },

      acceptRegistrationInitRequest: function (options) {
        options = utils.getOptionsWithDefaults(options, {accept: true}, 'data');
        utils.callbackExec(client, 'respondToCustomRegistrationInitRequest', options, callSuccessCallback, callErrorCallback);
      },

      denyRegistrationInitRequest: function (options) {
        options = utils.getOptionsWithDefaults(options, {accept: false});
        utils.callbackExec(client, 'respondToCustomRegistrationInitRequest', options, callSuccessCallback, callErrorCallback);
      },

      acceptRegistrationCompleteRequest: function (options) {
        options = utils.getOptionsWithDefaults(options, {accept: true}, 'data');
        utils.callbackExec(client, 'respondToCustomRegistrationCompleteRequest', options, callSuccessCallback, callErrorCallback);
      },

      denyRegistrationCompleteRequest: function () {
        options = utils.getOptionsWithDefaults(options, {accept: false});
        utils.callbackExec(client, 'respondToCustomRegistrationCompleteRequest', options, callSuccessCallback, callErrorCallback);
      },

      cancel: function () {
        utils.callbackExec(client, 'cancelFlow', {}, callSuccessCallback, callErrorCallback);
      }
    };

    function callSuccessCallback(options) {
      var event = options.pluginEvent;
      delete options.pluginEvent;

      if (self.callbacks[event]) {
        self.callbacks[event](self.callbackActions, options);
      }
    }

    function callErrorCallback(err) {
      if (self.callbacks.onError) {
        self.callbacks.onError(err);
      } else {
        console.warn('Onegini: An Error occurred but no error callback was registered');
        console.error('Onegini: ', err);
      }
    }

    utils.callbackExec(client, action, options, callSuccessCallback, callErrorCallback)
  }

  UserActionHandler.prototype.onPinRequest = function (cb) {
    this.callbacks.onPinRequest = cb;
    return this;
  };

  UserActionHandler.prototype.onCreatePinRequest = function (cb) {
    this.callbacks.onCreatePinRequest = cb;
    return this;
  };

  UserActionHandler.prototype.onFingerprintRequest = function (cb) {
    this.callbacks.onFingerprintRequest = cb;
    return this;
  };

  UserActionHandler.prototype.onFingerprintCaptured = function (cb) {
    this.callbacks.onFingerprintCaptured = cb;
    return this;
  };

  UserActionHandler.prototype.onFingerprintFailed = function (cb) {
    this.callbacks.onFingerprintFailed = cb;
    return this;
  };

  UserActionHandler.prototype.onRegistrationRequest = function (cb) {
    this.callbacks.onRegistrationRequest = cb;
    return this;
  };

  UserActionHandler.prototype.onCustomRegistrationInitRequest = function (cb) {
    this.callbacks.onCustomRegistrationInitRequest = cb;
    return this;
  };

  UserActionHandler.prototype.onCustomRegistrationCompleteRequest = function (cb) {
    this.callbacks.onCustomRegistrationCompleteRequest = cb;
    return this;
  };

  UserActionHandler.prototype.onError = function (cb) {
    this.callbacks.onError = cb;
    return this;
  };

  UserActionHandler.prototype.onSuccess = function (cb) {
    this.callbacks.onSuccess = cb;
    return this;
  };

  function authenticate(profileOptions, authenticatorOptions) {
    profileOptions = utils.getOptionsWithDefaults(profileOptions, {}, 'profileId');
    if (!profileOptions.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for user.authenticate");
    }

    const options = [profileOptions];

    if (authenticatorOptions) {
      authenticatorOptions = utils.getOptionsWithDefaults(authenticatorOptions, {}, 'authenticatorType');
      if (!authenticatorOptions.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for user.authenticate");
      }
      options.push(authenticatorOptions);
    }

    return new UserActionHandler(options, 'OneginiUserAuthenticationClient', 'authenticate');
  }

  function authenticateImplicitly(options, successCb, failureCb) {
    options = utils.getOptionsWithDefaults(options, {
      scopes: []
    }, 'profileId');

    if (!options || !options.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for user.authenticateImplicitly");
    }

    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'authenticateImplicitly', options, successCb, failureCb);
  }

  function register(options) {
    options = utils.getOptionsWithDefaults(options, {}, 'scopes');
    return new UserActionHandler(options, 'OneginiUserRegistrationClient', 'start');
  }

  function changePin() {
    return new UserActionHandler(null, 'OneginiChangePinClient', 'start');
  }

  var authenticators = {
    getAll: function (options, successCb, failureCb) {
      if (!options || !options.profileId) {
        throw new TypeError("Onegini: missing 'profileId' argument for authenticators.getAll");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'getAll', options, successCb, failureCb);
    },

    getRegistered: function (options, successCb, failureCb) {
      if (!options || !options.profileId) {
        throw new TypeError("Onegini: missing 'profileId' argument for authenticators.getRegistered");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'getRegistered', options, successCb, failureCb);
    },

    getNotRegistered: function (options, successCb, failureCb) {
      if (!options || !options.profileId) {
        throw new TypeError("Onegini: missing 'profileId' argument for authenticators.getNotRegistered");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'getNotRegistered', options, successCb, failureCb);
    },

    getPreferred: function (successCb, failureCb) {
      return utils.promiseOrCallbackExec("OneginiAuthenticatorsClient", "getPreferred", [], successCb, failureCb);
    },

    setPreferred: function (options, successCb, failureCb) {
      options = utils.getOptionsWithDefaults(options, {}, 'authenticatorType');
      if (!options || !options.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for authenticators.setPreferred");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorsClient', 'setPreferred', options, successCb, failureCb);
    },

    registerNew: function (options) {
      options = utils.getOptionsWithDefaults(options, {}, 'authenticatorType');
      if (!options || !options.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for authenticators.registerNew");
      }

      return new UserActionHandler(options, 'OneginiAuthenticatorRegistrationClient', 'start');
    },

    deregister: function (options, successCb, failureCb) {
      if (!options || !options.authenticatorType) {
        throw new TypeError("Onegini: missing 'authenticatorType' argument for authenticators.deregister");
      }
      return utils.promiseOrCallbackExec('OneginiAuthenticatorRegistrationClient', 'deregister', options, successCb, failureCb);
    }
  };

  function deregister(options, successCb, failureCb) {
    if (!options || !options.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for deregister");
    }
    return utils.promiseOrCallbackExec('OneginiUserDeregistrationClient', 'deregister', options, successCb, failureCb);
  }

  function isUserRegistered(options, successCb, failureCb) {
    if (!options || !options.profileId) {
      throw new TypeError("Onegini: missing 'profileId' argument for isUserRegistered");
    }
    return utils.promiseOrCallbackExec('OneginiUserRegistrationClient', 'isUserRegistered', options, successCb, failureCb);
  }

  function getUserProfiles(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserRegistrationClient', 'getUserProfiles', [], successCb, failureCb);
  }

  function getAuthenticatedUserProfile(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'getAuthenticatedUserProfile', [], successCb, failureCb);
  }

  function getImplicitlyAuthenticatedUserProfile(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'getImplicitlyAuthenticatedUserProfile', [], successCb, failureCb);
  }

  function logout(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiUserAuthenticationClient', 'logout', [], successCb, failureCb);
  }

  function validatePinWithPolicy(options, successCb, failureCb) {
    if (!options || !options.pin) {
      throw new TypeError("Onegini: missing 'pin' argument for validatePinWithPolicy");
    }
    return utils.promiseOrCallbackExec('OneginiUserClient', 'validatePinWithPolicy', options, successCb, failureCb);
  }

  function getIdentityProviders(successCb, failureCb) {
    return utils.promiseOrCallbackExec('OneginiIdentityProvidersClient', 'getIdentityProviders', [], successCb, failureCb);
  }

  return {
    authenticate: authenticate,
    authenticateImplicitly: authenticateImplicitly,
    register: register,
    changePin: changePin,
    authenticators: authenticators,
    deregister: deregister,
    isUserRegistered: isUserRegistered,
    getUserProfiles: getUserProfiles,
    getAuthenticatedUserProfile: getAuthenticatedUserProfile,
    getImplicitlyAuthenticatedUserProfile: getImplicitlyAuthenticatedUserProfile,
    logout: logout,
    validatePinWithPolicy: validatePinWithPolicy,
    getIdentityProviders: getIdentityProviders
  };
})();
<|endoftext|>


<commit_before>var RedisDocumentStore = require('../lib/redis_document_store');

describe('redis_document_store', function() {

  describe('set', function() {

    it('should be able to set a key and have an expiration set', function() {
      var store = new RedisDocumentStore({ expire: 10 });
      runs(function() {
        var _this = this;
        store.set('hello1', 'world', function(worked) {
          _this.result = worked;
        });
      });
      waitsFor(function() {
        return typeof(this.result) === 'boolean';
      });
      runs(function() {
        var _this = this;
        RedisDocumentStore.client.ttl('hello1', function(err, res) {
          expect(res).toBeGreaterThan(1);
          _this.done = true;
        });
      });
      waitsFor(function() {
        return this.done;
      });
    });

    it('should not set an expiration when told not to', function() {
      var store = new RedisDocumentStore({ expire: 10 });
      runs(function() {
        var _this = this;
        store.set('hello2', 'world', function(worked) {
          _this.result = worked;
        }, true);
      });
      waitsFor(function() {
        return typeof(this.result) === 'boolean';
      });
      runs(function() {
        var _this = this;
        RedisDocumentStore.client.ttl('hello2', function(err, res) {
          expect(res).toBe(-1);
          _this.done = true;
        });
      });
      waitsFor(function() {
        return this.done;
      });
    });

    it('should not set an expiration when expiration is off', function() {
      var store = new RedisDocumentStore({ expire: false });
      runs(function() {
        var _this = this;
        store.set('hello3', 'world', function(worked) {
          _this.result = worked;
        });
      });
      waitsFor(function() {
        return typeof(this.result) === 'boolean';
      });
      runs(function() {
        var _this = this;
        RedisDocumentStore.client.ttl('hello3', function(err, res) {
          expect(res).toBe(-1);
          _this.done = true;
        });
      });
      waitsFor(function() {
        return this.done;
      });
    });

  });

});
<commit_msg>Clean up redis test to exit properly<commit_after>var RedisDocumentStore = require('../lib/redis_document_store');

var winston = require('winston');
winston.remove(winston.transports.Console);

describe('redis_document_store', function() {

  /* reconnect to redis on each test */
  afterEach(function() {
    if (RedisDocumentStore.client) {
      RedisDocumentStore.client.quit();
      RedisDocumentStore.client = false;
    }
  });

  describe('set', function() {

    it('should be able to set a key and have an expiration set', function() {
      var store = new RedisDocumentStore({ expire: 10 });
      runs(function() {
        var _this = this;
        store.set('hello1', 'world', function(worked) {
          _this.result = worked;
        });
      });
      waitsFor(function() {
        return typeof(this.result) === 'boolean';
      });
      runs(function() {
        var _this = this;
        RedisDocumentStore.client.ttl('hello1', function(err, res) {
          expect(res).toBeGreaterThan(1);
          _this.done = true;
        });
      });
      waitsFor(function() {
        return this.done;
      });
    });

    it('should not set an expiration when told not to', function() {
      var store = new RedisDocumentStore({ expire: 10 });
      runs(function() {
        var _this = this;
        store.set('hello2', 'world', function(worked) {
          _this.result = worked;
        }, true);
      });
      waitsFor(function() {
        return typeof(this.result) === 'boolean';
      });
      runs(function() {
        var _this = this;
        RedisDocumentStore.client.ttl('hello2', function(err, res) {
          expect(res).toBe(-1);
          _this.done = true;
        });
      });
      waitsFor(function() {
        return this.done;
      });
    });

    it('should not set an expiration when expiration is off', function() {
      var store = new RedisDocumentStore({ expire: false });
      runs(function() {
        var _this = this;
        store.set('hello3', 'world', function(worked) {
          _this.result = worked;
        });
      });
      waitsFor(function() {
        return typeof(this.result) === 'boolean';
      });
      runs(function() {
        var _this = this;
        RedisDocumentStore.client.ttl('hello3', function(err, res) {
          expect(res).toBe(-1);
          _this.done = true;
        });
      });
      waitsFor(function() {
        return this.done;
      });
    });

  });

});
<|endoftext|>