<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import WebMidi from 'webmidi';
import FxUnit from '../../components/FxUnit';
import Mixer from '../../components/Mixer';
import Deck from '../../components/Deck';
import CrossFader from '../../components/CrossFader';
import SoundcloudDeck from '../../components/SoundcloudDeck';
import YoutubeDeck from '../../components/YoutubeDeck';
import s from './Home.css';

/* eslint-disable react/jsx-no-bind */
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      VolumeA: 0.0,
      VolumeB: 0.0,
      VolumeC: 0.0,
      VolumeD: 0.0,
      LowD: 63,
      LowC: 63,
      LowB: 63,
      LowA: 63,
      MidD: 63,
      MidC: 63,
      MidB: 63,
      MidA: 63,
      HighD: 63,
      HighC: 63,
      HighB: 63,
      HighA: 63,
      LowpassA: 63,
      LowpassB: 63,
      LowpassC: 63,
      LowpassD: 63,
      HighpassA: 63,
      HighpassB: 63,
      HighpassC: 63,
      HighpassD: 63,
    };
  }

  changeVolumeA = (newVolume) => { this.setState({ VolumeA: newVolume }); };
  changeVolumeB = (newVolume) => { this.setState({ VolumeB: newVolume }); };
  changeVolumeC = (newVolume) => { this.setState({ VolumeC: newVolume }); };
  changeVolumeD = (newVolume) => { this.setState({ VolumeD: newVolume }); };

  changeLowA = (newLow) => { this.setState({ LowA: newLow }); };
  changeLowB = (newLow) => { this.setState({ LowB: newLow }); };
  changeLowC = (newLow) => { this.setState({ LowC: newLow }); };
  changeLowD = (newLow) => { this.setState({ LowD: newLow }); };

  changeMidA = (newMid) => { this.setState({ MidA: newMid }); };
  changeMidB = (newMid) => { this.setState({ MidB: newMid }); };
  changeMidC = (newMid) => { this.setState({ MidC: newMid }); };
  changeMidD = (newMid) => { this.setState({ MidD: newMid }); };

  changeHighA = (newHigh) => { this.setState({ HighA: newHigh }); };
  changeHighB = (newHigh) => { this.setState({ HighB: newHigh }); };
  changeHighC = (newHigh) => { this.setState({ HighC: newHigh }); };
  changeHighD = (newHigh) => { this.setState({ HighD: newHigh }); };

  changeLowpassA = (newLowpass) => { this.setState({ LowpassA: newLowpass }); };
  changeLowpassB = (newLowpass) => { this.setState({ LowpassB: newLowpass }); };
  changeLowpassC = (newLowpass) => { this.setState({ LowpassC: newLowpass }); };
  changeLowpassD = (newLowpass) => { this.setState({ LowpassD: newLowpass }); };

  changeHighpassA = (newHighpass) => { this.setState({ HighpassA: newHighpass }); };
  changeHighpassB = (newHighpass) => { this.setState({ HighpassB: newHighpass }); };
  changeHighpassC = (newHighpass) => { this.setState({ HighpassC: newHighpass }); };
  changeHighpassD = (newHighpass) => { this.setState({ HighpassD: newHighpass }); };

  componentDidMount() {
    WebMidi.enable(function (err) {
      if (err) {
        console.log("WebMidi could not be enabled.", err);
      } else {
        console.log("WebMidi enabled!");
        console.log(WebMidi.inputs);
        console.log(WebMidi.outputs);

        var input = WebMidi.getInputByName('MPKmini2');

        input.addListener('pitchbend', 'all', function(e) {
          console.log('Pitch value: ' + e.value);
        });
      }
    });
  }

  render() {
    return (

              <FxUnit id="FX1" />

              <FxUnit id="FX2" />

          {/* AB */}

              <YoutubeDeck
                playing
                name="DeckA"
                url="https://www.youtube.com/watch?v=vbylJ3Ai7-M"
                volume={this.state.VolumeA}
                low={this.state.LowA}
                mid={this.state.MidA}
                high={this.state.HighA}
              />

                    <Mixer
                      name="MixerA"
                      volume={this.state.VolumeA}
                      changeVolume={this.changeVolumeA.bind(this)}
                      mid={this.state.MidA}
                      changeMid={this.changeMidA.bind(this)}
                      low={this.state.LowA}
                      changeLow={this.changeLowA.bind(this)}
                      high={this.state.HighA}
                      changeHigh={this.changeHighA.bind(this)}
                      lowpass={this.state.LowpassA}
                      changeLowpass={this.changeLowpassA.bind(this)}
                      highpass={this.state.HighpassA}
                      changeHighpass={this.changeHighpassA.bind(this)}
                    />

                    <Mixer
                      name="MixerB"
                      side="right"
                      otherside="left"
                      volume={this.state.VolumeB}
                      changeVolume={this.changeVolumeB.bind(this)}
                      low={this.state.LowB}
                      changeLow={this.changeLowB.bind(this)}
                      mid={this.stateeMidB}
                      changeMid={this.changeMidB.bind(this)}
                      high={this.state.HighB}
                      changeHigh={this.changeHighB.bind(this)}
                      lowpass={this.state.LowpassB}
                      changeLowpass={this.changeLowpassB.bind(this)}
                      highpass={this.state.HighpassB}
                      changeHighpass={this.changeHighpassB.bind(this)}
                    />

 {/* End AB Mixer */}

 {/* End Center Column */}

              <Deck
                playing
                name="DeckB"
                url="https://www.youtube.com/watch?v=j6sSQq7a_Po?html5=1"
                volume={this.state.VolumeB}
                low={this.state.LowB}
                mid={this.state.MidB}
                high={this.state.HighB}
              />

          {/* CD */}

              <SoundcloudDeck
                playing
                name="DeckC"
                url="https://soundcloud.com/loudpvck/lit"
                volume={this.state.VolumeC}
                low={this.state.LowC}
                mid={this.state.MidC}
                high={this.state.HighC}
                lowpass={this.state.LowpassC}
                highpass={this.state.HighpassC}
              />

                    <Mixer
                      name="MixerC"
                      volume={this.state.VolumeC}
                      changeVolume={this.changeVolumeC.bind(this)}
                      low={this.state.LowC}
                      changeLow={this.changeLowC.bind(this)}
                      mid={this.state.MidC}
                      changeMid={this.changeMidC.bind(this)}
                      high={this.state.HighC}
                      changeHigh={this.changeHighC.bind(this)}
                      lowpass={this.state.LowpassC}
                      changeLowpass={this.changeLowpassC.bind(this)}
                      highpass={this.state.HighpassC}
                      changeHighpass={this.changeHighpassC.bind(this)}
                    />

                    <Mixer
                      name="MixerD"
                      side="right"
                      otherside="left"
                      volume={this.state.VolumeD}
                      changeVolume={this.changeVolumeD.bind(this)}
                      low={this.state.LowD}
                      changeLow={this.changeLowD.bind(this)}
                      mid={this.state.MidD}
                      changeMid={this.changeMidD.bind(this)}
                      high={this.state.HighD}
                      changeHigh={this.changeHighD.bind(this)}
                      lowpass={this.state.LowpassD}
                      changeLowpass={this.changeLowpassD.bind(this)}
                      highpass={this.state.HighpassD}
                      changeHighpass={this.changeHighpassD.bind(this)}
                    />

 {/* End CD Mixer */}

 {/* End Center Column */}

              <SoundcloudDeck
                playing
                name="DeckD"
                url="https://soundcloud.com/skrillex/torro-torro-make-a-move-skrillex-remix"
                volume={this.state.VolumeD}
                low={this.state.LowD}
                mid={this.state.MidD}
                high={this.state.HighD}
                lowpass={this.state.LowpassD}
                highpass={this.state.HighpassD}
              />

            <CrossFader />

    );
  }
}

export default withStyles(s)(Home);
<commit_msg>isolate CC message by number<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import WebMidi from 'webmidi';
import FxUnit from '../../components/FxUnit';
import Mixer from '../../components/Mixer';
import Deck from '../../components/Deck';
import CrossFader from '../../components/CrossFader';
import SoundcloudDeck from '../../components/SoundcloudDeck';
import YoutubeDeck from '../../components/YoutubeDeck';
import s from './Home.css';

