<commit_before>        var map = L.map('map').setView([0, 0], 1);
        L.tileLayer('img/map/{z}/{y}-{x}.jpeg', {
            minZoom: 1,
            maxZoom: 4,
            attribution: 'ITP Map by /u/pauix',
            zomSnap: 0.25,
            tms: false,
			noWrap: true,
            maxBounds:new L.LatLngBounds(new L.LatLng(86, -180), new L.LatLng(-86, 0)),
			maxBoundsViscosity: 1.0
        }).addTo(map);

		/*This function gives you Lat Long of what you click on */

		function onMapClick(e) {
	//		if(confirm("ADD MARKER HERE?")){
				var name = prompt("Name")
                var type = prompt("Type")
				mark = new L.Marker([e.latlng.lat, e.latlng.lng], {icon: Keep_4}).bindPopup("txt");
				map.addLayer(mark)
              $("#text").val($("#text").val()+"["+e.latlng.lat+","+e.latlng.lng+",\""+name+"\",\""+type+"_4\",\""+type+"_3\",\""+type+"_2\"],\n")

         //       circle = L.circle([e.latlng.lat, e.latlng.lng],(1), {color: "#ffcc00", fillColor:"#ffcc00",fillOpacity:0.75}).addTo(map)
		//		$("#text").val($("#text").val()+"["+e.latlng.lat+","+e.latlng.lng+"],\n")

	//		}

		};
		map.on('click', onMapClick);

        var keeps = []
        keeps.concat(reachKeeps);

        var villages = []
        villages.concat(reachVillages);

        var resources = []
        resources.concat(reachResources);

		//Loop through the keep markers (declared on marker.js) array and add markers to layer
		var arrKeeps_4 = []
        var arrKeeps_3 = []
        var arrKeeps_2 = []

		//Loop through the village markers (declared on marker.js) array and add markers to layer
		var arrVillages_4 = []
        var arrVillages_3 = []
        var arrVillages_2 = []

		//Loop through the resource markers (declared on marker.js) array and add markers to layer
		var arrResources_4 = []
        var arrResources_3 = []
        var arrResources_2 = []

        for (var i=0; i<keeps.length; i++) {

            var lat = keeps[i][0];
            var lon = keeps[i][1];
            var popupText = keeps[i][2];

             var marker_4 = new L.Marker([lat, lon], {icon: keeps[i][3], title:popupText});//.on('click',function(e){$("#extras").html("")});
             var marker_3 = new L.Marker([lat, lon], {icon: keeps[i][4], title:popupText});//.on('click',function(e){$("#extras").html("")});
             var marker_2 = new L.Marker([lat, lon], {icon: keeps[i][5], title:popupText});//.on('click',function(e){$("#extras").html("")});

			arrKeeps_4.push(marker_4)
            arrKeeps_3.push(marker_3)
            arrKeeps_2.push(marker_2)
        }
		var keepLayer_4 = L.layerGroup(arrKeeps_4);
        var keepLayer_3 = L.layerGroup(arrKeeps_3);
        var keepLayer_2 = L.layerGroup(arrKeeps_2);

       for (var i=0; i<villages.length; i++) {

            var lat = villages[i][0];
            var lon = villages[i][1];
            var popupText = villages[i][2];

             var marker_4 = new L.Marker([lat, lon], {icon: villages[i][3]}).bindPopup(popupText);
             var marker_3 = new L.Marker([lat, lon], {icon: villages[i][4]}).bindPopup(popupText);
             var marker_2 = new L.Marker([lat, lon], {icon: villages[i][5]}).bindPopup(popupText);

			arrVillages_4.push(marker_4)
            arrVillages_3.push(marker_3)
            arrVillages_2.push(marker_2)
        }
		var villageLayer_4 = L.layerGroup(arrVillages_4);
        var villageLayer_3 = L.layerGroup(arrVillages_3);
        var villageLayer_2 = L.layerGroup(arrVillages_2);

       for (var i=0; i<resources.length; i++) {

            var lat = resources[i][0];
            var lon = resources[i][1];
            var popupText = resources[i][2];

             var marker_4 = new L.Marker([lat, lon], {icon: resources[i][3]}).bindPopup(popupText);
             var marker_3 = new L.Marker([lat, lon], {icon: resources[i][4]}).bindPopup(popupText);
             var marker_2 = new L.Marker([lat, lon], {icon: resources[i][5]}).bindPopup(popupText);

			arrResources_4.push(marker_4)
            arrResources_3.push(marker_3)
            arrResources_2.push(marker_2)
        }
		var resourceLayer_4 = L.layerGroup(arrResources_4);
        var resourceLayer_3 = L.layerGroup(arrResources_3);
        var resourceLayer_2 = L.layerGroup(arrResources_2);

        map.on('zoomend',function(e,m){
            e.target.removeLayer(keepLayer_2);
            e.target.removeLayer(keepLayer_3);
            e.target.removeLayer(keepLayer_4);

            e.target.removeLayer(villageLayer_2);
            e.target.removeLayer(villageLayer_3);
            e.target.removeLayer(villageLayer_4);

            e.target.removeLayer(resourceLayer_2);
            e.target.removeLayer(resourceLayer_3);
            e.target.removeLayer(resourceLayer_4);

            switch(e.target._zoom){
                case 1:
                break;

                case 2:
                    if(showKeeps) e.target.addLayer(keepLayer_2);
                    if(showVillages) e.target.addLayer(villageLayer_2);
                    if(showResources) e.target.addLayer(resourceLayer_2);
                break;

                case 3:
                    if(showKeeps) e.target.addLayer(keepLayer_3);
                    if(showVillages) e.target.addLayer(villageLayer_3);
                    if(showResources) e.target.addLayer(resourceLayer_3);
                break;

                case 4:
                    if(showKeeps) e.target.addLayer(keepLayer_4);
                    if(showVillages) e.target.addLayer(villageLayer_4);
                    if(showResources) e.target.addLayer(resourceLayer_4);
              break;
            }
            currentzoom = e.target._zoom;

        })

var currentzoom = 1;
 function toggle(type){
      switch(type){
          case "keep":
            showKeeps = !showKeeps;
         break;

         case "village":
            showVillages = !showVillages;
         break;

        case "resource":
            showResources = !showResources;
         break;
      }
      layer = eval(type+"Layer_"+currentzoom);

    if (map.hasLayer(layer) && currentzoom>1)     map.removeLayer(layer);
    else   map.addLayer(layer);
}<commit_msg>uygu<commit_after>        var map = L.map('map').setView([0, 0], 1);
        L.tileLayer('img/map/{z}/{y}-{x}.jpeg', {
            minZoom: 1,
            maxZoom: 4,
            attribution: 'ITP Map by /u/pauix',
            zomSnap: 0.25,
            tms: false,
			noWrap: true,
            maxBounds:new L.LatLngBounds(new L.LatLng(86, -180), new L.LatLng(-86, 0)),
			maxBoundsViscosity: 1.0
        }).addTo(map);

		/*This function gives you Lat Long of what you click on */

		function onMapClick(e) {
	//		if(confirm("ADD MARKER HERE?")){
				var name = prompt("Name")
                var type = prompt("Type")
				mark = new L.Marker([e.latlng.lat, e.latlng.lng], {icon: eval(type+"_"+4)}).bindPopup("txt");
				map.addLayer(mark)
              $("#text").val($("#text").val()+"["+e.latlng.lat+","+e.latlng.lng+",\""+name+"\",\""+type+"_4\",\""+type+"_3\",\""+type+"_2\"],\n")

         //       circle = L.circle([e.latlng.lat, e.latlng.lng],(1), {color: "#ffcc00", fillColor:"#ffcc00",fillOpacity:0.75}).addTo(map)
		//		$("#text").val($("#text").val()+"["+e.latlng.lat+","+e.latlng.lng+"],\n")

	//		}

		};
		map.on('click', onMapClick);

        var keeps = []
        keeps.concat(reachKeeps);

        var villages = []
        villages.concat(reachVillages);

        var resources = []
        resources.concat(reachResources);

		//Loop through the keep markers (declared on marker.js) array and add markers to layer
		var arrKeeps_4 = []
        var arrKeeps_3 = []
        var arrKeeps_2 = []

		//Loop through the village markers (declared on marker.js) array and add markers to layer
		var arrVillages_4 = []
        var arrVillages_3 = []
        var arrVillages_2 = []

		//Loop through the resource markers (declared on marker.js) array and add markers to layer
		var arrResources_4 = []
        var arrResources_3 = []
        var arrResources_2 = []

        for (var i=0; i<keeps.length; i++) {

            var lat = keeps[i][0];
            var lon = keeps[i][1];
            var popupText = keeps[i][2];

             var marker_4 = new L.Marker([lat, lon], {icon: keeps[i][3], title:popupText});//.on('click',function(e){$("#extras").html("")});
             var marker_3 = new L.Marker([lat, lon], {icon: keeps[i][4], title:popupText});//.on('click',function(e){$("#extras").html("")});
             var marker_2 = new L.Marker([lat, lon], {icon: keeps[i][5], title:popupText});//.on('click',function(e){$("#extras").html("")});

			arrKeeps_4.push(marker_4)
            arrKeeps_3.push(marker_3)
            arrKeeps_2.push(marker_2)
        }
		var keepLayer_4 = L.layerGroup(arrKeeps_4);
        var keepLayer_3 = L.layerGroup(arrKeeps_3);
        var keepLayer_2 = L.layerGroup(arrKeeps_2);

       for (var i=0; i<villages.length; i++) {

            var lat = villages[i][0];
            var lon = villages[i][1];
            var popupText = villages[i][2];

             var marker_4 = new L.Marker([lat, lon], {icon: villages[i][3]}).bindPopup(popupText);
             var marker_3 = new L.Marker([lat, lon], {icon: villages[i][4]}).bindPopup(popupText);
             var marker_2 = new L.Marker([lat, lon], {icon: villages[i][5]}).bindPopup(popupText);

			arrVillages_4.push(marker_4)
            arrVillages_3.push(marker_3)
            arrVillages_2.push(marker_2)
        }
		var villageLayer_4 = L.layerGroup(arrVillages_4);
        var villageLayer_3 = L.layerGroup(arrVillages_3);
        var villageLayer_2 = L.layerGroup(arrVillages_2);

       for (var i=0; i<resources.length; i++) {

            var lat = resources[i][0];
            var lon = resources[i][1];
            var popupText = resources[i][2];

             var marker_4 = new L.Marker([lat, lon], {icon: resources[i][3]}).bindPopup(popupText);
             var marker_3 = new L.Marker([lat, lon], {icon: resources[i][4]}).bindPopup(popupText);
             var marker_2 = new L.Marker([lat, lon], {icon: resources[i][5]}).bindPopup(popupText);

			arrResources_4.push(marker_4)
            arrResources_3.push(marker_3)
            arrResources_2.push(marker_2)
        }
		var resourceLayer_4 = L.layerGroup(arrResources_4);
        var resourceLayer_3 = L.layerGroup(arrResources_3);
        var resourceLayer_2 = L.layerGroup(arrResources_2);

        map.on('zoomend',function(e,m){
            e.target.removeLayer(keepLayer_2);
            e.target.removeLayer(keepLayer_3);
            e.target.removeLayer(keepLayer_4);

            e.target.removeLayer(villageLayer_2);
            e.target.removeLayer(villageLayer_3);
            e.target.removeLayer(villageLayer_4);

            e.target.removeLayer(resourceLayer_2);
            e.target.removeLayer(resourceLayer_3);
            e.target.removeLayer(resourceLayer_4);

            switch(e.target._zoom){
                case 1:
                break;

                case 2:
                    if(showKeeps) e.target.addLayer(keepLayer_2);
                    if(showVillages) e.target.addLayer(villageLayer_2);
                    if(showResources) e.target.addLayer(resourceLayer_2);
                break;

                case 3:
                    if(showKeeps) e.target.addLayer(keepLayer_3);
                    if(showVillages) e.target.addLayer(villageLayer_3);
                    if(showResources) e.target.addLayer(resourceLayer_3);
                break;

                case 4:
                    if(showKeeps) e.target.addLayer(keepLayer_4);
                    if(showVillages) e.target.addLayer(villageLayer_4);
                    if(showResources) e.target.addLayer(resourceLayer_4);
              break;
            }
            currentzoom = e.target._zoom;

        })

