<commit_before>var ref = new Firebase("https://phaser-app.firebaseio.com/");

var gameInfo = [];

var menuState = {

    create: function() {

       menuText = game.add.text(200, 200, 'welcome to the rock', { font: '24px Arial', fill: '#fff' });
       this.game.stage.backgroundColor = 0x330033;
       game.input.onDown.add(start, this);

    ref.once("value", function(snapshot) {
      var newPost = snapshot.val();
      gameInfo.push(newPost);
      addToTable(gameInfo)

 });

    //function to append a row to the table
function addToTable(gameInfo){

  // console.log(gameInfo[0])

  var newArr = [];

  $.each(gameInfo[0], function(key, value){
    // console.log(value)
    newArr.push(value)

  });

  newArr.sort(function(a, b){
    return(b.score - a.score)
  });
  // console.log(newArr)

var table = $("table")

for (i = 0; i < 10; i++){
  table.append("

");
  var $target = $("tr:last");

  $target.append(""+ newArr[i].name +"	");
  $target.append(""+ newArr[i].score +"	");
  }

}
}
   }

function start(){

  score = 0;
  $('button').prop("disabled",false);
  game.state.start('game',true, false);
}

var diedState = {

  create: function() {

    diedText = game.add.text(200, 200, 'You crashed with a score of ' + score + '. Click to play again', { font: '24px Arial', fill: '#fff' });
    var input = $('.input-container');
    input.css('display','initial');
    var button = $('button');

    button.on('click', function(){
      var name = $('input').val();
      if (name != '') {
      ref.push({name: name, score: score})
      }
      $(this).prop("disabled",true);
      $('input').val('');
    });
    game.input.onDown.add(start, this);
  }
}

var GameState = function(game) {
};

// Load images and sounds
GameState.prototype.preload = function() {
    this.game.load.spritesheet('ship', '/assets/ship.png', 32, 32);
    this.game.load.image('ground', '/assets/ground.png');
    this.game.load.spritesheet('explosion', '/assets/explosion.png', 128, 128);
    this.game.load.image('grapes', '/assets/grapes.png');

};

    var score = 0;
    var scoreString = '';
    var scoreText;

// Setup the example
GameState.prototype.create = function() {

    var input = $('.input-container');
    input.css('display','none');

    scoreString = 'Score: ';
    scoreText = game.add.text(32, 32, scoreString + score, { font: '24px Arial', fill: '#fff' });

    game.time.events.loop(100, updateScore, this);

    // Set stage background color
    this.game.stage.backgroundColor = 0x333333;

    // Define motion constants
    // // this.ROTATION_SPEED = 180; // degrees/second
    // this.ACCELERATION = 2000; // pixels/second/second
    this.MAX_SPEED = 250; // pixels/second
    this.DRAG = 100; // pixels/second
    this.GRAVITY = 400; // pixels/second/second

    // Add the ship to the stage
    this.ship = this.game.add.sprite(0, 0, 'ship');
    this.ship.anchor.setTo(0.5, 0.5);
    this.ship.angle = 0; // Point the ship up

    // Enable physics on the ship
    this.game.physics.enable(this.ship, Phaser.Physics.ARCADE);

    this.ship.body.collideWorldBounds = true;

    // this.ship.gravity = 300;

    // // Set maximum velocity
    this.ship.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED); // x, y

    // Add drag to the ship that slows it down when it is not accelerating
    this.ship.body.drag.setTo(this.DRAG, this.DRAG); // x, y

    // Choose a random starting angle and velocity for the ship
    this.resetShip();

    // Turn on gravity
    game.physics.arcade.gravity.y = this.GRAVITY;

    // Make ship bounce a little
    this.ship.body.bounce.setTo(0.25, 0.25);

     function updateScore() {

          score += 1;
          scoreText.text = scoreString + score;
}

     function updateGrapeScore() {
           score += 250;
           scoreText.text = scoreString + score;

     }

speed = 3000;
    game.time.events.loop(speed, sendGrapes, this);

    this.bunch = this.game.add.group();
    function sendGrapes(){

    // this.ground = this.game.add.group();
    for (x = 0; x < this.game.rnd.integerInRange(0, 1); x += 1) {
        var randomValue = this.game.rnd.integerInRange(100, 300);
        // Add the ground blocks, enable physics on each, make them immovable
        var grapes = this.game.add.sprite(game.width + 32, randomValue, 'grapes');
        grapes.width = 32;
        grapes.height = 32;
        this.game.physics.enable(grapes, Phaser.Physics.ARCADE);
        grapes.body.immovable = true;
        grapes.body.allowGravity = false;
        grapes.body.velocity.x = -300;
        // groundBlock.body.velocity.y = -10;
        this.bunch.add(grapes);

    }
  }

speed = 600;
    game.time.events.loop(speed, send, this);

    this.ground = this.game.add.group();
    function send(){

    // this.ground = this.game.add.group();
    for (x = 0; x < this.game.rnd.integerInRange(1, 2); x += 1) {
        var randomValue = this.game.rnd.integerInRange(0, 400);
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(game.width + 32, randomValue, 'ground');
        groundBlock.width = 32;
        groundBlock.height = 32;
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        groundBlock.body.velocity.x = -300;
        // groundBlock.body.velocity.y = -10;
        this.ground.add(groundBlock);

    }
  }
//make top and bottom borders
      for(var x = 0; x < this.game.width; x += 32) {
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
        var topBlock = this.game.add.sprite(x, this.game.height - 400, 'ground');
        topBlock.width = 32;
        topBlock.height = 32;
        groundBlock.width = 32;
        groundBlock.height = 32;
        this.game.physics.enable(topBlock, Phaser.Physics.ARCADE);
        topBlock.body.immovable = true;
        topBlock.body.allowGravity = false;
        this.ground.add(topBlock);
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        this.ground.add(groundBlock);
    }

    // Create a group for explosions
    this.explosionGroup = this.game.add.group();

    // Capture certain keys to prevent their default actions in the browser.
    // This is only necessary because this is an HTML5 game. Games on other
    // platforms may not need code like this.
    this.game.input.keyboard.addKeyCapture([
        Phaser.Keyboard.LEFT,
        Phaser.Keyboard.RIGHT,
        Phaser.Keyboard.UP,
        Phaser.Keyboard.DOWN
    ]);
};

// Try to get a used explosion from the explosionGroup.
// If an explosion isn't available, create a new one and add it to the group.
// Setup new explosions so that they animate and kill themselves when the
// animation is complete.
GameState.prototype.getExplosion = function(x, y) {
    // Get the first dead explosion from the explosionGroup
    var explosion = this.explosionGroup.getFirstDead();

    // If there aren't any available, create a new one
    if (explosion === null) {
        explosion = this.game.add.sprite(0, 0, 'explosion');
        explosion.anchor.setTo(0.5, 0.5);

        // Add an animation for the explosion that kills the sprite when the
        // animation is complete
        var animation = explosion.animations.add('boom', [0,1,2,3], 60, false);
        animation.killOnComplete = true;

        // Add the explosion sprite to the group
        this.explosionGroup.add(explosion);
    }

    // Revive the explosion (set it's alive property to true)
    // You can also define a onRevived event handler in your explosion objects
    // to do stuff when they are revived.
    explosion.revive();

    // Move the explosion to the given coordinates
    explosion.x = x;
    explosion.y = y;

    // Set rotation of the explosion at random for a little variety
    explosion.angle = this.game.rnd.integerInRange(0, 360);

    // Play the animation
    explosion.animations.play('boom');

    // Return the explosion itself in case we want to do anything else with it
    return explosion;
};

GameState.prototype.resetShip = function() {
    // Move the ship back to the top of the stage and set score back to zero
    this.ship.x = 100;
    this.ship.y = 100;
    this.ship.body.acceleration.setTo(0, 0);
    this.ship.body.velocity.setTo(0,0)

};

// The update() method is called every frame
GameState.prototype.update = function() {

      // Collide the ship with the grapes
    if(this.game.physics.arcade.overlap(this.ship, this.bunch)){

           score += 10;
           scoreText.text = scoreString + score;
           this.bunch.active = false;

          }

    // Collide the ship with the ground
    if(this.game.physics.arcade.collide(this.ship, this.ground)){

            this.getExplosion(this.ship.x, this.ship.y);
            this.resetShip()
            game.state.start('died',true, false);
          }

    if (this.upInputIsActive()) {
        // If the UP key is down, thrust
        // Calculate acceleration vector based on this.angle and this.ACCELERATION
        // this.ship.body.acceleration.x = Math.cos(this.ship.rotation) * this.ACCELERATION;
        // this.ship.body.acceleration.y = Math.sin(this.ship.rotation) * this.ACCELERATION;
        this.ship.body.velocity.y = -120;
        // Show the frame from the spritesheet with the engine on
        this.ship.frame = 1;
    } else {
        // Otherwise, stop thrusting
        // this.ship.body.acceleration.setTo(0, 0);

        // Show the frame from the spritesheet with the engine off
        this.ship.frame = 0;
    }
};

GameState.prototype.upInputIsActive = function() {
    var isActive = false;

    isActive = this.input.keyboard.isDown(Phaser.Keyboard.UP);
    isActive |= (this.game.input.activePointer.isDown &&
        this.game.input.activePointer.x > this.game.width/4 &&
        this.game.input.activePointer.x < this.game.width/2 + this.game.width/4);

    return isActive;
};

var game = new Phaser.Game(1000, 400, Phaser.CANVAS, 'roy');

game.state.add('game', GameState, true);
game.state.add('menu', menuState);
game.state.add('died', diedState);
game.state.start('menu');
// game.state.start('game',true, false);

<commit_msg>gradual increase in speed like the dinosaur game<commit_after>var ref = new Firebase("https://phaser-app.firebaseio.com/");

var gameInfo = [];