/* eslint-disable react/jsx-no-bind */
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      VolumeA: 0.0,
      VolumeB: 0.0,
      VolumeC: 0.0,
      VolumeD: 0.0,
      LowD: 63,
      LowC: 63,
      LowB: 63,
      LowA: 63,
      MidD: 63,
      MidC: 63,
      MidB: 63,
      MidA: 63,
      HighD: 63,
      HighC: 63,
      HighB: 63,
      HighA: 63,
      LowpassA: 63,
      LowpassB: 63,
      LowpassC: 63,
      LowpassD: 63,
      HighpassA: 63,
      HighpassB: 63,
      HighpassC: 63,
      HighpassD: 63,
    };
  }

  changeVolumeA = (newVolume) => { this.setState({ VolumeA: newVolume }); };
  changeVolumeB = (newVolume) => { this.setState({ VolumeB: newVolume }); };
  changeVolumeC = (newVolume) => { this.setState({ VolumeC: newVolume }); };
  changeVolumeD = (newVolume) => { this.setState({ VolumeD: newVolume }); };

  changeLowA = (newLow) => { this.setState({ LowA: newLow }); };
  changeLowB = (newLow) => { this.setState({ LowB: newLow }); };
  changeLowC = (newLow) => { this.setState({ LowC: newLow }); };
  changeLowD = (newLow) => { this.setState({ LowD: newLow }); };

  changeMidA = (newMid) => { this.setState({ MidA: newMid }); };
  changeMidB = (newMid) => { this.setState({ MidB: newMid }); };
  changeMidC = (newMid) => { this.setState({ MidC: newMid }); };
  changeMidD = (newMid) => { this.setState({ MidD: newMid }); };

  changeHighA = (newHigh) => { this.setState({ HighA: newHigh }); };
  changeHighB = (newHigh) => { this.setState({ HighB: newHigh }); };
  changeHighC = (newHigh) => { this.setState({ HighC: newHigh }); };
  changeHighD = (newHigh) => { this.setState({ HighD: newHigh }); };

  changeLowpassA = (newLowpass) => { this.setState({ LowpassA: newLowpass }); };
  changeLowpassB = (newLowpass) => { this.setState({ LowpassB: newLowpass }); };
  changeLowpassC = (newLowpass) => { this.setState({ LowpassC: newLowpass }); };
  changeLowpassD = (newLowpass) => { this.setState({ LowpassD: newLowpass }); };

  changeHighpassA = (newHighpass) => { this.setState({ HighpassA: newHighpass }); };
  changeHighpassB = (newHighpass) => { this.setState({ HighpassB: newHighpass }); };
  changeHighpassC = (newHighpass) => { this.setState({ HighpassC: newHighpass }); };
  changeHighpassD = (newHighpass) => { this.setState({ HighpassD: newHighpass }); };

  componentDidMount() {
    WebMidi.enable(function (err) {
      if (err) {
        console.log("WebMidi could not be enabled.", err);
      } else {
        console.log("WebMidi enabled!");
        console.log(WebMidi.inputs);
        console.log(WebMidi.outputs);

        var input = WebMidi.getInputByName('MPKmini2');

        input.addListener('pitchbend', 'all', function(e) {
          console.log('Pitch value: ' + e.value);
        });

        // Listen to control change message on all channels
        input.addListener('controlchange', 'all',
          function (e) {
            if (e.controller.number === 1){
              console.log("CC1", e);
            }
            if (e.controller.number === 2){
              console.log("CC2", e);
            }
            if (e.controller.number === 3){
              console.log("CC3", e);
            }
            if (e.controller.number === 4){
              console.log("CC4", e);
            }
            if (e.controller.number === 5){
              console.log("CC5", e);
            }
            if (e.controller.number === 6){
              console.log("CC6", e);
            }
            if (e.controller.number === 7){
              console.log("CC7", e);
            }
            if (e.controller.number === 8){
              console.log("CC8", e);
            }
          }
        );
      }
    });
  }

  render() {
    return (

              <FxUnit id="FX1" />

              <FxUnit id="FX2" />

          {/* AB */}

              <YoutubeDeck
                playing
                name="DeckA"
                url="https://www.youtube.com/watch?v=vbylJ3Ai7-M"
                volume={this.state.VolumeA}
                low={this.state.LowA}
                mid={this.state.MidA}
                high={this.state.HighA}
              />

                    <Mixer
                      name="MixerA"
                      volume={this.state.VolumeA}
                      changeVolume={this.changeVolumeA.bind(this)}
                      mid={this.state.MidA}
                      changeMid={this.changeMidA.bind(this)}
                      low={this.state.LowA}
                      changeLow={this.changeLowA.bind(this)}
                      high={this.state.HighA}
                      changeHigh={this.changeHighA.bind(this)}
                      lowpass={this.state.LowpassA}
                      changeLowpass={this.changeLowpassA.bind(this)}
                      highpass={this.state.HighpassA}
                      changeHighpass={this.changeHighpassA.bind(this)}
                    />

                    <Mixer
                      name="MixerB"
                      side="right"
                      otherside="left"
                      volume={this.state.VolumeB}
                      changeVolume={this.changeVolumeB.bind(this)}
                      low={this.state.LowB}
                      changeLow={this.changeLowB.bind(this)}
                      mid={this.stateeMidB}
                      changeMid={this.changeMidB.bind(this)}
                      high={this.state.HighB}
                      changeHigh={this.changeHighB.bind(this)}
                      lowpass={this.state.LowpassB}
                      changeLowpass={this.changeLowpassB.bind(this)}
                      highpass={this.state.HighpassB}
                      changeHighpass={this.changeHighpassB.bind(this)}
                    />

 {/* End AB Mixer */}

 {/* End Center Column */}

              <Deck
                playing
                name="DeckB"
                url="https://www.youtube.com/watch?v=j6sSQq7a_Po?html5=1"
                volume={this.state.VolumeB}
                low={this.state.LowB}
                mid={this.state.MidB}
                high={this.state.HighB}
              />

          {/* CD */}

              <SoundcloudDeck
                playing
                name="DeckC"
                url="https://soundcloud.com/loudpvck/lit"
                volume={this.state.VolumeC}
                low={this.state.LowC}
                mid={this.state.MidC}
                high={this.state.HighC}
                lowpass={this.state.LowpassC}
                highpass={this.state.HighpassC}
              />

                    <Mixer
                      name="MixerC"
                      volume={this.state.VolumeC}
                      changeVolume={this.changeVolumeC.bind(this)}
                      low={this.state.LowC}
                      changeLow={this.changeLowC.bind(this)}
                      mid={this.state.MidC}
                      changeMid={this.changeMidC.bind(this)}
                      high={this.state.HighC}
                      changeHigh={this.changeHighC.bind(this)}
                      lowpass={this.state.LowpassC}
                      changeLowpass={this.changeLowpassC.bind(this)}
                      highpass={this.state.HighpassC}
                      changeHighpass={this.changeHighpassC.bind(this)}
                    />

                    <Mixer
                      name="MixerD"
                      side="right"
                      otherside="left"
                      volume={this.state.VolumeD}
                      changeVolume={this.changeVolumeD.bind(this)}
                      low={this.state.LowD}
                      changeLow={this.changeLowD.bind(this)}
                      mid={this.state.MidD}
                      changeMid={this.changeMidD.bind(this)}
                      high={this.state.HighD}
                      changeHigh={this.changeHighD.bind(this)}
                      lowpass={this.state.LowpassD}
                      changeLowpass={this.changeLowpassD.bind(this)}
                      highpass={this.state.HighpassD}
                      changeHighpass={this.changeHighpassD.bind(this)}
                    />

 {/* End CD Mixer */}

 {/* End Center Column */}

              <SoundcloudDeck
                playing
                name="DeckD"
                url="https://soundcloud.com/skrillex/torro-torro-make-a-move-skrillex-remix"
                volume={this.state.VolumeD}
                low={this.state.LowD}
                mid={this.state.MidD}
                high={this.state.HighD}
                lowpass={this.state.LowpassD}
                highpass={this.state.HighpassD}
              />

            <CrossFader />

    );
  }
}

export default withStyles(s)(Home);
<|endoftext|>