var currentzoom = 1;
 function toggle(type){
      switch(type){
          case "keep":
            showKeeps = !showKeeps;
         break;

         case "village":
            showVillages = !showVillages;
         break;

        case "resource":
            showResources = !showResources;
         break;
      }
      layer = eval(type+"Layer_"+currentzoom);

    if (map.hasLayer(layer) && currentzoom>1)     map.removeLayer(layer);
    else   map.addLayer(layer);
}<|endoftext|>


<commit_before><commit_msg>career list fix<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';
import module from '../helpers/module-for-db';
import { test } from '../helpers/qunit';

const {
  RSVP: { all }
} = Ember;

const ddoc = {
  views: {
    'all': {
      map(doc) {
        /* global emit */
        emit(doc._id);
      }
    }
  }
};

module('document-paginated-proxy-remote', {
  async beforeEach() {
    this.owner = Ember.Object.create({ type: 'duck' });
    this.opts = {
      matches(/*doc, owner*/) {
        return true;
      },
      query(/*owner*/) {
        return { ddoc: 'main', view: 'all', limit: 3 };
      }
    };
    this.create = () => this.db._createInternalPaginatedProxy(this.owner, this.opts).model(true);
    this.insert = (count=10) => {
      let promises = [];
      for(let i = 0; i < count; i++) {
        promises.push(this.docs.save({ _id: `duck:${i}` }));
      }
      return all(promises);
    }
    await this.recreate();
    await this.docs.get('design').save('main', ddoc);
  }
});

test('exists', function(assert) {
  let proxy = this.create();
  assert.ok(proxy);
  assert.ok(proxy._internal);
});

test('load', async function(assert) {
  await this.insert();
  let proxy = this.create();
  await proxy.load();
  assert.equal(proxy.get('length'), 3);
});
<commit_msg>add didLoad for paginated proxy test<commit_after>import Ember from 'ember';
import module from '../helpers/module-for-db';
import { test } from '../helpers/qunit';

const {
  RSVP: { all }
} = Ember;

const ddoc = {
  views: {
    'all': {
      map(doc) {
        /* global emit */
        emit(doc._id);
      }
    }
  }
};

module('document-paginated-proxy-remote', {
  async beforeEach() {
    this.owner = Ember.Object.create({ type: 'duck' });
    this.opts = {
      matches(/*doc, owner*/) {
        return true;
      },
      query(/*owner*/) {
        return { ddoc: 'main', view: 'all', limit: 3 };
      },
      didLoad() {
        return {
          isMore: false,
          state: {}
        };
      }
    };
    this.create = () => this.db._createInternalPaginatedProxy(this.owner, this.opts).model(true);
    this.insert = (count=10) => {
      let promises = [];
      for(let i = 0; i < count; i++) {
        promises.push(this.docs.save({ _id: `duck:${i}` }));
      }
      return all(promises);
    }
    await this.recreate();
    await this.docs.get('design').save('main', ddoc);
  }
});

test('exists', function(assert) {
  let proxy = this.create();
  assert.ok(proxy);
  assert.ok(proxy._internal);
});