var menuState = {

  create: function() {

    menuText = game.add.text(200, 200, 'welcome to the rock', {
      font: '24px Arial',
      fill: '#fff'
    });

    this.game.stage.backgroundColor = 0x330033;
    game.input.onDown.add(start, this);

    ref.once("value", function(snapshot) {
      var newPost = snapshot.val();
      gameInfo.push(newPost);
      addToTable(gameInfo)
    });

    //function to append a row to the table
    function addToTable(gameInfo) {

      // console.log(gameInfo[0])

      var newArr = [];

      $.each(gameInfo[0], function(key, value) {
        // console.log(value)
        newArr.push(value)
      });

      newArr.sort(function(a, b) {
        return (b.score - a.score)
      });

      var table = $("table")

      for (i = 0; i < 10; i++) {

        table.append("

");
        var $target = $("tr:last");
        $target.append("" + newArr[i].name + "	");
        $target.append("" + newArr[i].score + "	");
      }
    }
  }
}

function start() {

  score = 0;
  $('button').prop("disabled", false);
  game.state.start('game', true, false);
}

var diedState = {

  create: function() {

    diedText = game.add.text(200, 200, 'You crashed with a score of ' + score + '. Click to play again', {
      font: '24px Arial',
      fill: '#fff'
    });
    var input = $('.input-container');
    input.css('display', 'initial');
    var button = $('button');

    button.on('click', function() {
      var name = $('input').val();
      if (name != '') {
        ref.push({
          name: name,
          score: score
        })
      }
      $(this).prop("disabled", true);
      $('input').val('');
    });
    game.input.onDown.add(start, this);
  }
}

var GameState = function(game) {};

// Load images and sounds
GameState.prototype.preload = function() {
  this.game.load.spritesheet('ship', '/assets/ship.png', 32, 32);
  this.game.load.image('ground', '/assets/ground.png');
  this.game.load.spritesheet('explosion', '/assets/explosion.png', 128, 128);
  this.game.load.image('grapes', '/assets/grapes.png');

};

var score = 0;
var scoreString = '';
var scoreText;

GameState.prototype.create = function() {

  var input = $('.input-container');
  input.css('display', 'none');
  scoreString = 'Score: ';
  scoreText = game.add.text(32, 32, scoreString + score, {
    font: '24px Arial',
    fill: '#fff'
  });

  game.time.events.loop(100, updateScore, this);

  // Set stage background color
  this.game.stage.backgroundColor = 0x333333;

  this.MAX_SPEED = 250; // pixels/second
  this.DRAG = 100; // pixels/second
  this.GRAVITY = 400; // pixels/second/second

  this.ship = this.game.add.sprite(0, 0, 'ship');
  this.ship.anchor.setTo(0.5, 0.5);
  this.ship.angle = 0;

  // Enable physics on the ship
  this.game.physics.enable(this.ship, Phaser.Physics.ARCADE);

  this.ship.body.collideWorldBounds = true;

  // // Set maximum velocity
  this.ship.body.maxVelocity.setTo(this.MAX_SPEED, this.MAX_SPEED); // x, y

  // Add drag to the ship that slows it down when it is not accelerating
  this.ship.body.drag.setTo(this.DRAG, this.DRAG); // x, y

  // Choose a random starting angle and velocity for the ship
  this.resetShip();

  // Turn on gravity
  game.physics.arcade.gravity.y = this.GRAVITY;

  // Make ship bounce a little
  this.ship.body.bounce.setTo(0.25, 0.25);

  function updateScore() {

    score += 1;
    scoreText.text = scoreString + score;
  }

  speed = 3000;
  game.time.events.loop(speed, sendGrapes, this);

  this.bunch = this.game.add.group();

  function sendGrapes() {

    // this.ground = this.game.add.group();
    for (x = 0; x < this.game.rnd.integerInRange(0, 1); x += 1) {
      var randomValue = this.game.rnd.integerInRange(100, 300);
      // Add the ground blocks, enable physics on each, make them immovable
      var grapes = this.game.add.sprite(game.width + 32, randomValue, 'grapes');
      grapes.width = 32;
      grapes.height = 32;
      this.game.physics.enable(grapes, Phaser.Physics.ARCADE);
      grapes.body.immovable = true;
      grapes.body.allowGravity = false;
      grapes.body.velocity.x = velocity -100;
      // groundBlock.body.velocity.y = -10;
      this.bunch.add(grapes);

    }
  }

  speed = 600;
  velocity = -350;
  game.time.events.loop(speed, send, this);

  this.ground = this.game.add.group();

  function send() {

      // this.ground = this.game.add.group();
      for (x = 0; x < this.game.rnd.integerInRange(1, 2); x += 1) {
        var randomValue = this.game.rnd.integerInRange(0, 400);
        // Add the ground blocks, enable physics on each, make them immovable
        var groundBlock = this.game.add.sprite(game.width + 32, randomValue, 'ground');
        groundBlock.width = 32;
        groundBlock.height = 32;
        this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
        groundBlock.body.immovable = true;
        groundBlock.body.allowGravity = false;
        velocity -= 1;
        groundBlock.body.velocity.x = velocity;
        // groundBlock.body.velocity.y = -10;
        this.ground.add(groundBlock);

      }
    }
    //make top and bottom borders
  for (var x = 0; x < this.game.width; x += 32) {
    // Add the ground blocks, enable physics on each, make them immovable
    var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
    var topBlock = this.game.add.sprite(x, this.game.height - 400, 'ground');
    topBlock.width = 32;
    topBlock.height = 32;
    groundBlock.width = 32;
    groundBlock.height = 32;
    this.game.physics.enable(topBlock, Phaser.Physics.ARCADE);
    topBlock.body.immovable = true;
    topBlock.body.allowGravity = false;
    this.ground.add(topBlock);
    this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
    groundBlock.body.immovable = true;
    groundBlock.body.allowGravity = false;
    this.ground.add(groundBlock);
  }

  // Create a group for explosions
  this.explosionGroup = this.game.add.group();

  // Capture certain keys to prevent their default actions in the browser.
  // This is only necessary because this is an HTML5 game. Games on other
  // platforms may not need code like this.
  this.game.input.keyboard.addKeyCapture([
    Phaser.Keyboard.LEFT,
    Phaser.Keyboard.RIGHT,
    Phaser.Keyboard.UP,
    Phaser.Keyboard.DOWN
  ]);
};

// Try to get a used explosion from the explosionGroup.
// If an explosion isn't available, create a new one and add it to the group.
// Setup new explosions so that they animate and kill themselves when the
// animation is complete.
GameState.prototype.getExplosion = function(x, y) {
  // Get the first dead explosion from the explosionGroup
  var explosion = this.explosionGroup.getFirstDead();

  // If there aren't any available, create a new one
  if (explosion === null) {
    explosion = this.game.add.sprite(0, 0, 'explosion');
    explosion.anchor.setTo(0.5, 0.5);

    // Add an animation for the explosion that kills the sprite when the
    // animation is complete
    var animation = explosion.animations.add('boom', [0, 1, 2, 3], 60, false);
    animation.killOnComplete = true;

    // Add the explosion sprite to the group
    this.explosionGroup.add(explosion);
  }

  // Revive the explosion (set it's alive property to true)
  // You can also define a onRevived event handler in your explosion objects
  // to do stuff when they are revived.
  explosion.revive();

  // Move the explosion to the given coordinates
  explosion.x = x;
  explosion.y = y;

  // Set rotation of the explosion at random for a little variety
  explosion.angle = this.game.rnd.integerInRange(0, 360);

  // Play the animation
  explosion.animations.play('boom');

  // Return the explosion itself in case we want to do anything else with it
  return explosion;
};

GameState.prototype.resetShip = function() {
  // Move the ship back to the top of the stage and set score back to zero
  this.ship.x = 100;
  this.ship.y = 100;
  this.ship.body.acceleration.setTo(0, 0);
  this.ship.body.velocity.setTo(0, 0)

};

// The update() method is called every frame
GameState.prototype.update = function() {

  // Collide the ship with the grapes
  if (this.game.physics.arcade.overlap(this.ship, this.bunch)) {

    score += 10;
    scoreText.text = scoreString + score;
    this.bunch.active = false;

  }

  // Collide the ship with the ground
  if (this.game.physics.arcade.collide(this.ship, this.ground)) {

    this.getExplosion(this.ship.x, this.ship.y);
    this.resetShip()
    game.state.start('died', true, false);
  }

  if (this.upInputIsActive()) {
    // If the UP key is down, thrust
    // Calculate acceleration vector based on this.angle and this.ACCELERATION
    // this.ship.body.acceleration.x = Math.cos(this.ship.rotation) * this.ACCELERATION;
    // this.ship.body.acceleration.y = Math.sin(this.ship.rotation) * this.ACCELERATION;
    this.ship.body.velocity.y = -120;
    // Show the frame from the spritesheet with the engine on
    this.ship.frame = 1;
  } else {
    // Otherwise, stop thrusting
    // this.ship.body.acceleration.setTo(0, 0);

    // Show the frame from the spritesheet with the engine off
    this.ship.frame = 0;
  }
};

GameState.prototype.upInputIsActive = function() {
  var isActive = false;

  isActive = this.input.keyboard.isDown(Phaser.Keyboard.UP);
  isActive |= (this.game.input.activePointer.isDown &&
    this.game.input.activePointer.x > this.game.width / 4 &&
    this.game.input.activePointer.x < this.game.width / 2 + this.game.width / 4);

  return isActive;
};

var game = new Phaser.Game(1000, 400, Phaser.CANVAS, 'roy');

game.state.add('game', GameState, true);
game.state.add('menu', menuState);
game.state.add('died', diedState);
game.state.start('menu');
// game.state.start('game',true, false);

<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { Section, Container, Box, Hidden, LayoutProvider } from '../src';
import Notification from './Notification';
import Welcome from './Welcome';
import VSCode from './Examples/VSCode';
import { injectGlobal } from 'styled-components';

injectGlobal`
  body {
    margin: 0;
    font-family: sans-serif;
  }
  code.hljs {
    border-radius: 4px;
    padding: 15px 25px;
    max-width: 100%;
    overflow: scroll;
  }
  ul {
    padding: 0;
    list-style: none;
    li {
      margin-bottom: 8px;
    }
  }
  a {
    color: dodgerblue;
  }
`;

storiesOf('Welcome', module)
  .add('Box Sizes (xs)', () => (
    <Welcome />
  ));

storiesOf('Vertical Boxes', module)
  .add('Box Sizes (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have only have the xs property set.

        <Container direction="vertical">
          <Box xs={1} />
          <Box xs={2} />
          <Box xs={3} />
          <Box xs={4} />
          <Box xs={5} />
          <Box xs={6} />
          <Box xs={7} />
          <Box xs={8} />
          <Box xs={9} />
          <Box xs={10} />
          <Box xs={11} />
          <Box xs={12} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have only have the sm property set.

        <Container direction="vertical">
          <Box sm={1} />
          <Box sm={2} />
          <Box sm={3} />
          <Box sm={4} />
          <Box sm={5} />
          <Box sm={6} />
          <Box sm={7} />
          <Box sm={8} />
          <Box sm={9} />
          <Box sm={10} />
          <Box sm={11} />
          <Box sm={12} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have only have the md property set.

        <Container direction="vertical">
          <Box md={1} />
          <Box md={2} />
          <Box md={3} />
          <Box md={4} />
          <Box md={5} />
          <Box md={6} />
          <Box md={7} />
          <Box md={8} />
          <Box md={9} />
          <Box md={10} />
          <Box md={11} />
          <Box md={12} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have only have the lg property set.

        <Container direction="vertical">
          <Box lg={1} />
          <Box lg={2} />
          <Box lg={3} />
          <Box lg={4} />
          <Box lg={5} />
          <Box lg={6} />
          <Box lg={7} />
          <Box lg={8} />
          <Box lg={9} />
          <Box lg={10} />
          <Box lg={11} />
          <Box lg={12} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box xsShift="100px">xsShift="100px"</Box>
          <Box xsShift="50%">xsShift="50%"</Box>
          <Box xsShift="auto">xsShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box smShift="100px">smShift="100px"</Box>
          <Box smShift="50%">smShift="50%"</Box>
          <Box smShift="auto">smShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box mdShift="100px">mdShift="100px"</Box>
          <Box mdShift="50%">mdShift="50%"</Box>
          <Box mdShift="auto">mdShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box lgShift="100px">lgShift="100px"</Box>
          <Box lgShift="50%">lgShift="50%"</Box>
          <Box lgShift="auto">lgShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ));