<commit_before>/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovies>"],
        licenses:["MIT"], //TODO: Licenses
        constants:{
            DISPLAY:"display",
            POSITION:"position"
        },

        init:function () {
            lastEvent = null;

            document.addEventListener(parser.events.PARSER_START, function (e) {
                lastEvent = e;
                buffer = {};
            }, false);

            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                lastEvent = e;
                if (isSupportedProperty(e.data.declaration)) {
                    store(e.data.selectorText, e.data.declaration);
                }
            }, false);

            document.addEventListener(parser.events.PARSER_DONE, function (e) {
                lastEvent = e;
                //TODO: validate and transform
            }, false);
            return templateLayout;
        },

        setTemplate:function (cssFile) {

            function readFile(url) {
                //TODO: refactor
                function ajaxReadFile() {
                    var request = new XMLHttpRequest();
                    request.open("get", url, false);
                    request.send("");
                    return request.responseText;
                }

                try {
                    return ajaxReadFile(url);
                } catch (e) {
                    //FIXME: chrome workaround
                    console.error(e);
                    throw "OperationNotSupportedException";
                }
            }

            parser.parse(readFile(cssFile));
        },

        //only for testing purposes
        getLastEvent:function () {
            return lastEvent;
        },
        getBuffer:function () {
            return buffer;
        }
    };

    var lastEvent = null;
    var buffer = {};

    function store(selector, declaration) {
        if (!buffer[selector]) {
            buffer[selector] = {};
        }
        buffer[selector][declaration.property] = declaration.valueText;

    }

    function isSupportedProperty(declaration) {
        for (var property in templateLayout.constants) {
            if (templateLayout.constants[property] == declaration.property) return true;
        }
        return false;
    }

    function Template(selectorText, model, situated) {
        this.selectorText = selectorText;
        this.model = model;
        this.situated = situated;
    }

    Template.prototype = {
        model:"",
        selectorText:"",
        situated:""
    };

    wef.plugins.register("templateLayout", templateLayout);
}

    )
    ();<commit_msg>Fix isSupportedProperty<commit_after>/*!
 * TemplateLayout Wef plugin
 * Copyright (c) 2011 Pablo Escalada
 * MIT Licensed
 */

//requires: cssParser
var parser = wef.fn.cssParser; //TODO: loader
//exports: templateLayout

(function () {
    var templateLayout = {
        name:"templateLayout",
        version:"0.0.1",
        description:"W3C CSS Template Layout Module",
        authors:["Pablo Escalada <uo1398@uniovies>"],
        licenses:["MIT"], //TODO: Licenses
        constants:{
            DISPLAY:"display",
            POSITION:"position"
        },

        init:function () {
            lastEvent = null;

            document.addEventListener(parser.events.PARSER_START, function (e) {
                lastEvent = e;
                buffer = {};
            }, false);

            document.addEventListener(parser.events.PROPERTY_FOUND, function (e) {
                lastEvent = e;
                if (isSupportedProperty(e.data)) {
                    store(e.data.selectorText, e.data.declaration);
                }
            }, false);

            document.addEventListener(parser.events.PARSER_DONE, function (e) {
                lastEvent = e;
                //TODO: validate and transform
            }, false);
            return templateLayout;
        },

        setTemplate:function (cssFile) {

            function readFile(url) {
                //TODO: refactor
                function ajaxReadFile() {
                    var request = new XMLHttpRequest();
                    request.open("get", url, false);
                    request.send("");
                    return request.responseText;
                }

                try {
                    return ajaxReadFile(url);
                } catch (e) {
                    //FIXME: chrome workaround
                    console.error(e);
                    throw "OperationNotSupportedException";
                }
            }

            parser.parse(readFile(cssFile));
        },

        //only for testing purposes
        getLastEvent:function () {
            return lastEvent;
        },

        getBuffer:function () {
            return buffer;
        }
    };

    var lastEvent = null;
    var buffer = {};

    function store(selectorText, declaration) {
        if (!buffer[selectorText]) {
            buffer[selectorText] = {};
        }
        buffer[selectorText][declaration.property] = declaration.valueText;
    }

    function isSupportedProperty(rule) {
        for (var property in templateLayout.constants) {
            if (templateLayout.constants[property] == rule.declaration.property) return true;
        }
        return false;
    }

    function Template(selectorText, display, position) {
        this.selectorText = selectorText;
        this.model = display;
        this.situated = position;
    }

    Template.prototype = {
        model:"",
        selectorText:"",
        situated:""
    };

    wef.plugins.register("templateLayout", templateLayout);
})();<|endoftext|>


<commit_before>import ReactGA from 'react-ga';

// We only need to import the modules necessary for initial render
import {
  HomeRoute,
  OrganizationsRoute,
  CareersRoute,
  AboutRoute,
  ContactRoute,
  TrainingRoute,
  UserRoute,
} from './routes';

import { Layout } from './components';

/*  Note: Instead of using JSX, we recommend using react-router
    PlainRoute objects to build route definitions.   */

import { injectReducer } from 'store/reducers';
import userReducer from './modules/user/user-reducer';
import contentReducer from './modules/content/content-reducer';

import { onSignInAndOnSignOut } from './modules/user/user-actions';
import { contentUpdate } from './modules/content/content-actions';

ReactGA.initialize('UA-86819304-1');

export const rootRoute = (store) => {
  injectReducer(store, { key: 'user', reducer: userReducer });
  injectReducer(store, { key: 'content', reducer: contentReducer });

  //
  // Asynchronous listener of the changes of the user's authentication state.
  // create signedIn and signedOut actions.  When the external model-service
  // user auth state changes from auth to unauth or vise versa, invokes the
  // store dispatcher for the signedIn and signedOut actions respectivelly.
  //
  store.dispatch(onSignInAndOnSignOut);

  //
  // Initialize static content
  //
  store.dispatch(contentUpdate);

  //
  // Subscribe each page view to google analytics
  //
  let pathname = '';
  store.subscribe(() => {
    let previousPathname = pathname;
    const { router } = store.getState();
    pathname = router.locationBeforeTransitions.pathname;
    if (previousPathname !== pathname) {
      ReactGA.pageview(pathname);
    }
  });

  return {
    path: '/',
    component: Layout,
    indexRoute: HomeRoute,
    childRoutes: [
      OrganizationsRoute,
      CareersRoute,
      AboutRoute,
      ContactRoute,
      TrainingRoute,
      UserRoute(store),
    ],
  };
};

export default rootRoute;
<commit_msg>update google analytics recording<commit_after>import ReactGA from 'react-ga';

// We only need to import the modules necessary for initial render
import {
  HomeRoute,
  OrganizationsRoute,
  CareersRoute,
  AboutRoute,
  ContactRoute,
  TrainingRoute,
  UserRoute,
} from './routes';

import { Layout } from './components';

/*  Note: Instead of using JSX, we recommend using react-router
    PlainRoute objects to build route definitions.   */

import { injectReducer } from 'store/reducers';
import userReducer from './modules/user/user-reducer';
import contentReducer from './modules/content/content-reducer';

import { onSignInAndOnSignOut } from './modules/user/user-actions';
import { contentUpdate } from './modules/content/content-actions';

ReactGA.initialize('UA-86819304-1');

export const rootRoute = (store) => {
  injectReducer(store, { key: 'user', reducer: userReducer });
  injectReducer(store, { key: 'content', reducer: contentReducer });

  //
  // Asynchronous listener of the changes of the user's authentication state.
  // create signedIn and signedOut actions.  When the external model-service
  // user auth state changes from auth to unauth or vise versa, invokes the
  // store dispatcher for the signedIn and signedOut actions respectivelly.
  //
  store.dispatch(onSignInAndOnSignOut);

  //
  // Initialize static content
  //
  store.dispatch(contentUpdate);

  //
  // Subscribe each page view to google analytics
  //
  let currentPathname = '';
  store.subscribe(() => {
    const { router: { locationBeforeTransitions: { pathname } } } = store.getState();
    if (currentPathname !== pathname) {
      currentPathname = pathname;
      ReactGA.pageview(currentPathname);
    }
  });

  return {
    path: '/',
    component: Layout,
    indexRoute: HomeRoute,
    childRoutes: [
      OrganizationsRoute,
      CareersRoute,
      AboutRoute,
      ContactRoute,
      TrainingRoute,
      UserRoute(store),
    ],
  };
};

export default rootRoute;
<|endoftext|>


