<commit_before>"use strict";

var angular = require("angular");
var angularSanitize = require("angular-sanitize");
var jQuery = require("jquery");
window.$ = window.jQuery = jQuery;
require("bootstrap/dist/js/bootstrap.js");
require("bootstrap/dist/css/bootstrap.css");
require("./yeoman-ui.css");

var io = window.io;

angular
  .module('app', [
    'ngSanitize',
    'yoUI'
  ]);

angular
  .module('yoUI', ['ngSanitize'])
  .factory('socket', function () {
    return io();
  })
  .directive('yoAutofocus', yoAutofocus)
  .controller('YoController', YoController);

function yoAutofocus() {
  return {
    restrict: 'A',
    link: function ($scope, $element) {
      setTimeout(function () {
        $element[0].focus();
      }, 0);
    }
  };
}

function yoNormalizePrompt(prompt) {
  // Default type is input
  if (!prompt.type) {
    prompt.type = 'input';
  }

  // Confirm prompt could be dropdown ?
  if (prompt.type === 'confirm') {
    prompt.choices = [{
      value: true,
      name: 'Yes'
    }, {
      value: false,
      name: 'No'
    }];
  }

  // Index is useful
  if (prompt.choices && prompt.choices.length) {
    if (typeof prompt.choices[0] === 'string') {
      prompt.choices = prompt.choices.map(function (choice, index) {
        return {
          key: choice.substr(0, 1),
          value: prompt.type === 'list' ? choice : index,
          name: choice
        };
      });
    }

    prompt.choices.forEach(function (choice, index) {
      choice.index = index;
    });
  }

  if (!prompt.default && prompt.type === 'expand') {
    prompt.default = 0;
  }

  prompt.value = prompt.default;

  return prompt;
}

function yoNormalizeAnswer(prompt) {
  if (prompt.type === 'checkbox') {
    prompt.value = [];
    prompt.choices.forEach(function (choice) {
      if (choice.checked) {
        prompt.value.push(choice.value);
      }
    });
  } else if (prompt.type === 'password') {
    var encodedPassword = "";
    for (var i = 0; i < prompt.value.length; i++) {
      encodedPassword += "*";
    }
    return encodedPassword;
  }

  // console.log('prompt.value: ', prompt.value);

  return prompt.value;
}

function YoController($scope, $sce, socket) {
  var self = this;

  self.generator = null;
  self.subgenerator = null;
  self.updateGenerator = _updateGenerator;
  self.run = _run;
  self.submit = _submit;
  self.reset = _reset;
  self.scopeApply = _scopeApply;
  self.isWaiting = _isWaiting;

  self.reset();

  socket.on('yo:list', function (generators) {
    self.generators = generators;
    self.scopeApply();
  });

  socket.emit('yo:list');

  socket.on('yo:prompt', function (prompt) {
    self.prompts.filter(function (prompt) {
      prompt.isDisabled = true;
    });
    prompt.isDisabled = false;
    self.activePromptIndex = self.prompts.length;
    self.prompts.push(yoNormalizePrompt(prompt));

    self.scopeApply();
    appendLog("\n? " + prompt.message);
  });

  socket.on('yo:diff', function (diffs) {
    self.diffs = diffs;
    self.scopeApply();
  });

  socket.on('yo:log', appendLog);
  function appendLog(logs) {
    var element = document.getElementById("logs");
    var oldLog = element.innerHTML;
    element.innerHTML = (oldLog ? oldLog : "") + "\n" + logs;
    element.scrollTop = element.scrollHeight;
    self.logs = $sce.trustAsHtml(logs);
    self.scopeApply("\n> " + prompt.message);
  }

  socket.on('yo:prompt:error', function (msg) {
    alert(msg);
    self.scopeApply();
  });

  socket.on('yo:end', function (data) {
    if (data.distId && data.distName) {
      window.location.href = '/dist/' + data.distId + '/' + data.distName;
    } else {
      alert('Sorry, an error has occured :(');
    }

    self.generator = null;
    self.subgenerator = null;
    self.reset();
    self.scopeApply();
  });

  function _updateGenerator() {
    self.reset();

    if (self.subgenerator && self.generator.subgenerators.indexOf(self.subgenerator) < 0) {
      self.subgenerator = null;
    }

    if (self.subgenerator) {
      return self.run(self.subgenerator.namespace);
    }

    if (self.generator && self.generator.subgenerators.length <= 1) {
      return self.run(self.generator.namespace);
    }
  }

  function _run(namespace) {
    socket.emit('yo:run', {
      namespace: namespace
    });
  }

  function _submit() {
    self.prompts[self.activePromptIndex].isDisabled = true;
    socket.emit('yo:prompt', {
      question: self.prompts[self.activePromptIndex],
      answer: yoNormalizeAnswer(self.prompts[self.activePromptIndex])
    });

    appendLog("    " + yoNormalizeAnswer(self.prompts[self.activePromptIndex]) + " ");
  }

  function _reset() {
    self.prompts = [];
    self.activePromptIndex = -1;
    self.diffs = [];
    self.logs = [];
  }

  function _scopeApply() {
    if (!$scope.$$phase) {
      $scope.$apply();
    }
  }

  function _isWaiting() {
    return self.prompts.filter(function (p1) {
        return !p1.isDisabled;
      }).length <= 0;
  }
}
<commit_msg>Changed the ui of list answers in command line displayer<commit_after>"use strict";

var angular = require("angular");
var angularSanitize = require("angular-sanitize");
var jQuery = require("jquery");
window.$ = window.jQuery = jQuery;
require("bootstrap/dist/js/bootstrap.js");
require("bootstrap/dist/css/bootstrap.css");
require("./yeoman-ui.css");

var io = window.io;

angular
  .module('app', [
    'ngSanitize',
    'yoUI'
  ]);

angular
  .module('yoUI', ['ngSanitize'])
  .factory('socket', function () {
    return io();
  })
  .directive('yoAutofocus', yoAutofocus)
  .controller('YoController', YoController);

function yoAutofocus() {
  return {
    restrict: 'A',
    link: function ($scope, $element) {
      setTimeout(function () {
        $element[0].focus();
      }, 0);
    }
  };
}

function yoNormalizePrompt(prompt) {
  // Default type is input
  if (!prompt.type) {
    prompt.type = 'input';
  }

  // Confirm prompt could be dropdown ?
  if (prompt.type === 'confirm') {
    prompt.choices = [{
      value: true,
      name: 'Yes'
    }, {
      value: false,
      name: 'No'
    }];
  }

  // Index is useful
  if (prompt.choices && prompt.choices.length) {
    if (typeof prompt.choices[0] === 'string') {
      prompt.choices = prompt.choices.map(function (choice, index) {
        return {
          key: choice.substr(0, 1),
          value: prompt.type === 'list' ? choice : index,
          name: choice
        };
      });
    }

    prompt.choices.forEach(function (choice, index) {
      choice.index = index;
    });
  }

  if (!prompt.default && prompt.type === 'expand') {
    prompt.default = 0;
  }

  prompt.value = prompt.default;

  return prompt;
}

function yoNormalizeAnswer(prompt) {
  if (prompt.type === 'checkbox') {
    prompt.value = [];
    prompt.choices.forEach(function (choice) {
      if (choice.checked) {
        prompt.value.push(choice.value);
      }
    });
  } else if (prompt.type === 'password') {
    var encodedPassword = "";
    for (var i = 0; i < prompt.value.length; i++) {
      encodedPassword += "*";
    }
    return encodedPassword;
  }

  // console.log('prompt.value: ', prompt.value);

  return prompt.value;
}

function YoController($scope, $sce, socket) {
  var self = this;

  self.generator = null;
  self.subgenerator = null;
  self.updateGenerator = _updateGenerator;
  self.run = _run;
  self.submit = _submit;
  self.reset = _reset;
  self.scopeApply = _scopeApply;
  self.isWaiting = _isWaiting;

  self.reset();

  socket.on('yo:list', function (generators) {
    self.generators = generators;
    self.scopeApply();
  });

  socket.emit('yo:list');

  socket.on('yo:prompt', function (prompt) {
    self.prompts.filter(function (prompt) {
      prompt.isDisabled = true;
    });
    prompt.isDisabled = false;
    self.activePromptIndex = self.prompts.length;
    self.prompts.push(yoNormalizePrompt(prompt));

    self.scopeApply();
    appendLog("\n? " + prompt.message);
  });

  socket.on('yo:diff', function (diffs) {
    self.diffs = diffs;
    self.scopeApply();
  });

  socket.on('yo:log', appendLog);
  function appendLog(logs) {
    var element = document.getElementById("logs");
    var oldLog = element.innerHTML;
    element.innerHTML = (oldLog ? oldLog : "") + "\n" + logs;
    element.scrollTop = element.scrollHeight;
    self.logs = $sce.trustAsHtml(logs);
    self.scopeApply("\n> " + prompt.message);
  }

  socket.on('yo:prompt:error', function (msg) {
    alert(msg);
    self.scopeApply();
  });

  socket.on('yo:end', function (data) {
    if (data.distId && data.distName) {
      window.location.href = '/dist/' + data.distId + '/' + data.distName;
    } else {
      alert('Sorry, an error has occured :(');
    }

    self.generator = null;
    self.subgenerator = null;
    self.reset();
    self.scopeApply();
  });

  function _updateGenerator() {
    self.reset();

    if (self.subgenerator && self.generator.subgenerators.indexOf(self.subgenerator) < 0) {
      self.subgenerator = null;
    }

    if (self.subgenerator) {
      return self.run(self.subgenerator.namespace);
    }

    if (self.generator && self.generator.subgenerators.length <= 1) {
      return self.run(self.generator.namespace);
    }
  }

  function _run(namespace) {
    socket.emit('yo:run', {
      namespace: namespace
    });
  }

  function _submit() {
    self.prompts[self.activePromptIndex].isDisabled = true;
    var answer = yoNormalizeAnswer(self.prompts[self.activePromptIndex]);
    socket.emit('yo:prompt', {
      question: self.prompts[self.activePromptIndex],
      answer: answer
    });

    if (answer && typeof answer === "object" && answer.length) {
      for (var i = 0; i < answer.length; i++) {
        appendLog("    " + answer[i] + "");
      }
    } else {
      appendLog("    " + answer + "");
    }
  }

  function _reset() {
    self.prompts = [];
    self.activePromptIndex = -1;
    self.diffs = [];
    self.logs = [];
  }

  function _scopeApply() {
    if (!$scope.$$phase) {
      $scope.$apply();
    }
  }

  function _isWaiting() {
    return self.prompts.filter(function (p1) {
        return !p1.isDisabled;
      }).length <= 0;
  }
}
<|endoftext|>