storiesOf('Horizontal Boxes', module)
  .add('Box Sizes (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have xs="grow" set on them

        <Container direction="horizontal">
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have sm="grow" set on them

        <Container direction="horizontal">
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have md="grow" set on them

        <Container direction="horizontal">
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have lg="grow" set on them

        <Container direction="horizontal">
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an xsShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box xsShift={0} />
          <Box xsShift={1} />
          <Box xsShift={2} />
          <Box xsShift={3} />
          <Box xsShift={4} />
          <Box xsShift={5} />
          <Box xsShift={6} />
          <Box xsShift={7} />
          <Box xsShift={8} />
          <Box xsShift={9} />
          <Box xsShift={10} />
          <Box xsShift={11} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an smShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box smShift={0} />
          <Box smShift={1} />
          <Box smShift={2} />
          <Box smShift={3} />
          <Box smShift={4} />
          <Box smShift={5} />
          <Box smShift={6} />
          <Box smShift={7} />
          <Box smShift={8} />
          <Box smShift={9} />
          <Box smShift={10} />
          <Box smShift={11} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an mdShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box mdShift={0} />
          <Box mdShift={1} />
          <Box mdShift={2} />
          <Box mdShift={3} />
          <Box mdShift={4} />
          <Box mdShift={5} />
          <Box mdShift={6} />
          <Box mdShift={7} />
          <Box mdShift={8} />
          <Box mdShift={9} />
          <Box mdShift={10} />
          <Box mdShift={11} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an lgShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box lgShift={0} />
          <Box lgShift={1} />
          <Box lgShift={2} />
          <Box lgShift={3} />
          <Box lgShift={4} />
          <Box lgShift={5} />
          <Box lgShift={6} />
          <Box lgShift={7} />
          <Box lgShift={8} />
          <Box lgShift={9} />
          <Box lgShift={10} />
          <Box lgShift={11} />
        </Container>

    </LayoutProvider>
  ));

storiesOf('Hidden', module)
  .add('xs', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on xs

        <Hidden xs><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ))
  .add('sm', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on sm

        <Hidden sm><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ))
  .add('md', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on md

        <Hidden md><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ))
  .add('lg', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on lg

        <Hidden lg><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ));

storiesOf('LayoutProvider', module)
  .add('Default Layout', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={20}>

          This layout is using the default breakpoints:
          500, 768, and 1100.

        <Container>
          <Box xs={12}>Header</Box>
        </Container>
        <Container>
          <Box sm={3}>Sidebar</Box>
          <Box sm={9} fluid>
            <Container>
              <Box md={6} lg={4}>A blog post</Box>
              <Box md={6} lg={4}>Another blog post</Box>
              <Box md={6} lg={4}>Yet another blog post</Box>
            </Container>
          </Box>
        </Container>
        <Container>
          <Box xs={12}>Footer</Box>
        </Container>

    </LayoutProvider>
  ));

storiesOf('Layout Examples', module)
  .add('Notifications', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={20}>

          <Container direction="vertical">
            {
              [...Array(4)].map((e, i) =>
                <Box key={i}>
                  <Notification>This is a notification</Notification>
                </Box>)
            }
          </Container>

        <Container>
          <Box xs="100%">Header</Box>
        </Container>
        <Container>
          <Box xs="grow" sm="25%">Sidebar</Box>
          <Box sm="grow" fluid>
            <Container>
              <Box sm="100%" md="50%" lg="grow">A blog post</Box>
              <Box sm="100%" md="50%" lg="grow">Another blog post</Box>
              <Box sm="100%" md="50%" lg="grow">Yet another blog post</Box>
            </Container>
          </Box>
        </Container>
        <Container>
          <Box xs="100%">Footer</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('VSCode Inspired', () => (
    <VSCode />
  ));
<commit_msg>fix vertical box sizes stories<commit_after>import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { Section, Container, Box, Hidden, LayoutProvider } from '../src';
import Notification from './Notification';
import Welcome from './Welcome';
import VSCode from './Examples/VSCode';
import { injectGlobal } from 'styled-components';

injectGlobal`
  body {
    margin: 0;
    font-family: sans-serif;
  }
  code.hljs {
    border-radius: 4px;
    padding: 15px 25px;
    max-width: 100%;
    overflow: scroll;
  }
  ul {
    padding: 0;
    list-style: none;
    li {
      margin-bottom: 8px;
    }
  }
  a {
    color: dodgerblue;
  }
`;

storiesOf('Welcome', module)
  .add('Box Sizes (xs)', () => (
    <Welcome />
  ));

storiesOf('Vertical Boxes', module)
  .add('Box Sizes (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box xs="100px">xs="100px"</Box>
          <Box xs="50%">xs="50%"</Box>
          <Box xs="grow">xs="grow"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box sm="100px">sm="100px"</Box>
          <Box sm="50%">sm="50%"</Box>
          <Box sm="grow">sm="grow"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box md="100px">md="100px"</Box>
          <Box md="50%">md="50%"</Box>
          <Box md="grow">md="grow"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box lg="100px">lg="100px"</Box>
          <Box lg="50%">lg="50%"</Box>
          <Box lg="grow">lg="grow"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box xsShift="100px">xsShift="100px"</Box>
          <Box xsShift="50%">xsShift="50%"</Box>
          <Box xsShift="auto">xsShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box smShift="100px">smShift="100px"</Box>
          <Box smShift="50%">smShift="50%"</Box>
          <Box smShift="auto">smShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box mdShift="100px">mdShift="100px"</Box>
          <Box mdShift="50%">mdShift="50%"</Box>
          <Box mdShift="auto">mdShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

        <Container direction="vertical">
          <Box lgShift="100px">lgShift="100px"</Box>
          <Box lgShift="50%">lgShift="50%"</Box>
          <Box lgShift="auto">lgShift="auto"</Box>
        </Container>

    </LayoutProvider>
  ));

storiesOf('Horizontal Boxes', module)
  .add('Box Sizes (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have xs="grow" set on them

        <Container direction="horizontal">
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
          <Box xs="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have sm="grow" set on them

        <Container direction="horizontal">
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
          <Box sm="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have md="grow" set on them

        <Container direction="horizontal">
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
          <Box md="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Sizes (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have lg="grow" set on them

        <Container direction="horizontal">
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
          <Box lg="grow">Test</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (xs)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an xsShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box xsShift={0} />
          <Box xsShift={1} />
          <Box xsShift={2} />
          <Box xsShift={3} />
          <Box xsShift={4} />
          <Box xsShift={5} />
          <Box xsShift={6} />
          <Box xsShift={7} />
          <Box xsShift={8} />
          <Box xsShift={9} />
          <Box xsShift={10} />
          <Box xsShift={11} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (sm)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an smShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box smShift={0} />
          <Box smShift={1} />
          <Box smShift={2} />
          <Box smShift={3} />
          <Box smShift={4} />
          <Box smShift={5} />
          <Box smShift={6} />
          <Box smShift={7} />
          <Box smShift={8} />
          <Box smShift={9} />
          <Box smShift={10} />
          <Box smShift={11} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (md)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an mdShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box mdShift={0} />
          <Box mdShift={1} />
          <Box mdShift={2} />
          <Box mdShift={3} />
          <Box mdShift={4} />
          <Box mdShift={5} />
          <Box mdShift={6} />
          <Box mdShift={7} />
          <Box mdShift={8} />
          <Box mdShift={9} />
          <Box mdShift={10} />
          <Box mdShift={11} />
        </Container>

    </LayoutProvider>
  ))
  .add('Box Shift (lg)', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={10}>

          These boxes have no set size, only an lgShift property.
        They automatically flex based on the amount of room left.

        <Container direction="horizontal">
          <Box lgShift={0} />
          <Box lgShift={1} />
          <Box lgShift={2} />
          <Box lgShift={3} />
          <Box lgShift={4} />
          <Box lgShift={5} />
          <Box lgShift={6} />
          <Box lgShift={7} />
          <Box lgShift={8} />
          <Box lgShift={9} />
          <Box lgShift={10} />
          <Box lgShift={11} />
        </Container>

    </LayoutProvider>
  ));