<commit_before>/*jshint bitwise:false, indent:2, curly:true eqeqeq:true, immed:true,
latedef:true, newcap:true, noarg:true, regexp:true, undef:true,
trailing:true white:true*/
/*global XT:true, XM:true, XV:true, _:true, enyo:true*/

(function () {

  /**
    Use this class to define the editor for `XV.ListRelationsEditorBox`.

    @class
    @name XV.RelationsEditor
    @extends XV.Groupbox
    @see XV.ListRelationsEditorBox
  */
  var editor = enyo.mixin(XV.EditorMixin, {
    name: "XV.RelationsEditor",
    kind: "XV.Groupbox",
    handlers: {
      onValueChange: "controlValueChanged"
    },
    setValue: function (value) {
      var changes = {},
        options = {},
        attrs,
        i;
      this.value = value;
      attrs = value.getAttributeNames();
      for (i = 0; i < attrs.length; i++) {
        changes[attrs[i]] = true;
      }
      options.changes = changes;
      this.attributesChanged(value, options);
    }
  });
  enyo.kind(editor);

  /**
    Must include a component called `list`.
    List must be of sub-kind `XV.ListRelations`.
    The `value` must be set to a collection of `XM.Model`.

    @class
    @name XV.ListRelationsEditorBox
    @extends XV.Groupbox
    @see XV.RelationsEditor
  */
  enyo.kind(/** @lends XV.ListRelationsEditorBox */{
    name: "XV.ListRelationsEditorBox",
    kind: "XV.Groupbox",
    classes: "panel xv-relations-editor-box",
    published: {
      attr: null,
      value: null,
      title: "",
      parentKey: "",
      listRelations: "",
      editor: null
    },
    handlers: {
      onSelect: "selectionChanged",
      onDeselect: "selectionChanged",
      onValueChange: "controlValueChanged"
    },
    attrChanged: function () {
      this.$.list.setAttr(this.attr);
    },
    controlValueChanged: function () {
      this.$.list.refresh();
      return true;
    },
    create: function () {
      this.inherited(arguments);
      var editor = this.getEditor(),
        panels,
        control;

      // Header
      this.createComponent({
        kind: "onyx.GroupboxHeader",
        content: this.getTitle()
      });

      // List
      panels = {
        kind: "Panels",
        fit: true,
        arrangerKind: "CollapsingArranger",
        components: [
          {kind: editor, name: "editor"},
          {kind: this.getListRelations(), name: "list",
            attr: this.getAttr(), fit: true}
        ]
      };
      control = this.createComponent(panels);
      control.setIndex(1);

      // Buttons
      this.createComponent({
        kind: "FittableColumns",
        classes: "xv-groupbox-buttons",
        components: [
          {kind: "onyx.Button", name: "newButton", onclick: "newItem",
            content: "_new".loc(), classes: "xv-groupbox-button-left"},
          {kind: "onyx.Button", name: "deleteButton", onclick: "deleteItem",
            content: "_delete".loc(), classes: "xv-groupbox-button-right",
            disabled: true}
        ]
      });

    },
    deleteItem: function () {
      var index = this.$.list.getFirstSelected(),
        model = index ? this.$.list.getModel(index) : null;
      this.$.list.getSelection().deselect(index, false);
      model.destroy();
      this.$.list.lengthChanged();
    },
    newItem: function () {
      var collection = this.$.list.getValue(),
        Klass = collection.model,
        model = new Klass(null, {isNew: true});
      this.$.editor.clear();
      collection.add(model);
      this.$.list.select(collection.length - 1);
    },
    selectionChanged: function (inSender, inEvent) {
      var index = this.$.list.getFirstSelected(),
        model = index ? this.$.list.getModel(index) : null,
        that = this;
      this.$.deleteButton.setDisabled(true);
      if (index) {
        this.$.editor.setValue(model);
        model.used({
          success: function (resp) {
            that.$.deleteButton.setDisabled(resp);
          }
        });
        this.$.panels.previous();
      } else {
        this.$.panels.setIndex(1);
      }
    },
    valueChanged: function () {
      var value = this.getValue();
      this.$.list.setValue(value);
    }
  });

}());
<commit_msg>get "done" button working right<commit_after>/*jshint bitwise:false, indent:2, curly:true eqeqeq:true, immed:true,
latedef:true, newcap:true, noarg:true, regexp:true, undef:true,
trailing:true white:true*/
/*global XT:true, XM:true, XV:true, _:true, enyo:true*/

(function () {

  /**
    Use this class to define the editor for `XV.ListRelationsEditorBox`.

    @class
    @name XV.RelationsEditor
    @extends XV.Groupbox
    @see XV.ListRelationsEditorBox
  */
  var editor = enyo.mixin(XV.EditorMixin, {
    name: "XV.RelationsEditor",
    kind: "XV.Groupbox",
    handlers: {
      onValueChange: "controlValueChanged"
    },
    setValue: function (value) {
      var changes = {},
        options = {},
        attrs,
        i;
      this.value = value;
      attrs = value.getAttributeNames();
      for (i = 0; i < attrs.length; i++) {
        changes[attrs[i]] = true;
      }
      options.changes = changes;
      this.attributesChanged(value, options);
    }
  });
  enyo.kind(editor);

  /**
    Must include a component called `list`.
    List must be of sub-kind `XV.ListRelations`.
    The `value` must be set to a collection of `XM.Model`.

    @class
    @name XV.ListRelationsEditorBox
    @extends XV.Groupbox
    @see XV.RelationsEditor
  */
  enyo.kind(/** @lends XV.ListRelationsEditorBox */{
    name: "XV.ListRelationsEditorBox",
    kind: "XV.Groupbox",
    classes: "panel xv-relations-editor-box",
    published: {
      attr: null,
      value: null,
      title: "",
      parentKey: "",
      listRelations: "",
      editor: null,
      fitButtons: true
    },
    handlers: {
      onSelect: "selectionChanged",
      onDeselect: "selectionChanged",
      onTransitionFinish: "transitionFinished",
      onValueChange: "controlValueChanged"
    },
    attrChanged: function () {
      this.$.list.setAttr(this.attr);
    },
    controlValueChanged: function () {
      this.$.list.refresh();
      return true;
    },
    create: function () {
      this.inherited(arguments);
      var editor = this.getEditor(),
        panels,
        control;

      // Header
      this.createComponent({
        kind: "onyx.GroupboxHeader",
        content: this.getTitle()
      });

      // List
      panels = {
        kind: "Panels",
        fit: true,
        arrangerKind: "CollapsingArranger",
        components: [
          {kind: editor, name: "editor"},
          {kind: this.getListRelations(), name: "list",
            attr: this.getAttr(), fit: true}
        ]
      };
      control = this.createComponent(panels);
      control.setIndex(1);

      // Buttons
      this.createComponent({
        kind: "FittableColumns",
        classes: "xv-groupbox-buttons",
        components: [
          {kind: "onyx.Button", name: "newButton", onclick: "newItem",
            content: "_new".loc(), classes: "xv-groupbox-button-left"},
          {kind: "onyx.Button", name: "deleteButton", onclick: "deleteItem",
            content: "_delete".loc(), classes: "xv-groupbox-button-center",
            disabled: true},
          {kind: "onyx.Button", name: "prevButton", onclick: "prevItem",
            content: "<", classes: "xv-groupbox-button-center",
            disabled: true},
          {kind: "onyx.Button", name: "nextButton", onclick: "nextItem",
            content: ">", classes: "xv-groupbox-button-center",
            disabled: true},
          {kind: "onyx.Button", name: "doneButton", onclick: "doneItem",
            content: "_done".loc(), classes: "xv-groupbox-button-right",
            disabled: true, fit: this.getFitButtons()}
        ]
      });

    },
    deleteItem: function () {
      var index = this.$.list.getFirstSelected(),
        model = index ? this.$.list.getModel(index) : null;
      this.$.list.getSelection().deselect(index, false);
      model.destroy();
      this.$.list.lengthChanged();
    },
    doneItem: function () {
      var index = this.$.list.getFirstSelected(),
        selection = this.$.list.getSelection();
      selection.deselect(index);
    },
    newItem: function () {
      var collection = this.$.list.getValue(),
        Klass = collection.model,
        model = new Klass(null, {isNew: true});
      this.$.editor.clear();
      collection.add(model);
      this.$.list.select(collection.length - 1);
    },
    selectionChanged: function (inSender, inEvent) {
      var index = this.$.list.getFirstSelected(),
        model = index ? this.$.list.getModel(index) : null,
        that = this;
      this.$.deleteButton.setDisabled(true);
      this.$.doneButton.setDisabled(!index);
      if (index) {
        this.$.editor.setValue(model);
        model.used({
          success: function (resp) {
            that.$.deleteButton.setDisabled(resp);
          }
        });
        if (this.$.panels.getIndex()) { this.$.panels.setIndex(0); }
        this.$.prevButton.setDisabled(index === 0);
        this.$.nextButton.setDisabled(index === this.$.list.value.length - 1);
      } else {
        if (!this.$.panels.getIndex()) { this.$.panels.setIndex(1); }
        this.$.prevButton.setDisabled(true);
        this.$.nextButton.setDisabled(true);
      }
    },
    transitionFinished: function (inSender, inEvent) {
      if (inEvent.originator.name === 'panels') {
        if (this.$.panels.getIndex() === 1) {
          this.doneItem();
        }
        return true;
      }
    },
    valueChanged: function () {
      var value = this.getValue();
      this.$.list.setValue(value);
    }
  });

}());
<|endoftext|>