<commit_before>//{{{ URL PARAMETER CONTROL

function add_parameters(url, parameters){
 var string;

 if ( typeof(parameters) == 'string' || typeof(parameters) == 'String'){
  string = parameters;
 }else{
  var pairs = [];
  for (parameter in parameters){
   pairs.push(parameter + "=" + parameters[parameter]);
  }
  string = pairs.join("&");
 }

 if (string.length == 0){return(url)}

 if (url.indexOf('?') == -1){
  return url + '?' + string;
 }else{
  return url + '&' + string;
 }
}

function add_parameter(url, parameter, value){
 var url = remove_section_hash(url)
 url = remove_parameter(url, parameter)
 url = add_parameters(url, parameter + "=" + value)
 return url;
}

function remove_section_hash(url){
 if (url.match("#")){
   return url.replace(/#.*/,'')
 }else{
   return url
 }
}

function remove_parameter(url, parameter){
 var url = remove_section_hash(url)

 if (url.match("&" + parameter + "=")){
  return url.replace("&" + parameter + "=", '&REMOVE=').replace(/REMOVE=[^&]+/, '').replace(/\?&/, '?').replace(/&&/, '&').replace(/[?&]$/, '');
 }else{
  return url.replace("?" + parameter + "=", '?REMOVE=').replace(/REMOVE=[^&]+/, '').replace(/\?&/, '?').replace(/&&/, '&').replace(/[?&]$/, '');
 }
}

function clean_element(elem){
 return elem.replace(/\//g, '-..-').replace(/%/g,'o-o').replace(/\[/g,'(.-(').replace(/\]/g,').-)')
}

function restore_element(elem){
 return unescape(elem.replace(/-\.\.-/g, '/').replace(/o-o/g,'%')).replace(/\(\.-\(/g,'[').replace(/\)\.-\)/g,']');
}

function parse_parameters(params){
 var ret = {},
 seg = params.replace(/^\?/,'').split('&'),
 len = seg.length, i = 0, s;
 for (;i<len;i++) {
  if (!seg[i]) { continue; }
  s = seg[i].split('=');
  ret[s[0]] = restore_element(s[1]);
 }
 return ret
}

var required_js = [];
function require_js(url, success, script){
 if (typeof url == 'object'){
   if (url.length > 1){
    var u = url.shift()
    require_js(u, function(){
     require_js(url, success);
    })
    return true
   }else{
    return require_js(url.shift(), success);
   }
 }else{
  var async = true;
  if (typeof production == 'undefined') production = false
  var cache = production;

  if (undefined === success){
   async = false;
  }else{
   async = true;
  }

  url = url.replace(/^\/js\//, '/js-find/')

  if ($.inArray(url, required_js) >= 0){
    if (typeof success == 'function'){ success.call(script) }
  }else{
    var _success = function(script_text){ required_js.push(url); console.log("Required and loaded JS: " + url); if (typeof success == 'function'){ success(script) }; }
    if (typeof rbbt.proxy != 'undefined')
      url = rbbt.proxy + url
    $.ajax({url: url, cache:cache, dataType:'script', async: async, success: _success} ).fail(function(jqxhr, settings, exception){ console.log('Failed to load ' + url + ': ' + exception)});
  }
 }
}

function remove_from_array(array, elem){
 return jQuery.grep(array, function(value) {
  return value != elem;
 });
}

function merge_hash(destination, source){
  for (var property in source) {
    if (source.hasOwnProperty(property)) {
      destination[property] = source[property];
    }
  }
  return destination;
}

function clean_hash(h){
  var clean = {}

  forHash(h, function(k,v){
    if (undefined !== v) clean[k] = v
  })

  return clean
}

function array_values(hash){
  var tmp_arr = [], key = '';
  for (key in hash) {
    tmp_arr[tmp_arr.length] = hash[key];
  }

  return tmp_arr;
}

function clean_attr(text){
  return encodeURIComponent(text)
}

function uniq(ary) {
  var seen = {};
  return ary.filter(function(elem) {
    var k = elem;
    return (seen[k] === 1) ? 0 : seen[k] = 1;
  })
}
function uniqBy(ary, key) {
  var seen = {};
  return ary.filter(function(elem) {
    var k = key(elem);
    return (seen[k] === 1) ? 0 : seen[k] = 1;
  })
}

function unique(arrayName) {
  var newArray=new Array();
  label:for(var i=0; i<arrayName.length;i++ ){
    for(var j=0; j<newArray.length;j++ ){
      if(newArray[j]==arrayName[i])
        continue label;
    }
    newArray[newArray.length] = arrayName[i];
  }
  return newArray;
}

function forHash(obj, fn, thisObj){
  var key, i = 0;
  function exec(fn, obj, key, thisObj){
    return fn.call(thisObj, key, obj[key], obj);
  }
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (exec(fn, obj, key, thisObj) === false) {
        break;
      }
    }
  }
  return forHash;
}

function forArray(obj, fn, thisObj){
  var key, i = 0;
  function exec(fn, obj, prop, thisObj){
    return fn.call(thisObj, obj[prop], obj);
  }
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      if (exec(fn, obj, prop, thisObj) === false) {
        break;
      }
    }
  }
  return forArray;
}

function mapArray(obj, fn, thisObj){
  var result = [];
  forArray(obj, function(e){
    result.push(fn.call(thisObj,e))
  },thisObj)
  return result;
}
function contains(a, obj) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}

function return_same(obj){ return obj }

function pvalue_score(pvalue){ if (undefined === pvalue || null == pvalue || pvalue == ""){ return pvalue }; if (pvalue < 0){ return 10 * Math.log10(-pvalue)}else{ return -10 * Math.log10(pvalue) }}

function get_gradient(values, color1, color2){
  var Color = net.brehaut.Color;
  var color1 = Color(color1)
  var color2 = Color(color2)
  var steps = values.length
  var clean_values = []
  forArray(values,function(v){
    if (typeof v == 'string') v = parseFloat(v)
    if (typeof v == 'number' && ! isNaN(v)) clean_values.push(v)
  })
  var max = Math.max.apply(null,clean_values)
  var min = Math.min.apply(null,clean_values)
  var diff = max - min
  var colors = []
  forArray(values, function(value){
    if (typeof value == 'string') value = parseFloat(value)
    if (typeof value == 'number'){
      var a
      if (diff != 0)
        a = (value - min)/diff
      else
        a = 1
      colors.push(color1.blend(color2, a).toString())
    }else{
      colors.push(undefined)
    }
  })
  return colors
}

function get_sign_gradient(values, color1, color0, color2){
  var Color = net.brehaut.Color;
  var color1 = Color(color1)
  var color0 = Color(color0)
  var color2 = Color(color2)
  var steps = values.length
  var clean_values = []
  forArray(values,function(v){
    if (typeof v == 'string') v = parseFloat(v)
    if (typeof v == 'number' && ! isNaN(v)) clean_values.push(v)
  })
  var max = Math.max.apply(null,clean_values)
  var min = Math.min.apply(null,clean_values)
  var colors = []
  forArray(values, function(value){
    if (typeof value == 'string') value = parseFloat(value)
    if (typeof value == 'number'){
      if (value >= 0){
        var a = value/max
        colors.push(color0.blend(color2, a).toString())
      }else{
        var a = value/min
        colors.push(color0.blend(color1, a).toString())
      }
    }else{
      colors.push(undefined)
    }
  })
  return colors
}

// from http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
function intersect_sorted(a, b)
{
  var ai=0, bi=0;
  var result = new Array();

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}

function intersect(array1, array2){
  return array1.filter(function(n) {
      return array2.indexOf(n) != -1
  });
}

function clean_array_properties(array){
  var n = {}

  for(var i = 0; i < array.length; i += 1){
    n[i.toString()] = array[i]
  }

  return(n)
}

function save_file(data, file, type){
  var blob = new Blob([data], {type: type});
  saveAs(blob, file);
}

function save_binary(data, file, type){
  var bytes = new Uint8Array(data.length);

  for (var i=0; i<data.length; i++) {
    bytes[i] = data.charCodeAt(i);
  }

  save_file(bytes, file, type)
}

function save_base64(data, file, type){
  data = atob(data)

  save_binary(data, file, type);
}

function is_array(obj){
  return obj.constructor === Array;
}
<commit_msg>Use script name in require_js<commit_after>//{{{ URL PARAMETER CONTROL

function add_parameters(url, parameters){
 var string;

 if ( typeof(parameters) == 'string' || typeof(parameters) == 'String'){
  string = parameters;
 }else{
  var pairs = [];
  for (parameter in parameters){
   pairs.push(parameter + "=" + parameters[parameter]);
  }
  string = pairs.join("&");
 }

 if (string.length == 0){return(url)}

 if (url.indexOf('?') == -1){
  return url + '?' + string;
 }else{
  return url + '&' + string;
 }
}

function add_parameter(url, parameter, value){
 var url = remove_section_hash(url)
 url = remove_parameter(url, parameter)
 url = add_parameters(url, parameter + "=" + value)
 return url;
}