test('load', async function(assert) {
  await this.insert();
  let proxy = this.create();
  await proxy.load();
  assert.equal(proxy.get('length'), 3);
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { addTodo } from '../actions/todosAction';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';

const AddTodo = ({ dispatch }) => {
  const style = {
    margin: 12
  };

  const addTodoItem = () => {
    let inputField = document.getElementById('addTodoText');
    dispatch(addTodo(inputField.value));
    inputField.value = '';
  };

  return (

      <TextField
        hintText="Enter todo item"
        id="addTodoText"
        aria-label="Enter todo item"
        onKeyPress= { (e) => {
          if (e.key === 'Enter') {
            addTodoItem();
          }
        }} />
      <RaisedButton
        aria-label="Add Item"
        label="Add"
        style={ style }
        primary={ true }
        onClick={ () => {
          addTodoItem();
        }} />

  );
};

AddTodo.propTypes = {
  dispatch: PropTypes.func.isRequired
};

export default connect()(AddTodo);
<commit_msg>Removed unecessary func call on component<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { addTodo } from '../actions/todosAction';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';

const AddTodo = ({ dispatch }) => {
  const style = {
    margin: 12
  };

  const addTodoItem = () => {
    let inputField = document.getElementById('addTodoText');
    dispatch(addTodo(inputField.value));
    inputField.value = '';
  };

  return (

      <TextField
        hintText="Enter todo item"
        id="addTodoText"
        aria-label="Enter todo item"
        onKeyPress= { (e) => {
          if (e.key === 'Enter') {
            addTodoItem();
          }
        }} />
      <RaisedButton
        aria-label="Add Item"
        label="Add"
        style={ style }
        primary={ true }
        onClick={ addTodoItem }
      />

  );
};

AddTodo.propTypes = {
  dispatch: PropTypes.func.isRequired
};

export default connect()(AddTodo);
<|endoftext|>


<commit_before>'use strict';
import React from 'react';

import GMap from './GMap';
// import vCard from '../../public/resources/Ralph Isenrich CFA.vcf';

const Contact = () => (

Please contact us to discuss investment opportunities

              {[
                <i key={ `FAIcon_User` } className="fa fa-user-circle" />,
                `Ralph Isenrich, CFA`
              ]}

              {[
                <i key={ `FAIcon_Envelope` } className="fa fa-envelope" />,
                `ralph@daviepoplarcapital.com`
              ]}

              {[
                <i key={ `FAIcon_Phone` } className="fa fa-phone-square" />,
                `(m) +1 (919) 334-8367`
              ]}

            {[
              <i key={ `FAIcon_AddressCard` } className="fa fa-address-card invert" />,
              `Download vCard`
            ]}

Davie Poplar Capital, LLC.

185 Windchime Ct., Suite 201

Raleigh, NC 27615

            {[
              <i key={ `FAIcon_Newspaper` } className="fa fa-newspaper-o invert" />,
              `Subscribe for News & Updates`
            ]}

    <GMap />

);

export default Contact;

// ralph@daviepoplarcapital.com
 -->

// Download vCard

// G-Maps URL:  https://www.google.com/maps/place/
// Ferro+Management+Group,+185+Wind+Chime+Ct+%23+201,+Raleigh,+NC+27615/@35.8761861,-78.6425212,19z/data=!3m1!4b1!4m2!3m1!1s0x89ac58133cd16d47:0xb239755f849eed8d?hl=en

// onmouseenter="ent()" onmouseleave="leave()">

//

//

//
Ralph Isenrich, CFA

//
//        revertPic('linkedIn_Glyph') } />
//
//

//

//
ralph@daviepoplarcapital.com

//
//      revertPic('email_Glyph') } />
//
//

//
(m) +1 (919) 334-8367

//

//   185 Windchime Ct, Suite 201
//   Raleigh NC 27615 US
//

<commit_msg>refactor: Map JSON data to contact info<commit_after>'use strict';
import React from 'react';

import GMap from './GMap';
import ContactInfo from '../constants/json/ContactInfoData.json';
import LocationInfo from '../constants/json/LocationInfoData.json';
// import vCard from '../../public/resources/Ralph Isenrich CFA.vcf';

const INFO_MAP = new Map([
  ['name', 'user-circle'],
  ['email', 'envelope'],
  ['phone', 'phone-square']
]);

const renderContactIcons = (datum) => datum.scheme ? (

    <i className={ `fa fa-${INFO_MAP.get(datum.type)}` } />

) : datum.type ? (
  <i className={ `fa fa-${INFO_MAP.get(datum.type)}` } />
) : null;

const renderContactInfo = (data) => data.map((datum, index) =>
  <p key={ `ContactInfo_${index}` }>
    {[
      renderContactIcons(datum),
      datum.hasOwnProperty('value') ? datum.value : datum
    ]}

);

const Contact = () => (

Please contact us to discuss investment opportunities

{ renderContactInfo(ContactInfo) }

            {[
              <i
                key={ `FAIcon_AddressCard` }
                className="fa fa-address-card invert" />,
              'Download vCard'
            ]}

            { renderContactInfo(LocationInfo) }

            {[
              <i
                key={ `FAIcon_Newspaper` }
                className="fa fa-newspaper-o invert" />,
              'Subscribe for News & Updates'
            ]}

    <GMap />

);

export default Contact;

// Download vCard

// G-Maps URL:  https://www.google.com/maps/place/
// Ferro+Management+Group,+185+Wind+Chime+Ct+%23+201,+Raleigh,+NC+27615/@35.8761861,-78.6425212,19z/data=!3m1!4b1!4m2!3m1!1s0x89ac58133cd16d47:0xb239755f849eed8d?hl=en
<|endoftext|>


<commit_before>import Ember from 'ember';
import fetch from 'fetch';
const { service } = Ember.inject;
import ENV from 'bracco/config/environment';

export default Ember.Component.extend({
  currentUser: service(),

  url: null,

  didReceiveAttrs() {
    this._super(...arguments);

    this.fetchURL();
  },

  fetchURL() {
    let self = this;
    let url = ENV.API_URL + '/dois/' + this.get('model').get('doi') + '/get-url';

    fetch(url, {
      headers: {
        'Authorization': 'Bearer ' + self.get('currentUser').get('jwt'),
        'Accept': 'application/vnd.api+json'
      }
    }).then(function(response) {
      if (response.ok) {
        return response.json().then(function(data) {
          if (data.errors) {
            let message = data.errors[0].title;
            return message;
          } else {
            self.set('url', data.url);
          }
        });
      } else {
        Ember.Logger.assert(false, response);
      }
    }).catch(function(error) {
      Ember.Logger.assert(false, error);
    });
  }
});
<commit_msg>update model url in doi form. datacite/datacite#506<commit_after>import Ember from 'ember';
import fetch from 'fetch';
const { service } = Ember.inject;
import ENV from 'bracco/config/environment';

export default Ember.Component.extend({
  currentUser: service(),

  url: null,

  didReceiveAttrs() {
    this._super(...arguments);

    this.fetchURL();
  },

  fetchURL() {
    let self = this;
    let url = ENV.API_URL + '/dois/' + this.get('model').get('doi') + '/get-url';

    fetch(url, {
      headers: {
        'Authorization': 'Bearer ' + self.get('currentUser').get('jwt'),
        'Accept': 'application/vnd.api+json'
      }
    }).then(function(response) {
      if (response.ok) {
        return response.json().then(function(data) {
          if (data.errors) {
            let message = data.errors[0].title;
            return message;
          } else {
            self.set('url', data.url);
            self.get('model').set('url', data.url);
          }
        });
      } else {
        Ember.Logger.assert(false, response);
      }
    }).catch(function(error) {
      Ember.Logger.assert(false, error);
    });
  }
});
<|endoftext|>


<commit_before>
var loop;
var level;

function parse(str) {

    var i = 0;

     loop = setInterval(function () {

        i++;

        console.log("ROUND " + i + " ------------------");

        check();

        switch (Player.checkNextField(Map.map)) {
            case 'r':
                var audio = new Audio('assets/sounds/coin.mp3');
                audio.play();
                break;
            case 'e':
                console.log("yo");
                Player.canMove = false;
                break;
            default:
                break;
        }

        eval(str);

        Display.draw(Map.map);

        if(i>25){ clearInterval(loop);}

    }, 500);

}

function check() {
    if (Player.getX() === 10){

        clearInterval(loop);
        level++;
        console.log("Victory!");
        Map.map.splice(0,Map.map.length);
        loadMap(level);
    }
    if(Player.health <= 0){
        clearInterval(loop);
        console.log("Defeat!");
        Map.map.splice(0,Map.map.length);
        loadMap(level);
    }
}

function victory() {

}

function loadMap(level) {
    $.when(
        $.get("assets/levels/level" + level + ".txt")
    ).then(function (response) {
        Player.constructor();
        Display.setPlayer = Player;
        console.log("in loadmap");
            Map.parseLevel(response);
        Display.draw(Map.map);
    });
};

$(function () {
   level = 1;
    loadMap(level);
});

<commit_msg>Clear console<commit_after>
var loop;
var level;

function parse(str) {

    var i = 0;

     loop = setInterval(function () {

        i++;

        console.log("ROUND " + i + " ------------------");

        check();

        switch (Player.checkNextField(Map.map)) {
            case 'r':
                var audio = new Audio('assets/sounds/coin.mp3');
                audio.play();
                break;
            case 'e':
                console.log("yo");
                Player.canMove = false;
                break;
            default:
                break;
        }

        eval(str);

        Display.draw(Map.map);

        if(i>25){ clearInterval(loop);}

    }, 500);

}

function check() {
    if (Player.getX() === 10){

        clearInterval(loop);
        level++;
        $('#console-log-text').text('');
        console.log("Victory!");
        Map.map.splice(0,Map.map.length);
        loadMap(level);
    }
    if(Player.health <= 0){
        clearInterval(loop);
        $('#console-log-text').text('');
        console.log("Defeat!");
        Map.map.splice(0,Map.map.length);
        loadMap(level);
    }
}

function victory() {

}

function loadMap(level) {
    $.when(
        $.get("assets/levels/level" + level + ".txt")
    ).then(function (response) {
        Player.constructor();
        Display.setPlayer = Player;
        console.log("in loadmap");
            Map.parseLevel(response);
        Display.draw(Map.map);
    });
};

$(function () {
   level = 1;
    loadMap(level);
});

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Utils from '../utils';
import Task from '../task';
import colormap from 'colormap';
import { Handler, HandlerPopup } from './handler';
import classNames from 'classnames';

/* These are mostly for drawing */
const NUM_COLORS = 32;
const COLORS = colormap({
  colormap: 'rainbow-soft',   // pick a builtin colormap or add your own
  nshades: NUM_COLORS       // how many divisions
});
function hashCode(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
        hash = ~~(((hash << 5) - hash) + str.charCodeAt(i));
    }
    return Math.abs(hash);
}
function getColor2(str) {
  return COLORS[hashCode(str) % NUM_COLORS];
}
function getColor(logEntry) {
  const hue = Task.getProjectColor(logEntry.project);
  return 'hsl(' + hue + ',100%,85%)';
}
function getStyle(logEntry) {
  const hue = Task.getProjectColor(logEntry.project);
}
function hoursToMS(h) {
    return h * 60 * 60 * 1000;
}
function roundToHour(t, offset) {
    let d = new Date(t);
    d.setMinutes(0);
    d.setSeconds(0);
    d.setMilliseconds(0);
    if (offset) {
      d.setHours(d.getHours() + offset);
    }
    return d;
}
function getDurationMS(t1, t2) {
  try {
    const duration = Math.floor((new Date(t2) - new Date(t1)));
    if (isNaN(duration)) {
      throw "NaN!";
    }
    // console.log("" + t2 + " - " + t1 + " = " + duration);
    return duration;
  }
  catch (e) {
    console.log("" + t1 + " - " + t2 + " = " + e);
    return 0;
  }
}
/* Format a short time, eg. '6a', '9p'*/
function toShortTime(h) {
    const am_pm = (h < 12) ? 'a' : 'p';
    const hour = (h % 12) || 12;
    return '' + hour + am_pm;
}

class GroupChart {

    constructor(id, startTime, endTime) {
        this.id = id;
        this.startTime = roundToHour(startTime, 0);
        this.endTime = roundToHour(endTime, 1);
        this.durationMS = getDurationMS(this.startTime, this.endTime);
    }

    /* Create a row for the given entry. It is absolutely positioned
     * and sized in proportion to its duration.
     */
    createChartRow(logEntry, i) {
        const offset = this.chartHeight(this.getLogOffsetMS(logEntry.startTime));
        const height = Math.max(
            this.chartHeight(getDurationMS(logEntry.startTime, logEntry.endTime)),
            Math.min(2, 100-offset));
        const style = {
            bottom: '' + offset + '%',
            height: '' + height + '%',
            background: getColor(logEntry)
        };
        return (

        );
    }

    /* Height in px for a chart of duration ms */
    chartHeight(duration) {
        const height = parseInt((duration*100)/this.durationMS);
        if (isNaN(height)) {
            console.log("NaN for " + duration + " / " + this.durationMS);
        }
        return height;
    }
    /* Get offset from start time */
    getLogOffsetMS(logTime) {
        return getDurationMS(this.startTime, logTime);
    }
    formatMarkerLabel(h) {
        return toShortTime(h);
        /*
        if (h == 12) { return 'n'; }
        if (h == startTime) { return toShortTime(h); }
        if (h == endTime) { return toShortTime(h); }
        return '';
        */
    }
    createMarker(h, i) {
        const isTop = (h == this.endTime.getHours());
        const className = classNames(
          'chart-time-label',
          { 'chart-time-label-top': isTop }
        );
        const style = isTop ?
            {top:"0%"} :
            {bottom:""+this.chartHeight(hoursToMS(h-this.startTime.getHours()))+'%'};
        const label = this.formatMarkerLabel(h);
        return (

{label}

        );
    }
    createMarkers(numRows) {
        const chartMarkers = [];
        const hoursPerMarker = parseInt(numRows/2);
        const t = new Date(this.startTime);
        while (t <= this.endTime) {
          chartMarkers.push(this.createMarker(t.getHours(), chartMarkers.length));
          t.setHours(t.getHours() + 1);
        }
        return chartMarkers;
    }
}

/**
 * Show the work log
 * <Log log=[log entries] />
 */
export default class Log extends Component {

  constructor(props) {
      super(props);
      this.state = {
          edit: '',
          editStart: '',
          editEnd: ''
      };
  }

  shouldComponentUpdate(nextProps, nextState) {
    try {
      if (nextProps.log[0].endTime != this.props.log[0].endTime) { return true; }
    } catch (e) {}
    return (nextState.edit != this.state.edit);
  }

  getDuration(t1, t2) {
    return getDurationMS(t1, t2)/1000;
  }

  getLogEntryId(logEntry) {
    return logEntry.taskId + '.' + logEntry.startTime;
  }

  edit(logEntryId) {
    this.setState({
      edit: logEntryId
    });
  }

  render() {
    // 2017-02-24
    // 12:30 - 2:30 Documentation #21 35m (34%)
    // 2:30 - 4:00 Github Style 90m (100%)

    console.log("Rendering log");

    // grouped in chunks
    const groups = [];
    const entriesByGroup = {};
    let lastEntry = null;

    const mergeGapSize = 10*60;
    const groupGapSize = 6*60*60;

    this.props.log.forEach( (logEntry, i) => {
      const gap = (lastEntry ?
        this.getDuration(logEntry.endTime, lastEntry.startTime) :
        -1);
      // console.log("Gap:", gap, Utils.getDayTime(logEntry.endTime), Utils.getDayTime(lastEntry && lastEntry.startTime));
      if (lastEntry
          && lastEntry.taskId == logEntry.taskId
          && gap > 0 && gap < mergeGapSize) {
        // Merge with previous entry
        console.log("Merging log");
        lastEntry.startTime = logEntry.startTime;
        lastEntry.timeElapsed += logEntry.timeElapsed;
        lastEntry.taskName += "*";
      } else {
        // create new group
        if (!lastEntry || gap > groupGapSize) {
          console.log("Creating new group");
          groups.push([]);
        }
        // Add a copy since we might merge things into it
        lastEntry = Object.assign({}, logEntry);
        groups[groups.length - 1].push(lastEntry);
      }
    });
    const rows = [];
    groups.forEach((group, groupIdx) => {
      // dayEntries.reverse();
      const groupStats = {
        numEntries: group.length,
        startTime: null,
        endTime: null,
        duration: 0,
        worked: 0
      };
      // Cumulative stats
      group.forEach( (logEntry) => {
        if (!groupStats.startTime || groupStats.startTime > logEntry.startTime) {
          groupStats.startTime = logEntry.startTime;
        }
        if (!groupStats.endTime || groupStats.endTime < logEntry.endTime) {
          groupStats.endTime = logEntry.endTime;
        }
        groupStats.worked += logEntry.timeElapsed;
      });
      groupStats.duration = this.getDuration(groupStats.startTime, groupStats.endTime);
      const timespan = Utils.getDayTime(groupStats.startTime) + " - " + Utils.getDayTime(groupStats.endTime);
      rows.push((

          {timespan}

            {Utils.formatTimespan(groupStats.worked, true)}
             ({Utils.formatTimespan(groupStats.duration, true)})

      ));

      const groupChart = new GroupChart(groupIdx, groupStats.startTime, groupStats.endTime);
      const chartMarkers = groupChart.createMarkers(group.length);

      // The log entries
      const subrows = [];
      group.forEach( (logEntry, i) => {
        const label = logEntry.taskName || logEntry.task;
        const duration = this.getDuration(logEntry.startTime, logEntry.endTime);
        const utilization = Math.floor((logEntry.timeElapsed * 100) / duration);
        const timespan = "" + Utils.getTime(logEntry.startTime) + " - " + Utils.getTime(logEntry.endTime);
        const chartRow = groupChart.createChartRow(logEntry, i);
        const style = {
          background: getColor(logEntry)
        };
        const logEntryId = this.getLogEntryId(logEntry);
        const editing = (logEntryId == this.state.edit);
        const edit = () => {
          console.log("Editing " + logEntryId);
          this.edit(logEntryId);
        };
        const className = classNames(
          'log-entry',
          { 'editing': editing }
        );
        const title = Utils.getDayTime(logEntry.startTime) + " - " + Utils.getDayTime(logEntry.endTime);
        subrows.push((

              {chartRow}

            {label}
            {timespan}

              {Utils.formatTimespan(logEntry.timeElapsed, true)}
              {Utils.formatTimespan(duration, true)}
              {utilization}%

        ));
      });

      rows.push((

            {chartMarkers}

          {subrows}

      ));

    });

    return (

        {rows}

    );
  }
}
<commit_msg>Drawing fix<commit_after>import React, { Component } from 'react';
import Utils from '../utils';
import Task from '../task';
import colormap from 'colormap';
import { Handler, HandlerPopup } from './handler';
import classNames from 'classnames';

/* These are mostly for drawing */
const NUM_COLORS = 32;
const COLORS = colormap({
  colormap: 'rainbow-soft',   // pick a builtin colormap or add your own
  nshades: NUM_COLORS       // how many divisions
});
function hashCode(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
        hash = ~~(((hash << 5) - hash) + str.charCodeAt(i));
    }
    return Math.abs(hash);
}
function getColor2(str) {
  return COLORS[hashCode(str) % NUM_COLORS];
}
function getColor(logEntry) {
  const hue = Task.getProjectColor(logEntry.project);
  return 'hsl(' + hue + ',100%,85%)';
}
function getStyle(logEntry) {
  const hue = Task.getProjectColor(logEntry.project);
}
function hoursToMS(h) {
    return h * 60 * 60 * 1000;
}
function roundToHour(t, offset) {
    let d = new Date(t);
    d.setMinutes(0);
    d.setSeconds(0);
    d.setMilliseconds(0);
    if (offset) {
      d.setHours(d.getHours() + offset);
    }
    return d;
}
function getDurationMS(t1, t2) {
  try {
    const duration = Math.floor((new Date(t2) - new Date(t1)));
    if (isNaN(duration)) {
      throw "NaN!";
    }
    // console.log("" + t2 + " - " + t1 + " = " + duration);
    return duration;
  }
  catch (e) {
    console.log("" + t1 + " - " + t2 + " = " + e);
    return 0;
  }
}
/* Format a short time, eg. '6a', '9p'*/
function toShortTime(h) {
    const am_pm = (h < 12) ? 'a' : 'p';
    const hour = (h % 12) || 12;
    return '' + hour + am_pm;
}