<commit_before>'use strict';
define(
    [
        'config',
        'three',
        'stats',
        'Hud',
        'InputHandler',
        'Debug',
        'Camera',
        'GameObjectManager',
        'Grid'
    ],
    function(config, THREE, Stats, Hud, InputHandler, Debug, Camera, GameObjectManager, Grid) {
        // Initialize stats
        let stats = new Stats();
        stats.showPanel(0);
        document.body.appendChild(stats.dom);

        // Create & initialize renderer
        let renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(config.canvasWidth, config.canvasHeight);
        document.getElementById('game').appendChild(renderer.domElement);
        config.maxAnisotropy = renderer.getMaxAnisotropy();
        window.addEventListener('resize', onWindowResize, false);

        // Create scene
        let scene = new THREE.Scene();
        scene.fog = new THREE.Fog(0x000000, 100, 1000);

        // Create HUD
        let hud = new Hud();

        // Create camera
        let camera = new Camera(
            scene,
            renderer,
            config.camera.fov,
            config.canvasWidth / config.canvasHeight,
            config.camera.near,
            config.camera.far,
            new THREE.Vector3(
                config.camera.initialPosition.x,
                config.camera.initialPosition.y,
                config.camera.initialPosition.z
            )
        );

        scene.background = createCubeMap();
        scene.add(new THREE.AmbientLight(0x101010));

        GameObjectManager.add(new Grid(scene, 'xz_grid', { moveWithCamera: true }));
        GameObjectManager.load('assets/data/galaxy.json', scene, beginGame);

        // Declare variables to calculate deltaT
        // and smoothed deltaT
        let lastFrameTime    = 0;
        let lastDeltaTValues = [];
        let smoothDeltaT     = 0;
        let inputHandler     = null;

        // #############################################################################################################

        function createCubeMap() {
            // Create cube map
            let baseUrl = 'assets/textures/';
            let format = '.png';
            let urls = [
                baseUrl + 'px' + format, baseUrl + 'nx' + format,
                baseUrl + 'py' + format, baseUrl + 'ny' + format,
                baseUrl + 'pz' + format, baseUrl + 'nz' + format
            ];

            let cube = new THREE.CubeTextureLoader().load(urls);
            cube.format = THREE.RGBFormat;

            return cube;
        }

        // #############################################################################################################

        function beginGame() {
            requestAnimationFrame(update);
            inputHandler = new InputHandler(scene, camera, GameObjectManager.get('player'));
        }

        // #############################################################################################################

        function update(currentFrameTime) {
            stats.begin();
            Debug.clear();

            let deltaT = currentFrameTime - lastFrameTime;
            lastFrameTime = currentFrameTime;

            // Ugly hack to prevent "jumps" when the tab lost focus
            if(deltaT > 32) deltaT = 1000/60;

            // Smooth deltaT
            while(lastDeltaTValues.length >= config.framesToSmoothDeltaT) {
                lastDeltaTValues.splice(0, 1);
            }
            lastDeltaTValues.push(deltaT);
            smoothDeltaT = lastDeltaTValues.reduce(function(prev, cur) { return prev + cur;}) / lastDeltaTValues.length;

            // Update controls
            camera.controls.update();

            // Handle user input
            inputHandler.checkInput();

            // Update all the objects' positions
            GameObjectManager.updatePositions(deltaT, smoothDeltaT);

            // Update all the objects
            GameObjectManager.update(deltaT, smoothDeltaT);

            // Update HUD
            hud.update();

            // Render the scene
            renderer.render(scene, camera.camera);

            // Render HUD
            renderer.render(hud.scene, hud.camera);

            stats.end();
            requestAnimationFrame(update);
        }

        // #############################################################################################################

        function onWindowResize() {
            camera.camera.aspect = window.innerWidth / window.innerHeight;
            camera.camera.updateProjectionMatrix();

            renderer.setSize(window.innerWidth, window.innerHeight);
        }

        // #############################################################################################################
    }
);
<commit_msg>Using ES2016 imports now<commit_after>'use strict';

import * as THREE        from './lib/three';

import Camera            from './classes/Camera';
import GameObjectManager from './classes/GameObjectManager';
import Grid              from './classes/Grid';
import Hud               from './classes/Hud';
import InputHandler      from './classes/InputHandler';
import Stats             from './lib/stats';

import config from './config';

// Initialize stats
let stats = new Stats();
stats.showPanel(0);
document.body.appendChild(stats.dom);

// Create & initialize renderer
let renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(config.canvasWidth, config.canvasHeight);
document.getElementById('game').appendChild(renderer.domElement);
config.maxAnisotropy = renderer.getMaxAnisotropy();
window.addEventListener('resize', onWindowResize, false);

// Create scene
let scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x000000, 100, 1000);

// Create HUD
let hud = new Hud();

// Create camera
let camera = new Camera(
    scene,
    renderer,
    config.camera.fov,
    config.canvasWidth / config.canvasHeight,
    config.camera.near,
    config.camera.far,
    new THREE.Vector3(
        config.camera.initialPosition.x,
        config.camera.initialPosition.y,
        config.camera.initialPosition.z
    )
);

scene.background = createCubeMap();
scene.add(new THREE.AmbientLight(0x101010));

GameObjectManager.add(new Grid(scene, 'xz_grid', { moveWithCamera: true }));
GameObjectManager.load('assets/data/galaxy.json', scene, beginGame);

// Declare variables to calculate deltaT
// and smoothed deltaT
let lastFrameTime    = 0;
let lastDeltaTValues = [];
let smoothDeltaT     = 0;
let inputHandler     = null;

// #############################################################################################################

function createCubeMap() {
    // Create cube map
    let baseUrl = 'assets/textures/';
    let format = '.png';
    let urls = [
        baseUrl + 'px' + format, baseUrl + 'nx' + format,
        baseUrl + 'py' + format, baseUrl + 'ny' + format,
        baseUrl + 'pz' + format, baseUrl + 'nz' + format
    ];

    let cube = new THREE.CubeTextureLoader().load(urls);
    cube.format = THREE.RGBFormat;

    return cube;
}

// #############################################################################################################

function beginGame() {
    requestAnimationFrame(update);
    inputHandler = new InputHandler(scene, camera, GameObjectManager.get('player'));
}

// #############################################################################################################

function update(currentFrameTime) {
    stats.begin();
    Debug.clear();

    let deltaT = currentFrameTime - lastFrameTime;
    lastFrameTime = currentFrameTime;

    // Ugly hack to prevent "jumps" when the tab lost focus
    if(deltaT > 32) deltaT = 1000/60;

    // Smooth deltaT
    while(lastDeltaTValues.length >= config.framesToSmoothDeltaT) {
        lastDeltaTValues.splice(0, 1);
    }
    lastDeltaTValues.push(deltaT);
    smoothDeltaT = lastDeltaTValues.reduce(function(prev, cur) { return prev + cur;}) / lastDeltaTValues.length;

    // Update controls
    camera.controls.update();

    // Handle user input
    inputHandler.checkInput();

    // Update all the objects' positions
    GameObjectManager.updatePositions(deltaT, smoothDeltaT);

    // Update all the objects
    GameObjectManager.update(deltaT, smoothDeltaT);

    // Update HUD
    hud.update();

    // Render the scene
    renderer.render(scene, camera.camera);

    // Render HUD
    renderer.render(hud.scene, hud.camera);

    stats.end();
    requestAnimationFrame(update);
}