storiesOf('Hidden', module)
  .add('xs', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on xs

        <Hidden xs><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ))
  .add('sm', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on sm

        <Hidden sm><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ))
  .add('md', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on md

        <Hidden md><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ))
  .add('lg', () => (
    <LayoutProvider debug={{ enabled: true }}>

          This row is hidden on lg

        <Hidden lg><Container><Box /></Container></Hidden>

    </LayoutProvider>
  ));

storiesOf('LayoutProvider', module)
  .add('Default Layout', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={20}>

          This layout is using the default breakpoints:
          500, 768, and 1100.

        <Container>
          <Box xs={12}>Header</Box>
        </Container>
        <Container>
          <Box sm={3}>Sidebar</Box>
          <Box sm={9} fluid>
            <Container>
              <Box md={6} lg={4}>A blog post</Box>
              <Box md={6} lg={4}>Another blog post</Box>
              <Box md={6} lg={4}>Yet another blog post</Box>
            </Container>
          </Box>
        </Container>
        <Container>
          <Box xs={12}>Footer</Box>
        </Container>

    </LayoutProvider>
  ));

storiesOf('Layout Examples', module)
  .add('Notifications', () => (
    <LayoutProvider debug={{ enabled: true }} gutter={20}>

          <Container direction="vertical">
            {
              [...Array(4)].map((e, i) =>
                <Box key={i}>
                  <Notification>This is a notification</Notification>
                </Box>)
            }
          </Container>

        <Container>
          <Box xs="100%">Header</Box>
        </Container>
        <Container>
          <Box xs="grow" sm="25%">Sidebar</Box>
          <Box sm="grow" fluid>
            <Container>
              <Box sm="100%" md="50%" lg="grow">A blog post</Box>
              <Box sm="100%" md="50%" lg="grow">Another blog post</Box>
              <Box sm="100%" md="50%" lg="grow">Yet another blog post</Box>
            </Container>
          </Box>
        </Container>
        <Container>
          <Box xs="100%">Footer</Box>
        </Container>

    </LayoutProvider>
  ))
  .add('VSCode Inspired', () => (
    <VSCode />
  ));
<|endoftext|>


<commit_before>import React from 'react';
import { setAddon, storiesOf } from '@storybook/react';
import { withKnobs, text } from '@storybook/addon-knobs';
import Moment from '../src/index';

const dateToFormat = '1976-04-19T12:59-0500';

storiesOf('Moment', module)
  .addDecorator(withKnobs)
  .addWithJSX('standard', () => {
      return (
        <Moment date={text('date', dateToFormat)} />
      )
    }
  )
  .addWithJSX('formatting', () => {
    return (
      <Moment format="YYYY/MM/DD" date={text('date', dateToFormat)} />
    )
  })
  .addWithJSX('fromNow', () => {
    return (
      <Moment fromNow date={text('date', dateToFormat)} />
    )
  })
  .addWithJSX('unix', () => {
    return (
      <Moment unix date={text('unix time', 198784740)} />
    )
  })
;
<commit_msg>Fixes error in story<commit_after>import React from 'react';
import { setAddon, storiesOf } from '@storybook/react';
import { withKnobs, text, number } from '@storybook/addon-knobs';
import Moment from '../src/index';

const dateToFormat = '1976-04-19T12:59-0500';

storiesOf('Moment', module)
  .addDecorator(withKnobs)
  .addWithJSX('standard', () => {
      return (
        <Moment date={text('date', dateToFormat)} />
      )
    }
  )
  .addWithJSX('formatting', () => {
    return (
      <Moment format="YYYY/MM/DD" date={text('date', dateToFormat)} />
    )
  })
  .addWithJSX('fromNow', () => {
    return (
      <Moment fromNow date={text('date', dateToFormat)} />
    )
  })
  .addWithJSX('unix', () => {
    return (
      <Moment unix date={number('unix time', 198784740)} />
    )
  })
;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { storiesOf, action } from '@kadira/storybook';
import PieChart from '../src/index.js';

const ContainDecorator = (story) => (

    {story()}

);

const dataMock = [
  { value: 10, key: 1, color: 'blue' },
  { value: 15, key: 2, color: 'orange' },
  { value: 20, key: 3, color: 'green' },
];

storiesOf('React minimal pie chart', module)
  .addDecorator(ContainDecorator)
  .add('default', () => (
    <PieChart
      data={dataMock}
    />
  ))
  .add('180° arc with custom "startAngle"/"lengthAngle"', () => (
    <PieChart
      data={dataMock}
      startAngle={-180}
      lengthAngle={180}
    />
  ))
  .add('with custom "lineWidth"', () => (
    <PieChart
      data={dataMock}
      lineWidth={15}
    />
  ))
  .add('with custom "lineWidth" + "rounded"', () => (
    <PieChart
      data={dataMock}
      lineWidth={15}
      rounded
    />
  ))
  .add('with custom "lineWidth" + "paddingAngle"', () => (
    <PieChart
      data={dataMock}
      lineWidth={15}
      paddingAngle={5}
    />
  ))
  .add('with custom "style" height', () => (
    <PieChart
      data={dataMock}
      style={{ height: '100px' }}
    />
  ))
  .add('uncomplete chart with custom "totalValue"', () => (
    <PieChart
      data={dataMock}
      totalValue={60}
    />
  ))
  .add('animation on mount with "animate"', () => (
    <PieChart
      data={dataMock}
      animate
    />
  ))
  .add('as a loading bar with "reveal"', () => {
    const Wrapper = class Wrapper extends Component {
      constructor(props) {
        super(props);

        this.state = {
          percentage: 20,
        }

        this.handleRangeChange = this.handleRangeChange.bind(this);
      }

      handleRangeChange(e) {
        const newValue = e.target.value;
        this.setState(() => ({ percentage: Number(newValue) }));
      }

      render() {
        return(

            <PieChart
              data={[
                { value: 1, key: 1, color: 'blue' },
              ]}
              reveal={this.state.percentage}
              animate
            />
          Reveal: {this.state.percentage}%
            <input
              type="range"
              min="0"
              max="100"
              step="1"
              value={this.state.percentage}
              style={{width: '100%'}}
              onChange={this.handleRangeChange}
            />

        );
      }
    };

    return <Wrapper />;
  })
<commit_msg>Add a story for counterclockwise chart<commit_after>import React, { Component } from 'react';
import { storiesOf, action } from '@kadira/storybook';
import PieChart from '../src/index.js';

const ContainDecorator = (story) => (

    {story()}

);

const dataMock = [
  { value: 10, key: 1, color: 'blue' },
  { value: 15, key: 2, color: 'orange' },
  { value: 20, key: 3, color: 'green' },
];

storiesOf('React minimal pie chart', module)
  .addDecorator(ContainDecorator)
  .add('default', () => (
    <PieChart
      data={dataMock}
    />
  ))
  .add('180° arc with custom "startAngle"/"lengthAngle"', () => (
    <PieChart
      data={dataMock}
      startAngle={-180}
      lengthAngle={180}
    />
  ))
  .add('with custom "lineWidth"', () => (
    <PieChart
      data={dataMock}
      lineWidth={15}
    />
  ))
  .add('with custom "lineWidth" + "rounded"', () => (
    <PieChart
      data={dataMock}
      lineWidth={15}
      rounded
    />
  ))
  .add('with custom "lineWidth" + "paddingAngle"', () => (
    <PieChart
      data={dataMock}
      lineWidth={15}
      paddingAngle={5}
    />
  ))
  .add('with custom "style" height', () => (
    <PieChart
      data={dataMock}
      style={{ height: '100px' }}
    />
  ))
  .add('uncomplete chart with custom "totalValue"', () => (
    <PieChart
      data={dataMock}
      totalValue={60}
    />
  ))
  .add('animation on mount with "animate"', () => (
    <PieChart
      data={dataMock}
      animate
    />
  ))
  .add('animation on mount with "animate" and negative lengthAngle', () => (
    <PieChart
      data={dataMock}
      lengthAngle={-360}
      animate
    />
  ))
  .add('as a loading bar with "reveal"', () => {
    const Wrapper = class Wrapper extends Component {
      constructor(props) {
        super(props);

        this.state = {
          percentage: 20,
        }

        this.handleRangeChange = this.handleRangeChange.bind(this);
      }

      handleRangeChange(e) {
        const newValue = e.target.value;
        this.setState(() => ({ percentage: Number(newValue) }));
      }

      render() {
        return(

            <PieChart
              data={[
                { value: 1, key: 1, color: 'blue' },
              ]}
              reveal={this.state.percentage}
              animate
            />
          Reveal: {this.state.percentage}%
            <input
              type="range"
              min="0"
              max="100"
              step="1"
              value={this.state.percentage}
              style={{width: '100%'}}
              onChange={this.handleRangeChange}
            />

        );
      }
    };

    return <Wrapper />;
  })
<|endoftext|>


<commit_before>/**
 *	ACTIVE-CHART => simple, responsive d3 charts
 *
 **/