class GroupChart {

    constructor(id, startTime, endTime) {
        this.id = id;
        this.startTime = roundToHour(startTime, 0);
        this.endTime = roundToHour(endTime, 1);
        this.durationMS = getDurationMS(this.startTime, this.endTime);
    }

    /* Create a row for the given entry. It is absolutely positioned
     * and sized in proportion to its duration.
     */
    createChartRow(logEntry, i) {
        const offset = this.chartHeight(this.getLogOffsetMS(logEntry.startTime));
        const height = Math.max(
            this.chartHeight(getDurationMS(logEntry.startTime, logEntry.endTime)),
            Math.min(2, 100-offset));
        const style = {
            bottom: '' + offset + '%',
            height: '' + height + '%',
            background: getColor(logEntry)
        };
        return (

        );
    }

    /* Height in px for a chart of duration ms */
    chartHeight(duration) {
        const height = parseInt((duration*100)/this.durationMS);
        if (isNaN(height)) {
            console.log("NaN for " + duration + " / " + this.durationMS);
        }
        return height;
    }
    /* Get offset from start time */
    getLogOffsetMS(logTime) {
        return getDurationMS(this.startTime, logTime);
    }
    formatMarkerLabel(h) {
        return toShortTime(h);
        /*
        if (h == 12) { return 'n'; }
        if (h == startTime) { return toShortTime(h); }
        if (h == endTime) { return toShortTime(h); }
        return '';
        */
    }
    createMarker(h, i) {
        const isTop = (h == this.endTime.getHours());
        const className = classNames(
          'chart-time-label',
          { 'chart-time-label-top': isTop }
        );
        const style = isTop ?
            {top:"0%"} :
            {bottom:""+this.chartHeight(hoursToMS(h-this.startTime.getHours()))+'%'};
        const label = this.formatMarkerLabel(h);
        return (

{label}

        );
    }
    createMarkers(numRows) {
        const chartMarkers = [];
        const hoursPerMarker = parseInt(numRows/2);
        const t = new Date(this.startTime);
        while (t <= this.endTime) {
          chartMarkers.push(this.createMarker(t.getHours(), chartMarkers.length));
          t.setHours(t.getHours() + 1);
        }
        return chartMarkers;
    }
}

/**
 * Show the work log
 * <Log log=[log entries] />
 */
export default class Log extends Component {

  constructor(props) {
      super(props);
      this.state = {
          edit: '',
          editStart: '',
          editEnd: '',
          lastTime: null,
      };
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (!nextState.popup) { return false; }
    try {
      if (nextProps.log[0].endTime != this.state.lastTime) {
        this.setState({
          lastTime: nextProps.log[0].endTime
        });
        console.log("updating log");
        return true;
      }
    } catch (e) {}
    return (nextState.edit != this.state.edit);
  }

  getDuration(t1, t2) {
    return getDurationMS(t1, t2)/1000;
  }

  getLogEntryId(logEntry) {
    return logEntry.taskId + '.' + logEntry.startTime;
  }

  edit(logEntryId) {
    this.setState({
      edit: logEntryId
    });
  }

  render() {
    // 2017-02-24
    // 12:30 - 2:30 Documentation #21 35m (34%)
    // 2:30 - 4:00 Github Style 90m (100%)

    console.log("Rendering log");

    // grouped in chunks
    const groups = [];
    const entriesByGroup = {};
    let lastEntry = null;

    const mergeGapSize = 10*60;
    const groupGapSize = 6*60*60;

    this.props.log.forEach( (logEntry, i) => {
      const gap = (lastEntry ?
        this.getDuration(logEntry.endTime, lastEntry.startTime) :
        -1);
      // console.log("Gap:", gap, Utils.getDayTime(logEntry.endTime), Utils.getDayTime(lastEntry && lastEntry.startTime));
      if (lastEntry
          && lastEntry.taskId == logEntry.taskId
          && gap > 0 && gap < mergeGapSize) {
        // Merge with previous entry
        console.log("Merging log");
        lastEntry.startTime = logEntry.startTime;
        lastEntry.timeElapsed += logEntry.timeElapsed;
        lastEntry.taskName += "*";
      } else {
        // create new group
        if (!lastEntry || gap > groupGapSize) {
          console.log("Creating new group");
          groups.push([]);
        }
        // Add a copy since we might merge things into it
        lastEntry = Object.assign({}, logEntry);
        groups[groups.length - 1].push(lastEntry);
      }
    });
    const rows = [];
    groups.forEach((group, groupIdx) => {
      // dayEntries.reverse();
      const groupStats = {
        numEntries: group.length,
        startTime: null,
        endTime: null,
        duration: 0,
        worked: 0
      };
      // Cumulative stats
      group.forEach( (logEntry) => {
        if (!groupStats.startTime || groupStats.startTime > logEntry.startTime) {
          groupStats.startTime = logEntry.startTime;
        }
        if (!groupStats.endTime || groupStats.endTime < logEntry.endTime) {
          groupStats.endTime = logEntry.endTime;
        }
        groupStats.worked += logEntry.timeElapsed;
      });
      groupStats.duration = this.getDuration(groupStats.startTime, groupStats.endTime);
      const timespan = Utils.getDayTime(groupStats.startTime) + " - " + Utils.getDayTime(groupStats.endTime);
      rows.push((

          {timespan}

            {Utils.formatTimespan(groupStats.worked, true)}
             ({Utils.formatTimespan(groupStats.duration, true)})

      ));

      const groupChart = new GroupChart(groupIdx, groupStats.startTime, groupStats.endTime);
      const chartMarkers = groupChart.createMarkers(group.length);

      // The log entries
      const subrows = [];
      group.forEach( (logEntry, i) => {
        const label = logEntry.taskName || logEntry.task;
        const duration = this.getDuration(logEntry.startTime, logEntry.endTime);
        const utilization = Math.floor((logEntry.timeElapsed * 100) / duration);
        const timespan = "" + Utils.getTime(logEntry.startTime) + " - " + Utils.getTime(logEntry.endTime);
        const chartRow = groupChart.createChartRow(logEntry, i);
        const style = {
          background: getColor(logEntry)
        };
        const logEntryId = this.getLogEntryId(logEntry);
        const editing = (logEntryId == this.state.edit);
        const edit = () => {
          console.log("Editing " + logEntryId);
          this.edit(logEntryId);
        };
        const className = classNames(
          'log-entry',
          { 'editing': editing }
        );
        const title = Utils.getDayTime(logEntry.startTime) + " - " + Utils.getDayTime(logEntry.endTime);
        subrows.push((

              {chartRow}

            {label}
            {timespan}

              {Utils.formatTimespan(logEntry.timeElapsed, true)}
              {Utils.formatTimespan(duration, true)}
              {utilization}%

        ));
      });

      rows.push((

            {chartMarkers}

          {subrows}

      ));

    });

    return (

        {rows}

    );
  }
}
<|endoftext|>