function remove_section_hash(url){
 if (url.match("#")){
   return url.replace(/#.*/,'')
 }else{
   return url
 }
}

function remove_parameter(url, parameter){
 var url = remove_section_hash(url)

 if (url.match("&" + parameter + "=")){
  return url.replace("&" + parameter + "=", '&REMOVE=').replace(/REMOVE=[^&]+/, '').replace(/\?&/, '?').replace(/&&/, '&').replace(/[?&]$/, '');
 }else{
  return url.replace("?" + parameter + "=", '?REMOVE=').replace(/REMOVE=[^&]+/, '').replace(/\?&/, '?').replace(/&&/, '&').replace(/[?&]$/, '');
 }
}

function clean_element(elem){
 return elem.replace(/\//g, '-..-').replace(/%/g,'o-o').replace(/\[/g,'(.-(').replace(/\]/g,').-)')
}

function restore_element(elem){
 return unescape(elem.replace(/-\.\.-/g, '/').replace(/o-o/g,'%')).replace(/\(\.-\(/g,'[').replace(/\)\.-\)/g,']');
}

function parse_parameters(params){
 var ret = {},
 seg = params.replace(/^\?/,'').split('&'),
 len = seg.length, i = 0, s;
 for (;i<len;i++) {
  if (!seg[i]) { continue; }
  s = seg[i].split('=');
  ret[s[0]] = restore_element(s[1]);
 }
 return ret
}

var required_js = [];
function require_js(url, success, script){
 if (typeof url == 'object'){
   if (url.length > 1){
    var u = url.shift()
    require_js(u, function(){
     require_js(url, success);
    })
    return true
   }else{
    return require_js(url.shift(), success);
   }
 }else{
  var async = true;
  if (typeof production == 'undefined') production = false
  var cache = production;

  if (undefined === success){
   async = false;
  }else{
   async = true;
  }

  url = url.replace(/^\/js\//, '/js-find/')

  if ($.inArray(url, required_js) >= 0){
    if (typeof success == 'function'){ success.call(script) }
  }else{
    var _success = function(script_text){ required_js.push(url); console.log("Required and loaded JS: " + url); if (typeof success == 'function'){ success(script) }; }
    if (typeof rbbt.proxy != 'undefined')
      url = rbbt.proxy + url
    url = rbbt.url_add_script_name(url)
    $.ajax({url: url, cache:cache, dataType:'script', async: async, success: _success} ).fail(function(jqxhr, settings, exception){ console.log('Failed to load ' + url + ': ' + exception)});
  }
 }
}

function remove_from_array(array, elem){
 return jQuery.grep(array, function(value) {
  return value != elem;
 });
}

function merge_hash(destination, source){
  for (var property in source) {
    if (source.hasOwnProperty(property)) {
      destination[property] = source[property];
    }
  }
  return destination;
}

function clean_hash(h){
  var clean = {}

  forHash(h, function(k,v){
    if (undefined !== v) clean[k] = v
  })

  return clean
}

function array_values(hash){
  var tmp_arr = [], key = '';
  for (key in hash) {
    tmp_arr[tmp_arr.length] = hash[key];
  }

  return tmp_arr;
}

function clean_attr(text){
  return encodeURIComponent(text)
}

function uniq(ary) {
  var seen = {};
  return ary.filter(function(elem) {
    var k = elem;
    return (seen[k] === 1) ? 0 : seen[k] = 1;
  })
}
function uniqBy(ary, key) {
  var seen = {};
  return ary.filter(function(elem) {
    var k = key(elem);
    return (seen[k] === 1) ? 0 : seen[k] = 1;
  })
}

function unique(arrayName) {
  var newArray=new Array();
  label:for(var i=0; i<arrayName.length;i++ ){
    for(var j=0; j<newArray.length;j++ ){
      if(newArray[j]==arrayName[i])
        continue label;
    }
    newArray[newArray.length] = arrayName[i];
  }
  return newArray;
}

function forHash(obj, fn, thisObj){
  var key, i = 0;
  function exec(fn, obj, key, thisObj){
    return fn.call(thisObj, key, obj[key], obj);
  }
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (exec(fn, obj, key, thisObj) === false) {
        break;
      }
    }
  }
  return forHash;
}

function forArray(obj, fn, thisObj){
  var key, i = 0;
  function exec(fn, obj, prop, thisObj){
    return fn.call(thisObj, obj[prop], obj);
  }
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      if (exec(fn, obj, prop, thisObj) === false) {
        break;
      }
    }
  }
  return forArray;
}

function mapArray(obj, fn, thisObj){
  var result = [];
  forArray(obj, function(e){
    result.push(fn.call(thisObj,e))
  },thisObj)
  return result;
}
function contains(a, obj) {
  for (var i = 0; i < a.length; i++) {
    if (a[i] === obj) {
      return true;
    }
  }
  return false;
}

function return_same(obj){ return obj }

function pvalue_score(pvalue){ if (undefined === pvalue || null == pvalue || pvalue == ""){ return pvalue }; if (pvalue < 0){ return 10 * Math.log10(-pvalue)}else{ return -10 * Math.log10(pvalue) }}

function get_gradient(values, color1, color2){
  var Color = net.brehaut.Color;
  var color1 = Color(color1)
  var color2 = Color(color2)
  var steps = values.length
  var clean_values = []
  forArray(values,function(v){
    if (typeof v == 'string') v = parseFloat(v)
    if (typeof v == 'number' && ! isNaN(v)) clean_values.push(v)
  })
  var max = Math.max.apply(null,clean_values)
  var min = Math.min.apply(null,clean_values)
  var diff = max - min
  var colors = []
  forArray(values, function(value){
    if (typeof value == 'string') value = parseFloat(value)
    if (typeof value == 'number'){
      var a
      if (diff != 0)
        a = (value - min)/diff
      else
        a = 1
      colors.push(color1.blend(color2, a).toString())
    }else{
      colors.push(undefined)
    }
  })
  return colors
}

function get_sign_gradient(values, color1, color0, color2){
  var Color = net.brehaut.Color;
  var color1 = Color(color1)
  var color0 = Color(color0)
  var color2 = Color(color2)
  var steps = values.length
  var clean_values = []
  forArray(values,function(v){
    if (typeof v == 'string') v = parseFloat(v)
    if (typeof v == 'number' && ! isNaN(v)) clean_values.push(v)
  })
  var max = Math.max.apply(null,clean_values)
  var min = Math.min.apply(null,clean_values)
  var colors = []
  forArray(values, function(value){
    if (typeof value == 'string') value = parseFloat(value)
    if (typeof value == 'number'){
      if (value >= 0){
        var a = value/max
        colors.push(color0.blend(color2, a).toString())
      }else{
        var a = value/min
        colors.push(color0.blend(color1, a).toString())
      }
    }else{
      colors.push(undefined)
    }
  })
  return colors
}

// from http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript
function intersect_sorted(a, b)
{
  var ai=0, bi=0;
  var result = new Array();

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}

function intersect(array1, array2){
  return array1.filter(function(n) {
      return array2.indexOf(n) != -1
  });
}

function clean_array_properties(array){
  var n = {}

  for(var i = 0; i < array.length; i += 1){
    n[i.toString()] = array[i]
  }

  return(n)
}

function save_file(data, file, type){
  var blob = new Blob([data], {type: type});
  saveAs(blob, file);
}

function save_binary(data, file, type){
  var bytes = new Uint8Array(data.length);

  for (var i=0; i<data.length; i++) {
    bytes[i] = data.charCodeAt(i);
  }

  save_file(bytes, file, type)
}

function save_base64(data, file, type){
  data = atob(data)

  save_binary(data, file, type);
}