;( function(d3) {

	'use strict';

	// String to Int parsing method
	String.prototype.toInt = function() {
		return parseInt(this, 10);
	};

	// hold all constant data for the project
	// includes api defaults; error messages; encapsulated properties (perhaps)
	var _consts = {

		error: {
		'invalidId': 'first function parameter much be a valid element id',
		'invalidOrient': 'orient property much be set to either veritical or horizontal'
		},

		defaults: {
			'height': 1000,
			'scale': 1,
			'innerPadding': 0,
			'outerPadding': 0,
			'orient': 'vertical'
		}

		// MAY add default custom color range for d3 chart later (unknown data length??)
	},

	_util = {

		is: function(entity, type) {
			var clas = Object.prototype.toString.call(entity).slice(8, -1);
			return (clas === type);
		},

		setPadding: function(width, dataLen) {

			var datumLen = (width/dataLen);

			return {
				'inner': function(inner) {
					return  datumLen * inner;
				},

				'outer': function(outer) {
					return datumLen * outer;
				}
			};
		}
	},

	// return d3.scale x/y for the charting function
	_scale = (function() {
		var xScale = d3.scale.ordinal(),
		yScale = d3.scale.linear();

		// dimensions -> [width:Number, height:Number]
		// padding -> [innerPadding:Number, outerPadding:Number]
		return function(dimensions, padding) {

			var innerP = padding[0]/dimensions[0],
			outerP = padding[1]/dimensions[1];

			return {
				'xScale': xScale.rangeRoundBands([0, dimensions[0]], innerP, outerP),
				'yScale': yScale.range([dimensions[1], 10])
			};
		};
	})(),

	// take the chartable data
	// can compute domains for d3.scale(s) on the data
	_domain = function(data) {

		return function(scale, domain) {
			return scale.domain(data.map(function(d) { return d[domain]; }));
		};

	},

	// return d3 color scale with set color range
	_color = function(colRange) {
		return d3.scale.ordinal().range(colRange);
	},

	// takes a d3 html node element that can build svg element from
	_svg = function(from) {

		return {
			'create': function(dimensions) {
				return from.append('svg')
					.attr('width', dimensions[0])
					.attr('height', dimensions[1]);
			}
		};
	},

	// d3 chart generatating function
	// takes chart options, set by Active Chart api [node, dimensions, padding, colRang]
	_chart = function(scales, domains, colorScale, node) {

		// height scale for svg
		var height = node.attr('height'),

		// set chart scales
		xScale = scales.xScale,
		yScale = scales.yScale,

		// set domain from which to apply x/y scales
		xDomain = domains[0],
		yDomain = domains[1];

		return function(domain, data) {

			// TODO: generate axis

			// TODO: generate the chart .... really basic right now
			node.selectAll('.bar')
				.data(data)
				.enter()
				.append('rect')
				.attr('x', function(d) { return xScale(d[domain.x]); })
				.attr('width', xScale.rangeBand())
				.attr('y', function(d) { return yScale(d[domain.y]); })
				.attr('height', function(d) { return height - yScale(d[domain.y]); })
				.style('fill', function(d, i) { return colorScale(i); })
				/*
				.each(function() {
					console.log(this);
				})
				*/;
		};
	};

	// Active Chart api
	function ActiveChart(id) {
		try {
			this.node = d3.select(id);
			this.width = this.node.style('width').toInt()
		}
		catch (e) {
			throw new Error(_consts.error.invalidId);
		}
	}

	// set the chart domain from data given (object, [xdomain, ydomain])
	ActiveChart.prototype.data = function(data, domain) {

		this.data = data;

		this.domain = {
			'x': domain[0],
			'y': domain[1]
		};

		return this;
	};

	// width scale (1 -> 100%, .5 -> 50%)
	ActiveChart.prototype.scale = function(widthScale) {
		this.scale = _util.is(widthScale, 'Number')? widthScale : _consts.defaults.scale;

		return this;
	};

	ActiveChart.prototype.height = function(height) {
		this.height = _util.is(height, 'Number')? height : _consts.defaults.height;

		return this;
	};

	// inner & outer chart padding [inner, outer]
	ActiveChart.prototype.padding = function(padding) {

		var paddingInner = padding[0]? padding[0] : _consts.defaults.innerPadding,
		paddingOuter = padding[1]? padding[1] : _consts.defaults.outerPadding;

		this.padding = [paddingInner, paddingOuter];

		return this;
	};

	// veritical or horizontal
	ActiveChart.prototype.orient = function(orient) {

		var isOrientString = _util.is(orient, 'String');

		if(isOrientString) {
			if(orient === 'vertical' || orient === 'horizontal') {
				this.orient = orient;
			} else {
				this.orient = _defaults.orient;
			}
		} else {
			throw new Error(_consts.error.invalidOrient);
		}

		return this;
	};

	// should take a color range array
	ActiveChart.prototype.color = function(colRange) {
		this.colRange = _util.is(colRange, 'Array')? colRange : null;

		return this;
	}

	// draw the chart
	ActiveChart.prototype.draw = function() {

		// apply user defined scale to current container width
		var realWidth = this.width*this.scale,

		padding = _util.setPadding(realWidth, this.data.length),
		innerPadding = padding.inner(this.padding[0]),
		outerPadding = padding.outer(this.padding[1]),

		// array [ width, height]
		dimensions = [realWidth, this.height],

		// { xScale: d3.scale.ordinal, yScale: d3.scale.linear }
		scales = _scale(dimensions, [innerPadding, outerPadding]),

		domain = _domain(this.data),

		// Array [ xScale: d3.domain, yScale, d3.domain ]
		domains = [
			domain(scales['xScale'], this.domain['x']),
			domain(scales['yScale'], this.domain['y'])
		],

		// d3.scale.ordinal with color range OR default 20c
		color = this.colRange? _color(this.colRange) : d3.scale.category20c(),

		// d3 svg node with set width/height
		svgNode = _svg(this.node).create(dimensions);

		// draw the chart using computed properties side-effectfully (for now...)
		_chart(scales, domains, color, svgNode)(this.domain, this.data);
	};

	// removes the need for user to use 'new'
	var activeChart = function(id) {
		return new ActiveChart(id);
	};

	// outward facing api namespace(s)
	window.activeChart = window.AC = activeChart;

} )(d3);<commit_msg>moved setPadding function outside util object as it is project specific<commit_after>/**
 *	ACTIVE-CHART => simple, responsive d3 charts
 *
 **/
;( function(d3) {

	'use strict';

	// String to Int parsing method
	String.prototype.toInt = function() {
		return parseInt(this, 10);
	};

	// hold all constant data for the project
	// includes api defaults; error messages; encapsulated properties (perhaps)
	var _consts = {

		error: {
		'invalidId': 'first function parameter much be a valid element id',
		'invalidOrient': 'orient property much be set to either veritical or horizontal'
		},

		defaults: {
			'height': 1000,
			'scale': 1,
			'innerPadding': 0,
			'outerPadding': 0,
			'orient': 'vertical'
		}

		// MAY add default custom color range for d3 chart later (unknown data length??)
	},

	_util = {

		is: function(entity, type) {
			var clas = Object.prototype.toString.call(entity).slice(8, -1);
			return (clas === type);
		}
	},

	_setPadding = function(width, dataLen) {

		var datumLen = (width/dataLen);

		return {
			'inner': function(inner) {
				return  datumLen * inner;
			},

			'outer': function(outer) {
				return datumLen * outer;
			}
		};
	},

	// return d3.scale x/y for the charting function
	_scale = (function() {
		var xScale = d3.scale.ordinal(),
		yScale = d3.scale.linear();

		// dimensions -> [width:Number, height:Number]
		// padding -> [innerPadding:Number, outerPadding:Number]
		return function(dimensions, padding) {

			var innerP = padding[0]/dimensions[0],
			outerP = padding[1]/dimensions[1];

			return {
				'xScale': xScale.rangeRoundBands([0, dimensions[0]], innerP, outerP),
				'yScale': yScale.range([dimensions[1], 10])
			};
		};
	})(),

	// take the chartable data
	// can compute domains for d3.scale(s) on the data
	_domain = function(data) {

		return function(scale, domain) {
			return scale.domain(data.map(function(d) { return d[domain]; }));
		};

	},

	// return d3 color scale with set color range
	_color = function(colRange) {
		return d3.scale.ordinal().range(colRange);
	},

	// takes a d3 html node element that can build svg element from
	_svg = function(from) {

		return {
			'create': function(dimensions) {
				return from.append('svg')
					.attr('width', dimensions[0])
					.attr('height', dimensions[1]);
			}
		};
	},

	// d3 chart generatating function
	// takes chart options, set by Active Chart api [node, dimensions, padding, colRang]
	_chart = function(scales, domains, colorScale, node) {

		// height scale for svg
		var height = node.attr('height'),

		// set chart scales
		xScale = scales.xScale,
		yScale = scales.yScale,

		// set domain from which to apply x/y scales
		xDomain = domains[0],
		yDomain = domains[1];

		return function(domain, data) {

			// TODO: generate axis

			// TODO: generate the chart .... really basic right now
			node.selectAll('.bar')
				.data(data)
				.enter()
				.append('rect')
				.attr('x', function(d) { return xScale(d[domain.x]); })
				.attr('width', xScale.rangeBand())
				.attr('y', function(d) { return yScale(d[domain.y]); })
				.attr('height', function(d) { return height - yScale(d[domain.y]); })
				.style('fill', function(d, i) { return colorScale(i); })
				/*
				.each(function() {
					console.log(this);
				})
				*/;
		};
	};

	// Active Chart api
	function ActiveChart(id) {
		try {
			this.node = d3.select(id);
			this.width = this.node.style('width').toInt()
		}
		catch (e) {
			throw new Error(_consts.error.invalidId);
		}
	}

	// set the chart domain from data given (object, [xdomain, ydomain])
	ActiveChart.prototype.data = function(data, domain) {

		this.data = data;

		this.domain = {
			'x': domain[0],
			'y': domain[1]
		};

		return this;
	};

	// width scale (1 -> 100%, .5 -> 50%)
	ActiveChart.prototype.scale = function(widthScale) {
		this.scale = _util.is(widthScale, 'Number')? widthScale : _consts.defaults.scale;

		return this;
	};

	ActiveChart.prototype.height = function(height) {
		this.height = _util.is(height, 'Number')? height : _consts.defaults.height;

		return this;
	};

	// inner & outer chart padding [inner, outer]
	ActiveChart.prototype.padding = function(padding) {

		var paddingInner = padding[0]? padding[0] : _consts.defaults.innerPadding,
		paddingOuter = padding[1]? padding[1] : _consts.defaults.outerPadding;

		this.padding = [paddingInner, paddingOuter];

		return this;
	};

	// veritical or horizontal
	ActiveChart.prototype.orient = function(orient) {

		var isOrientString = _util.is(orient, 'String');

		if(isOrientString) {
			if(orient === 'vertical' || orient === 'horizontal') {
				this.orient = orient;
			} else {
				this.orient = _defaults.orient;
			}
		} else {
			throw new Error(_consts.error.invalidOrient);
		}

		return this;
	};

	// should take a color range array
	ActiveChart.prototype.color = function(colRange) {
		this.colRange = _util.is(colRange, 'Array')? colRange : null;

		return this;
	}

	// draw the chart
	ActiveChart.prototype.draw = function() {

		// apply user defined scale to current container width
		var realWidth = this.width*this.scale,

		padding = _setPadding(realWidth, this.data.length),

		innerPadding = padding.inner(this.padding[0]),
		outerPadding = padding.outer(this.padding[1]),

		// array [ width, height]
		dimensions = [realWidth, this.height],

		// { xScale: d3.scale.ordinal, yScale: d3.scale.linear }
		scales = _scale(dimensions, [innerPadding, outerPadding]),

		domain = _domain(this.data),

		// Array [ xScale: d3.domain, yScale, d3.domain ]
		domains = [
			domain(scales['xScale'], this.domain['x']),
			domain(scales['yScale'], this.domain['y'])
		],

		// d3.scale.ordinal with color range OR default 20c
		color = this.colRange? _color(this.colRange) : d3.scale.category20c(),

		// d3 svg node with set width/height
		svgNode = _svg(this.node).create(dimensions);

		// draw the chart using computed properties side-effectfully (for now...)
		_chart(scales, domains, color, svgNode)(this.domain, this.data);
	};

	// removes the need for user to use 'new'
	var activeChart = function(id) {
		return new ActiveChart(id);
	};

	// outward facing api namespace(s)
	window.activeChart = window.AC = activeChart;

} )(d3);<|endoftext|>