// #############################################################################################################

function onWindowResize() {
    camera.camera.aspect = window.innerWidth / window.innerHeight;
    camera.camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);
}

// #############################################################################################################<|endoftext|>


<commit_before>pavlov.specify("Omega.Planet", function(){
describe("Omega.Planet", function(){
  it("converts location", function(){
    var planet = new Omega.Planet({location :
      {json_class : 'Motel::Location', data : {x: 10, y: 20, z:30}}});
    assert(planet.location).isOfType(Omega.Location);
    assert(planet.location.x).equals(10);
    assert(planet.location.y).equals(20);
    assert(planet.location.z).equals(30);
  });

  describe("#load_gfx", function(){
    describe("graphics are initialized", function(){
      var orig;

      before(function(){
        orig = {gfx: Omega.Planet.gfx,
                mesh: Omega.Planet.gfx ? Omega.Planet.gfx.mesh : null};
      })

      after(function(){
        Omega.Planet.gfx = orig.gfx;
        if(Omega.Planet.gfx) Omega.Planet.gfx.mesh = orig.mesh;
      });

      it("does nothing / just returns", function(){
        Omega.Planet.gfx = {};
        Omega.Planet.mesh = null;
        new Omega.Planet().load_gfx();
        assert(Omega.Planet.mesh).isNull();
      });
    });

    it("creates mesh for Planet", function(){
      Omega.Test.Canvas.Entities();
      assert(Omega.Planet.gfx.mesh).isOfType(THREE.Mesh);
      assert(Omega.Planet.gfx.mesh.geometry).isOfType(THREE.SphereGeometry);
      assert(Omega.Planet.gfx.mesh.material).isOfType(THREE.MeshLambertMaterial);
    });

    it("creates orbit material for Planet", function(){
      Omega.Test.Canvas.Entities();
      assert(Omega.Planet.gfx.orbit_material).isOfType(THREE.LineBasicMaterial);
    });
  });

  describe("#_load_material", function(){
    it("loads texture corresponding to color", function(){
      var page   = Omega.Test.Page();
      var basepath = 'http://' + page.config.http_host + page.config.url_prefix + page.config.images_path + '/textures/planet';
      var planet = Omega.Test.Canvas.Entities().planet;
      planet.color = '000000';
      var mat = planet._load_material(page.config, function(){});
      assert(mat.map.image.src).equals(basepath + '0.png');
      planet.color = '000001';
      mat = planet._load_material(page.config, function(){});
      assert(mat.map.image.src).equals(basepath + '1.png');
    });
  });

  describe("#_calc_orbit", function(){
    it("sets planet orbit properties", function(){
      var ms  = {e : 0, p : 10, speed: 1.57,
                 dmajx: 0, dmajy : 1, dmajz : 0,
                 dminx: 0, dminy : 0, dminz : 1};
      var loc = new Omega.Location({id : 42, movement_strategy : ms});
      var pl  = new Omega.Planet({location : loc});
      pl._calc_orbit();

      assert(pl.a).equals(10);
      assert(pl.b).equals(10);
      assert(pl.le).equals(0);
      assert(pl.cx).equals(0);
      assert(pl.cy).equals(0);
      assert(pl.cz).equals(0);
      assert(pl.rot_plane.angle).close(1.57,2);
      assert(pl.rot_axis.angle).close(1.57,2);

      assert(pl.rot_plane.axis[0]).equals(0)
      assert(pl.rot_plane.axis[1]).equals(1)
      assert(pl.rot_plane.axis[2]).equals(0)
      assert(pl.rot_axis.axis[0]).equals(1)
      assert(pl.rot_axis.axis[1]).equals(0)
      assert(pl.rot_axis.axis[2]).close(0, 0.00001)
    });
  });

  describe("#_init_orbit_gfx", function(){
    it("calculates orbit", function(){
      var pl  = new Omega.Planet({});
      var calc_orbit = sinon.spy(pl, '_calc_orbit')
      pl._init_orbit_gfx();
      sinon.assert.called(calc_orbit);
    });

    it("creates orbit mesh", function(){
      var ms  = {e : 0, p : 10, speed: 1.57,
                 dmajx: 0, dmajy : 1, dmajz : 0,
                 dminx: 0, dminy : 0, dminz : 1};
      var loc = new Omega.Location({id : 42, movement_strategy : ms});
      var pl  = new Omega.Planet({location : loc});
      pl._init_orbit_gfx();
      assert(pl.orbit_mesh).isOfType(THREE.Line);
      // TODO verify actual line vertices
    });
  });

  describe("#init_gfx", function(){
    var config, event_cb;

    before(function(){
      config   = Omega.Config;
      event_cb = function(){};
    });

    after(function(){
      if(Omega.Planet.gfx){
        if(Omega.Planet.gfx.mesh.clone.restore) Omega.Planet.gfx.mesh.clone.restore();
      }
    });

    it("loads planet gfx", function(){
      var planet = new Omega.Planet();
      var load_gfx  = sinon.spy(planet, 'load_gfx');
      planet.init_gfx(config, event_cb);
      sinon.assert.called(load_gfx);
    });

    it("clones Planet mesh", function(){
      Omega.Test.Canvas.Entities();
      var planet = new Omega.Planet();
      var mesh   = new THREE.Mesh();
      sinon.stub(Omega.Planet.gfx.mesh, 'clone').returns(mesh);
      planet.init_gfx(config, event_cb);
      assert(planet.mesh).equals(mesh);
    });

    it("sets mesh omega_entity", function(){
      var planet = new Omega.Planet();
      planet.init_gfx(config, event_cb);
      assert(planet.mesh.omega_entity).equals(planet);
    });

    it("loads/sets planet mesh material", function(){
      var planet = new Omega.Planet({color: 'ABABAB'});
      var material = new THREE.Material();
      var load_material = sinon.stub(planet, '_load_material');
      load_material.returns(material);

      planet.init_gfx(config, event_cb);
      sinon.assert.calledWith(load_material, config, event_cb, '0xABABAB');
    });

    it("refreshes graphics", function(){
      var planet = new Omega.Planet({});
      var update_gfx = sinon.spy(planet, 'update_gfx');
      planet.init_gfx(config, event_cb);
      sinon.assert.called(update_gfx);
    });

    it("loads planet orbit gfx", function(){
      var planet = new Omega.Planet({});
      var init_orbit_gfx = sinon.spy(planet, '_init_orbit_gfx');
      planet.init_gfx(config, event_cb);
      sinon.assert.called(init_orbit_gfx);
    });

    it("adds mesh and orbit mesh to planet scene components", function(){
      var planet = new Omega.Planet();
      planet.init_gfx(config, event_cb);
      assert(planet.components[0]).equals(planet.mesh);
      assert(planet.components[1]).equals(planet.orbit_mesh);
    });
  });

  describe("#update_gfx", function(){
    it("sets mesh position from planet location", function(){
      var planet = Omega.Test.Canvas.Entities().planet;
      planet.location = new Omega.Location({x : 20, y : 30, z : -20});
      planet.update_gfx();
      assert(planet.mesh.position.x).equals( 20);
      assert(planet.mesh.position.y).equals( 30);
      assert(planet.mesh.position.z).equals(-20);
    });
  });

  describe("#run_effects", function(){
    var pl;

    before(function(){

      // XXX should specify full movement strategy & invoke
      // 'pl._calc_orbit' instead of specifying calculated
      // orbit properties manually
      var loc = new Omega.Location({id : 42, x : 0, y : 0, z : 10,
                 movement_strategy : {speed: -1.57}});
      pl  = new Omega.Planet({
                  location : loc,
                  last_moved : new Date() - 1000,
                  a  : 10,  b : 10,
                  cx :  0, cy :  0, cz : 0,
                  rot_axis  : {angle : 0,
                               axis  : [1, 0, 0]},
                  rot_plane : {angle : 1.57,
                               axis  : [1, 0, 0]}});
    });

    it("moves planet", function(){
      // XXX sinon-qunit enables fake timers by default
      this.clock.restore();

      pl.run_effects();
      assert(pl.location.x).close(10,2);
      assert(pl.location.y).close( 0,2);
      assert(pl.location.z).close( 0,2);
    });

    it("refreshes planet graphics", function(){
      var update_gfx = sinon.spy(pl, 'update_gfx');
      pl.last_moved = new Date();
      pl.run_effects();
      sinon.assert.called(update_gfx);
    });

    it("sets planet last movement time", function(){
      pl.last_moved = null;
      pl.run_effects();
      assert(pl.last_moved).isNotNull();
    });
  });
});}); // Omega.Planet
<commit_msg>Fix test broken by #06b233095<commit_after>pavlov.specify("Omega.Planet", function(){
describe("Omega.Planet", function(){
  it("converts location", function(){
    var planet = new Omega.Planet({location :
      {json_class : 'Motel::Location', data : {x: 10, y: 20, z:30}}});
    assert(planet.location).isOfType(Omega.Location);
    assert(planet.location.x).equals(10);
    assert(planet.location.y).equals(20);
    assert(planet.location.z).equals(30);
  });

  describe("#load_gfx", function(){
    describe("graphics are initialized", function(){
      var orig;

      before(function(){
        orig = {gfx: Omega.Planet.gfx,
                mesh: Omega.Planet.gfx ? Omega.Planet.gfx.mesh : null};
      })

      after(function(){
        Omega.Planet.gfx = orig.gfx;
        if(Omega.Planet.gfx) Omega.Planet.gfx.mesh = orig.mesh;
      });

      it("does nothing / just returns", function(){
        Omega.Planet.gfx = {};
        Omega.Planet.mesh = null;
        new Omega.Planet().load_gfx(Omega.Config);
        assert(Omega.Planet.mesh).isNull();
      });
    });

    it("creates mesh for Planet", function(){
      Omega.Test.Canvas.Entities();
      assert(Omega.Planet.gfx.mesh).isOfType(THREE.Mesh);
      assert(Omega.Planet.gfx.mesh.geometry).isOfType(THREE.SphereGeometry);
      assert(Omega.Planet.gfx.mesh.material).isOfType(THREE.MeshLambertMaterial);
    });

    it("creates orbit material for Planet", function(){
      Omega.Test.Canvas.Entities();
      assert(Omega.Planet.gfx.orbit_material).isOfType(THREE.LineBasicMaterial);
    });
  });

  describe("#_load_material", function(){
    it("loads texture corresponding to color", function(){
      var page   = Omega.Test.Page();
      var basepath = 'http://' + page.config.http_host + page.config.url_prefix + page.config.images_path + '/textures/planet';
      var planet = Omega.Test.Canvas.Entities().planet;
      planet.color = '000000';
      var mat = planet._load_material(page.config, function(){});
      assert(mat.map.image.src).equals(basepath + '0.png');
      planet.color = '000001';
      mat = planet._load_material(page.config, function(){});
      assert(mat.map.image.src).equals(basepath + '1.png');
    });
  });

  describe("#_calc_orbit", function(){
    it("sets planet orbit properties", function(){
      var ms  = {e : 0, p : 10, speed: 1.57,
                 dmajx: 0, dmajy : 1, dmajz : 0,
                 dminx: 0, dminy : 0, dminz : 1};
      var loc = new Omega.Location({id : 42, movement_strategy : ms});
      var pl  = new Omega.Planet({location : loc});
      pl._calc_orbit();

      assert(pl.a).equals(10);
      assert(pl.b).equals(10);
      assert(pl.le).equals(0);
      assert(pl.cx).equals(0);
      assert(pl.cy).equals(0);
      assert(pl.cz).equals(0);
      assert(pl.rot_plane.angle).close(1.57,2);
      assert(pl.rot_axis.angle).close(1.57,2);

      assert(pl.rot_plane.axis[0]).equals(0)
      assert(pl.rot_plane.axis[1]).equals(1)
      assert(pl.rot_plane.axis[2]).equals(0)
      assert(pl.rot_axis.axis[0]).equals(1)
      assert(pl.rot_axis.axis[1]).equals(0)
      assert(pl.rot_axis.axis[2]).close(0, 0.00001)
    });
  });

  describe("#_init_orbit_gfx", function(){
    it("calculates orbit", function(){
      var pl  = new Omega.Planet({});
      var calc_orbit = sinon.spy(pl, '_calc_orbit')
      pl._init_orbit_gfx();
      sinon.assert.called(calc_orbit);
    });

    it("creates orbit mesh", function(){
      var ms  = {e : 0, p : 10, speed: 1.57,
                 dmajx: 0, dmajy : 1, dmajz : 0,
                 dminx: 0, dminy : 0, dminz : 1};
      var loc = new Omega.Location({id : 42, movement_strategy : ms});
      var pl  = new Omega.Planet({location : loc});
      pl._init_orbit_gfx();
      assert(pl.orbit_mesh).isOfType(THREE.Line);
      // TODO verify actual line vertices
    });
  });

  describe("#init_gfx", function(){
    var config, event_cb;

    before(function(){
      config   = Omega.Config;
      event_cb = function(){};
    });

    after(function(){
      if(Omega.Planet.gfx){
        if(Omega.Planet.gfx.mesh.clone.restore) Omega.Planet.gfx.mesh.clone.restore();
      }
    });

    it("loads planet gfx", function(){
      var planet = new Omega.Planet();
      var load_gfx  = sinon.spy(planet, 'load_gfx');
      planet.init_gfx(config, event_cb);
      sinon.assert.called(load_gfx);
    });

    it("clones Planet mesh", function(){
      Omega.Test.Canvas.Entities();
      var planet = new Omega.Planet();
      var mesh   = new THREE.Mesh();
      sinon.stub(Omega.Planet.gfx.mesh, 'clone').returns(mesh);
      planet.init_gfx(config, event_cb);
      assert(planet.mesh).equals(mesh);
    });

    it("sets mesh omega_entity", function(){
      var planet = new Omega.Planet();
      planet.init_gfx(config, event_cb);
      assert(planet.mesh.omega_entity).equals(planet);
    });

    it("loads/sets planet mesh material", function(){
      var planet = new Omega.Planet({color: 'ABABAB'});
      var material = new THREE.Material();
      var load_material = sinon.stub(planet, '_load_material');
      load_material.returns(material);

      planet.init_gfx(config, event_cb);
      sinon.assert.calledWith(load_material, config, event_cb, '0xABABAB');
    });

    it("refreshes graphics", function(){
      var planet = new Omega.Planet({});
      var update_gfx = sinon.spy(planet, 'update_gfx');
      planet.init_gfx(config, event_cb);
      sinon.assert.called(update_gfx);
    });

    it("loads planet orbit gfx", function(){
      var planet = new Omega.Planet({});
      var init_orbit_gfx = sinon.spy(planet, '_init_orbit_gfx');
      planet.init_gfx(config, event_cb);
      sinon.assert.called(init_orbit_gfx);
    });

    it("adds mesh and orbit mesh to planet scene components", function(){
      var planet = new Omega.Planet();
      planet.init_gfx(config, event_cb);
      assert(planet.components[0]).equals(planet.mesh);
      assert(planet.components[1]).equals(planet.orbit_mesh);
    });
  });

  describe("#update_gfx", function(){
    it("sets mesh position from planet location", function(){
      var planet = Omega.Test.Canvas.Entities().planet;
      planet.location = new Omega.Location({x : 20, y : 30, z : -20});
      planet.update_gfx();
      assert(planet.mesh.position.x).equals( 20);
      assert(planet.mesh.position.y).equals( 30);
      assert(planet.mesh.position.z).equals(-20);
    });
  });

  describe("#run_effects", function(){
    var pl;

    before(function(){

      // XXX should specify full movement strategy & invoke
      // 'pl._calc_orbit' instead of specifying calculated
      // orbit properties manually
      var loc = new Omega.Location({id : 42, x : 0, y : 0, z : 10,
                 movement_strategy : {speed: -1.57}});
      pl  = new Omega.Planet({
                  location : loc,
                  last_moved : new Date() - 1000,
                  a  : 10,  b : 10,
                  cx :  0, cy :  0, cz : 0,
                  rot_axis  : {angle : 0,
                               axis  : [1, 0, 0]},
                  rot_plane : {angle : 1.57,
                               axis  : [1, 0, 0]}});
    });

    it("moves planet", function(){
      // XXX sinon-qunit enables fake timers by default
      this.clock.restore();

      pl.run_effects();
      assert(pl.location.x).close(10,2);
      assert(pl.location.y).close( 0,2);
      assert(pl.location.z).close( 0,2);
    });

    it("refreshes planet graphics", function(){
      var update_gfx = sinon.spy(pl, 'update_gfx');
      pl.last_moved = new Date();
      pl.run_effects();
      sinon.assert.called(update_gfx);
    });

    it("sets planet last movement time", function(){
      pl.last_moved = null;
      pl.run_effects();
      assert(pl.last_moved).isNotNull();
    });
  });
});}); // Omega.Planet
<|endoftext|>