function is_array(obj){
  return obj.constructor === Array;
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    plug = require('gulp-load-plugins')(),
    pkg = require('./package.json'),
    del = require('del'),
    merge = require('merge-stream');

function plumber() {
  return plug.plumber({ errorHandler: function (err) {
    plug.util.beep();
    plug.util.log(plug.util.colors.red(err.toString()));
  } });
}

/*
  library CSS
 */
gulp.task('css:lib', ['fonts'], function() {
  return gulp.src([
      './app/css/bootstrap.less',
      './bower_components/angular/angular-csp.css',
      './bower_components/angular-loading-bar/build/loading-bar.min.css',
      './bower_components/angular-motion/dist/angular-motion.min.css',
      './bower_components/font-awesome/css/font-awesome.min.css'
    ])
    .pipe(plumber())
    .pipe(plug.if('*.less', plug.less()))
    .pipe(plug.concat('lib.css'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  fonts
 */
gulp.task('fonts', function() {
  return gulp.src([
      // './bower_components/bootstrap/dist/fonts/*',
      './bower_components/font-awesome/fonts/*'
    ])
    .pipe(gulp.dest('./dist/fonts'));
});

/*
  application CSS
 */
gulp.task('css:app', function() {
  return gulp.src([
      './app/js/directives/**/*.{less,css}',
      './app/css/themes/*.less',
      './app/css/common.less',
      './app/css/states.less'
    ])
    .pipe(plumber())
    .pipe(plug.if('*.less', plug.less()))
    .pipe(plug.concat('app.css'))
    .pipe(plug.autoprefixer(["> 1%"], {cascade:true}))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  library javascript
 */
gulp.task('js:lib', function() {
  return gulp.src([
      // './bower_components/es5-shim/es5-shim.js',

      './bower_components/angular/angular.js',

      './bower_components/angular-sanitize/angular-sanitize.js',
      './bower_components/angular-animate/angular-animate.js',
      './bower_components/angular-resource/angular-resource.js',

      './bower_components/angular-ui-router/release/angular-ui-router.js',

      './bower_components/angular-strap/dist/modules/dimensions.js',
      './bower_components/angular-strap/dist/modules/button.js',
      './bower_components/angular-strap/dist/modules/tab.js',
      './bower_components/angular-strap/dist/modules/tab.tpl.js',
      './bower_components/angular-strap/dist/modules/tooltip.js',
      './bower_components/angular-strap/dist/modules/tooltip.tpl.js',
      './bower_components/angular-strap/dist/modules/dropdown.js',
      './bower_components/angular-strap/dist/modules/dropdown.tpl.js',
      './bower_components/angular-strap/dist/modules/modal.js',
      './bower_components/angular-strap/dist/modules/modal.tpl.js',
      './bower_components/angular-strap/dist/modules/alert.js',
      './bower_components/angular-strap/dist/modules/alert.tpl.js',
      './bower_components/angular-strap/dist/modules/popover.js',
      './bower_components/angular-strap/dist/modules/popover.tpl.js',
      './bower_components/angular-strap/dist/modules/collapse.js',

      './bower_components/moment/moment.js',
      './bower_components/angular-moment/angular-moment.js',

      './bower_components/ngstorage/ngStorage.js',
      './bower_components/angular-loading-bar/build/loading-bar.js'

    ])
    .pipe(plug.concat('lib.js'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  application javascript
 */
gulp.task('js:app', function() {
  var PKG = JSON.stringify({
    name: pkg.name,
    v: pkg.version
  });
  return gulp.src([
      './app/**/*.js',
      '!./app/**/*-test.js'
    ])
    .pipe(plumber())
    .pipe(plug.ngAnnotate())
    .pipe(plug.wrapper({
       header: '\n(function (PKG){ /* ${filename} */\n',
       footer: '\n})('+PKG+');\n'
    }))
    .pipe(plug.concat('app.js'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  images
  TODO: imgmin?
 */
gulp.task('img', function() {
  return gulp.src('./app/img/**/*')
    .pipe(gulp.dest('./dist/img'));
});

/*
  template cache
 */
gulp.task('tpl', function() {
  return merge(

    gulp.src([
      './app/js/directives/**/*.html'
    ])
      .pipe(plug.angularTemplatecache({
        module: pkg.name + '.directives'
      })),

    gulp.src([
      './app/partials/home.html'
    ])
      .pipe(plug.angularTemplatecache({
        module: pkg.name,
        base: __dirname + '/app',
        root: '/'
      }))

  )
    .pipe(plug.concat('tpl.js'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  Markup
 */
gulp.task('html:partials', function() {
  return gulp.src('./app/partials/**/*.html')
      .pipe(gulp.dest('./dist/partials'));
});

gulp.task('html:main', function() {
  return gulp.src('./app/*.html')
      .pipe(gulp.dest('./dist'));
});
gulp.task('html', ['html:main', 'html:partials']);

/*
  JS hint
 */
gulp.task('lint', function() {
  return gulp.src('./app/**/*.js')
    .pipe(plug.jshint())
    .pipe(plug.jshint.reporter())
    .pipe(plug.jshint.reporter('fail'));
});
gulp.task('jshint', ['lint']);
gulp.task('hint', ['lint']);

/*
  clean dist
 */
gulp.task('clean', function(cb) {
  del(['./dist/*'], cb);
});

/*
  minification
 */
gulp.task('js:minify', ['js'], function() {
  return gulp.src('./dist/bundle/{app,lib}.js')
    .pipe(plug.uglify())
    .pipe(gulp.dest('./dist/bundle'));
});

gulp.task('css:minify', ['css'], function() {
  return gulp.src('./dist/bundle/*.css')
    .pipe(plug.minifyCss({keepBreaks:true}))
    .pipe(gulp.dest('./dist/bundle'));
});

gulp.task('minify', ['js:minify', 'css:minify']);

/*
  rev'd assets
 */

gulp.task('rev:manifest', function() {
  return gulp.src(['./dist/bundle/{app,lib,tpl}.*'])
    .pipe(plug.rev())
    .pipe(plug.size({showFiles:true, gzip:true, total:true}))
    .pipe(gulp.dest('./dist/bundle'))  // write rev'd assets to build dir

    .pipe(plug.rev.manifest({path:'manifest.json'}))
    .pipe(gulp.dest('./dist')); // write manifest

});
gulp.task('rev', ['html:main', 'rev:manifest'], function() {
  var rev = require('./dist/manifest.json'),
      out = gulp.src('./dist/*.html'),
      p = '/bundle/';
  for (var f in rev) {
    out = out.pipe(plug.replace(p+f, p+rev[f]));
  };
  return out.pipe(gulp.dest('./dist'));
});

/*
  alias tasks
 */
gulp.task('lib', ['js:lib', 'css:lib']);
gulp.task('app', ['js:app', 'css:app']);
gulp.task('js', ['js:lib', 'js:app']);
gulp.task('css', ['css:lib', 'css:app']);
gulp.task('style', ['css']);

gulp.task('build', ['js', 'css', 'img', 'tpl', 'html']);

gulp.task('default', ['lint', 'build']);

/*
  watch
 */
gulp.task('watch', ['build'], function() {
  plug.livereload.listen();

  gulp.watch('./dist/**/*')
    .on('change', plug.livereload.changed);

  gulp.watch(['./app/**/*.js', '!./app/**/*-test.js'], ['js:app']);
  gulp.watch('./app/**/*.{less,css}', ['css:app']);
  gulp.watch(['./app/js/directives/**/*.html', './app/partials/home.html'], ['tpl']);
  gulp.watch('./app/**/*.html', ['html']);
  gulp.watch('./app/img/**/*', ['img']);

});
<commit_msg>gulp distribute<commit_after>var gulp = require('gulp'),
    plug = require('gulp-load-plugins')(),
    pkg = require('./package.json'),
    del = require('del'),
    merge = require('merge-stream');

function plumber() {
  return plug.plumber({ errorHandler: function (err) {
    plug.util.beep();
    plug.util.log(plug.util.colors.red(err.toString()));
  } });
}

/*
  library CSS
 */
gulp.task('css:lib', ['fonts'], function() {
  return gulp.src([
      './app/css/bootstrap.less',
      './bower_components/angular/angular-csp.css',
      './bower_components/angular-loading-bar/build/loading-bar.min.css',
      './bower_components/angular-motion/dist/angular-motion.min.css',
      './bower_components/font-awesome/css/font-awesome.min.css'
    ])
    .pipe(plumber())
    .pipe(plug.if('*.less', plug.less()))
    .pipe(plug.concat('lib.css'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  fonts
 */
gulp.task('fonts', function() {
  return gulp.src([
      // './bower_components/bootstrap/dist/fonts/*',
      './bower_components/font-awesome/fonts/*'
    ])
    .pipe(gulp.dest('./dist/fonts'));
});

/*
  application CSS
 */
gulp.task('css:app', function() {
  return gulp.src([
      './app/js/directives/**/*.{less,css}',
      './app/css/themes/*.less',
      './app/css/common.less',
      './app/css/states.less'
    ])
    .pipe(plumber())
    .pipe(plug.if('*.less', plug.less()))
    .pipe(plug.concat('app.css'))
    .pipe(plug.autoprefixer(["> 1%"], {cascade:true}))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  library javascript
 */
gulp.task('js:lib', function() {
  return gulp.src([
      // './bower_components/es5-shim/es5-shim.js',

      './bower_components/angular/angular.js',

      './bower_components/angular-sanitize/angular-sanitize.js',
      './bower_components/angular-animate/angular-animate.js',
      './bower_components/angular-resource/angular-resource.js',

      './bower_components/angular-ui-router/release/angular-ui-router.js',

      './bower_components/angular-strap/dist/modules/dimensions.js',
      './bower_components/angular-strap/dist/modules/button.js',
      './bower_components/angular-strap/dist/modules/tab.js',
      './bower_components/angular-strap/dist/modules/tab.tpl.js',
      './bower_components/angular-strap/dist/modules/tooltip.js',
      './bower_components/angular-strap/dist/modules/tooltip.tpl.js',
      './bower_components/angular-strap/dist/modules/dropdown.js',
      './bower_components/angular-strap/dist/modules/dropdown.tpl.js',
      './bower_components/angular-strap/dist/modules/modal.js',
      './bower_components/angular-strap/dist/modules/modal.tpl.js',
      './bower_components/angular-strap/dist/modules/alert.js',
      './bower_components/angular-strap/dist/modules/alert.tpl.js',
      './bower_components/angular-strap/dist/modules/popover.js',
      './bower_components/angular-strap/dist/modules/popover.tpl.js',
      './bower_components/angular-strap/dist/modules/collapse.js',

      './bower_components/moment/moment.js',
      './bower_components/angular-moment/angular-moment.js',

      './bower_components/ngstorage/ngStorage.js',
      './bower_components/angular-loading-bar/build/loading-bar.js'

    ])
    .pipe(plug.concat('lib.js'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  application javascript
 */
gulp.task('js:app', function() {
  var PKG = JSON.stringify({
    name: pkg.name,
    v: pkg.version
  });
  return gulp.src([
      './app/**/*.js',
      '!./app/**/*-test.js'
    ])
    .pipe(plumber())
    .pipe(plug.ngAnnotate())
    .pipe(plug.wrapper({
       header: '\n(function (PKG){ /* ${filename} */\n',
       footer: '\n})('+PKG+');\n'
    }))
    .pipe(plug.concat('app.js'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  images
  TODO: imgmin?
 */
gulp.task('img', function() {
  return gulp.src('./app/img/**/*')
    .pipe(gulp.dest('./dist/img'));
});

/*
  template cache
 */
gulp.task('tpl', function() {
  return merge(

    gulp.src([
      './app/js/directives/**/*.html'
    ])
      .pipe(plug.angularTemplatecache({
        module: pkg.name + '.directives'
      })),

    gulp.src([
      './app/partials/home.html'
    ])
      .pipe(plug.angularTemplatecache({
        module: pkg.name,
        base: __dirname + '/app',
        root: '/'
      }))

  )
    .pipe(plug.concat('tpl.js'))
    .pipe(gulp.dest('./dist/bundle'));
});

/*
  Markup
 */
gulp.task('html:partials', function() {
  return gulp.src('./app/partials/**/*.html')
      .pipe(gulp.dest('./dist/partials'));
});

gulp.task('html:main', function() {
  return gulp.src('./app/*.html')
      .pipe(gulp.dest('./dist'));
});

gulp.task('html', ['html:main', 'html:partials']);

/*
  JS hint
 */
gulp.task('lint', function() {
  return gulp.src('./app/**/*.js')
    .pipe(plug.jshint())
    .pipe(plug.jshint.reporter())
    .pipe(plug.jshint.reporter('fail'));
});
gulp.task('jshint', ['lint']);
gulp.task('hint', ['lint']);

/*
  clean dist
 */
gulp.task('clean', function(cb) {
  del(['./dist/*'], cb);
});

/*
  minification
 */
gulp.task('js:minify', ['js'], function() {
  return gulp.src('./dist/bundle/{app,lib}.js')
    .pipe(plug.uglify())
    .pipe(gulp.dest('./dist/bundle'));
});

gulp.task('css:minify', ['css'], function() {
  return gulp.src('./dist/bundle/*.css')
    .pipe(plug.minifyCss({keepBreaks:true}))
    .pipe(gulp.dest('./dist/bundle'));
});

gulp.task('minify', ['js:minify', 'css:minify']);

/*
  rev'd assets
 */

gulp.task('rev:manifest', ['js', 'css', 'tpl'], function() {
  return gulp.src(['./dist/bundle/{app,lib,tpl}.*'])
    .pipe(plug.rev())
    .pipe(plug.size({showFiles:true, gzip:true, total:true}))
    .pipe(gulp.dest('./dist/bundle'))  // write rev'd assets to build dir

    .pipe(plug.rev.manifest({path:'manifest.json'}))
    .pipe(gulp.dest('./dist')); // write manifest

});
gulp.task('rev:replace', ['html:main', 'rev:manifest'], function() {
  var rev = require('./dist/manifest.json'),
      out = gulp.src('./dist/*.html'),
      p = '/bundle/';
  for (var f in rev) {
    out = out.pipe(plug.replace(p+f, p+rev[f]));
  };
  return out.pipe(gulp.dest('./dist'));
});

/*
  alias tasks
 */
gulp.task('lib', ['js:lib', 'css:lib']);
gulp.task('app', ['js:app', 'css:app']);
gulp.task('js', ['js:lib', 'js:app']);
gulp.task('css', ['css:lib', 'css:app']);
gulp.task('style', ['css']);

gulp.task('build', ['js', 'css', 'img', 'tpl', 'html']);
gulp.task('distribute', ['build', 'rev:replace']);

gulp.task('default', ['lint', 'build']);

/*
  watch
 */
gulp.task('watch', ['build'], function() {
  plug.livereload.listen();

  gulp.watch('./dist/**/*')
    .on('change', plug.livereload.changed);

  gulp.watch(['./app/**/*.js', '!./app/**/*-test.js'], ['js:app']);
  gulp.watch('./app/**/*.{less,css}', ['css:app']);
  gulp.watch(['./app/js/directives/**/*.html', './app/partials/home.html'], ['tpl']);
  gulp.watch('./app/partials/**/*.html', ['html:partials']);
  gulp.watch('./app/img/**/*', ['img']);

});
<|endoftext|>


<commit_before>"use strict";

var angular = require("angular");
var angularSanitize = require("angular-sanitize");
var jQuery = require("jquery");
window.$ = window.jQuery = jQuery;
require("bootstrap/dist/js/bootstrap.js");
require("bootstrap/dist/css/bootstrap.css");
require("./yeoman-ui.css");

var io = window.io;

angular
  .module('app', [
    'ngSanitize',
    'yoUI'
  ]);

angular
  .module('yoUI', ['ngSanitize'])
  .factory('socket', function() {
    return io();
  })
  .directive('yoAutofocus', yoAutofocus)
  .controller('YoController', YoController);

function yoAutofocus() {
  return {
    restrict: 'A',
    link: function($scope, $element) {
      setTimeout(function() {
        $element[0].focus();
      }, 0);
    }
  };
}

function yoNormalizePrompt(prompt) {
  // Default type is input
  if(!prompt.type) {
    prompt.type = 'input';
  }

  // Confirm prompt could be dropdown ?
  if(prompt.type === 'confirm') {
    prompt.choices = [{
      value: true,
      name: 'Yes'
    }, {
      value: false,
      name: 'No'
    }];
  }

  // Index is useful
  if(prompt.choices && prompt.choices.length) {
    if(typeof prompt.choices[0] === 'string') {
      prompt.choices = prompt.choices.map(function(choice, index) {
        return {
          key: choice.substr(0, 1),
          value: prompt.type === 'list' ? choice : index,
          name: choice
        };
      });
    }

    prompt.choices.forEach(function(choice, index) {
      choice.index = index;
    });
  }

  if(!prompt.default && prompt.type === 'expand') {
    prompt.default = 0;
  }

  prompt.value = prompt.default;

  return prompt;
}

function yoNormalizeAnswer(prompt) {
  if(prompt.type === 'checkbox') {
    prompt.value = [];
    prompt.choices.forEach(function(choice) {
      if(choice.checked) {
        prompt.value.push(choice.value);
      }
    });
  }

  // console.log('prompt.value: ', prompt.value);

  return prompt.value;
}

function YoController($scope, $sce, socket) {
  var self = this;

  self.generator = null;
  self.subgenerator = null;
  self.updateGenerator = _updateGenerator;
  self.run = _run;
  self.submit = _submit;
  self.reset = _reset;
  self.scopeApply = _scopeApply;
  self.isWaiting = _isWaiting;

  self.reset();

  socket.on('yo:list', function(generators) {
    self.generators = generators;
    self.scopeApply();
  });

  socket.emit('yo:list');

  socket.on('yo:prompt', function(prompt) {
    self.prompts.filter(function (prompt) {
      prompt.isDisabled = true;
    });
    prompt.isDisabled = false;
    self.activePromptIndex = self.prompts.length;
    self.prompts.push(yoNormalizePrompt(prompt));

    self.scopeApply();
    appendLog("\n? " + prompt.message);
  });

  socket.on('yo:diff', function(diffs) {
    self.diffs = diffs;
    self.scopeApply();
  });

  socket.on('yo:log', appendLog);
  function appendLog(logs) {
    var element = document.getElementById("logs");
    var oldLog = element.innerHTML;
    element.innerHTML = (oldLog ? oldLog : "") + "\n" + logs;
    element.scrollTop = element.scrollHeight;
    self.logs = $sce.trustAsHtml(logs);
    self.scopeApply("\n> " + prompt.message);
  }

  socket.on('yo:prompt:error', function(msg) {
    alert(msg);
    self.scopeApply();
  });

  socket.on('yo:end', function(data) {
    if(data.distId && data.distName) {
      window.location.href = '/dist/' + data.distId + '/' + data.distName;
    } else {
      alert('Sorry, an error has occured :(');
    }

    self.generator = null;
    self.subgenerator = null;
    self.reset();
    self.scopeApply();
  });

  function _updateGenerator() {
    self.reset();

    if(self.subgenerator && self.generator.subgenerators.indexOf(self.subgenerator) < 0) {
      self.subgenerator = null;
    }

    if(self.subgenerator) {
      return self.run(self.subgenerator.namespace);
    }

    if(self.generator && self.generator.subgenerators.length <= 1) {
      return self.run(self.generator.namespace);
    }
  }

  function _run(namespace) {
    socket.emit('yo:run', {
      namespace: namespace
    });
  }

  function _submit() {
    self.prompts[self.activePromptIndex].isDisabled = true;
    socket.emit('yo:prompt', {
      question: self.prompts[self.activePromptIndex],
      answer: yoNormalizeAnswer(self.prompts[self.activePromptIndex])
    });

    appendLog("    " + yoNormalizeAnswer(self.prompts[self.activePromptIndex]) + " ");
  }

  function _reset() {
    self.prompts = [];
    self.activePromptIndex = -1;
    self.diffs = [];
    self.logs = [];
  }

  function _scopeApply() {
    if (!$scope.$$phase) {
      $scope.$apply();
    }
  }

  function _isWaiting() {
    return self.prompts.filter(function (p1) { return !p1.isDisabled; }).length <= 0;
  }
}
<commit_msg>Refactoring<commit_after>"use strict";

var angular = require("angular");
var angularSanitize = require("angular-sanitize");
var jQuery = require("jquery");
window.$ = window.jQuery = jQuery;
require("bootstrap/dist/js/bootstrap.js");
require("bootstrap/dist/css/bootstrap.css");
require("./yeoman-ui.css");

var io = window.io;

angular
  .module('app', [
    'ngSanitize',
    'yoUI'
  ]);

angular
  .module('yoUI', ['ngSanitize'])
  .factory('socket', function () {
    return io();
  })
  .directive('yoAutofocus', yoAutofocus)
  .controller('YoController', YoController);

function yoAutofocus() {
  return {
    restrict: 'A',
    link: function ($scope, $element) {
      setTimeout(function () {
        $element[0].focus();
      }, 0);
    }
  };
}

function yoNormalizePrompt(prompt) {
  // Default type is input
  if (!prompt.type) {
    prompt.type = 'input';
  }

  // Confirm prompt could be dropdown ?
  if (prompt.type === 'confirm') {
    prompt.choices = [{
      value: true,
      name: 'Yes'
    }, {
      value: false,
      name: 'No'
    }];
  }

  // Index is useful
  if (prompt.choices && prompt.choices.length) {
    if (typeof prompt.choices[0] === 'string') {
      prompt.choices = prompt.choices.map(function (choice, index) {
        return {
          key: choice.substr(0, 1),
          value: prompt.type === 'list' ? choice : index,
          name: choice
        };
      });
    }

    prompt.choices.forEach(function (choice, index) {
      choice.index = index;
    });
  }

  if (!prompt.default && prompt.type === 'expand') {
    prompt.default = 0;
  }

  prompt.value = prompt.default;

  return prompt;
}

function yoNormalizeAnswer(prompt) {
  if (prompt.type === 'checkbox') {
    prompt.value = [];
    prompt.choices.forEach(function (choice) {
      if (choice.checked) {
        prompt.value.push(choice.value);
      }
    });
  }

  // console.log('prompt.value: ', prompt.value);

  return prompt.value;
}

function YoController($scope, $sce, socket) {
  var self = this;

  self.generator = null;
  self.subgenerator = null;
  self.updateGenerator = _updateGenerator;
  self.run = _run;
  self.submit = _submit;
  self.reset = _reset;
  self.scopeApply = _scopeApply;
  self.isWaiting = _isWaiting;

  self.reset();

  socket.on('yo:list', function (generators) {
    self.generators = generators;
    self.scopeApply();
  });

  socket.emit('yo:list');

  socket.on('yo:prompt', function (prompt) {
    self.prompts.filter(function (prompt) {
      prompt.isDisabled = true;
    });
    prompt.isDisabled = false;
    self.activePromptIndex = self.prompts.length;
    self.prompts.push(yoNormalizePrompt(prompt));

    self.scopeApply();
    appendLog("\n? " + prompt.message);
  });

  socket.on('yo:diff', function (diffs) {
    self.diffs = diffs;
    self.scopeApply();
  });

  socket.on('yo:log', appendLog);
  function appendLog(logs) {
    var element = document.getElementById("logs");
    var oldLog = element.innerHTML;
    element.innerHTML = (oldLog ? oldLog : "") + "\n" + logs;
    element.scrollTop = element.scrollHeight;
    self.logs = $sce.trustAsHtml(logs);
    self.scopeApply("\n> " + prompt.message);
  }

  socket.on('yo:prompt:error', function (msg) {
    alert(msg);
    self.scopeApply();
  });

  socket.on('yo:end', function (data) {
    if (data.distId && data.distName) {
      window.location.href = '/dist/' + data.distId + '/' + data.distName;
    } else {
      alert('Sorry, an error has occured :(');
    }

    self.generator = null;
    self.subgenerator = null;
    self.reset();
    self.scopeApply();
  });

  function _updateGenerator() {
    self.reset();

    if (self.subgenerator && self.generator.subgenerators.indexOf(self.subgenerator) < 0) {
      self.subgenerator = null;
    }

    if (self.subgenerator) {
      return self.run(self.subgenerator.namespace);
    }

    if (self.generator && self.generator.subgenerators.length <= 1) {
      return self.run(self.generator.namespace);
    }
  }

  function _run(namespace) {
    socket.emit('yo:run', {
      namespace: namespace
    });
  }

  function _submit() {
    self.prompts[self.activePromptIndex].isDisabled = true;
    socket.emit('yo:prompt', {
      question: self.prompts[self.activePromptIndex],
      answer: yoNormalizeAnswer(self.prompts[self.activePromptIndex])
    });

    appendLog("    " + yoNormalizeAnswer(self.prompts[self.activePromptIndex]) + " ");
  }

  function _reset() {
    self.prompts = [];
    self.activePromptIndex = -1;
    self.diffs = [];
    self.logs = [];
  }

  function _scopeApply() {
    if (!$scope.$$phase) {
      $scope.$apply();
    }
  }

  function _isWaiting() {
    return self.prompts.filter(function (p1) {
        return !p1.isDisabled;
      }).length <= 0;
  }
}
<|endoftext|>


<commit_before>// @flow
import * as Kb from '../../common-adapters/mobile.native'
import * as React from 'react'
import * as Styles from '../../styles'
import * as Tabs from '../../constants/tabs'
import type {Props} from '.'

const icons = {
  [Tabs.chatTab]: 'iconfont-nav-2-chat',
  [Tabs.teamsTab]: 'iconfont-nav-2-teams',
  [Tabs.peopleTab]: 'iconfont-nav-2-people',
  [Tabs.settingsTab]: 'iconfont-nav-2-more',
  [Tabs.walletsTab]: 'iconfont-nav-2-wallets',
}

const tabs = [Tabs.peopleTab, Tabs.chatTab, Tabs.teamsTab, Tabs.settingsTab]

// Immediately draw selected and don't wait for the store
type State = {|justSelected: ?string|}
class TabBar extends React.PureComponent<Props, State> {
  state = {justSelected: null}
  _onTabClick = justSelected => {
    this.setState(p => (p.justSelected === justSelected ? null : {justSelected}))
    this.props.onTabClick(justSelected)
  }

  componentDidUpdate(prevProps: Props) {
    if (this.props.selectedTab !== prevProps.selectedTab) {
      const justSelected = this.props.selectedTab
      this.setState(p => (p.justSelected === justSelected ? null : {justSelected}))
    }
  }

  render() {
    const selectedTab = this.state.justSelected || this.props.selectedTab
    const p = this.props
    return (
      !!p.username && (
        <Kb.NativeSafeAreaView style={styles.safe}>
          <Kb.Box2 direction="horizontal" fullWidth={true} style={styles.container}>
            {tabs.map(t => (
              <Kb.Box2 key={t} direction="vertical" style={styles.iconContainer}>
                <Kb.Icon
                  type={icons[t]}
                  onClick={() => this._onTabClick(t)}
                  fontSize={32}
                  style={styles.tab}
                  color={t === selectedTab ? Styles.globalColors.white : Styles.globalColors.darkBlue4}
                />
                {!!p.badgeNumbers[t] && (
                  <Kb.Badge badgeNumber={p.badgeNumbers[t]} badgeStyle={styles.badge} />
                )}
              </Kb.Box2>
            ))}
          </Kb.Box2>
        </Kb.NativeSafeAreaView>
      )
    )
  }
}

// TEMP to really know you're on this branch. Leave until we flip the feature flag
const backgroundColor = 'pink' // Styles.globalColors.darkBlue2,

const styles = Styles.styleSheetCreate({
  badge: {
    position: 'absolute',
    right: 8,
    top: 3,
  },
  container: {
    alignItems: 'center',
    backgroundColor,
    height: Styles.isAndroid ? 56 : 48,
    justifyContent: 'space-around',
  },
  iconContainer: {
    position: 'relative',
  },
  // When we have new tabs
  meta: {
    position: 'absolute',
    right: 0,
    top: 0,
  },
  safe: {
    backgroundColor,
    flexGrow: 0,
  },
  tab: {
    paddingBottom: 6,
    paddingLeft: 16,
    paddingRight: 16,
    paddingTop: 6,
  },
})

export default TabBar
<commit_msg>make tab bar blue in native nav2 (#16952)<commit_after>// @flow
import * as Kb from '../../common-adapters/mobile.native'
import * as React from 'react'
import * as Styles from '../../styles'
import * as Tabs from '../../constants/tabs'
import type {Props} from '.'

const icons = {
  [Tabs.chatTab]: 'iconfont-nav-2-chat',
  [Tabs.teamsTab]: 'iconfont-nav-2-teams',
  [Tabs.peopleTab]: 'iconfont-nav-2-people',
  [Tabs.settingsTab]: 'iconfont-nav-2-more',
  [Tabs.walletsTab]: 'iconfont-nav-2-wallets',
}

const tabs = [Tabs.peopleTab, Tabs.chatTab, Tabs.teamsTab, Tabs.settingsTab]

// Immediately draw selected and don't wait for the store
type State = {|justSelected: ?string|}
class TabBar extends React.PureComponent<Props, State> {
  state = {justSelected: null}
  _onTabClick = justSelected => {
    this.setState(p => (p.justSelected === justSelected ? null : {justSelected}))
    this.props.onTabClick(justSelected)
  }

  componentDidUpdate(prevProps: Props) {
    if (this.props.selectedTab !== prevProps.selectedTab) {
      const justSelected = this.props.selectedTab
      this.setState(p => (p.justSelected === justSelected ? null : {justSelected}))
    }
  }

  render() {
    const selectedTab = this.state.justSelected || this.props.selectedTab
    const p = this.props
    return (
      !!p.username && (
        <Kb.NativeSafeAreaView style={styles.safe}>
          <Kb.Box2 direction="horizontal" fullWidth={true} style={styles.container}>
            {tabs.map(t => (
              <Kb.Box2 key={t} direction="vertical" style={styles.iconContainer}>
                <Kb.Icon
                  type={icons[t]}
                  onClick={() => this._onTabClick(t)}
                  fontSize={32}
                  style={styles.tab}
                  color={t === selectedTab ? Styles.globalColors.white : Styles.globalColors.darkBlue4}
                />
                {!!p.badgeNumbers[t] && (
                  <Kb.Badge badgeNumber={p.badgeNumbers[t]} badgeStyle={styles.badge} />
                )}
              </Kb.Box2>
            ))}
          </Kb.Box2>
        </Kb.NativeSafeAreaView>
      )
    )
  }
}

const styles = Styles.styleSheetCreate({
  badge: {
    position: 'absolute',
    right: 8,
    top: 3,
  },
  container: {
    alignItems: 'center',
    backgroundColor: Styles.globalColors.darkBlue2,
    height: Styles.isAndroid ? 56 : 48,
    justifyContent: 'space-around',
  },
  iconContainer: {
    position: 'relative',
  },
  // When we have new tabs
  meta: {
    position: 'absolute',
    right: 0,
    top: 0,
  },
  safe: {
    backgroundColor: Styles.globalColors.darkBlue2,
    flexGrow: 0,
  },
  tab: {
    paddingBottom: 6,
    paddingLeft: 16,
    paddingRight: 16,
    paddingTop: 6,
  },
})

export default TabBar
<|endoftext|>


<commit_before>var Places = {
	auditorium: {
		left: "images/auditorium/left.jpg",
		right: "images/auditorium/right.jpg",
		name: "Auditorium",
		frames:[
				{left:["images/auditorium/single_left.jpg", "images/auditorium/single_left2.jpg"],
				right:["images/auditorium/single_right.jpg", "images/auditorium/single_right2.jpg"],
				scaleL:[0.7, 0.7, 0.7],
				positionL:[6.5, -7.5, 11],
				rotationL:[-5.8, -2.8, 0.1],
				scaleR:[0.9, 0.9, 0.89],
				positionR:[6.5, -9.5, 13.5],
				rotationR:[-5.7, -2.9, 0]}
			]
	},
	technopark: {
		left: "images/technopark/left.jpg",
		right: "images/technopark/right.jpg",
		name: "Technopark",
		frames:[]
	},
	swisscom: {
		left: "images/swisscom/left.jpg",
		right: "images/swisscom/right.jpg",
		name: "Swisscom",
		frames:[]
	},
	hackzurich: {
		left: "images/hackzurich/left.jpg",
		right: "images/hackzurich/right.jpg",
		name: "Swisscom",
		frames:[]
	}
}
<commit_msg>reformat<commit_after>var Places = {
  auditorium: {
    left: "images/auditorium/left.jpg",
    right: "images/auditorium/right.jpg",
    name: "Auditorium",
    frames: [{
      left: ["images/auditorium/single_left.jpg", "images/auditorium/single_left2.jpg"],
      right: ["images/auditorium/single_right.jpg", "images/auditorium/single_right2.jpg"],
      scaleL: [0.7, 0.7, 0.7],
      positionL: [6.5, -7.5, 11],
      rotationL: [-5.8, -2.8, 0.1],
      scaleR: [0.9, 0.9, 0.89],
      positionR: [6.5, -9.5, 13.5],
      rotationR: [-5.7, -2.9, 0]
    }]
  },
  technopark: {
    left: "images/technopark/left.jpg",
    right: "images/technopark/right.jpg",
    name: "Technopark",
    frames: []
  },
  swisscom: {
    left: "images/swisscom/left.jpg",
    right: "images/swisscom/right.jpg",
    name: "Swisscom",
    frames: []
  },
  hackzurich: {
    left: "images/hackzurich/left.jpg",
    right: "images/hackzurich/right.jpg",
    name: "Swisscom",
    frames: []
  }
};
<|endoftext|>


<commit_before>function Player(hockey, team, positionId) {
    this.hockey = hockey;
    this.team = team;
    this.position = Player.CONSTANTS.positions[positionId];
    this.bodyRadius = 8;
    this.stickReach = 7;
    this.stickLength = 15;
    this.speed = 1;
    this.layer = team.layer;
    this.location = {
	    x: this.startingPoint('x'),
	    y: this.startingPoint('y')
    };
    this.stickAngle = Math.random() * Math.PI * 2;
    this.selected = false;
    this.collided = false;
    this.collisionType = null;
    this.render();
}

Player.prototype.startingPoint = function(axis) {
    // Randomize player starting point
    var random = Math.random() * Math.abs(this.position.boundaries[axis][1] - this.position.boundaries[axis][0]);
    var position = random + this.position.boundaries[axis][0];
    if(this.team.id > 1) {
    	position = this.hockey.rink.size[axis] - Math.min(this.position.boundaries[axis][1], this.position.boundaries[axis][0]) - random;
    }
    return position;
};

Player.prototype.render = function() {
    this.player = {};
    this.player.group = new Kinetic.Group({
        x: this.location.x + this.hockey.rink.offset.x,
        y: this.location.y + this.hockey.rink.offset.y,
        rotation: this.stickAngle
    });

    this.player.body = new Kinetic.Circle({
	    radius: this.bodyRadius,
	    stroke: '#000',
	    fill: (this.team.id == 1)? '#F47940': '#E13A3E'
	});
    this.player.group.add(this.player.body);

    if(this.position.hasStick) {
        var stickStart = this.bodyRadius / 2 + this.stickReach;
        this.player.stick = new Kinetic.Line({
            points: [[stickStart, 0],[stickStart + this.stickLength, 0]],
            stroke: '#452200',
            strokeWidth: 3
        });
        this.player.group.add(this.player.stick);
    }

    this.player.boundary = new Kinetic.Line({
	// assumes all skaters can only go straight, you know, like in bubble hockey
	    points: this.team.id == 1? [
		    [this.hockey.rink.offset.x + this.position.boundaries.x[0], this.hockey.rink.offset.y + this.position.boundaries.y[0]],
		    [this.hockey.rink.offset.x + this.position.boundaries.x[1], this.hockey.rink.offset.y + this.position.boundaries.y[1]]
	    ] : [
		    [this.hockey.rink.offset.x + this.hockey.rink.size.x - Math.min(this.position.boundaries.x[1], this.position.boundaries.x[0]),
		    this.hockey.rink.offset.y + this.hockey.rink.size.y - Math.min(this.position.boundaries.y[1], this.position.boundaries.y[0])],
		    [this.hockey.rink.offset.x + this.hockey.rink.size.x - Math.max(this.position.boundaries.x[1], this.position.boundaries.x[0]),
		    this.hockey.rink.offset.y + this.hockey.rink.size.y - Math.max(this.position.boundaries.y[1], this.position.boundaries.y[0])]
	    ],
	    stroke: '#333',
	    opacity: '.3',
	    strokeWidth: 2,
	}
    );

    if(this.team.id == 1) {
        this.player.playerSelector = new PlayerSelector(this);
    }

    this.layer.add(this.player.boundary);
    this.hockey.rink.layer.add(this.player.boundary);
    this.layer.add(this.player.group);
};

Player.prototype.move = function(x,y) {
    var _this = this;
    this.stopMovement();    // One animation movement at a time people
    this.movement = new Kinetic.Animation(
	    function(frame) {
	        _this.advance(x, y);
	    }, _this.layer
    );
    this.movement.start();
};

Player.prototype.rotate = function(rad) {
    // This would be neater as an animation
	var newRotation = this.player.group.getRotation() + rad;
	while(newRotation > 2 * Math.PI) {
		newRotation -= 2 * Math.PI;
	}
	while(newRotation < -2 * Math.PI) {
		newRotation += 2 * Math.PI;
	}
	this.player.group.setRotation(newRotation);
	this.stickAngle = newRotation;
	this.detectCollision();
};

Player.prototype.detectCollision = function() {
    var xOffset = this.location.x - this.hockey.puck.location.x, xDistance = Math.abs(xOffset);
    var yOffset = this.location.y - this.hockey.puck.location.y, yDistance = Math.abs(yOffset);
    if(xDistance < this.bodyRadius && yDistance < this.bodyRadius) {
        // Body Bump
        this.collisionType = Player.CONSTANTS.collisionTypes.BUMP;
    } else if(xDistance < (this.bodyRadius + this.stickLength + this.stickReach) && yDistance < (this.bodyRadius + this.stickLength + this.stickReach)) {
        // Potential for Shot, depending on stick angle (ignore possibility of puck going between stick & body for now)
		var puckOffset = 0;
		if(xOffset <= 0 && yOffset >= 0) {  // puck is in first quadrent
			puckOffset = 0 ;
			console.log("Q1")
		} else if(xOffset <= 0 && yOffset <= 0) { // second quandrent
			puckOffset = Math.PI / 2;
			console.log("Q2")
		} else if(xOffset >= 0 && yOffset <= 0) { // third quadrent
			puckOffset = Math.PI;
			console.log("Q3")
		} else if(xOffset >= 0 && yOffset >= 0) { // fourth quadrent
			puckOffset = 3 * Math.PI / 2;
			console.log("Q4")
		}

		var puckAngle = puckOffset + Math.atan(xOffset / yOffset); // Angle the puck is from the player
        if(Math.abs(puckAngle - this.stickAngle) < Math.PI / 16) {  // If the stick is reasonable close
        	this.collisionType = Player.CONSTANTS.collisionTypes.SHOT;
		}
    }
};

Player.prototype.advance = function(x, y) {
    // This works fine for team 0, but the locations on team 2 are jacked.  need to figure out how to handle drawing dots better, perhaps two boundaries objects for each position, one per team?
    if(this.location.x != x) {
        // Goalie movement
        this.location.x = this.location.x + this.speed;
    }
    if(this.location.y != y) {
        // Vertical Movement of skaters
        this.location.y = this.location.y < y ? (this.location.y + Math.min(this.speed, (y - this.location.y))) : (this.location.y - Math.min(this.speed, (this.location.y - y)));
    }
    // Ensure that we're within the dimensions allowed
    if(this.location.y > this.position.boundaries.y[1]) {
        this.location.y = this.position.boundaries.y[1];
    } else if(this.location.y < this.position.boundaries.y[0]) {
        this.location.y = this.position.boundaries.y[0];
    }
    if( (this.location.x == x || this.location.x == this.position.boundaries.x[0] || this.location.x == this.position.boundaries.x[1]) && (this.location.y == y || this.location.y == this.position.boundaries.y[0] || this.location.y == this.position.boundaries.y[1]) ) {
        this.stopMovement();
        return false;
    }
    this.player.group.setX(this.location.x + this.hockey.rink.offset.x);
    this.player.group.setY(this.location.y + this.hockey.rink.offset.y);
    this.advance(x,y);
};

Player.prototype.select = function() {
    this.team.resetSelectors();
    this.player.playerSelector.icon.setFill('red');
    this.layer.draw();
    this.selected = true;
};

Player.prototype.stopMovement = function() {
    if(this.movement) this.movement.stop();
};

Player.prototype.resetCollisions = function() {
    this.collisionType = null;
};

Player.CONSTANTS = {
    positions: [ {positionId: 1, abbreviation: 'LW', name: 'Left Wing', boundaries : { x: [25, 25], y: [20, 250]}, hasStick: true, wrapperWidth: 50, wrapperTop: 0, wrapperLeft: 0 },
		{positionId: 2, abbreviation: 'RW', name: 'Right Wing', boundaries : { x: [196, 196], y: [20, 250]}, hasStick: true, wrapperWidth: 50, wrapperTop: 0, wrapperLeft: 0 },
		{positionId: 3, abbreviation: 'C', name: 'Center', boundaries: { x:[110, 110], y:[65, 250]}, hasStick: true, wrapperWidth: 50, wrapperTop: 0, wrapperLeft: 0 },
		{positionId: 4, abbreviation: 'LD', name: 'Left Defenseman', boundaries: { x:[67, 67], y:[280, 500]}, hasStick: true, wrapperWidth: 80, wrapperTop: 265, wrapperLeft: -15 },
		{positionId: 5, abbreviation: 'RD', name: 'Right Defenseman', boundaries: { x:[154, 154], y:[280, 500]}, hasStick: true, wrapperWidth: 80, wrapperTop: 265, wrapperLeft: -15 },
		{positionId: 6, abbreviation: 'G', name: 'Goalie', boundaries: {x:[90,130], y:[485, 485]}, hasStick: false }
    ],
    collisionTypes: {
            "SHOT": 1,
            "BUMP": 2
    }

};

function PlayerSelector(player) {
    this.player = player;
    this.hockey = player.hockey;
    if(this.player.position && player.position.abbreviation != 'G') {
        this.group = new Kinetic.Group({
            x: this.hockey.rink.offset.x + this.player.position.boundaries.x[0] - 25,
            y: this.hockey.rink.offset.y - 2,
            height:600
        });

        this.wrapper = new Kinetic.Rect({
            width: this.player.position.wrapperWidth,
            height: 260,
            x: this.player.position.wrapperLeft,
            y: this.player.position.wrapperTop,
            stroke: 'black',
            fill: 'blue',
            opacity: 0
        })
        this.group.add(this.wrapper);

        this.icon = new Kinetic.Circle({
            x: 25,
            radius: 15,
            stroke: 'black',
            strokeWidth:2,
            fill: '#ccc'
        });

        var _this = this;
        this.group.on('mouseover touchstart', function() {
            _this.player.select();
        });

        this.group.add(this.icon);

        this.character = new Kinetic.Text({
            fontSize: 15,
            x: 0,
            y: -8,
            width:50,
            align: 'center',
            text: this.player.position.abbreviation,
            fill: 'black',
            fontStyle: 'bold'
        });
        this.group.add(this.character);
        this.player.layer.add(this.group);
    }
};
<commit_msg>spaces -> tabs<commit_after>function Player(hockey, team, positionId) {
    this.hockey = hockey;
    this.team = team;
    this.position = Player.CONSTANTS.positions[positionId];
    this.bodyRadius = 8;
    this.stickReach = 7;
    this.stickLength = 15;
    this.speed = 1;
    this.layer = team.layer;
    this.location = {
	    x: this.startingPoint('x'),
	    y: this.startingPoint('y')
    };
    this.stickAngle = Math.random() * Math.PI * 2;
    this.selected = false;
    this.collided = false;
    this.collisionType = null;
    this.render();
}

Player.prototype.startingPoint = function(axis) {
    // Randomize player starting point
    var random = Math.random() * Math.abs(this.position.boundaries[axis][1] - this.position.boundaries[axis][0]);
    var position = random + this.position.boundaries[axis][0];
    if(this.team.id > 1) {
    	position = this.hockey.rink.size[axis] - Math.min(this.position.boundaries[axis][1], this.position.boundaries[axis][0]) - random;
    }
    return position;
};

Player.prototype.render = function() {
    this.player = {};
    this.player.group = new Kinetic.Group({
        x: this.location.x + this.hockey.rink.offset.x,
        y: this.location.y + this.hockey.rink.offset.y,
        rotation: this.stickAngle
    });

    this.player.body = new Kinetic.Circle({
	    radius: this.bodyRadius,
	    stroke: '#000',
	    fill: (this.team.id == 1)? '#F47940': '#E13A3E'
	});
    this.player.group.add(this.player.body);

    if(this.position.hasStick) {
        var stickStart = this.bodyRadius / 2 + this.stickReach;
        this.player.stick = new Kinetic.Line({
            points: [[stickStart, 0],[stickStart + this.stickLength, 0]],
            stroke: '#452200',
            strokeWidth: 3
        });
        this.player.group.add(this.player.stick);
    }

    this.player.boundary = new Kinetic.Line({
	// assumes all skaters can only go straight, you know, like in bubble hockey
	    points: this.team.id == 1? [
		    [this.hockey.rink.offset.x + this.position.boundaries.x[0], this.hockey.rink.offset.y + this.position.boundaries.y[0]],
		    [this.hockey.rink.offset.x + this.position.boundaries.x[1], this.hockey.rink.offset.y + this.position.boundaries.y[1]]
	    ] : [
		    [this.hockey.rink.offset.x + this.hockey.rink.size.x - Math.min(this.position.boundaries.x[1], this.position.boundaries.x[0]),
		    this.hockey.rink.offset.y + this.hockey.rink.size.y - Math.min(this.position.boundaries.y[1], this.position.boundaries.y[0])],
		    [this.hockey.rink.offset.x + this.hockey.rink.size.x - Math.max(this.position.boundaries.x[1], this.position.boundaries.x[0]),
		    this.hockey.rink.offset.y + this.hockey.rink.size.y - Math.max(this.position.boundaries.y[1], this.position.boundaries.y[0])]
	    ],
	    stroke: '#333',
	    opacity: '.3',
	    strokeWidth: 2,
	}
    );

    if(this.team.id == 1) {
        this.player.playerSelector = new PlayerSelector(this);
    }

    this.layer.add(this.player.boundary);
    this.hockey.rink.layer.add(this.player.boundary);
    this.layer.add(this.player.group);
};

Player.prototype.move = function(x,y) {
    var _this = this;
    this.stopMovement();    // One animation movement at a time people
    this.movement = new Kinetic.Animation(
	    function(frame) {
	        _this.advance(x, y);
	    }, _this.layer
    );
    this.movement.start();
};

Player.prototype.rotate = function(rad) {
    // This would be neater as an animation
	var newRotation = this.player.group.getRotation() + rad;
	while(newRotation > 2 * Math.PI) {
		newRotation -= 2 * Math.PI;
	}
	while(newRotation < -2 * Math.PI) {
		newRotation += 2 * Math.PI;
	}
	this.player.group.setRotation(newRotation);
	this.stickAngle = newRotation;
	this.detectCollision();
};

Player.prototype.detectCollision = function() {
	var xOffset = this.location.x - this.hockey.puck.location.x, xDistance = Math.abs(xOffset);
	var yOffset = this.location.y - this.hockey.puck.location.y, yDistance = Math.abs(yOffset);
	if(xDistance < this.bodyRadius && yDistance < this.bodyRadius) {
		// Body Bump
		this.collisionType = Player.CONSTANTS.collisionTypes.BUMP;
	} else if(xDistance < (this.bodyRadius + this.stickLength + this.stickReach) && yDistance < (this.bodyRadius + this.stickLength + this.stickReach)) {
		// Potential for Shot, depending on stick angle (ignore possibility of puck going between stick & body for now)
		var puckOffset = 0;
		if(xOffset <= 0 && yOffset >= 0) {  // puck is in first quadrent
			puckOffset = 0 ;
			console.log("Q1")
		} else if(xOffset <= 0 && yOffset <= 0) { // second quandrent
			puckOffset = Math.PI / 2;
			console.log("Q2")
		} else if(xOffset >= 0 && yOffset <= 0) { // third quadrent
			puckOffset = Math.PI;
			console.log("Q3")
		} else if(xOffset >= 0 && yOffset >= 0) { // fourth quadrent
			puckOffset = 3 * Math.PI / 2;
			console.log("Q4")
		}

		var puckAngle = puckOffset + Math.atan(xOffset / yOffset); // Angle the puck is from the player
		if(Math.abs(puckAngle - this.stickAngle) < Math.PI / 16) {  // If the stick is reasonable close
			this.collisionType = Player.CONSTANTS.collisionTypes.SHOT;
		}
	}
};

Player.prototype.advance = function(x, y) {
    // This works fine for team 0, but the locations on team 2 are jacked.  need to figure out how to handle drawing dots better, perhaps two boundaries objects for each position, one per team?
    if(this.location.x != x) {
        // Goalie movement
        this.location.x = this.location.x + this.speed;
    }
    if(this.location.y != y) {
        // Vertical Movement of skaters
        this.location.y = this.location.y < y ? (this.location.y + Math.min(this.speed, (y - this.location.y))) : (this.location.y - Math.min(this.speed, (this.location.y - y)));
    }
    // Ensure that we're within the dimensions allowed
    if(this.location.y > this.position.boundaries.y[1]) {
        this.location.y = this.position.boundaries.y[1];
    } else if(this.location.y < this.position.boundaries.y[0]) {
        this.location.y = this.position.boundaries.y[0];
    }
    if( (this.location.x == x || this.location.x == this.position.boundaries.x[0] || this.location.x == this.position.boundaries.x[1]) && (this.location.y == y || this.location.y == this.position.boundaries.y[0] || this.location.y == this.position.boundaries.y[1]) ) {
        this.stopMovement();
        return false;
    }
    this.player.group.setX(this.location.x + this.hockey.rink.offset.x);
    this.player.group.setY(this.location.y + this.hockey.rink.offset.y);
    this.advance(x,y);
};

Player.prototype.select = function() {
    this.team.resetSelectors();
    this.player.playerSelector.icon.setFill('red');
    this.layer.draw();
    this.selected = true;
};

Player.prototype.stopMovement = function() {
    if(this.movement) this.movement.stop();
};

Player.prototype.resetCollisions = function() {
    this.collisionType = null;
};

Player.CONSTANTS = {
    positions: [ {positionId: 1, abbreviation: 'LW', name: 'Left Wing', boundaries : { x: [25, 25], y: [20, 250]}, hasStick: true, wrapperWidth: 50, wrapperTop: 0, wrapperLeft: 0 },
		{positionId: 2, abbreviation: 'RW', name: 'Right Wing', boundaries : { x: [196, 196], y: [20, 250]}, hasStick: true, wrapperWidth: 50, wrapperTop: 0, wrapperLeft: 0 },
		{positionId: 3, abbreviation: 'C', name: 'Center', boundaries: { x:[110, 110], y:[65, 250]}, hasStick: true, wrapperWidth: 50, wrapperTop: 0, wrapperLeft: 0 },
		{positionId: 4, abbreviation: 'LD', name: 'Left Defenseman', boundaries: { x:[67, 67], y:[280, 500]}, hasStick: true, wrapperWidth: 80, wrapperTop: 265, wrapperLeft: -15 },
		{positionId: 5, abbreviation: 'RD', name: 'Right Defenseman', boundaries: { x:[154, 154], y:[280, 500]}, hasStick: true, wrapperWidth: 80, wrapperTop: 265, wrapperLeft: -15 },
		{positionId: 6, abbreviation: 'G', name: 'Goalie', boundaries: {x:[90,130], y:[485, 485]}, hasStick: false }
    ],
    collisionTypes: {
            "SHOT": 1,
            "BUMP": 2
    }

};

function PlayerSelector(player) {
    this.player = player;
    this.hockey = player.hockey;
    if(this.player.position && player.position.abbreviation != 'G') {
        this.group = new Kinetic.Group({
            x: this.hockey.rink.offset.x + this.player.position.boundaries.x[0] - 25,
            y: this.hockey.rink.offset.y - 2,
            height:600
        });

        this.wrapper = new Kinetic.Rect({
            width: this.player.position.wrapperWidth,
            height: 260,
            x: this.player.position.wrapperLeft,
            y: this.player.position.wrapperTop,
            stroke: 'black',
            fill: 'blue',
            opacity: 0
        })
        this.group.add(this.wrapper);

        this.icon = new Kinetic.Circle({
            x: 25,
            radius: 15,
            stroke: 'black',
            strokeWidth:2,
            fill: '#ccc'
        });

        var _this = this;
        this.group.on('mouseover touchstart', function() {
            _this.player.select();
        });

        this.group.add(this.icon);

        this.character = new Kinetic.Text({
            fontSize: 15,
            x: 0,
            y: -8,
            width:50,
            align: 'center',
            text: this.player.position.abbreviation,
            fill: 'black',
            fontStyle: 'bold'
        });
        this.group.add(this.character);
        this.player.layer.add(this.group);
    }
};
<|endoftext|>