<commit_before>/**
 * Copyright 2018, Google, Inc.
 * 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.
 */

'use strict';

// [START automl_quickstart]
// TBD
// [END automl_quickstart]

<commit_msg>feat: add .repo-metadata.json; allows us to generate new docs site (#183)<commit_after>/**
 * Copyright 2019, Google, Inc.
 * 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.
 */

'use strict';

async function main(
  projectId,
  computeRegion,
  modelId,
  filePath,
  scoreThreshold
) {
  // [START automl_quickstart]
  const automl = require('@google-cloud/automl');
  const fs = require('fs');

  // Create client for prediction service.
  const client = new automl.PredictionServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = `The GCLOUD_PROJECT string, e.g. "my-gcloud-project"`;
  // const computeRegion = `region-name, e.g. "us-central1"`;
  // const modelId = `id of the model, e.g. “ICN723541179344731436”`;
  // const filePath = `local text file path of content to be classified, e.g. "./resources/flower.png"`;
  // const scoreThreshold = `value between 0.0 and 1.0, e.g. "0.5"`;

  // Get the full path of the model.
  const modelFullId = client.modelPath(projectId, computeRegion, modelId);

  // Read the file content for prediction.
  const content = fs.readFileSync(filePath, 'base64');

  const params = {};

  if (scoreThreshold) {
    params.score_threshold = scoreThreshold;
  }

  // Set the payload by giving the content and type of the file.
  const payload = {};
  payload.image = {imageBytes: content};

  // params is additional domain-specific parameters.
  // currently there is no additional parameters supported.
  const [response] = await client.predict({
    name: modelFullId,
    payload: payload,
    params: params,
  });
  console.log(`Prediction results:`);
  response.payload.forEach(result => {
    console.log(`Predicted class name: ${result.displayName}`);
    console.log(`Predicted class score: ${result.classification.score}`);
  });
  // [END automl_quickstart]
}
main(...process.argv.slice(2)).catch(err => {
  console.error(err);
  process.exitCode = 1;
});
<|endoftext|>


<commit_before>/*
 * Backbone.Subviews, v1.1.0
 * Copyright (c)2013-2017 Rotunda Software, LLC.
 * Distributed under MIT license
 * http://github.com/rotundasoftware/backbone.subviews
*/
( function( root, factory ) {
	// UMD wrapper
	if ( typeof define === 'function' && define.amd ) {
		// AMD
		define( [ 'underscore', 'backbone', 'jquery' ], factory );
	} else if ( typeof exports !== 'undefined' ) {
		// Node/CommonJS
		module.exports = factory( require('underscore' ), require( 'backbone' ), require( 'backbone' ).$ );
	} else {
		// Browser globals
		factory( root._, root.Backbone, ( root.jQuery || root.Zepto || root.$ ) );
	}
}( this, function( _, Backbone, $ ) {
	Backbone.Subviews = {};

	Backbone.Subviews.add = function( view ) {
		var overriddenViewMethods = {
			render : view.render,
			remove : view.remove
		};

		// ****************** Overridden Backbone.View methods ******************

		view.render = function( options ) {
			var args = Array.prototype.slice.call( arguments );

			_prerender.call( this );
			var returnValue = overriddenViewMethods.render.apply( this, args );
			_postrender.call( this, args );

			return returnValue;
		};

		view.remove = function() {
			this.removeSubviews();
			return overriddenViewMethods.remove.call( this );
		};

		// ****************** Additional public methods ******************

		view.removeSubviews = function() {
			// Removes all subviews and cleans up references in this.subviews.
			var _this = this;

			if( this.subviews ) {
				_.each( this.subviews, function( thisSubview, thisSubviewName ) {
					thisSubview.remove();
					delete _this.subviews[ thisSubviewName ];
				} );
			}
		};

		// ****************** Additional private methods ******************

		view._createSubview = function( subviewName, placeHolderDiv ) {
			// Return a new subview instance given a subview name and its placeHolderDiv.
			// Implemented as instance method so that this behavior may be customized / overridden.
			var subviewCreator = this.subviewCreators[ subviewName ];
			if( _.isUndefined( subviewCreator ) ) throw new Error( "Can not find subview creator for subview named: " + subviewName );

			return subviewCreator.apply( this );
		};
	};

	// ****************** Private utility functions ******************

	function _prerender() {
		if( ! this.subviews ) this.subviews = {};

		// Detach each of our subviews that we have already created during previous
		// renders from the DOM, so that they do not loose their DOM events when
		// we re-render the contents of this view's DOM element.
		_.each( this.subviews, function( thisSubview ) {
			thisSubview.$el.detach();
		} );
	}

	function _postrender( renderArguments ) {
		var _this = this;
		this.subviewCreators = this.subviewCreators || {};

		// Support subviewCreators as both objects and functions.
		if( _.isFunction( this.subviewCreators ) ) this.subviewCreators = this.subviewCreators();

		this.$( "[data-subview]" ).each( function() {
			var thisPlaceHolderDiv = $( this );
			var subviewName = thisPlaceHolderDiv.attr( "data-subview" );
			var newSubview;

			if( _.isUndefined( _this.subviews[ subviewName ] ) ) {
				newSubview = _this._createSubview( subviewName, thisPlaceHolderDiv );
				if( newSubview === null ) return;  // subview creators can return null to indicate that the subview should not be created
				_this.subviews[ subviewName ] = newSubview;
			}
			else {
				// If the subview is already defined, then use the existing subview instead
				// of creating a new one. This allows us to re-render a parent view without
				// loosing any dynamic state data on the existing subview objects. To force
				// re-initialization of subviews, call view.removeSubviews before re-rendering.

				newSubview = _this.subviews[ subviewName ];
			}

			thisPlaceHolderDiv.replaceWith( newSubview.$el );
		} );

		if( _.isFunction( this.onSubviewsCreated ) ) this.onSubviewsCreated.call( this );
		if( _.isFunction( this._onSubviewsCreated ) ) this._onSubviewsCreated.call( this );

		// Now that all subviews have been created, render them one at a time, in the
		// order they occur in the DOM.
		_.each( this.subviews, function( thisSubview ) {
			thisSubview.render.apply( thisSubview, renderArguments );
		} );

		// Call this.onSubviewsRendered after everything is done (hook for application defined logic)
		if( _.isFunction( this.onSubviewsRendered ) ) this.onSubviewsRendered.call( this );
		if( _.isFunction( this._onSubviewsRendered ) ) this._onSubviewsRendered.call( this );
	}

	return Backbone.Subviews;
} ) );
<commit_msg>fix placeholder div getting left in view if subviewCreator returns null<commit_after>/*
 * Backbone.Subviews, v1.1.0
 * Copyright (c)2013-2017 Rotunda Software, LLC.
 * Distributed under MIT license
 * http://github.com/rotundasoftware/backbone.subviews
*/
( function( root, factory ) {
	// UMD wrapper
	if ( typeof define === 'function' && define.amd ) {
		// AMD
		define( [ 'underscore', 'backbone', 'jquery' ], factory );
	} else if ( typeof exports !== 'undefined' ) {
		// Node/CommonJS
		module.exports = factory( require('underscore' ), require( 'backbone' ), require( 'backbone' ).$ );
	} else {
		// Browser globals
		factory( root._, root.Backbone, ( root.jQuery || root.Zepto || root.$ ) );
	}
}( this, function( _, Backbone, $ ) {
	Backbone.Subviews = {};

	Backbone.Subviews.add = function( view ) {
		var overriddenViewMethods = {
			render : view.render,
			remove : view.remove
		};

		// ****************** Overridden Backbone.View methods ******************

		view.render = function( options ) {
			var args = Array.prototype.slice.call( arguments );

			_prerender.call( this );
			var returnValue = overriddenViewMethods.render.apply( this, args );
			_postrender.call( this, args );

			return returnValue;
		};

		view.remove = function() {
			this.removeSubviews();
			return overriddenViewMethods.remove.call( this );
		};

		// ****************** Additional public methods ******************

		view.removeSubviews = function() {
			// Removes all subviews and cleans up references in this.subviews.
			var _this = this;

			if( this.subviews ) {
				_.each( this.subviews, function( thisSubview, thisSubviewName ) {
					thisSubview.remove();
					delete _this.subviews[ thisSubviewName ];
				} );
			}
		};

		// ****************** Additional private methods ******************

		view._createSubview = function( subviewName, placeHolderDiv ) {
			// Return a new subview instance given a subview name and its placeHolderDiv.
			// Implemented as instance method so that this behavior may be customized / overridden.
			var subviewCreator = this.subviewCreators[ subviewName ];
			if( _.isUndefined( subviewCreator ) ) throw new Error( "Can not find subview creator for subview named: " + subviewName );

			return subviewCreator.apply( this );
		};
	};

	// ****************** Private utility functions ******************

	function _prerender() {
		if( ! this.subviews ) this.subviews = {};

		// Detach each of our subviews that we have already created during previous
		// renders from the DOM, so that they do not loose their DOM events when
		// we re-render the contents of this view's DOM element.
		_.each( this.subviews, function( thisSubview ) {
			thisSubview.$el.detach();
		} );
	}

	function _postrender( renderArguments ) {
		var _this = this;
		this.subviewCreators = this.subviewCreators || {};

		// Support subviewCreators as both objects and functions.
		if( _.isFunction( this.subviewCreators ) ) this.subviewCreators = this.subviewCreators();

		this.$( "[data-subview]" ).each( function() {
			var thisPlaceHolderDiv = $( this );
			var subviewName = thisPlaceHolderDiv.attr( "data-subview" );
			var newSubview;

			if( _.isUndefined( _this.subviews[ subviewName ] ) ) {
				newSubview = _this._createSubview( subviewName, thisPlaceHolderDiv );

				if( newSubview === null ) {
					// subview creators can return null to indicate that the subview should not be created
					thisPlaceHolderDiv.remove();
					return;
				}

				_this.subviews[ subviewName ] = newSubview;
			}
			else {
				// If the subview is already defined, then use the existing subview instead
				// of creating a new one. This allows us to re-render a parent view without
				// loosing any dynamic state data on the existing subview objects. To force
				// re-initialization of subviews, call view.removeSubviews before re-rendering.

				newSubview = _this.subviews[ subviewName ];
			}

			thisPlaceHolderDiv.replaceWith( newSubview.$el );
		} );

		if( _.isFunction( this.onSubviewsCreated ) ) this.onSubviewsCreated.call( this );
		if( _.isFunction( this._onSubviewsCreated ) ) this._onSubviewsCreated.call( this );

		// Now that all subviews have been created, render them one at a time, in the
		// order they occur in the DOM.
		_.each( this.subviews, function( thisSubview ) {
			thisSubview.render.apply( thisSubview, renderArguments );
		} );

		// Call this.onSubviewsRendered after everything is done (hook for application defined logic)
		if( _.isFunction( this.onSubviewsRendered ) ) this.onSubviewsRendered.call( this );
		if( _.isFunction( this._onSubviewsRendered ) ) this._onSubviewsRendered.call( this );
	}

	return Backbone.Subviews;
} ) );
<|endoftext|>


<commit_before>phoxy._ApiSubsystem =
{
  ApiAnswer : function( answer, callback )
    {
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);

      function Before()
      {
        function AfterBefore(_answer)
        {
          if (_answer !== undefined)
            answer = _answer;
          phoxy.ScriptsLoaded(answer, callback);
        }

        if (answer.before === undefined)
          return AfterBefore();

        phoxy.FindRouteline(answer.before)(AfterBefore, answer);
      }

      if (answer.script)
        require(answer.script, Before);
      else
        Before();
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        phoxy.FindRouteline(answer.routeline, answer)();
        if (callback)
          callback(answer);
        if (!phoxy.state.loaded)
          phoxy._internal.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var canvas = phoxy.PrepareCanvas('<render>');
      var id = canvas.id;
      var render_id = id;

      var element = canvas.html;

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            document.getElementsByTagName('body')[0].appendChild(canvas.obj);
          else if (typeof answer.result === 'string')
            document.getElementById(answer.result).innerHTML = element;
          else
            for (var k in answer.result)
            {
              var v = document.getElementById(answer.result[k]);
              if (v != null)
                v.innerHTML = element;
            }

        else
          render_id = answer.replace;

        phoxy.RenderReplace(
          render_id,
          answer.design,
          answer.data || {},
          ScriptsFiresUp);
      });
    }
  ,
  FindRouteline : function( routeline )
  {
    if (typeof routeline === 'undefined')
      return function() {};
    if (typeof window[routeline] === 'function')
      return window[routeline];
    var arr = routeline.split(".");
    var method = arr.pop();

    var obj = window;
    for (var k in arr)
      if (typeof obj[arr[k]] === 'undefined')
        throw "Routeline context locate failed";
      else
        obj = obj[arr[k]];

    if (typeof obj[method] !== 'function')
      throw "Routeline locate failed";

    return obj[method];
  }
  ,
  ForwardDownload : function( url, callback_or_true_for_return )
    {
      if (typeof(storage) === "undefined")
        storage = {};

      if (callback_or_true_for_return === true)
        return storage[url];

      function AddToLocalStorage(data)
      {
        storage[url] = data;
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(data);
      }

      if (storage[url] != undefined)
      {
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(storage[url]);
        return true;
      }

      phoxy.ajax(url, AddToLocalStorage);
      return false;
    }
  , // vanilla.js ajax
  ajax : function ()
    {
      phoxy.ajax = phoxy._EarlyStage.ajax;
      phoxy.ajax.apply(this, arguments);
    }
  ,
  AJAX : function( url, callback, params )
    {
      url = phoxy.ConstructURL(url);

      var current_ajax_id = phoxy.state.ajax.active_id++;
      phoxy.state.ajax.active[current_ajax_id] = arguments;

      if (!phoxy.state.ajax.nesting_level++)
        if (typeof phoxy.prestart.OnAjaxBegin === 'function')
          phoxy.prestart.OnAjaxBegin(phoxy.state.ajax.active[current_ajax_id]);

      phoxy.ajax(phoxy.Config()['api_dir'] + "/" + url, function(response)
        {
          data = JSON.parse(response);
          if (params == undefined)
            params = [];
          params.unshift(data);
          callback.apply(this, params);

          if (!--phoxy.state.ajax.nesting_level)
            if (typeof phoxy.prestart.OnAjaxEnd === 'function')
              phoxy.prestart.OnAjaxEnd(phoxy.state.ajax.active[current_ajax_id]);
          delete phoxy.state.ajax.active[current_ajax_id];
        });
    }
  ,
  Serialize : function(obj, nested_mode)
    {
      json_encoded = JSON.stringify(obj);
      send_string = json_encoded.substring(1, json_encoded.length - 1);

      function EscapeReserved(str, reserved)
      {
        reserved_characters = reserved.split('');
        search_string = "\\" + reserved_characters.join("|\\");
        var regexp = new RegExp(search_string, "gi");

        return str.replace(regexp,
          function(matched)
          {
            return escape(escape(matched));
          });
      }

      return EscapeReserved(send_string, "()?#\\");
    }
  ,
  ConstructURL : function(arr)
  {
    if (typeof arr === 'string')
      return arr;

    arr = arr.slice(0);
    var url = arr.shift();
    if (arr.length > 0)
      url += '(' + phoxy.Serialize(arr) + ')';
    return url;
  }
  ,
  ApiRequest : function( url, callback )
    {
      if (phoxy._deprecated.IsObjectOptionalDetected.apply(this, arguments))
        phoxy._deprecated.ObjectOptional(phoxy.MenuCall, arguments);

      url = phoxy.ConstructURL(url);

      phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
      if (phoxy._deprecated.IsObjectOptionalDetected.apply(this, arguments))
        phoxy._deprecated.ObjectOptional(phoxy.MenuCall, arguments);

      phoxy.ChangeURL('/' + url);
      phoxy.ApiRequest(url, callback);
    }
}<commit_msg>Lighten up api submodule<commit_after>phoxy._ApiSubsystem =
{
  ApiAnswer : function( answer, callback )
    {
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);

      function Before()
      {
        function AfterBefore(_answer)
        {
          if (_answer !== undefined)
            answer = _answer;
          phoxy._api.ScriptsLoaded(answer, callback);
        }

        if (answer.before === undefined)
          return AfterBefore();

        phoxy._api.FindRouteline(answer.before)(AfterBefore, answer);
      }

      if (answer.script)
        require(answer.script, Before);
      else
        Before();
    }
  ,
  AJAX : function( url, callback, params )
    {
      url = phoxy.ConstructURL(url);

      var current_ajax_id = phoxy.state.ajax.active_id++;
      phoxy.state.ajax.active[current_ajax_id] = arguments;

      if (!phoxy.state.ajax.nesting_level++)
        if (typeof phoxy.prestart.OnAjaxBegin === 'function')
          phoxy.prestart.OnAjaxBegin(phoxy.state.ajax.active[current_ajax_id]);

      phoxy._api.ajax(phoxy.Config()['api_dir'] + "/" + url, function(response)
        {
          data = JSON.parse(response);
          if (params == undefined)
            params = [];
          params.unshift(data);
          callback.apply(this, params);

          if (!--phoxy.state.ajax.nesting_level)
            if (typeof phoxy.prestart.OnAjaxEnd === 'function')
              phoxy.prestart.OnAjaxEnd(phoxy.state.ajax.active[current_ajax_id]);
          delete phoxy.state.ajax.active[current_ajax_id];
        });
    }
  ,
  ConstructURL : function(arr)
  {
    if (typeof arr === 'string')
      return arr;

    arr = arr.slice(0);
    var url = arr.shift();
    if (arr.length > 0)
      url += '(' + phoxy._api.Serialize(arr) + ')';
    return url;
  }
  ,
  ApiRequest : function( url, callback )
    {
      if (phoxy._deprecated.IsObjectOptionalDetected.apply(this, arguments))
        phoxy._deprecated.ObjectOptional(phoxy.MenuCall, arguments);

      phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
      if (phoxy._deprecated.IsObjectOptionalDetected.apply(this, arguments))
        phoxy._deprecated.ObjectOptional(phoxy.MenuCall, arguments);

      phoxy.ChangeURL(url);
      phoxy.ApiRequest(url, callback);
    }
}