<commit_before>require('dashboard/core');
require('dashboard/model');

Dashboard.GitHubAdpater = DS.Adapter.extend({
  PREFIX: 'https://api.github.com',

  ajax: function(url, target, callback) {
    Ember.$.ajax({
      url: this.PREFIX + url,
      dataType: 'jsonp',
      context: this,
      success: function(data) {
        this._ajaxSuccess(data, target, callback);
      }
    });
  },

  _ajaxSuccess: function(response, target, callback) {
    this._updateLimits(response);
    if (Ember.typeOf(target) === 'function') {
      target.apply(this, [response.data]);
    } else {
      Ember.tryInvoke(target, callback, [response.data]);
    }
  },

  _updateLimits: function(response) {
    if (response.meta) {
      this.set('remaining', response.meta['X-RateLimit-Remaining']);
      this.set('limit', response.meta['X-RateLimit-Limit']);
    }
  },

  findQuery: function(store, type, query, modelArray) {
    if (Dashboard.Repository.detect(type) && 'watched' === query.type) {
      this.watchedRepositories(query.username, modelArray, 'load');
    }
  },

  watchedRepositories: function(username, target, callback) {
    this.ajax('/users/%@/watched'.fmt(username), target, callback);
  }
});<commit_msg>Implement find for Repository on GitHubAdpater<commit_after>require('dashboard/core');
require('dashboard/model');

Dashboard.GitHubAdpater = DS.Adapter.extend({
  PREFIX: 'https://api.github.com',

  ajax: function(url, target, callback) {
    Ember.$.ajax({
      url: this.PREFIX + url,
      dataType: 'jsonp',
      context: this,
      success: function(data) {
        this._ajaxSuccess(data, target, callback);
      }
    });
  },

  _ajaxSuccess: function(response, target, callback) {
    this._updateLimits(response);
    if (Ember.typeOf(target) === 'function') {
      target.apply(this, [response.data]);
    } else {
      Ember.tryInvoke(target, callback, [response.data]);
    }
  },

  _updateLimits: function(response) {
    if (response.meta) {
      this.set('remaining', response.meta['X-RateLimit-Remaining']);
      this.set('limit', response.meta['X-RateLimit-Limit']);
    }
  },

  find: function(store, type, id) {
    if (Dashboard.Repository.detect(type)) {
      this.ajax('/repos/%@'.fmt(id), function(data) {
        store.load(type, id, data);
      });
    }
  },

  findQuery: function(store, type, query, modelArray) {
    if (Dashboard.Repository.detect(type) && 'watched' === query.type) {
      this.watchedRepositories(query.username, modelArray, 'load');
    }
  },

  watchedRepositories: function(username, target, callback) {
    this.ajax('/users/%@/watched'.fmt(username), target, callback);
  }
});<|endoftext|>


<commit_before>
var Joi = require('joi');
var routes = require('./routes');

var queue = {
	params: Joi.object().keys({
		name: Joi.string().required()
	}),
	routes: Joi.any()
};

module.exports = queue;<commit_msg>Поменял схему очереди<commit_after>var Joi = require('joi');
var routes = require('./routes');

var queue = {
    params: Joi.object().keys({
        name: Joi.string().required(),
        operators: Joi.object().keys({
            static: Joi.array().items(
                Joi.object().keys({
                    type: Joi.string().required().allow(['peer', 'outbound']),
                    id: Joi.string().required()
                })
            ),
            dynamic: Joi.array().items(
                Joi.object().keys({
                    type: Joi.string().required().allow(['user']),
                    id: Joi.string().required()
                })
            )
        })
    }),
    routes: Joi.any()
};

module.exports = queue;<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2013 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
 *
 *     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.
 */

/** Create a sub-context, populating with bindings from opt_args. **/
function sub(opt_args, opt_name) {
//  var sub = Object.create(this);
  var sub = {__proto__: this};

  if ( opt_args ) for ( var key in opt_args ) {
    if ( opt_args.hasOwnProperty(key) ) {
      // It looks like the chrome debug console is overwriting sub.window
      // but this prevents it.
      Object.defineProperty(
        sub,
        key,
        {
          value: opt_args[key],
          writable: key !== 'window',
          configurable: true
        }
      );
    }
  }
  if ( opt_name ) {
    sub.NAME = opt_name;
    sub.toString = function() { return 'CONTEXT(' + opt_name + ')'; };
  }
  return sub;
}

function subWindow(w, opt_name, isBackground) {
  if ( ! w ) return this.sub();

  var document = this.subDocument ? this.subDocument(w.document) : w.document;
  var installedModels = new WeakMap();

  var map = {
    registerModel: function(model, opt_name) {
      if ( model.getPrototype && model.getPrototype().installInDocument && ! installedModels.has(model) ) {
        // console.log('installing model: ', model.name);
        installedModels.set(model, true);
        model.getPrototype().installInDocument(this, document);
      }
      return GLOBAL.registerModel.call(this, model, opt_name);
    },
    addStyle: function(css) {
      var s = document.createElement('style');
      s.innerHTML = css;
      this.document.head.appendChild(s);
    },
    isBackground: !!isBackground,
    window: w,
    document: document,
    console: w.console,
    log: w.console.log.bind(console),
    warn: w.console.warn.bind(console),
    info: w.console.info.bind(console),
    error: w.console.error.bind(console),
    $: function(id) {
      if ( document.FOAM_OBJECTS && document.FOAM_OBJECTS[id] )
        return document.FOAM_OBJECTS[id];

      return document.getElementById(id);
    },
    $$: function(cls) {
      return document.getElementsByClassName(cls);
    },
    dynamic: function(fn, opt_fn) { Events.dynamic(fn, opt_fn, this); },
    animate: function(duration, fn, opt_interp, opt_onEnd) {
      Movement.animate(duration, fn, opt_interp, opt_onEnd, this);
    },
    // TODO(kgr): rename this to onAnimation(), why was this removed?
//    animate: function(fn, opt_fn) { Events.dynamic(fn, opt_fn, this); },
    memento: w.WindowHashValue && w.WindowHashValue.create({window: w}),
    setTimeout: w.setTimeout.bind(w),
    clearTimeout: w.clearTimeout.bind(w),
    setInterval: w.setInterval.bind(w),
    clearInterval: w.clearInterval.bind(w),
    requestAnimationFrame: function(f) { if ( ! w.requestAnimationFrame ) debugger; return w.requestAnimationFrame(f); },
    cancelAnimationFrame: w.cancelAnimationFrame && w.cancelAnimationFrame.bind(w)
  };

  if ( isBackground ) {
    map.requestAnimationFrame = function(f) { return w.setTimeout(f, 16); };
    map.cancelAnimationFrame = map.clearTimeout;
  }

  var X = this.sub(map, opt_name);
  w.X = X;
  return X;
}

// Using the existence of 'process' to determine that we're running in Node.
var X = this.subWindow(window, 'DEFAULT WINDOW', typeof process === 'object').sub({IN_WINDOW: false});

function registerModel(model, opt_name) {
  /*
  if ( model.X === this ) {
    this[model.name] = model;

    return model;
  }
  */
  var thisX = this;

  var thisModel = this === GLOBAL ? model : {
    __proto__: model,
      create: function(args, opt_X) {
        return this.__proto__.create(args, thisX);
      }
  };

  Object.defineProperty(
    this,
    opt_name || model.name,
    {
      get: function() {
        return ( this === thisX ) ? thisModel : this.registerModel(model);
      },
      configurable: true
    }
  );

  return thisModel;
};

var registerFactory = function(model, factory) {
  // TODO
};

var registerModelForModel = function(modelType, targetModel, model) {

};

var registerFactoryForModel = function(factory, targetModel, model) {

};
<commit_msg>Fix for context.animate(), wasn't returning value.<commit_after>/**
 * @license
 * Copyright 2013 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
 *
 *     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.
 */

/** Create a sub-context, populating with bindings from opt_args. **/
function sub(opt_args, opt_name) {
//  var sub = Object.create(this);
  var sub = {__proto__: this};

  if ( opt_args ) for ( var key in opt_args ) {
    if ( opt_args.hasOwnProperty(key) ) {
      // It looks like the chrome debug console is overwriting sub.window
      // but this prevents it.
      Object.defineProperty(
        sub,
        key,
        {
          value: opt_args[key],
          writable: key !== 'window',
          configurable: true
        }
      );
    }
  }
  if ( opt_name ) {
    sub.NAME = opt_name;
    sub.toString = function() { return 'CONTEXT(' + opt_name + ')'; };
  }
  return sub;
}