<commit_before>var express = require('express'),
    jwt = require("jwt-simple"),
    config = require("config"),
    game = require("../model/game");

var router = express.Router();

// define the home page route
router.get('/', function(req, res) {
   game.allGames(function (games) {
      res.jsonp(games);
   });
})

module.exports = router;
<commit_msg>Added game info lookup<commit_after>var express = require('express'),
    jwt = require("jwt-simple"),
    config = require("config"),
    game = require("../model/game"),
    debug = require('debug')('spectator');

var router = express.Router();

// define the base page route
router.get('/', function(req, res) {
   game.allGames(function (games) {
      res.jsonp(games);
   });
})

// define the game page route
router.get('/:gameident', function(req, res) {
   game.fetchGame(req.gameident, function(gameModel) {
      res.jsonp({
         'meta': {
            'code': 200
         },
         'payload': {
            'game': gameModel
         }
      });
   });
})

// route middleware to validate :gameident
router.param('gameident', function(req, res, next, gameident) {
   debug('validating gameident: ['+gameident+']');

   if (gameident.match(/[[:xdigit:]]*/g)) {
      req.gameident = gameident;
      next();
   }else {
      debug('gameident ['+gameident+'] is not valid');

      res.jsonp({
         'meta': {
            'error': 'invalid game identifier',
            'code': 400
         },
         'payload': {}
      });
   }
});