phoxy._ApiSubsystem._api =
{
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        phoxy._api.FindRouteline(answer.routeline, answer)();
        if (callback)
          callback(answer);
        if (!phoxy.state.loaded)
          phoxy._internal.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var canvas = phoxy.PrepareCanvas('<render>');
      var id = canvas.id;
      var render_id = id;

      var element = canvas.html;

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy._api.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            document.getElementsByTagName('body')[0].appendChild(canvas.obj);
          else if (typeof answer.result === 'string')
            document.getElementById(answer.result).innerHTML = element;
          else
            for (var k in answer.result)
            {
              var v = document.getElementById(answer.result[k]);
              if (v != null)
                v.innerHTML = element;
            }

        else
          render_id = answer.replace;

        phoxy.RenderReplace(
          render_id,
          answer.design,
          answer.data || {},
          ScriptsFiresUp);
      });
    }
  ,
  FindRouteline : function( routeline )
  {
    if (typeof routeline === 'undefined')
      return function() {};
    if (typeof window[routeline] === 'function')
      return window[routeline];
    var arr = routeline.split(".");
    var method = arr.pop();

    var obj = window;
    for (var k in arr)
      if (typeof obj[arr[k]] === 'undefined')
        throw "Routeline context locate failed";
      else
        obj = obj[arr[k]];

    if (typeof obj[method] !== 'function')
      throw "Routeline locate failed";

    return obj[method];
  }
  ,
  ForwardDownload : function( url, callback_or_true_for_return )
    {
      if (typeof(storage) === "undefined")
        storage = {};

      if (callback_or_true_for_return === true)
        return storage[url];

      function AddToLocalStorage(data)
      {
        storage[url] = data;
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(data);
      }

      if (storage[url] != undefined)
      {
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(storage[url]);
        return true;
      }

      phoxy.ajax(url, AddToLocalStorage);
      return false;
    }
  ,
  ajax : function ()
    {
      phoxy.ajax = phoxy._EarlyStage.ajax;
      phoxy.ajax.apply(this, arguments);
    }
  ,
  Serialize : function(obj, nested_mode)
    {
      json_encoded = JSON.stringify(obj);
      send_string = json_encoded.substring(1, json_encoded.length - 1);

      function EscapeReserved(str, reserved)
      {
        reserved_characters = reserved.split('');
        search_string = "\\" + reserved_characters.join("|\\");
        var regexp = new RegExp(search_string, "gi");

        return str.replace(regexp,
          function(matched)
          {
            return escape(escape(matched));
          });
      }

      return EscapeReserved(send_string, "()?#\\");
    }
  ,
};<|endoftext|>