function subWindow(w, opt_name, isBackground) {
  if ( ! w ) return this.sub();

  var document = this.subDocument ? this.subDocument(w.document) : w.document;
  var installedModels = new WeakMap();

  var map = {
    registerModel: function(model, opt_name) {
      if ( model.getPrototype && model.getPrototype().installInDocument && ! installedModels.has(model) ) {
        // console.log('installing model: ', model.name);
        installedModels.set(model, true);
        model.getPrototype().installInDocument(this, document);
      }
      return GLOBAL.registerModel.call(this, model, opt_name);
    },
    addStyle: function(css) {
      var s = document.createElement('style');
      s.innerHTML = css;
      this.document.head.appendChild(s);
    },
    isBackground: !!isBackground,
    window: w,
    document: document,
    console: w.console,
    log: w.console.log.bind(console),
    warn: w.console.warn.bind(console),
    info: w.console.info.bind(console),
    error: w.console.error.bind(console),
    $: function(id) {
      if ( document.FOAM_OBJECTS && document.FOAM_OBJECTS[id] )
        return document.FOAM_OBJECTS[id];

      return document.getElementById(id);
    },
    $$: function(cls) {
      return document.getElementsByClassName(cls);
    },
    dynamic: function(fn, opt_fn) { Events.dynamic(fn, opt_fn, this); },
    animate: function(duration, fn, opt_interp, opt_onEnd) {
      return Movement.animate(duration, fn, opt_interp, opt_onEnd, this);
    },
    // TODO(kgr): rename this to onAnimation(), why was this removed?
//    animate: function(fn, opt_fn) { Events.dynamic(fn, opt_fn, this); },
    memento: w.WindowHashValue && w.WindowHashValue.create({window: w}),
    setTimeout: w.setTimeout.bind(w),
    clearTimeout: w.clearTimeout.bind(w),
    setInterval: w.setInterval.bind(w),
    clearInterval: w.clearInterval.bind(w),
    requestAnimationFrame: function(f) { if ( ! w.requestAnimationFrame ) debugger; return w.requestAnimationFrame(f); },
    cancelAnimationFrame: w.cancelAnimationFrame && w.cancelAnimationFrame.bind(w)
  };

  if ( isBackground ) {
    map.requestAnimationFrame = function(f) { return w.setTimeout(f, 16); };
    map.cancelAnimationFrame = map.clearTimeout;
  }

  var X = this.sub(map, opt_name);
  w.X = X;
  return X;
}

// Using the existence of 'process' to determine that we're running in Node.
var X = this.subWindow(window, 'DEFAULT WINDOW', typeof process === 'object').sub({IN_WINDOW: false});

function registerModel(model, opt_name) {
  /*
  if ( model.X === this ) {
    this[model.name] = model;

    return model;
  }
  */
  var thisX = this;

  var thisModel = this === GLOBAL ? model : {
    __proto__: model,
      create: function(args, opt_X) {
        return this.__proto__.create(args, thisX);
      }
  };

  Object.defineProperty(
    this,
    opt_name || model.name,
    {
      get: function() {
        return ( this === thisX ) ? thisModel : this.registerModel(model);
      },
      configurable: true
    }
  );

  return thisModel;
};

var registerFactory = function(model, factory) {
  // TODO
};

var registerModelForModel = function(modelType, targetModel, model) {

};

var registerFactoryForModel = function(factory, targetModel, model) {

};
<|endoftext|>


<commit_before>import {style, inline, Node} from "../model"
import {canLift, canWrap, joinPoint} from "../transform"
import {elt} from "../edit/dom"

export class Item {
  constructor(icon, title) {
    this.icon = icon
    this.title = title
  }
  active() { return false }
  select() { return true }
}

export class LiftItem extends Item {
  constructor(icon, title) {
    super(icon, title || "Move out of block")
  }
  select(pm) {
    let sel = pm.selection
    return canLift(pm.doc, sel.from, sel.to)
  }
  apply(pm) {
    let sel = pm.selection
    pm.apply(pm.tr.lift(sel.from, sel.to))
  }
}

export class JoinItem extends Item {
  constructor(icon, title) {
    super(icon, title || "Join with above block")
  }
  select(pm) {
    return joinPoint(pm.doc, pm.selection.head)
  }
  apply(pm) {
    pm.apply(pm.tr.join(joinPoint(pm.doc, pm.selection.head)))
  }
}

export class SubmenuItem extends Item {
  constructor(icon, title, submenu) {
    super(icon, title)
    this.submenu = submenu || []
  }
  select(pm) { return this.submenu.some(i => i.select(pm)) }
  apply(pm) { return this.submenu.filter(i => i.select(pm)) }
}

export class BlockTypeItem extends Item {
  constructor(icon, title, type, attrs) {
    super(icon, title)
    this.type = type
    this.attrs = attrs
  }
  apply(pm) {
    let sel = pm.selection
    pm.apply(pm.tr.setBlockType(sel.from, sel.to, new Node(this.type, this.attrs)))
  }
}

export class InsertBlockItem extends Item {
  constructor(icon, title, type, attrs) {
    super(icon, title)
    this.type = type
    this.attrs = attrs
  }
  select(pm) {
    let sel = pm.selection
    return sel.empty && pm.doc.path(sel.head.path).type.type == Node.types[this.type].type
  }
  apply(pm) {
    let sel = pm.selection, tr = pm.tr, off = 0
    if (sel.head.offset) {
      tr.split(sel.head)
      off = 1
    }
    pm.apply(tr.insert(sel.head.shorten(null, off), new Node(this.type, this.attrs)))
  }
}

export class WrapItem extends Item {
  constructor(icon, title, type) {
    super(icon, title)
    this.type = type
  }
  select(pm) {
    return canWrap(pm.doc, pm.selection.from, pm.selection.to, new Node(this.type))
  }
  apply(pm) {
    let sel = pm.selection
    pm.apply(pm.tr.wrap(sel.from, sel.to, new Node(this.type)))
  }
}

export class InlineStyleItem extends Item {
  constructor(icon, title, style, dialog) {
    super(icon, title)
    this.style = typeof style == "string" ? {type: style} : style
    this.dialog = dialog
  }
  active(pm) {
    let sel = pm.selection
    return inline.rangeHasInlineStyle(pm.doc, sel.from, sel.to, this.style.type)
  }
  apply(pm) {
    let sel = pm.selection
    if (this.active(pm))
      pm.apply(pm.tr.removeStyle(sel.from, sel.to, this.style.type))
    else if (this.dialog)
      return this.dialog
    else
      pm.apply(pm.tr.addStyle(sel.from, sel.to, this.style))
  }
}

export class ImageItem extends Item {
  constructor(icon, title) {
    super(icon, title || "Insert image")
  }
  apply() { return new ImageDialog }
}

export class Dialog {
  constructor() {
    this.id = Math.floor(Math.random() * 0xffffff).toString(16)
  }

  focus(form) {
    let input = form.querySelector("input")
    if (input) input.focus()
  }

  buildForm(pm) {
    let form = this.form(pm)
    form.appendChild(elt("button", {type: "submit", style: "display: none"}))
    return form
  }
}

export class LinkDialog extends Dialog {
  form() {
    return elt("form", null,
               elt("div", null, elt("input", {name: "href", type: "text", placeholder: "Target URL",
                                              size: 40, autocomplete: "off"})),
               elt("div", null, elt("input", {name: "title", type: "text", placeholder: "Title",
                                              size: 40, autocomplete: "off"})))
  }

  apply(form, pm) {
    let elts = form.elements
    if (!elts.href.value) return
    let sel = pm.selection
    pm.apply(pm.tr.addStyle(sel.from, sel.to, style.link(elts.href.value, elts.title.value)))
  }
}

export class ImageDialog extends Dialog {
  form(pm) {
    let alt = pm.selectedText
    return elt("form", null,
               elt("div", null, elt("input", {name: "src", type: "text", placeholder: "Image URL",
                                              size: 40, autocomplete: "off"})),
               elt("div", null, elt("input", {name: "alt", type: "text", value: alt, autocomplete: "off",
                                              placeholder: "Description / alternative text", size: 40})),
               elt("div", null, elt("input", {name: "title", type: "text", placeholder: "Title",
                                              size: 40, autcomplete: "off"})))
  }

  apply(form, pm) {
    let elts = form.elements
    if (!elts.src.value) return
    let sel = pm.selection, tr = pm.tr
    tr.delete(sel.from, sel.to)
    let attrs = {src: elts.src.value, alt: elts.alt.value, title: elts.title.value}
    pm.apply(tr.insertInline(sel.from, new Node.Inline("image", attrs, null, null)))
  }
}
<commit_msg>Allow autofocus textareas in menu dialogs<commit_after>import {style, inline, Node} from "../model"
import {canLift, canWrap, joinPoint} from "../transform"
import {elt} from "../edit/dom"

export class Item {
  constructor(icon, title) {
    this.icon = icon
    this.title = title
  }
  active() { return false }
  select() { return true }
}

export class LiftItem extends Item {
  constructor(icon, title) {
    super(icon, title || "Move out of block")
  }
  select(pm) {
    let sel = pm.selection
    return canLift(pm.doc, sel.from, sel.to)
  }
  apply(pm) {
    let sel = pm.selection
    pm.apply(pm.tr.lift(sel.from, sel.to))
  }
}

export class JoinItem extends Item {
  constructor(icon, title) {
    super(icon, title || "Join with above block")
  }
  select(pm) {
    return joinPoint(pm.doc, pm.selection.head)
  }
  apply(pm) {
    pm.apply(pm.tr.join(joinPoint(pm.doc, pm.selection.head)))
  }
}

export class SubmenuItem extends Item {
  constructor(icon, title, submenu) {
    super(icon, title)
    this.submenu = submenu || []
  }
  select(pm) { return this.submenu.some(i => i.select(pm)) }
  apply(pm) { return this.submenu.filter(i => i.select(pm)) }
}

export class BlockTypeItem extends Item {
  constructor(icon, title, type, attrs) {
    super(icon, title)
    this.type = type
    this.attrs = attrs
  }
  apply(pm) {
    let sel = pm.selection
    pm.apply(pm.tr.setBlockType(sel.from, sel.to, new Node(this.type, this.attrs)))
  }
}

export class InsertBlockItem extends Item {
  constructor(icon, title, type, attrs) {
    super(icon, title)
    this.type = type
    this.attrs = attrs
  }
  select(pm) {
    let sel = pm.selection
    return sel.empty && pm.doc.path(sel.head.path).type.type == Node.types[this.type].type
  }
  apply(pm) {
    let sel = pm.selection, tr = pm.tr, off = 0
    if (sel.head.offset) {
      tr.split(sel.head)
      off = 1
    }
    pm.apply(tr.insert(sel.head.shorten(null, off), new Node(this.type, this.attrs)))
  }
}