module.exports = router;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function Headers(headers) {
    this.map = {}

    var self = this
    if (headers instanceof Headers) {
      headers.forEach(function(name, values) {
        values.forEach(function(value) {
          self.append(name, value)
        })
      })

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        self.append(name, headers[name])
      })
    }
  }

  Headers.prototype.append = function(name, value) {
    name = name.toLowerCase()
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[name.toLowerCase()]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[name.toLowerCase()]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[name.toLowerCase()] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(name.toLowerCase())
  }

  Headers.prototype.set = function(name, value) {
    this.map[name.toLowerCase()] = [value]
  }

  // Instead of iterable for now.
  Headers.prototype.forEach = function(callback) {
    var self = this
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      callback(name, self.map[name])
    })
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var blobSupport = 'FileReader' in self && 'Blob' in self && (function() {
    try {
      new Blob();
      return true
    } catch(e) {
      return false
    }
  })();

  function Body() {
    this.bodyUsed = false

    if (blobSupport) {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if ('Blob' in self && Blob.prototype.isPrototypeOf(body)) {
          this._bodyBlob = body
        } else if ('FormData' in self && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if ('FormData' in self && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if ('FormData' in self) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(url, options) {
    options = options || {}
    this.url = url

    this.credentials = options.credentials || 'omit'
    this.headers = new Headers(options.headers)
    this.method = normalizeMethod(options.method || 'GET')
    this.mode = options.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && options.body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(options.body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Request.prototype.fetch = function() {
    var self = this

    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest()

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      xhr.onload = function() {
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(self.method, self.url, true)
      if ('responseType' in xhr && blobSupport) {
        xhr.responseType = 'blob'
      }

      self.headers.forEach(function(name, values) {
        values.forEach(function(value) {
          xhr.setRequestHeader(name, value)
        })
      })

      xhr.send(typeof self._bodyInit === 'undefined' ? null : self._bodyInit)
    })
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.statusText = options.statusText
    this.headers = options.headers
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function (url, options) {
    return new Request(url, options).fetch()
  }
  self.fetch.polyfill = true
})();
<commit_msg>If cors, with credentials<commit_after>(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function Headers(headers) {
    this.map = {}

    var self = this
    if (headers instanceof Headers) {
      headers.forEach(function(name, values) {
        values.forEach(function(value) {
          self.append(name, value)
        })
      })

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        self.append(name, headers[name])
      })
    }
  }

  Headers.prototype.append = function(name, value) {
    name = name.toLowerCase()
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[name.toLowerCase()]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[name.toLowerCase()]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[name.toLowerCase()] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(name.toLowerCase())
  }

  Headers.prototype.set = function(name, value) {
    this.map[name.toLowerCase()] = [value]
  }

  // Instead of iterable for now.
  Headers.prototype.forEach = function(callback) {
    var self = this
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      callback(name, self.map[name])
    })
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var blobSupport = 'FileReader' in self && 'Blob' in self && (function() {
    try {
      new Blob();
      return true
    } catch(e) {
      return false
    }
  })();

  function Body() {
    this.bodyUsed = false

    if (blobSupport) {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if ('Blob' in self && Blob.prototype.isPrototypeOf(body)) {
          this._bodyBlob = body
        } else if ('FormData' in self && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if ('FormData' in self && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if ('FormData' in self) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(url, options) {
    options = options || {}
    this.url = url

    this.credentials = options.credentials || 'omit'
    this.headers = new Headers(options.headers)
    this.method = normalizeMethod(options.method || 'GET')
    this.mode = options.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && options.body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(options.body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Request.prototype.fetch = function() {
    var self = this

    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest()
      if (self.credentials === 'cors') {
        xhr.withCredentials = true;
      }

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      xhr.onload = function() {
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(self.method, self.url, true)
      if ('responseType' in xhr && blobSupport) {
        xhr.responseType = 'blob'
      }

      self.headers.forEach(function(name, values) {
        values.forEach(function(value) {
          xhr.setRequestHeader(name, value)
        })
      })

      xhr.send(typeof self._bodyInit === 'undefined' ? null : self._bodyInit)
    })
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.statusText = options.statusText
    this.headers = options.headers
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function (url, options) {
    return new Request(url, options).fetch()
  }
  self.fetch.polyfill = true
})();
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Mickael Jeanroy
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

var gulp = require('gulp');
var rename = require('gulp-rename');
var vulcanize = require('gulp-vulcanize');

module.exports = function(options) {
  gulp.task('vulcanize:csp', ['less', 'minify:polymer'], function() {
    return gulp.src('src/polymer/waffle-polymer.html')
      .pipe(rename('waffle-polymer-csp.html'))
      .pipe(gulp.dest(options.dist));
  });

  gulp.task('vulcanize', ['vulcanize:csp'], function() {
    return gulp.src(options.dist + '/waffle-polymer-csp.html')
        .pipe(vulcanize({
            abspath: '',
            excludes: [],
            stripExcludes: false,
            inlineScripts: true,
            inlineCss: true
        }))
        .pipe(rename('waffle-polymer.html'))
        .pipe(gulp.dest(options.dist));
  });
};<commit_msg>fix: fix polymer vulcanize build<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Mickael Jeanroy
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

var gulp = require('gulp');
var rename = require('gulp-rename');
var vulcanize = require('gulp-vulcanize');

module.exports = function(options) {
  gulp.task('vulcanize:csp', ['less', 'minify:polymer'], function() {
    return gulp.src('src/polymer/waffle-polymer.html')
      .pipe(rename('waffle-polymer-csp.html'))
      .pipe(gulp.dest(options.dist));
  });

  gulp.task('vulcanize', ['vulcanize:csp'], function() {
    return gulp.src(options.dist + '/waffle-polymer-csp.html')
        .pipe(vulcanize({
            abspath: '/',
            excludes: [],
            stripExcludes: false,
            inlineScripts: true,
            inlineCss: true
        }))
        .pipe(rename('waffle-polymer.html'))
        .pipe(gulp.dest(options.dist));
  });
};<|endoftext|>