<commit_before>var messageTransmitter = require('./messageTransmitter.js');

var processConnect = function(connectedClient, jsonMessage){
//console.log("jsonMessage " + JSON.stringify(jsonMessage));
        connectedClient.data.name = jsonMessage.data.name;
        connectedClient.data.type = jsonMessage.data.clientType;
        connectedClient.data.ready = jsonMessage.data.ready;
/*
        Code mit dem reconnectende Robos gefunden werden können
        Damit dieser funktioniert muss der disconnect Code in websocket.js entsprechend angepasst werden
        und connectedClients muss wieder in diese function übergeben werden.

        for(i in connectedClients) {
            var roboDCName = connectedClient.data.name + "(dc)";
            if(connectedClients.length > 1 && connectedClients[i].data.selectedRobo != undefined) {
                if(connectedClients[i].data.selectedRobo.name === roboDCName) {
                    console.log("equal: " + connectedClients[i].data.selectedRobo.name + " / " + roboDCName);
                    var restoreName = connectedClients[i].data.selectedRobo.name;
                    restoreName = restoreName.substring(0, restoreName.length -5);
                    connectedClients[i].data.selectedRobo.name = restoreName;
                    connectedClients[i].data.ready = "true";
                }
            }
        }*/
    },
    processSpeed = function(roboclient, jsonMessage){
        roboclient.data.speed = jsonMessage.data.speed;
    },
    processRoboSelected = function(appclient, jsonMessage, datamodel){
        var controlledRobo = datamodel.getClientByName(jsonMessage.data.robo);
        appclient.data.selectedRobo = controlledRobo.data;
        controlledRobo.data.controlledBy = appclient.data.name;
    },
    processRoboDeselect = function(appclient, datamodel){
        if(appclient.data.selectedRobo != null) {
            var roboToDeselect = datamodel.getClientByName(appclient.data.selectedRobo.name);
        }
        delete appclient.data.selectedRobo;
        appclient.data.ready = "false";
        if(roboToDeselect) {
            delete roboToDeselect.data.controlledBy;
        }
    },
    processReady = function(appclient, jsonMessage, connectedClients){
        appclient.data.ready = jsonMessage.data.ready;
        var readyClients = 0,
            countRobos = 0,
            assignedClients = [];

        for (i in connectedClients) {
            if (connectedClients[i].data.type == "robo") {
                countRobos+=1;
            } else if (connectedClients[i].data.type == "app" && connectedClients[i].data.selectedRobo && connectedClients[i].data.ready == "true") {
                readyClients+=1;
                assignedClients += connectedClients[i];
            }
        }
        console.log("Pruefe ob  Robos ready sind..." + countRobos + " - " + readyClients);
        if(countRobos == readyClients) {
            console.log("Alle Robos ready")

            messageTransmitter.transmitCountdownStart(assignedClients);
            setTimeout(function() {messageTransmitter.transmitStart(connectedClients)}, 3000);
        }
    }

module.exports = {
    processConnect: processConnect,
    processSpeed: processSpeed,
    processRoboSelected: processRoboSelected,
    processRoboDeselect: processRoboDeselect,
    processReady: processReady
};
<commit_msg>möglicher fix für... #2<commit_after>var messageTransmitter = require('./messageTransmitter.js');

var processConnect = function(connectedClient, jsonMessage){
//console.log("jsonMessage " + JSON.stringify(jsonMessage));
        connectedClient.data.name = jsonMessage.data.name;
        connectedClient.data.type = jsonMessage.data.clientType;
        connectedClient.data.ready = jsonMessage.data.ready;
/*
        Code mit dem reconnectende Robos gefunden werden können
        Damit dieser funktioniert muss der disconnect Code in websocket.js entsprechend angepasst werden
        und connectedClients muss wieder in diese function übergeben werden.

        for(i in connectedClients) {
            var roboDCName = connectedClient.data.name + "(dc)";
            if(connectedClients.length > 1 && connectedClients[i].data.selectedRobo != undefined) {
                if(connectedClients[i].data.selectedRobo.name === roboDCName) {
                    console.log("equal: " + connectedClients[i].data.selectedRobo.name + " / " + roboDCName);
                    var restoreName = connectedClients[i].data.selectedRobo.name;
                    restoreName = restoreName.substring(0, restoreName.length -5);
                    connectedClients[i].data.selectedRobo.name = restoreName;
                    connectedClients[i].data.ready = "true";
                }
            }
        }*/
    },
    processSpeed = function(roboclient, jsonMessage){
        roboclient.data.speed = jsonMessage.data.speed;
    },
    processRoboSelected = function(appclient, jsonMessage, datamodel){
        var controlledRobo = datamodel.getClientByName(jsonMessage.data.robo);
        appclient.data.selectedRobo = controlledRobo.data;
        controlledRobo.data.controlledBy = appclient.data.name;
    },
    processRoboDeselect = function(appclient, datamodel){
        if(appclient.data.selectedRobo != null) {
            var roboToDeselect = datamodel.getClientByName(appclient.data.selectedRobo.name);
        }
        delete appclient.data.selectedRobo;
        appclient.data.ready = "false";
        if(roboToDeselect) {
            delete roboToDeselect.data.controlledBy;
        }
    },
    processReady = function(appclient, jsonMessage, connectedClients){
        appclient.data.ready = jsonMessage.data.ready;
        var readyClients = 0,
            countRobos = 0,
            assignedClients = [];

        for (i in connectedClients) {
            if (connectedClients[i].data.type == "robo") {
                countRobos+=1;
            } else if (connectedClients[i].data.type == "app" && connectedClients[i].data.selectedRobo && connectedClients[i].data.ready == "true") {
                readyClients+=1;
                assignedClients.push(connectedClients[i]);
            }
        }
        console.log("Pruefe ob  Robos ready sind..." + countRobos + " - " + readyClients);
        if(countRobos == readyClients) {
            console.log("Alle Robos ready")

            messageTransmitter.transmitCountdownStart(assignedClients);
            setTimeout(function() {messageTransmitter.transmitStart(connectedClients)}, 3000);
        }
    }

module.exports = {
    processConnect: processConnect,
    processSpeed: processSpeed,
    processRoboSelected: processRoboSelected,
    processRoboDeselect: processRoboDeselect,
    processReady: processReady
};
<|endoftext|>