export class WrapItem extends Item {
  constructor(icon, title, type) {
    super(icon, title)
    this.type = type
  }
  select(pm) {
    return canWrap(pm.doc, pm.selection.from, pm.selection.to, new Node(this.type))
  }
  apply(pm) {
    let sel = pm.selection
    pm.apply(pm.tr.wrap(sel.from, sel.to, new Node(this.type)))
  }
}

export class InlineStyleItem extends Item {
  constructor(icon, title, style, dialog) {
    super(icon, title)
    this.style = typeof style == "string" ? {type: style} : style
    this.dialog = dialog
  }
  active(pm) {
    let sel = pm.selection
    return inline.rangeHasInlineStyle(pm.doc, sel.from, sel.to, this.style.type)
  }
  apply(pm) {
    let sel = pm.selection
    if (this.active(pm))
      pm.apply(pm.tr.removeStyle(sel.from, sel.to, this.style.type))
    else if (this.dialog)
      return this.dialog
    else
      pm.apply(pm.tr.addStyle(sel.from, sel.to, this.style))
  }
}

export class ImageItem extends Item {
  constructor(icon, title) {
    super(icon, title || "Insert image")
  }
  apply() { return new ImageDialog }
}

export class Dialog {
  constructor() {
    this.id = Math.floor(Math.random() * 0xffffff).toString(16)
  }

  focus(form) {
    let input = form.querySelector("input, textarea")
    if (input) input.focus()
  }

  buildForm(pm) {
    let form = this.form(pm)
    form.appendChild(elt("button", {type: "submit", style: "display: none"}))
    return form
  }
}

export class LinkDialog extends Dialog {
  form() {
    return elt("form", null,
               elt("div", null, elt("input", {name: "href", type: "text", placeholder: "Target URL",
                                              size: 40, autocomplete: "off"})),
               elt("div", null, elt("input", {name: "title", type: "text", placeholder: "Title",
                                              size: 40, autocomplete: "off"})))
  }

  apply(form, pm) {
    let elts = form.elements
    if (!elts.href.value) return
    let sel = pm.selection
    pm.apply(pm.tr.addStyle(sel.from, sel.to, style.link(elts.href.value, elts.title.value)))
  }
}

export class ImageDialog extends Dialog {
  form(pm) {
    let alt = pm.selectedText
    return elt("form", null,
               elt("div", null, elt("input", {name: "src", type: "text", placeholder: "Image URL",
                                              size: 40, autocomplete: "off"})),
               elt("div", null, elt("input", {name: "alt", type: "text", value: alt, autocomplete: "off",
                                              placeholder: "Description / alternative text", size: 40})),
               elt("div", null, elt("input", {name: "title", type: "text", placeholder: "Title",
                                              size: 40, autcomplete: "off"})))
  }

  apply(form, pm) {
    let elts = form.elements
    if (!elts.src.value) return
    let sel = pm.selection, tr = pm.tr
    tr.delete(sel.from, sel.to)
    let attrs = {src: elts.src.value, alt: elts.alt.value, title: elts.title.value}
    pm.apply(tr.insertInline(sel.from, new Node.Inline("image", attrs, null, null)))
  }
}
<|endoftext|>


<commit_before>describe('su-dropdown', function () {
  let tag, select
  let spyOnOpen = sinon.spy()
  let spyOnClose = sinon.spy()
  let spyOnSelect = sinon.spy()

  let items = [
    {
      label: 'Gender',
      value: null,
      default: true
    },
    {
      label: 'Male',
      value: 1
    },
    {
      label: 'Female',
      value: 2
    },
  ]

  let keys = {
    enter: 13,
    upArrow: 38,
    downArrow: 40
  }

  let fireKeyEvent = function (el, name, keyCode) {
    let eventObj = document.createEvent("Events")
    eventObj.initEvent(name, true, true);
    eventObj.keyCode = keyCode;
    el.dispatchEvent(eventObj)
  }

  beforeEach(function () {
    $('body').append('<su-dropdown></su-dropdown>')
    tag = riot.mount('su-dropdown', {
      items
    })[0]
    tag.on('open', spyOnOpen)
      .on('close', spyOnClose)
      .on('select', spyOnSelect)
    this.clock = sinon.useFakeTimers()
  })

  afterEach(function () {
    spyOnOpen.reset()
    spyOnClose.reset()
    spyOnSelect.reset()
    this.clock.restore()
    tag.unmount()
  })

  it('is mounted', function () {
    tag.isMounted.should.be.true
  })

  it('has no items visible on load', function () {
    $('su-dropdown .menu .item').length.should.equal(0)
  })

  it('clicking dropdown opens/closes dropdown and triggers open/close event', function () {
    $('su-dropdown .menu').is(':visible').should.equal(false)

    $('su-dropdown').click()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(true)
    spyOnOpen.should.have.been.calledOnce

    $('su-dropdown').click()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('focusing/blurring dropdown opens/closes dropdown and triggers open/close event', function () {
    $('su-dropdown .menu').is(':visible').should.equal(false)

    $('su-dropdown').focus()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(true)
    spyOnOpen.should.have.been.calledOnce

    $('su-dropdown').blur()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('clicking default item', function () {
    $('su-dropdown').click()
    this.clock.tick(310)

    $('su-dropdown .item:first-child').click()
    $('su-dropdown > .text').text().trim().should.equal(items[0].label)
    $('su-dropdown > .text').hasClass('default').should.equal(true)
    spyOnSelect.should.have.been.calledOnce

    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('clicking item', function () {
    $('su-dropdown').click()
    this.clock.tick(310)

    $('su-dropdown .item:eq(1)').click()
    $('su-dropdown > .text').text().trim().should.equal(items[1].label)
    $('su-dropdown > .text').hasClass('default').should.equal(false)
    spyOnSelect.should.have.been.calledOnce

    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('pressing enter key on item', function () {
    $('su-dropdown').focus()
    this.clock.tick(310)

    let dropdown = $('su-dropdown')[0]
    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    fireKeyEvent(dropdown, 'keyup', keys.enter)

    $('su-dropdown > .text').text().trim().should.equal(items[1].label)
    $('su-dropdown > .text').hasClass('default').should.equal(false)
    spyOnSelect.should.have.been.calledOnce

    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('pressing key down will active item', function () {
    $('su-dropdown').focus()

    let dropdown = $('su-dropdown')[0]
    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[0].label)

    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[1].label)

    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[2].label)

    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[2].label)

    fireKeyEvent(dropdown, 'keydown', keys.upArrow)
    $('su-dropdown .active .text').text().should.equal(items[1].label)

    fireKeyEvent(dropdown, 'keydown', keys.upArrow)
    $('su-dropdown .active .text').text().should.equal(items[0].label)

    fireKeyEvent(dropdown, 'keydown', keys.upArrow)
    $('su-dropdown .active .text').text().should.equal(items[0].label)

    $('su-dropdown').blur()
  })

})
<commit_msg>Add test for su-dropdown<commit_after>describe('su-dropdown', function () {
  let tag, select
  let spyOnOpen = sinon.spy()
  let spyOnClose = sinon.spy()
  let spyOnSelect = sinon.spy()

  let items = [
    {
      label: 'Gender',
      value: null,
      default: true
    },
    {
      label: 'Male',
      value: 1
    },
    {
      label: 'Female',
      value: 2
    },
  ]

  let keys = {
    enter: 13,
    escape: 27,
    upArrow: 38,
    downArrow: 40
  }

  let fireKeyEvent = function (el, name, keyCode) {
    let eventObj = document.createEvent("Events")
    eventObj.initEvent(name, true, true);
    eventObj.keyCode = keyCode;
    el.dispatchEvent(eventObj)
  }

  beforeEach(function () {
    $('body').append('<su-dropdown></su-dropdown>')
    tag = riot.mount('su-dropdown', {
      items
    })[0]
    tag.on('open', spyOnOpen)
      .on('close', spyOnClose)
      .on('select', spyOnSelect)
    this.clock = sinon.useFakeTimers()
  })

  afterEach(function () {
    spyOnOpen.reset()
    spyOnClose.reset()
    spyOnSelect.reset()
    this.clock.restore()
    tag.unmount()
  })

  it('is mounted', function () {
    tag.isMounted.should.be.true
  })

  it('has no items visible on load', function () {
    $('su-dropdown .menu .item').length.should.equal(0)
  })

  it('clicking dropdown opens/closes dropdown and triggers open/close event', function () {
    $('su-dropdown .menu').is(':visible').should.equal(false)

    $('su-dropdown').click()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(true)
    spyOnOpen.should.have.been.calledOnce

    $('su-dropdown').click()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('focusing/blurring dropdown opens/closes dropdown and triggers open/close event', function () {
    $('su-dropdown .menu').is(':visible').should.equal(false)

    $('su-dropdown').focus()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(true)
    spyOnOpen.should.have.been.calledOnce

    $('su-dropdown').blur()
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('clicking default item', function () {
    $('su-dropdown').click()
    this.clock.tick(310)

    $('su-dropdown .item:first-child').click()
    $('su-dropdown > .text').text().trim().should.equal(items[0].label)
    $('su-dropdown > .text').hasClass('default').should.equal(true)
    spyOnSelect.should.have.been.calledOnce

    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('clicking item', function () {
    $('su-dropdown').click()
    this.clock.tick(310)

    $('su-dropdown .item:eq(1)').click()
    $('su-dropdown > .text').text().trim().should.equal(items[1].label)
    $('su-dropdown > .text').hasClass('default').should.equal(false)
    spyOnSelect.should.have.been.calledOnce

    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('pressing enter key on item', function () {
    $('su-dropdown').focus()
    this.clock.tick(310)

    let dropdown = $('su-dropdown')[0]
    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    fireKeyEvent(dropdown, 'keyup', keys.enter)

    $('su-dropdown > .text').text().trim().should.equal(items[1].label)
    $('su-dropdown > .text').hasClass('default').should.equal(false)
    spyOnSelect.should.have.been.calledOnce

    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

  it('pressing key down will active item', function () {
    $('su-dropdown').focus()

    let dropdown = $('su-dropdown')[0]
    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[0].label)

    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[1].label)

    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[2].label)

    fireKeyEvent(dropdown, 'keydown', keys.downArrow)
    $('su-dropdown .active .text').text().should.equal(items[2].label)

    fireKeyEvent(dropdown, 'keydown', keys.upArrow)
    $('su-dropdown .active .text').text().should.equal(items[1].label)

    fireKeyEvent(dropdown, 'keydown', keys.upArrow)
    $('su-dropdown .active .text').text().should.equal(items[0].label)

    fireKeyEvent(dropdown, 'keydown', keys.upArrow)
    $('su-dropdown .active .text').text().should.equal(items[0].label)

    $('su-dropdown').blur()
  })

  it('pressing escape key', function () {
    $('su-dropdown').focus()
    this.clock.tick(310)

    let dropdown = $('su-dropdown')[0]
    fireKeyEvent(dropdown, 'keydown', keys.escape)
    this.clock.tick(310)
    $('su-dropdown .menu').is(':visible').should.equal(false)
    spyOnClose.should.have.been.calledOnce
  })

})
<|endoftext|>


<commit_before>////////////////////////////////
// Controller for admin panel //
////////////////////////////////

'use strict';

pay.controller('Admin', [
    '$scope',
    '$http',
    '$timeout',
    'PayAuth',
    'Event',
    'FormValidator',
    'Error',
    function ($scope, $http, $timeout, PayAuth, Event, FormValidator, Error) {
        if (!PayAuth.needUser()) { return; }

        $scope.isAdmin = PayAuth.etu.isAdmin === true;
        $scope.fundation = PayAuth.etu.fundation;

        /**
         * Show events list
         */
        function getEventsListsWithAccounts (callback) {
            Event.query(function (events) {
                var keptEvents = [];
                var keptEventsSeller = [];
                var keptEventsSellerWithEventCard = [];
                // Prevent duplicates in keptEventsSellerWithEventCard
                var addedEventsSellerWithEventCardIds = [];
                // Prevent duplicates in keptEvents
                var addedEvents = [];
                // Prevent duplicates in keptEventsSeller
                var addedEventsSeller = [];

                $http.get('/api/accounts/' + PayAuth.etu.id).then(function (accountsRes) {
                    accountsRes.data.forEach(function (account) {
                        events.forEach(function (event) {
                            if (event.id === account.event) {
                                if (PayAuth.etu.isAdmin) {
                                    if (addedEvents.indexOf(event.id) === -1) {
                                        keptEvents.push(event);
                                        addedEvents.push(event.id);
                                    }
                                    if (addedEventsSeller.indexOf(event.id) === -1) {
                                        keptEventsSeller.push(event);
                                        addedEventsSeller.push(event.id);
                                    }
                                } else if (account.admin) {
                                    if (addedEvents.indexOf(event.id) === -1) {
                                        keptEvents.push(event);
                                        addedEvents.push(event.id);
                                    }
                                } else {
                                    if (addedEventsSeller.indexOf(event.id) === -1) {
                                        keptEventsSeller.push(event);
                                        addedEventsSeller.push(event.id);
                                    }

                                    if (event.bdeCard) {
                                        if (addedEventsSellerWithEventCardIds.indexOf(event.id) === -1) {
                                            keptEventsSellerWithEventCard.push(event);
                                            addedEventsSellerWithEventCardIds.push(event.id);
                                        }
                                    }
                                }
                            }
                        });
                    });
                    if (typeof callback === 'function') { callback(); }
                }, function () {
                    if (typeof callback === 'function') { callback(); }
                    Error('Erreur', 0);
                });

                $scope.events = keptEvents;
                $scope.eventsSeller = keptEventsSeller;
                $scope.eventsSellerWithEventCard = keptEventsSellerWithEventCard;
            });
        }

        getEventsListsWithAccounts();

        // Model for the new event
        $scope.newEvent = {};
        $scope.fileInfo = null;
        $scope.datePattern = /^\d{1,2}\/\d{1,2}\/\d{4} [0-2][0-9]?:[0-5]?[0-9]$/;

        /**
         * Called when the ng-if has been evaluted
         */
        this.activateDate = function () {
            // Activate the datepicker, and ng-validate when the date changes
            $('.date').datetimepicker().on('dp.change', function () {
                var $self = $(this).children().first();
                $timeout(function () {
                    $self.data().$ngModelController.$setViewValue($self.val());
                }, 0);
            });
        };

        /**
         * Called when the ng-if has been evaluated
         */
        this.activateFile = function () {
            // Updates the input text with the input file name
            $('input[type=file]').on('change', function (e) {
                if (this.files.length === 1) {
                    $(this).parent().parent().next().val(this.files[0].name);
                }
            });
        };

        /**
         * Creates a event
         * @param {object} e The click event
         */
        this.createEvent = function (e) {
            if (!FormValidator(newEventForm, 'file')) {
                return;
            }

            var $btn = $(e.currentTarget).attr('disabled', '');
            var file = newEventForm.file.files[0];

            // Image -> string
            var reader = new FileReader();
            reader.onload = function (e) {
                var result = e.currentTarget.result;
                // Duplicate event to preserve from changes made by the resource
                var newEventData = jQuery.extend(true, {}, $scope.newEvent);

                newEventData.image = result;
                newEventData.date = moment(newEventData.date, 'DD/MM/YYYY HH:mm').toDate();
                newEventData.fundationId = $scope.fundation.id;
                var newEvent = new Event(newEventData);
                newEvent.$save(function () {
                    getEventsListsWithAccounts(function () {
                        $scope.$emit('$locationChangeSuccess', '');
                        $btn.removeAttr('disabled');
                        $('html, body').animate({
                            scrollTop: 0
                        }, 'fast');
                    });
                }, function (res) {
                    $btn.removeAttr('disabled');
                    // Request entity too large => file size too large
                    if (res.status === 413) {
                        Error('Erreur', 16);
                    }
                    Error('Erreur', res.data.error);
                });
            };
            reader.readAsDataURL(file);
        };
    }
]);
<commit_msg>Useless variable<commit_after>////////////////////////////////
// Controller for admin panel //
////////////////////////////////

'use strict';

pay.controller('Admin', [
    '$scope',
    '$http',
    '$timeout',
    'PayAuth',
    'Event',
    'FormValidator',
    'Error',
    function ($scope, $http, $timeout, PayAuth, Event, FormValidator, Error) {
        if (!PayAuth.needUser()) { return; }

        $scope.isAdmin = PayAuth.etu.isAdmin === true;
        $scope.fundation = PayAuth.etu.fundation;

        /**
         * Show events list
         */
        function getEventsListsWithAccounts (callback) {
            Event.query(function (events) {
                var keptEvents = [];
                var keptEventsSeller = [];
                var keptEventsSellerWithEventCard = [];
                // Prevent duplicates in keptEventsSellerWithEventCard
                var addedEventsSellerWithEventCardIds = [];
                // Prevent duplicates in keptEvents
                var addedEvents = [];
                // Prevent duplicates in keptEventsSeller
                var addedEventsSeller = [];

                $http.get('/api/accounts/' + PayAuth.etu.id).then(function (accountsRes) {
                    accountsRes.data.forEach(function (account) {
                        events.forEach(function (event) {
                            if (event.id === account.event) {
                                if (PayAuth.etu.isAdmin) {
                                    if (addedEvents.indexOf(event.id) === -1) {
                                        keptEvents.push(event);
                                        addedEvents.push(event.id);
                                    }
                                    if (addedEventsSeller.indexOf(event.id) === -1) {
                                        keptEventsSeller.push(event);
                                        addedEventsSeller.push(event.id);
                                    }
                                } else if (account.admin) {
                                    if (addedEvents.indexOf(event.id) === -1) {
                                        keptEvents.push(event);
                                        addedEvents.push(event.id);
                                    }
                                } else {
                                    if (addedEventsSeller.indexOf(event.id) === -1) {
                                        keptEventsSeller.push(event);
                                        addedEventsSeller.push(event.id);
                                    }

                                    if (event.bdeCard) {
                                        if (addedEventsSellerWithEventCardIds.indexOf(event.id) === -1) {
                                            keptEventsSellerWithEventCard.push(event);
                                            addedEventsSellerWithEventCardIds.push(event.id);
                                        }
                                    }
                                }
                            }
                        });
                    });
                    if (typeof callback === 'function') { callback(); }
                }, function () {
                    if (typeof callback === 'function') { callback(); }
                    Error('Erreur', 0);
                });

                $scope.events = keptEvents;
                $scope.eventsSeller = keptEventsSeller;
                $scope.eventsSellerWithEventCard = keptEventsSellerWithEventCard;
            });
        }

        getEventsListsWithAccounts();

        // Model for the new event
        $scope.newEvent = {};
        $scope.fileInfo = null;
        $scope.datePattern = /^\d{1,2}\/\d{1,2}\/\d{4} [0-2][0-9]?:[0-5]?[0-9]$/;

        /**
         * Called when the ng-if has been evaluted
         */
        this.activateDate = function () {
            // Activate the datepicker, and ng-validate when the date changes
            $('.date').datetimepicker().on('dp.change', function () {
                var $self = $(this).children().first();
                $timeout(function () {
                    $self.data().$ngModelController.$setViewValue($self.val());
                }, 0);
            });
        };

        /**
         * Called when the ng-if has been evaluated
         */
        this.activateFile = function () {
            // Updates the input text with the input file name
            $('input[type=file]').on('change', function () {
                if (this.files.length === 1) {
                    $(this).parent().parent().next().val(this.files[0].name);
                }
            });
        };

        /**
         * Creates a event
         * @param {object} e The click event
         */
        this.createEvent = function (e) {
            if (!FormValidator(newEventForm, 'file')) {
                return;
            }

            var $btn = $(e.currentTarget).attr('disabled', '');
            var file = newEventForm.file.files[0];

            // Image -> string
            var reader = new FileReader();
            reader.onload = function (e) {
                var result = e.currentTarget.result;
                // Duplicate event to preserve from changes made by the resource
                var newEventData = jQuery.extend(true, {}, $scope.newEvent);

                newEventData.image = result;
                newEventData.date = moment(newEventData.date, 'DD/MM/YYYY HH:mm').toDate();
                newEventData.fundationId = $scope.fundation.id;
                var newEvent = new Event(newEventData);
                newEvent.$save(function () {
                    getEventsListsWithAccounts(function () {
                        $scope.$emit('$locationChangeSuccess', '');
                        $btn.removeAttr('disabled');
                        $('html, body').animate({
                            scrollTop: 0
                        }, 'fast');
                    });
                }, function (res) {
                    $btn.removeAttr('disabled');
                    // Request entity too large => file size too large
                    if (res.status === 413) {
                        Error('Erreur', 16);
                    }
                    Error('Erreur', res.data.error);
                });
            };
            reader.readAsDataURL(file);
        };
    }
]);
<|endoftext|>