<commit_before>import ControlledModalWrapper from 'components/Modals/ControlledModalWrapper';
import layerKeys from 'constants/LayerConstants';
import rasterFuncs from 'utils/rasterFunctions';
import {modalText, assetUrls} from 'js/config';
import {loadJS, loadCSS} from 'utils/loaders';
import mapActions from 'actions/MapActions';
import mapStore from 'stores/MapStore';
import utils from 'utils/AppUtils';
import text from 'js/languages';
import React, {
  Component,
  PropTypes
} from 'react';

export default class CanopyModal extends Component {

  static contextTypes = {
    language: PropTypes.string.isRequired,
    settings: PropTypes.object.isRequired,
    map: PropTypes.object.isRequired
  };

  componentDidMount() {
    const base = window._app.base ? window._app.base + '/' : '';
    // loadJS(base + assetUrls.jQuery);
    loadJS(base + assetUrls.rangeSlider).then(() => {
      $('#tree-cover-slider').ionRangeSlider({
        type: 'double',
        values: modalText.canopy.slider,
        hide_min_max: true,
        grid_snap: true,
        to_fixed: true,
        from_min: 1,
        from_max: 7,
        grid: true,
        from: 5,
        onFinish: this.sliderChanged,
        prettify: value => (value + '%')
      });
    }, console.error);
    loadCSS(base + assetUrls.ionCSS);
    loadCSS(base + assetUrls.ionSkinCSS);
  }

  componentDidUpdate(prevProps, prevState, prevContext) {
    //- Set the default canopy density when the map loads
    const {map} = this.context;
    if (!prevContext.map.loaded && map.loaded) {
      const {canopyDensity} = mapStore.getState();
      //- Wait for layers to load
      const signal = map.on('update-end', () => {
        signal.remove(); //- Remove the event so it does not continue ot fire
        this.updateTreeCoverDefinitions(canopyDensity);
        this.updateAGBiomassLayer(canopyDensity);
      });
    }
  }

  updateTreeCoverDefinitions = (density) => {
    const {map, settings} = this.context;
    if (map.loaded) {
      //- Get the layer config, I am hardcoding en becuase I do not need anything language specific, just its config
      const lcGroupLayers = settings.layerPanel.GROUP_LC ? settings.layerPanel.GROUP_LC.layers : [];
      const layerConfig = utils.getObject(lcGroupLayers, 'id', layerKeys.TREE_COVER);
      const layer = map.getLayer(layerKeys.TREE_COVER);

      if (layer && layerConfig) {
        const renderingRule = rasterFuncs.getColormapRemap(layerConfig.colormap, [density, layerConfig.inputRange[1]], layerConfig.outputRange);
        layer.setRenderingRule(renderingRule);
      }
    }
  };

  updateAGBiomassLayer = (density) => {
    const {map} = this.context;
    if (map.loaded) {
      const layer = map.getLayer(layerKeys.AG_BIOMASS);
      const mosaicRule = rasterFuncs.getBiomassMosaicRule(density);

      if (layer) {
        layer.setMosaicRule(mosaicRule);
      }
    }
  };

  sliderChanged = (data) => {
    this.updateTreeCoverDefinitions(data.from_value);
    this.updateAGBiomassLayer(data.from_value);
    //- Update the store, this will allow any other components interested in this information to react
    mapActions.updateCanopyDensity(data.from_value);
  };

  close = () => {
    mapActions.toggleCanopyModal({ visible: false });
  };

  render() {
    const {language} = this.context;

    return (
      <ControlledModalWrapper onClose={this.close}>

{text[language].CANOPY_MODAL_TEXT}

      </ControlledModalWrapper>
    );
  }

}
<commit_msg>Ensuring we have the ionRangeSlider avaiable when we load it<commit_after>import ControlledModalWrapper from 'components/Modals/ControlledModalWrapper';
import layerKeys from 'constants/LayerConstants';
import rasterFuncs from 'utils/rasterFunctions';
import {modalText, assetUrls} from 'js/config';
import {loadJS, loadCSS} from 'utils/loaders';
import mapActions from 'actions/MapActions';
import mapStore from 'stores/MapStore';
import utils from 'utils/AppUtils';
import text from 'js/languages';
import React, {
  Component,
  PropTypes
} from 'react';

export default class CanopyModal extends Component {

  static contextTypes = {
    language: PropTypes.string.isRequired,
    settings: PropTypes.object.isRequired,
    map: PropTypes.object.isRequired
  };

  componentDidMount() {
    const base = window._app.base ? window._app.base + '/' : '';
    this.loadedSlider = false;
    // loadJS(base + assetUrls.jQuery);
    loadJS(base + assetUrls.rangeSlider).then(() => {
      if ($('#tree-cover-slider').ionRangeSlider) {
        $('#tree-cover-slider').ionRangeSlider({
          type: 'double',
          values: modalText.canopy.slider,
          hide_min_max: true,
          grid_snap: true,
          to_fixed: true,
          from_min: 1,
          from_max: 7,
          grid: true,
          from: 5,
          onFinish: this.sliderChanged,
          prettify: value => (value + '%')
        });
        this.loadedSlider = true;
      }

    }, console.error);
    loadCSS(base + assetUrls.ionCSS);
    loadCSS(base + assetUrls.ionSkinCSS);
  }

  componentDidUpdate(prevProps, prevState, prevContext) {
    if (this.loadedSlider === false) {
      if ($('#tree-cover-slider').ionRangeSlider) {
        $('#tree-cover-slider').ionRangeSlider({
          type: 'double',
          values: modalText.canopy.slider,
          hide_min_max: true,
          grid_snap: true,
          to_fixed: true,
          from_min: 1,
          from_max: 7,
          grid: true,
          from: 5,
          onFinish: this.sliderChanged,
          prettify: value => (value + '%')
        });
        this.loadedSlider = true;
      }
    }
    //- Set the default canopy density when the map loads
    const {map} = this.context;
    if (!prevContext.map.loaded && map.loaded) {
      const {canopyDensity} = mapStore.getState();
      //- Wait for layers to load
      const signal = map.on('update-end', () => {
        signal.remove(); //- Remove the event so it does not continue ot fire
        this.updateTreeCoverDefinitions(canopyDensity);
        this.updateAGBiomassLayer(canopyDensity);
      });
    }
  }

  updateTreeCoverDefinitions = (density) => {
    const {map, settings} = this.context;
    if (map.loaded) {
      //- Get the layer config, I am hardcoding en becuase I do not need anything language specific, just its config
      const lcGroupLayers = settings.layerPanel.GROUP_LC ? settings.layerPanel.GROUP_LC.layers : [];
      const layerConfig = utils.getObject(lcGroupLayers, 'id', layerKeys.TREE_COVER);
      const layer = map.getLayer(layerKeys.TREE_COVER);

      if (layer && layerConfig) {
        const renderingRule = rasterFuncs.getColormapRemap(layerConfig.colormap, [density, layerConfig.inputRange[1]], layerConfig.outputRange);
        layer.setRenderingRule(renderingRule);
      }
    }
  };

  updateAGBiomassLayer = (density) => {
    const {map} = this.context;
    if (map.loaded) {
      const layer = map.getLayer(layerKeys.AG_BIOMASS);
      const mosaicRule = rasterFuncs.getBiomassMosaicRule(density);

      if (layer) {
        layer.setMosaicRule(mosaicRule);
      }
    }
  };

  sliderChanged = (data) => {
    this.updateTreeCoverDefinitions(data.from_value);
    this.updateAGBiomassLayer(data.from_value);
    //- Update the store, this will allow any other components interested in this information to react
    mapActions.updateCanopyDensity(data.from_value);
  };

  close = () => {
    mapActions.toggleCanopyModal({ visible: false });
  };

  render() {
    const {language} = this.context;

    return (
      <ControlledModalWrapper onClose={this.close}>

{text[language].CANOPY_MODAL_TEXT}

      </ControlledModalWrapper>
    );
  }

}
<|endoftext|>


<commit_before>/**
 * NAVBAR
 *
 * The navbar controller manages the bar at the top of the screen.
 */

var Amount = ripple.Amount,
    settings = require('../util/settings'),
    rewriter = require('../util/jsonrewriter');

var module = angular.module('navbar', []);

module.controller('NavbarCtrl', ['$scope', '$element', '$compile', 'rpId',
                                 'rpNetwork', '$location',
                                 function ($scope, el, $compile, id,
                                           network, $location)
{
  $scope.loading = true;
  var queue = [];
  var tickInterval = 4000;
  var tickUpcoming = false;

  var tplAccount = require('../../jade/notification/account.jade');

  // Activate #status panel
  $scope.toggle_secondary = function () {
    $scope.show_secondary = !$scope.show_secondary;
  };

  $scope.page_reload = function () {
      // Reload
      location.reload();
  };

  $scope.$watch('fee', function(){
    $scope.currentFee = ripple.Amount.from_json($scope.fee).to_human();

    if(!$scope.connected && $scope.userCredentials.username) {
      $scope.serverStatus = 'disconnected';
    }
    else if ($scope.currentFee && $scope.connected && $scope.currentFee > Options.low_load_threshold && $scope.currentFee < ripple.Amount.from_json(Options.max_tx_network_fee).to_human()) {
      $scope.serverLoad = 'mediumLoad';
      $scope.serverStatus = 'mediumLoad';
    }
    else if ($scope.currentFee && $scope.connected && $scope.currentFee >= ripple.Amount.from_json(Options.max_tx_network_fee).to_human()) {
      $scope.serverLoad = 'highLoad';
      $scope.serverStatus = 'highLoad';
    }
    else if ($scope.currentFee && $scope.connected) {
      $scope.serverLoad = '';
      $scope.serverStatus = 'lowLoad';
    }
    else {
      $scope.serverStatus = 'connected';
    }
  }, true);

  // Username
  $scope.$watch('userCredentials', function(){
    var username = $scope.userCredentials.username;
    if(username) $scope.loading = false;
    $scope.shortUsername = null;

    if(username && username.length > 25) {
      $scope.shortUsername = username.substring(0,24)+'...';
    }
  }, true);

  var updateNotifications = function () {
    if ($scope.events) {
      $scope.notifications = $scope.events.slice(0,10);
    }
  };

  $scope.$on('$eventsUpdate', updateNotifications);

  /**
   * Marks all the notifications as seen.
   */
  $scope.read = function() {
    // don't do anything if account is unfunded
    if (!$scope.notifications.length)
      return;

    var lastTxDate = $scope.notifications[0].date;

    if ($scope.unseen > 0) {
      $scope.unseen = 0;
    }

    if (settings.getSetting($scope.userBlob, 'lastSeenTxDate', 0) < lastTxDate) {
      // Remember last seen date
      $scope.userBlob.set('/clients/rippletradecom/lastSeenTxDate', lastTxDate);

      // Reset the counter
      $scope.unseen = $scope.unseenNotifications.count;
      $scope.unseenNotifications.count = 0;

      // Set seen for all the events
//      _.each($scope.events, function(event){
//        event.unseen = false;
//      })
    }
  };

  /**
   * Graphically display a network-related notifications.
   *
   * This function does no filtering - we assume that any transaction that makes
   * it here is ready to be rendered by the notification area.
   *
   * @param {Object} e Angular event object
   * @param {Object} tx Transaction info, returned from JsonRewriter#processTxn
   */

// VH: Hiding this for now.
//  $scope.$on('$appTxNotification', function (e, tx) {
//    var $localScope = $scope.$new();
//    $localScope.tx = tx.tx;
//
//    var html = tplAccount($localScope);
//
//    if (html.length) {
//      var msg = $compile(html)($localScope);
//      enqueue(msg);
//    }
//  });

  // A notification might have been queued already before the app was fully
  // initialized. If so, we display it now.
  if (queue.length) tick();

  var notifyEl = $('<div>').attr('id', 'notification').insertAfter(el);

  /**
   * Add the status message to the queue.
   */
  function enqueue(msg)
  {
    queue.push(msg);
    if (!tickUpcoming) {
      setImmediate(tick);
    }
  }

  /**
   * Proceed to next notification.
   */
  var prevEl = null;
  function tick()
  {
    if (prevEl) {
      // Hide notification box
      prevEl.removeClass('active');
      var prevElRef = prevEl;
      setTimeout(function () {
        prevElRef.remove();
      }, 1000);
      prevEl = null;
    }

    tickUpcoming = false;
    if (queue.length) {
      // Ensure secondary currencies pulldown is closed
      $scope.$apply(function() {
        $scope.show_secondary = false;
      });

      // Show next status message
      var next = queue.shift();

      var el = $(next);
      el.addClass('notification');
      el.appendTo(notifyEl);
      setImmediate(function () {
        el.addClass('active');
      });

      prevEl = el;

      tickUpcoming = true;
      setTimeout(tick, tickInterval);
    }
  }

  updateNotifications();

  // Testing Hooks
  this.enqueue             = enqueue;
  this.tick                = tick;
}]);
<commit_msg>[FIX] Status icon for unfunded wallet (RT-3322)<commit_after>/**
 * NAVBAR
 *
 * The navbar controller manages the bar at the top of the screen.
 */

var Amount = ripple.Amount,
    settings = require('../util/settings'),
    rewriter = require('../util/jsonrewriter');

var module = angular.module('navbar', []);

module.controller('NavbarCtrl', ['$scope', '$element', '$compile', 'rpId',
                                 'rpNetwork', '$location',
                                 function ($scope, el, $compile, id,
                                           network, $location)
{
  $scope.loading = true;
  var queue = [];
  var tickInterval = 4000;
  var tickUpcoming = false;

  var tplAccount = require('../../jade/notification/account.jade');

  // Activate #status panel
  $scope.toggle_secondary = function () {
    $scope.show_secondary = !$scope.show_secondary;
  };

  $scope.page_reload = function () {
      // Reload
      location.reload();
  };

  $scope.$watch('fee', function(){
    $scope.currentFee = ripple.Amount.from_json($scope.fee).to_human();

    if(!$scope.connected && $scope.userCredentials.username) {
      $scope.serverStatus = 'disconnected';
    }
    else if ($scope.currentFee && $scope.connected && ($scope.currentFee > Options.low_load_threshold) && ($scope.currentFee < ripple.Amount.from_json(Options.max_tx_network_fee).to_human())) {
      $scope.serverLoad = 'mediumLoad';
      $scope.serverStatus = 'mediumLoad';
    }
    else if ($scope.currentFee && $scope.connected && ($scope.currentFee >= ripple.Amount.from_json(Options.max_tx_network_fee).to_human())) {
      $scope.serverLoad = 'highLoad';
      $scope.serverStatus = 'highLoad';
    }
    else if ($scope.currentFee && $scope.connected) {
      $scope.serverLoad = '';
      $scope.serverStatus = 'lowLoad';
    }
    else {
      $scope.serverStatus = 'connected';
    }
  }, true);

  // Username
  $scope.$watch('userCredentials', function(){
    var username = $scope.userCredentials.username;
    if(username) $scope.loading = false;
    $scope.shortUsername = null;

    if(username && username.length > 25) {
      $scope.shortUsername = username.substring(0,24)+'...';
    }
  }, true);

  var updateNotifications = function () {
    if ($scope.events) {
      $scope.notifications = $scope.events.slice(0,10);
    }
  };

  $scope.$on('$eventsUpdate', updateNotifications);

  /**
   * Marks all the notifications as seen.
   */
  $scope.read = function() {
    // don't do anything if account is unfunded
    if (!$scope.notifications.length)
      return;

    var lastTxDate = $scope.notifications[0].date;

    if ($scope.unseen > 0) {
      $scope.unseen = 0;
    }

    if (settings.getSetting($scope.userBlob, 'lastSeenTxDate', 0) < lastTxDate) {
      // Remember last seen date
      $scope.userBlob.set('/clients/rippletradecom/lastSeenTxDate', lastTxDate);

      // Reset the counter
      $scope.unseen = $scope.unseenNotifications.count;
      $scope.unseenNotifications.count = 0;

      // Set seen for all the events
//      _.each($scope.events, function(event){
//        event.unseen = false;
//      })
    }
  };

  /**
   * Graphically display a network-related notifications.
   *
   * This function does no filtering - we assume that any transaction that makes
   * it here is ready to be rendered by the notification area.
   *
   * @param {Object} e Angular event object
   * @param {Object} tx Transaction info, returned from JsonRewriter#processTxn
   */

// VH: Hiding this for now.
//  $scope.$on('$appTxNotification', function (e, tx) {
//    var $localScope = $scope.$new();
//    $localScope.tx = tx.tx;
//
//    var html = tplAccount($localScope);
//
//    if (html.length) {
//      var msg = $compile(html)($localScope);
//      enqueue(msg);
//    }
//  });

  // A notification might have been queued already before the app was fully
  // initialized. If so, we display it now.
  if (queue.length) tick();

  var notifyEl = $('<div>').attr('id', 'notification').insertAfter(el);

  /**
   * Add the status message to the queue.
   */
  function enqueue(msg)
  {
    queue.push(msg);
    if (!tickUpcoming) {
      setImmediate(tick);
    }
  }

  /**
   * Proceed to next notification.
   */
  var prevEl = null;
  function tick()
  {
    if (prevEl) {
      // Hide notification box
      prevEl.removeClass('active');
      var prevElRef = prevEl;
      setTimeout(function () {
        prevElRef.remove();
      }, 1000);
      prevEl = null;
    }

    tickUpcoming = false;
    if (queue.length) {
      // Ensure secondary currencies pulldown is closed
      $scope.$apply(function() {
        $scope.show_secondary = false;
      });

      // Show next status message
      var next = queue.shift();

      var el = $(next);
      el.addClass('notification');
      el.appendTo(notifyEl);
      setImmediate(function () {
        el.addClass('active');
      });

      prevEl = el;

      tickUpcoming = true;
      setTimeout(tick, tickInterval);
    }
  }

  updateNotifications();

  // Testing Hooks
  this.enqueue             = enqueue;
  this.tick                = tick;
}]);
<|endoftext|>


<commit_before>
import * as Behaviors from '../behaviors/_all';
import Attacks from '../attacks/_all';
import { Entities as Glyphs } from '../../constants/glyphs';
import { Entities as GlyphColors } from '../../constants/glyphColors';

export const waterNymph = { difficulty: 5, spawnPattern: '1d3 + 1', frequency: 1, init: () =>
  ({ glyph: { key: Glyphs.Nymph, fg: GlyphColors.Elements.Water },
  attributes: { ac: -1, speed: 100, level: 3, killXp: '7d7', spawnHp: '5d5 + 5' },
  stats: { name: 'water nymph', race: 'Elf',
    behaviors: [Behaviors.LeavesCorpse(), Behaviors.SeeksTargetViaHearing(), Behaviors.SeeksTargetInSight(), Behaviors.Steals(), Behaviors.Attacks(), Behaviors.DropsItems()],
    attacks: [Attacks.Claw({ roll: '1d2 + 1' }), Attacks.SeductiveTouch({ roll: '1d2', chance: 20 })]
  } }) };<commit_msg>added new nymphs<commit_after>
import * as Behaviors from '../behaviors/_all';
import Attacks from '../attacks/_all';
import { Entities as Glyphs } from '../../constants/glyphs';
import { Entities as GlyphColors } from '../../constants/glyphColors';

export const waterNymph = { difficulty: 5, spawnPattern: '1d3 + 1', frequency: 0, init: () =>
  ({ glyph: { key: Glyphs.Nymph, fg: GlyphColors.Elements.Water },
  attributes: { ac: -1, speed: 100, level: 3, killXp: '7d7', spawnHp: '5d5 + 5' },
  stats: { name: 'water nymph', race: 'Elf',
    behaviors: [Behaviors.LeavesCorpse(), Behaviors.SeeksTargetViaHearing(), Behaviors.SeeksTargetInSight(), Behaviors.Steals(), Behaviors.Attacks(), Behaviors.DropsItems()],
    attacks: [Attacks.Claw({ roll: '1d2 + 1' }), Attacks.SeductiveTouch({ roll: '1d2', chance: 20 })]
  } }) };

export const forestNymph = { difficulty: 5, spawnPattern: '1d1', frequency: 1, init: () =>
  ({ glyph: { key: Glyphs.Nymph, fg: GlyphColors.Colors.Green },
    attributes: { ac: -1, speed: 100, level: 3, killXp: '7d7', spawnHp: '5d5 + 5' },
    stats: { name: 'forest nymph', race: 'Elf',
      behaviors: [Behaviors.LeavesCorpse(), Behaviors.SeeksTargetViaHearing(), Behaviors.SeeksTargetInSight(), Behaviors.Steals(), Behaviors.Attacks(), Behaviors.DropsItems()],
      attacks: [Attacks.Claw({ roll: '1d3 + 1' }), Attacks.SeductiveTouch({ roll: '1d3', chance: 30 })]
    } }) };

export const mountainNymph = { difficulty: 25, spawnPattern: '1d1', frequency: 1, init: () =>
  ({ glyph: { key: Glyphs.Nymph, fg: GlyphColors.Colors.Brown },
    attributes: { ac: -8, speed: 150, level: 3, killXp: '20d7', spawnHp: '20d5' },
    stats: { name: 'mountain nymph', race: 'Elf',
      behaviors: [Behaviors.LeavesCorpse(), Behaviors.SeeksTargetViaHearing(), Behaviors.SeeksTargetInSight(), Behaviors.Steals(), Behaviors.Attacks(), Behaviors.DropsItems()],
      attacks: [Attacks.Claw({ roll: '2d4' }), Attacks.SeductiveTouch({ roll: '2d3', chance: 40 })]
    } }) };<|endoftext|>


<commit_before>const SAFE_ZONE_WIDTH = 768;
const SAFE_ZONE_HEIGHT = 1280;

var game = new Phaser.Game(SAFE_ZONE_WIDTH, SAFE_ZONE_HEIGHT, Phaser.AUTO, '', {
    preload: preload,
    create: create,
    update: update
});

var running = true;

var player;
var coconut;
var bg;
var isPressed = false;

$(document).hasResized(function () {
    resizeGame();
});

function preload() {
    game.load.image('bg', 'assets/img/bg.png');
    game.load.image('player', 'assets/img/player.png');
    game.load.image('coconut', 'assets/img/coconut.png');
    game.load.image('playagain', 'assets/img/playagain.png');
}

function resizeGame() {

    game.scale.setExactFit();
    game.scale.refresh();

}

function create() {
    // Some browsers have a useragent margin. Override this.
    $("body").css("margin", "0");

    // Aligning the game correctly for all devices
    game.scale.pageAlignVertically = true;
    game.scale.pageAlignHorizontally = true;
    game.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT;
    game.stage.forcePortrait = true;
    window.resizeGame();

    // Adding a background image
    bg = game.add.image(0, 0, 'bg');

    // Adding the player
    player = game.add.sprite(game.world.centerX, game.world.height - 100, 'player');
    player.anchor.set(0.5);

    coconut = game.add.sprite(game.world.centerX, 50, 'coconut');
    coconut.anchor.set(0.5);

    bg.inputEnabled = true;
    bg.events.onInputDown.add(function () {
        isPressed = true;
    }, this);
    bg.events.onInputUp.add(function () {
        isPressed = false;
    }, this);

    // Enabling arcade physics
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.setBounds(0, 0, game.world.width, game.world.height);

    // Player stuff
    game.physics.enable(player, Phaser.Physics.ARCADE);
    player.enableBody = true;
    player.body.collideWorldBounds = true;

    // Coconut stuff
    game.physics.enable(coconut, Phaser.Physics.ARCADE);
    coconut.enableBody = true;
    coconut.body.collideWorldBounds = true;
    coconut.body.bounce.setTo(1.1, 1.1);
}

function setPlayerXY(x, y) {
    player.x = x;
    player.y = y;
}

function playerListener() {
    var speed = 10;

    if (isPressed) {

        var input_x = game.input.x;
        var input_y = game.input.y;

        if (player.x != input_x && player.y != input_y) {
            if (player.x < input_x && player.y < input_y) {
                player.x += speed;
                player.y += speed;
            }
            if (player.x > input_x && player.y > input_y) {
                player.x -= speed;
                player.y -= speed;
            }
            if (player.x > input_x && player.y < input_y) {
                player.x -= speed;
                player.y += speed;
            }
            if (player.x < input_x && player.y > input_y) {
                player.x += speed;
                player.y -= speed;
            }
        }

        game.physics.arcade.accelerateToObject(coconut, player);
    }
}

function update() {
    if (running) {
        playerListener();
        game.physics.arcade.collide(player, coconut, hitCoconut, null, this);
    }
}

function hitCoconut(body1, body2) {
    running = false;

    var text = "You lose";
    var style = {
        font: "10em Arial",
        fill: "#F00",
        align: "center"
    };

    var t = game.add.text(game.world.centerX - 180, 0, text, style);
    var playAgainButton = game.add.button(game.world.centerX - 125, game.world.centerY + 100, 'playagain', resetGame, this);

}

function resetGame() {
    location.reload();
}<commit_msg>Almost got smoothing working, but the player keeps getting physics aplied after the user releases.<commit_after>const SAFE_ZONE_WIDTH = 768;
const SAFE_ZONE_HEIGHT = 1280;

var game = new Phaser.Game(SAFE_ZONE_WIDTH, SAFE_ZONE_HEIGHT, Phaser.AUTO, '', {
    preload: preload,
    create: create,
    update: update,
    render: render
});

var running = true;

var player;
var coconut;
var bg;
var isPressed = false;

$(document).hasResized(function () {
    resizeGame();
});

function preload() {
    game.load.image('bg', 'assets/img/bg.png');
    game.load.image('player', 'assets/img/player.png');
    game.load.image('coconut', 'assets/img/coconut.png');
    game.load.image('playagain', 'assets/img/playagain.png');
}

function resizeGame() {

    game.scale.setExactFit();
    game.scale.refresh();

}

function create() {
    // Some browsers have a useragent margin. Override this.
    $("body").css("margin", "0");

    // Aligning the game correctly for all devices
    game.scale.pageAlignVertically = true;
    game.scale.pageAlignHorizontally = true;
    game.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT;
    game.stage.forcePortrait = true;
    window.resizeGame();

    // Adding a background image
    bg = game.add.image(0, 0, 'bg');

    // Adding the player
    player = game.add.sprite(game.world.centerX, game.world.height - 100, 'player');
    player.anchor.set(0.5);

    coconut = game.add.sprite(game.world.centerX, 50, 'coconut');
    coconut.anchor.set(0.5);

    bg.inputEnabled = true;
    bg.events.onInputDown.add(function () {
        isPressed = true;
    }, this);
    bg.events.onInputUp.add(function () {
        isPressed = false;
    }, this);

    // Enabling arcade physics
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.world.setBounds(0, 0, game.world.width, game.world.height);

    // Player stuff
    game.physics.enable(player, Phaser.Physics.ARCADE);
    player.enableBody = true;
    player.body.collideWorldBounds = true;

    // Coconut stuff
    game.physics.enable(coconut, Phaser.Physics.ARCADE);
    coconut.enableBody = true;
    coconut.body.collideWorldBounds = true;
    coconut.body.bounce.setTo(1.1, 1.1);
}

function playerListener() {
    var speed = 50;

    if (isPressed) {

        var input_x = game.input.x;
        var input_y = game.input.y;

        if (player.x != input_x || player.y != input_y) {
            game.physics.arcade.moveToXY(player, input_x, input_y, 500);
            //            if (player.x < input_x - diam && player.y < input_y - diam) {
            //                player.x += speed;
            //                player.y += speed;
            //            }
            //            if (player.x > input_x + diam && player.y > input_y + diam) {
            //                player.x -= speed;
            //                player.y -= speed;
            //            }
            //            if (player.x > input_x + diam && player.y < input_y - diam) {
            //                player.x -= speed;
            //                player.y += speed;
            //            }
            //            if (player.x < input_x - diam && player.y > input_y + diam) {
            //                player.x += speed;
            //                player.y -= speed;
            //            }
        }

        game.physics.arcade.accelerateToObject(coconut, player);
    }
}

function update() {
    if (running) {
        playerListener();
        game.physics.arcade.collide(player, coconut, hitCoconut, null, this);
    }
}

function hitCoconut(body1, body2) {
    running = false;

    var text = "You lose";
    var style = {
        font: "10em Arial",
        fill: "#F00",
        align: "center"
    };

    var t = game.add.text(game.world.centerX - 180, 0, text, style);
    var playAgainButton = game.add.button(game.world.centerX - 125, game.world.centerY + 100, 'playagain', resetGame, this);

}

function render() {
    game.debug.body(coconut);
    game.debug.body(player);
}

function resetGame() {
    location.reload();
}<|endoftext|>


<commit_before>import calf from './support/calf';
import * as ajax from './support/ajax';
import * as common from './support/common';
import * as dataObj from './support/dataObj';
import * as layout from './support/layout';
import * as system from './support/system';
import * as task from './support/task';

var disableItemColoring;
var showExtraLinks;
var showQuickDropLinks;
var showQuickSendLinks;
var extraLinks;
var paintCount;
var itemsAry;
var checkAll;
var itemsHash;
var dropLinks;
var invItems;
var colouring;
var sendLinks;

function moveItemsToFolder() { // Bad jQuery
  var invList = [];
  $('input[name="removeIndex[]"]:checked').each(function(i) {
    var batchNo = Math.floor(i / 50);
    invList[batchNo] = invList[batchNo] || [];
    invList[batchNo].push($(this).val());
  });
  calf.moveItemsCallback = invList.length;
  invList.forEach(function(val) {
    $.ajax({
      dataType: 'json',
      url: 'index.php',
      data: {
        'cmd': 'profile',
        'subcmd': 'sendtofolder',
        'inv_list': JSON.stringify(val),
        'folder_id': $('#selectFolderId option:selected').val(),
        'ajax': 1
      },
      success: function() {
        calf.moveItemsCallback -= 1;
        if (calf.moveItemsCallback === 0) {location.reload();}
      }
    });
  });
}

function injectMoveItems() { // Bad jQuery
  var foldersEnabled = $('img[src$="/folder_on.gif"]');
  if (foldersEnabled.length !== 1) {return;}
  var otherFolders = $('#pCC a').has('img[src$="/folder.gif"]');
  if (otherFolders.length === 0) {return;}
  var select = $('<select name=folder id=selectFolderId class=' +
    'customselect></select>');
  otherFolders.each(function() {
    var self = $(this);
    select.append('<option value=' + self.attr('href')
    .match(/&folder_id=(-*\d+)/i)[1] + '>' +
    self.parent().text() + '</option>');
  });
  $('#pCC tr').has(otherFolders[0]).first().after($('
')
    .append($('Move selected items to: 	')
      .append(select)
      .append(' <input type="button" class="custombutton"' +
        ' id="fshMove" value="Move">')));
  $('#fshMove').click(moveItemsToFolder);
}

function doToggleButtons() { // Native
  // Option toggle buttons for both screens
  var insertHere = layout.pCC.getElementsByTagName('form')[0]
    .previousElementSibling.firstElementChild;
  var inject = '[' +
    (showExtraLinks ? 'Hide' : 'Show') +
    ' AH and UFSG links] ' +
    '[' +
    (showQuickDropLinks ? 'Hide' : 'Show') +
    ' Quick Drop links] ';
  if (calf.subcmd2 === 'storeitems') {
    inject += '[' +
      ' Select All Guild Locked] ';
  }
  insertHere.innerHTML = inject;
}

function invPaint() { // Native - abstract this pattern
  var limit = performance.now() + 5;
  while (performance.now() < limit && paintCount < itemsAry.length) {
    var o = itemsAry[paintCount];

    var item = invItems[o.invid];

    var pattern = '';
    if (!extraLinks && showExtraLinks) {
      pattern += '';
      if (!item.bound) {
        pattern += '[AH]';
      }
      pattern += '[UFSG]';
      if (pattern !== '') {
        o.injectHere.insertAdjacentHTML('afterbegin', pattern);
      }
    }

    pattern = '';
    if (!checkAll && itemsHash[item.item_id] !== 1) {
      pattern += ' [Check all]';
    }
    if (!colouring && !disableItemColoring) {
      o.injectHere.classList.add(dataObj.rarity[item.rarity].clas);
    }
    if (!sendLinks && showQuickSendLinks && !item.bound) {
      pattern += ' [Quick Send]';
    }
    if (!dropLinks && showQuickDropLinks && item.guild_tag === '-1') {
      pattern += ' [Quick Drop]';
    }
    if (pattern !== '') {o.injectHere.insertAdjacentHTML('beforeend', pattern);}

    paintCount += 1;
  }
  if (paintCount < itemsAry.length) {
    task.add(3, invPaint);
  } else {
    if (showExtraLinks) {extraLinks = true;}
    checkAll = true;
    colouring = true;
    if (showQuickDropLinks) {dropLinks = true;}
    sendLinks = true;
  }
}

function toggleShowExtraLinks() { // Native
  showExtraLinks = !showExtraLinks;
  system.setValue('showExtraLinks', showExtraLinks);
  doToggleButtons();
  if (!extraLinks) {
    paintCount = 0;
    task.add(3, invPaint);
  } else {
    itemsAry.forEach(function(o) {
      var el = o.injectHere.firstElementChild;
      el.classList.toggle('fshHide');
    });
  }
}

function toggleShowQuickDropLinks() { // Native
  showQuickDropLinks = !showQuickDropLinks;
  system.setValue('showQuickDropLinks', showQuickDropLinks);
  doToggleButtons();
  if (!dropLinks) {
    paintCount = 0;
    task.add(3, invPaint);
  } else {
    itemsAry.forEach(function(o) {
      var el = o.injectHere.querySelector('.dropLink');
      el.classList.toggle('fshHide');
    });
  }
}

function anotherSpinner(self) { // Native
  self.innerHTML = '';
}

function doCheckboxes(type, itemId) { // Native
  itemsAry.forEach(function(o) {
    var el = o.el.parentNode.parentNode.previousElementSibling
      .firstElementChild;
    if (type === 'guild') {
      el.checked = !el.disabled &&
        invItems[o.invid].guild_tag !== '-1' ?
        true : false;
    }
    if (type === 'item' && invItems[o.invid].item_id === itemId) {
      el.checked = !el.disabled && !el.checked ? true : false;
    }
  });
}

function quickSendItem(evt){ // jQuery
  var self = evt.target;
  self.className = 'quickAction';
  var itemInvId = self.getAttribute('itemInvId');
  ajax.sendItem([itemInvId]).done(function(data){
    if (data.r === 1) {return;}
    self.style.color = 'green';
    self.innerHTML = 'Sent';
  });
  $(self).qtip('hide');
  anotherSpinner(self);
  var theTd = self.parentNode;
  var quickDrop = theTd.querySelector('.dropLink');
  if (quickDrop) {
    quickDrop.className = 'quickAction';
    quickDrop.innerHTML = '';
  }
  var checkbox = theTd.parentNode.firstElementChild.firstElementChild;
  checkbox.checked = false;
  checkbox.disabled = true;
}

function quickDropItem(evt){ // jQuery
  var self = evt.target;
  self.className = 'quickAction';
  var itemInvId = self.getAttribute('itemInvId');
  ajax.dropItem([itemInvId]).done(function(data){
    if (data.r === 1) {return;}
    self.style.color = 'green';
    self.innerHTML = 'Dropped';
  });
  $(self).qtip('hide');
  anotherSpinner(self);
  var theTd = self.parentNode;
  var quickSend = theTd.querySelector('.sendLink');
  if (quickSend) {
    quickSend.className = 'quickAction';
    quickSend.innerHTML = '';
  }
  var checkbox = theTd.parentNode.firstElementChild.firstElementChild;
  checkbox.checked = false;
  checkbox.disabled = true;
}

function evtHandler(evt) { // Native
  if (evt.target.tagName !== 'SPAN') {return;}
  var self = evt.target;
  var myId = self.id;
  if (myId === 'fshShowExtraLinks') {toggleShowExtraLinks();}
  if (myId === 'fshShowQuickDropLinks') {toggleShowQuickDropLinks();}
  if (myId === 'fshSelectAllGuildLocked') {doCheckboxes('guild');}
  if (self.hasAttribute('linkto')) {
    doCheckboxes('item', evt.target.getAttribute('linkto'));}
  var myClasses = self.classList;
  if (myClasses.contains('sendLink')) {quickSendItem(evt);}
  if (myClasses.contains('dropLink')) {quickDropItem(evt);}
}

function getItems() { // Native
  common.addStatTotalToMouseover();
  disableItemColoring = system.getValue('disableItemColoring');
  showExtraLinks = system.getValue('showExtraLinks');
  showQuickDropLinks = system.getValue('showQuickDropLinks');
  showQuickSendLinks = system.getValue('showQuickSendLinks');
  doToggleButtons();
  layout.pCC.addEventListener('click', evtHandler);
  var allTables = layout.pCC.getElementsByTagName('table');
  var lastTable = allTables[allTables.length - 1];
  var imgList = lastTable.getElementsByTagName('img');
  itemsAry = [];
  itemsHash = {};
  Array.prototype.forEach.call(imgList, function(el) {
    var tipped = el.getAttribute('data-tipped');
    var matches = tipped.match(dataObj.itemRE);
    itemsHash[matches[1]] = (itemsHash[matches[1]] || 0) + 1;
    var injectHere = el.parentNode.parentNode.nextElementSibling;
    itemsAry.push({
      el: el,
      invid: matches[2],
      injectHere: injectHere
    });
  });
}

function inventory(data) { // Native
  extraLinks = false;
  checkAll = false;
  invItems = data.items;
  colouring = false;
  dropLinks = false;
  sendLinks = false;
  paintCount = 0;
  task.add(3, invPaint);
}

function injectDropItems() { // Native
  ajax.getInventoryById().done(inventory);
  task.add(3, getItems);
}

export function injectProfileDropItems() { // Native
  injectDropItems();
  injectMoveItems();
}

export function injectStoreItems() { // Native
  injectDropItems();
}
<commit_msg>Drop Items - tidy up and minimise use of jQuery<commit_after>import calf from './support/calf';
import * as ajax from './support/ajax';
import * as common from './support/common';
import * as dataObj from './support/dataObj';
import * as layout from './support/layout';
import * as system from './support/system';
import * as task from './support/task';

var disableItemColoring;
var showExtraLinks;
var showQuickDropLinks;
var showQuickSendLinks;
var extraLinks;
var paintCount;
var itemsAry;
var checkAll;
var itemsHash;
var dropLinks;
var invItems;
var colouring;
var sendLinks;

function moveItemsToFolder() { // jQuery.min
  var folderId = document.getElementById('selectFolderId').value;
  var batchNo;
  var counter = 0;
  var invList = [];
  var prm = [];
  itemsAry.forEach(function(o) {
    var el = o.injectHere.previousElementSibling.previousElementSibling
      .firstElementChild;
    if (el.checked) {
      batchNo = Math.floor(counter / 50);
      invList[batchNo] = invList[batchNo] || [];
      invList[batchNo].push(o.invid);
      counter += 1;
      if (counter % 50 === 0) {
        prm.push(ajax.moveItem(invList[batchNo], folderId));
      }
    }
  });
  if (counter % 50 !== 0) {
    prm.push(ajax.moveItem(invList[batchNo], folderId));
  }
  $.when.apply($, prm).done(function() {location.reload();});
}

function injectMoveItems() { // Native
  var flrRow = layout.pCC.getElementsByTagName('form')[0]
    .nextElementSibling.nextElementSibling.nextElementSibling;
  var folders = flrRow.getElementsByTagName('img');
  var flrEnabled;
  var oFlr;
  var options = '
Move selected items to: ' +
    '<select name="folder" id="selectFolderId" class="customselect">';
  Array.prototype.forEach.call(folders, function(e) {
    var src = e.getAttribute('src');
    if (src.indexOf('/folder_on.gif') !== -1) {flrEnabled = true;}
    if (src.indexOf('/folder.gif') !== -1) {
      oFlr = true;
      options += '<option value=' + e.parentNode.getAttribute('href')
        .match(/&folder_id=(-*\d+)/i)[1] + '>' +
        e.parentNode.parentNode.textContent + '</option>';
    }
  });
  if (!flrEnabled || !oFlr) {return;}
  options += '</select> <input type="button" class="custombutton" ' +
    'id="fshMove" value="Move">
';
  flrRow.insertAdjacentHTML('afterend', options);
}

function doToggleButtons() { // Native
  // Option toggle buttons for both screens
  var insertHere = layout.pCC.getElementsByTagName('form')[0]
    .previousElementSibling.firstElementChild;
  var inject = '[' +
    (showExtraLinks ? 'Hide' : 'Show') +
    ' AH and UFSG links] ' +
    '[' +
    (showQuickDropLinks ? 'Hide' : 'Show') +
    ' Quick Drop links] ';
  if (calf.subcmd2 === 'storeitems') {
    inject += '[' +
      ' Select All Guild Locked] ';
  }
  insertHere.innerHTML = inject;
}

function afterbegin(o, item) { // Native
  if (extraLinks || !showExtraLinks) {return;}
  var pattern = '';
  if (!item.bound) {
    pattern += '[AH]';
  }
  pattern += '[UFSG]';
  o.injectHere.insertAdjacentHTML('afterbegin',  pattern);
}

function beforeend(o, item) { // Native
  var pattern = '';
  if (!checkAll && itemsHash[item.item_id] !== 1) {
    pattern += ' [Check all]';
  }
  if (!colouring && !disableItemColoring) {
    o.injectHere.classList.add(dataObj.rarity[item.rarity].clas);
  }
  if (!sendLinks && showQuickSendLinks && !item.bound) {
    pattern += ' [Quick Send]';
  }
  if (!dropLinks && showQuickDropLinks && item.guild_tag === '-1') {
    pattern += ' [Quick Drop]';
  }
  if (pattern !== '') {o.injectHere.insertAdjacentHTML('beforeend', pattern);}
}

function invPaint() { // Native - abstract this pattern
  var limit = performance.now() + 5;
  while (performance.now() < limit && paintCount < itemsAry.length) {
    var o = itemsAry[paintCount];
    var item = invItems[o.invid];
    afterbegin(o, item);
    beforeend(o, item);
    paintCount += 1;
  }
  if (paintCount < itemsAry.length) {
    task.add(3, invPaint);
  } else {
    if (showExtraLinks) {extraLinks = true;}
    checkAll = true;
    colouring = true;
    if (showQuickDropLinks) {dropLinks = true;}
    sendLinks = true;
  }
}

function toggleShowExtraLinks() { // Native
  showExtraLinks = !showExtraLinks;
  system.setValue('showExtraLinks', showExtraLinks);
  doToggleButtons();
  if (!extraLinks) {
    paintCount = 0;
    task.add(3, invPaint);
  } else {
    itemsAry.forEach(function(o) {
      var el = o.injectHere.firstElementChild;
      el.classList.toggle('fshHide');
    });
  }
}

function toggleShowQuickDropLinks() { // Native
  showQuickDropLinks = !showQuickDropLinks;
  system.setValue('showQuickDropLinks', showQuickDropLinks);
  doToggleButtons();
  if (!dropLinks) {
    paintCount = 0;
    task.add(3, invPaint);
  } else {
    itemsAry.forEach(function(o) {
      var el = o.injectHere.querySelector('.dropLink');
      el.classList.toggle('fshHide');
    });
  }
}

function anotherSpinner(self) { // Native
  self.innerHTML = '';
}

function doCheckboxes(type, itemId) { // Native
  itemsAry.forEach(function(o) {
    var el = o.el.parentNode.parentNode.previousElementSibling
      .firstElementChild;
    if (type === 'guild') {
      el.checked = !el.disabled && invItems[o.invid].guild_tag !== '-1';
    }
    if (type === 'item' && invItems[o.invid].item_id === itemId) {
      el.checked = !el.disabled && !el.checked;
    }
  });
}

function quickAction(self, success, otherClass) { // jQuery.min
  self.className = 'quickAction';
  var itemInvId = self.getAttribute('itemInvId');
  ajax.sendItem([itemInvId]).done(function(data){
    if (data.r === 1) {return;}
    self.style.color = 'green';
    self.innerHTML = success;
  });
  $(self).qtip('hide');
  anotherSpinner(self);
  var theTd = self.parentNode;
  var otherButton = theTd.querySelector(otherClass);
  if (otherButton) {
    otherButton.className = 'quickAction';
    otherButton.innerHTML = '';
  }
  var checkbox = theTd.parentNode.firstElementChild.firstElementChild;
  checkbox.checked = false;
  checkbox.disabled = true;
}

function evtHandler(evt) { // Native
  var self = evt.target;
  var myId = self.id;
  if (myId === 'fshShowExtraLinks') {toggleShowExtraLinks();}
  if (myId === 'fshShowQuickDropLinks') {toggleShowQuickDropLinks();}
  if (myId === 'fshSelectAllGuildLocked') {doCheckboxes('guild');}
  if (myId === 'fshMove') {moveItemsToFolder();}
  if (self.hasAttribute('linkto')) {
    doCheckboxes('item', evt.target.getAttribute('linkto'));
  }
  var myClasses = self.classList;
  if (myClasses.contains('sendLink')) {
    quickAction(evt.target, 'Sent', '.dropLink');
  }
  if (myClasses.contains('dropLink')) {
    quickAction(evt.target, 'Dropped', '.sendLink');
  }
}

function getItems() { // Native
  common.addStatTotalToMouseover();
  disableItemColoring = system.getValue('disableItemColoring');
  showExtraLinks = system.getValue('showExtraLinks');
  showQuickDropLinks = system.getValue('showQuickDropLinks');
  showQuickSendLinks = system.getValue('showQuickSendLinks');
  doToggleButtons();
  layout.pCC.addEventListener('click', evtHandler);
  var allTables = layout.pCC.getElementsByTagName('table');
  var lastTable = allTables[allTables.length - 1];
  var imgList = lastTable.getElementsByTagName('img');
  itemsAry = [];
  itemsHash = {};
  Array.prototype.forEach.call(imgList, function(el) {
    var tipped = el.getAttribute('data-tipped');
    var matches = tipped.match(dataObj.itemRE);
    itemsHash[matches[1]] = (itemsHash[matches[1]] || 0) + 1;
    var injectHere = el.parentNode.parentNode.nextElementSibling;
    itemsAry.push({
      el: el,
      invid: matches[2],
      injectHere: injectHere
    });
  });
}

function inventory(data) { // Native
  // console.log('inventory', data);
  extraLinks = false;
  checkAll = false;
  invItems = data.items;
  colouring = false;
  dropLinks = false;
  sendLinks = false;
  paintCount = 0;
  task.add(3, invPaint);
}

function injectDropItems() { // Native
  ajax.getInventoryById().done(inventory);
  task.add(3, getItems);
}

export function injectProfileDropItems() { // Native
  injectDropItems();
  injectMoveItems();
}

export function injectStoreItems() { // Native
  injectDropItems();
}
<|endoftext|>


<commit_before>import expect from 'expect.js'
import {create} from '../../src'
import RegularRule from '../../src/plugins/RegularRule'
import {generateClassName} from '../utils'

describe('Integration: sheet', () => {
  let jss

  beforeEach(() => {
    jss = create({generateClassName})
  })

  describe('.createStyleSheet()', () => {
    it('should create a sheet without args', () => {
      const sheet = jss.createStyleSheet()
      expect(sheet.deployed).to.be(false)
      expect(sheet.attached).to.be(false)
      expect(sheet.linked).to.be(false)
      expect(sheet.classes).to.eql({})
      expect(sheet.options).to.be.an(Object)
      expect(sheet.options.index).to.be(0)
      expect(sheet.options.sheet).to.be(sheet)
      expect(sheet.options.parent).to.be(sheet)
    })

    it('should create a sheet with one rule', () => {
      const sheet = jss.createStyleSheet({a: {float: 'left'}})
      const rule = sheet.getRule('a')
      expect(rule).to.be.a(RegularRule)
      expect(sheet.classes.a).to.be('a-id')
      expect(rule.className).to.be('a-id')
      expect(rule.selector).to.be('.a-id')
    })

    it('should register a conditional child rule in classes', () => {
      const sheet = jss.createStyleSheet({
        '@media print': {
          a: {float: 'left'}
        }
      })
      expect(sheet.classes.a).to.be('a-id')
    })

    it('should create rule classNames using the rule name', () => {
      const styles = {bar: {color: 'red'}}
      const sheet = jss.createStyleSheet(styles)
      expect(sheet.classes.bar).to.be('bar-id')
    })
  })

  describe('sheet.getRule()', () => {
    it('should return a rule by name and selector from named sheet', () => {
      const sheet = jss.createStyleSheet({a: {float: 'left'}})
      expect(sheet.getRule('a')).to.be.a(RegularRule)
    })

    it('should return a rule by selector from unnamed sheet', () => {
      const sheet = jss.createStyleSheet({a: {float: 'left'}}, {named: false})
      expect(sheet.getRule('a')).to.be.a(RegularRule)
    })
  })

  describe('sheet.indexOf()', () => {
    it('should return the index of a rule', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        b: {color: 'blue'}
      })
      expect(sheet.indexOf(sheet.getRule('a'))).to.be(0)
      expect(sheet.indexOf(sheet.getRule('b'))).to.be(1)
      expect(sheet.indexOf(sheet.getRule('c'))).to.be(-1)
    })
  })

  describe('sheet.addRule()', () => {
    it('should add a rule with "className" in options', () => {
      const sheet = jss.createStyleSheet()
      const rule = sheet.addRule('a', {color: 'red'}, {className: 'test'})
      expect(rule.className).to.be('test')
      expect(rule.selector).to.be('.test')
      expect(sheet.getRule('a')).to.be(rule)
    })

    it('should add a rule with "index" in options', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        c: {color: 'blue'}
      })
      sheet.addRule('b', {color: 'green'}, {index: 1})
      expect(sheet.indexOf(sheet.getRule('a'))).to.be(0)
      expect(sheet.indexOf(sheet.getRule('b'))).to.be(1)
      expect(sheet.indexOf(sheet.getRule('c'))).to.be(2)
      expect(sheet.toString()).to.equal(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '.b-id {\n' +
        '  color: green;\n' +
        '}\n' +
        '.c-id {\n' +
        '  color: blue;\n' +
        '}'
      )
    })

    it('should apply plugins in the correct order', () => {
      jss.use((rule) => {
        if (rule.name === 'a') {
          rule.options.sheet.addRule('b', {color: 'green'}, {index: 1})
        }
      })

      const classNames = []
      jss.use((rule) => {
        classNames.push(rule.className)
      })

      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        c: {color: 'blue'}
      })

      expect(sheet.indexOf(sheet.getRule('a'))).to.be(0)
      expect(sheet.indexOf(sheet.getRule('b'))).to.be(1)
      expect(sheet.indexOf(sheet.getRule('c'))).to.be(2)
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '.b-id {\n' +
        '  color: green;\n' +
        '}\n' +
        '.c-id {\n' +
        '  color: blue;\n' +
        '}'
      )
      expect(classNames).to.eql(['b-id', 'a-id', 'c-id'])
    })
  })

  describe('sheet.deleteRule()', () => {
    it('should delete a rule', () => {
      const sheet = jss.createStyleSheet({a: {color: 'red'}})
      expect(sheet.deleteRule('a')).to.be(true)
      expect(sheet.toString()).to.equal('')
    })
  })

  describe('sheet.toString()', () => {
    it('should compile all rule types to CSS', () => {
      const sheet = jss.createStyleSheet({
        '@charset': '"utf-8"',
        '@import': 'bla',
        '@namespace': 'bla',
        a: {
          float: 'left'
        },
        '@font-face': {
          'font-family': 'MyHelvetica',
          src: 'local("Helvetica")'
        },
        '@keyframes id': {
          from: {top: 0}
        },
        '@media print': {
          b: {display: 'none'}
        },
        '@supports ( display: flexbox )': {
          c: {
            display: 'none'
          }
        }
      }, {named: false})

      expect(sheet.toString()).to.be(
        '@charset "utf-8";\n' +
        '@import bla;\n' +
        '@namespace bla;\n' +
        '.a-id {\n  float: left;\n}\n' +
        '@font-face {\n  font-family: MyHelvetica;\n  src: local("Helvetica");\n}\n' +
        '@keyframes id {\n  from {\n    top: 0;\n  }\n}\n' +
        '@media print {\n  .b-id {\n    display: none;\n  }\n}\n' +
        '@supports ( display: flexbox ) {\n  .c-id {\n    display: none;\n  }\n}'
      )
    })

    it('should compile a single media query', () => {
      const sheet = jss.createStyleSheet({
        '@media (min-width: 1024px)': {a: {color: 'blue'}},
      })
      expect(sheet.toString()).to.be(
        '@media (min-width: 1024px) {\n' +
        '  .a-id {\n' +
        '    color: blue;\n' +
        '  }\n' +
        '}'
      )
    })

    it('should compile multiple media queries in unnamed sheet', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        '@media (min-width: 1024px)': {a: {color: 'blue'}},
        '@media (min-width: 1000px)': {a: {color: 'green'}}
      })
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '@media (min-width: 1024px) {\n' +
        '  .a-id {\n' +
        '    color: blue;\n' +
        '  }\n' +
        '}\n' +
        '@media (min-width: 1000px) {\n' +
        '  .a-id {\n' +
        '    color: green;\n' +
        '  }\n' +
        '}'
      )
    })

    it('should compile multiple media queries in named sheet', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        '@media (min-width: 1024px)': {a: {color: 'blue'}},
        '@media (min-width: 1000px)': {a: {color: 'green'}}
      })
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '@media (min-width: 1024px) {\n' +
        '  .a-id {\n' +
        '    color: blue;\n' +
        '  }\n' +
        '}\n' +
        '@media (min-width: 1000px) {\n' +
        '  .a-id {\n' +
        '    color: green;\n' +
        '  }\n' +
        '}'
      )
    })

    it('should use the class name of a conditional child', () => {
      const options = {generateClassName: () => 'my-special-id'}
      const sheet = create(options).createStyleSheet({
        '@media print': {
          a: {float: 'left'}
        },
        a: {color: 'red'}
      })
      expect(sheet.toString()).to.be(
        '@media print {\n' +
        '  .my-special-id {\n' +
        '    float: left;\n' +
        '  }\n' +
        '}\n' +
        '.my-special-id {\n' +
        '  color: red;\n' +
        '}'
      )
    })

    it('should use the class name of the first conditional child', () => {
      const options = {generateClassName: () => 'my-special-id'}
      const sheet = create(options).createStyleSheet({
        '@media print': {
          a: {float: 'left'}
        },
        '@media screen': {
          a: {float: 'right'}
        }
      })
      expect(sheet.toString()).to.be(
        '@media print {\n' +
        '  .my-special-id {\n' +
        '    float: left;\n' +
        '  }\n' +
        '}\n' +
        '@media screen {\n' +
        '  .my-special-id {\n' +
        '    float: right;\n' +
        '  }\n' +
        '}'
      )
    })

    describe('skip empty rules', () => {
      it('should skip empty rules', () => {
        const sheet = jss.createStyleSheet({
          a: {color: 'red'},
          b: {},
          c: {color: 'green'},
          d: {}
        })
        expect(sheet.toString()).to.be(
          '.a-id {\n' +
          '  color: red;\n' +
          '}\n' +
          '.c-id {\n' +
          '  color: green;\n' +
          '}'
        )
      })

      it('should skip empty font-face rule', () => {
        const sheet = jss.createStyleSheet({
          a: {color: 'red'},
          b: {},
          c: {color: 'green'},
          '@font-face': {}
        })
        expect(sheet.toString()).to.be(
          '.a-id {\n' +
          '  color: red;\n' +
          '}\n' +
          '.c-id {\n' +
          '  color: green;\n' +
          '}'
        )
      })

      it('should skip empty conditional rule', () => {
        const sheet = jss.createStyleSheet({
          a: {color: 'red'},
          '@media print': {}
        })
        expect(sheet.toString()).to.be(
          '.a-id {\n' +
          '  color: red;\n' +
          '}'
        )
      })
    })
  })

  describe('skip empty values', () => {
    it('should skip empty values', () => {
      const sheet = jss.createStyleSheet({
        a: {
          margin: 0,
          color: null
        }
      })
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  margin: 0;\n' +
        '}'
      )
    })

    it('should skip rule if empty value was skipped', () => {
      const sheet = jss.createStyleSheet({
        a: {
          color: null
        }
      })
      expect(sheet.toString()).to.be('')
    })
  })
})
<commit_msg>fix the conditional rule class name test<commit_after>import expect from 'expect.js'
import {create} from '../../src'
import RegularRule from '../../src/plugins/RegularRule'
import {generateClassName} from '../utils'

describe('Integration: sheet', () => {
  let jss

  beforeEach(() => {
    jss = create({generateClassName})
  })

  describe('.createStyleSheet()', () => {
    it('should create a sheet without args', () => {
      const sheet = jss.createStyleSheet()
      expect(sheet.deployed).to.be(false)
      expect(sheet.attached).to.be(false)
      expect(sheet.linked).to.be(false)
      expect(sheet.classes).to.eql({})
      expect(sheet.options).to.be.an(Object)
      expect(sheet.options.index).to.be(0)
      expect(sheet.options.sheet).to.be(sheet)
      expect(sheet.options.parent).to.be(sheet)
    })

    it('should create a sheet with one rule', () => {
      const sheet = jss.createStyleSheet({a: {float: 'left'}})
      const rule = sheet.getRule('a')
      expect(rule).to.be.a(RegularRule)
      expect(sheet.classes.a).to.be('a-id')
      expect(rule.className).to.be('a-id')
      expect(rule.selector).to.be('.a-id')
    })

    it('should register a conditional child rule in classes', () => {
      const sheet = jss.createStyleSheet({
        '@media print': {
          a: {float: 'left'}
        }
      })
      expect(sheet.classes.a).to.be('a-id')
    })

    it('should create rule classNames using the rule name', () => {
      const styles = {bar: {color: 'red'}}
      const sheet = jss.createStyleSheet(styles)
      expect(sheet.classes.bar).to.be('bar-id')
    })
  })

  describe('sheet.getRule()', () => {
    it('should return a rule by name and selector from named sheet', () => {
      const sheet = jss.createStyleSheet({a: {float: 'left'}})
      expect(sheet.getRule('a')).to.be.a(RegularRule)
    })

    it('should return a rule by selector from unnamed sheet', () => {
      const sheet = jss.createStyleSheet({a: {float: 'left'}}, {named: false})
      expect(sheet.getRule('a')).to.be.a(RegularRule)
    })
  })

  describe('sheet.indexOf()', () => {
    it('should return the index of a rule', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        b: {color: 'blue'}
      })
      expect(sheet.indexOf(sheet.getRule('a'))).to.be(0)
      expect(sheet.indexOf(sheet.getRule('b'))).to.be(1)
      expect(sheet.indexOf(sheet.getRule('c'))).to.be(-1)
    })
  })

  describe('sheet.addRule()', () => {
    it('should add a rule with "className" in options', () => {
      const sheet = jss.createStyleSheet()
      const rule = sheet.addRule('a', {color: 'red'}, {className: 'test'})
      expect(rule.className).to.be('test')
      expect(rule.selector).to.be('.test')
      expect(sheet.getRule('a')).to.be(rule)
    })

    it('should add a rule with "index" in options', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        c: {color: 'blue'}
      })
      sheet.addRule('b', {color: 'green'}, {index: 1})
      expect(sheet.indexOf(sheet.getRule('a'))).to.be(0)
      expect(sheet.indexOf(sheet.getRule('b'))).to.be(1)
      expect(sheet.indexOf(sheet.getRule('c'))).to.be(2)
      expect(sheet.toString()).to.equal(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '.b-id {\n' +
        '  color: green;\n' +
        '}\n' +
        '.c-id {\n' +
        '  color: blue;\n' +
        '}'
      )
    })

    it('should apply plugins in the correct order', () => {
      jss.use((rule) => {
        if (rule.name === 'a') {
          rule.options.sheet.addRule('b', {color: 'green'}, {index: 1})
        }
      })

      const classNames = []
      jss.use((rule) => {
        classNames.push(rule.className)
      })

      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        c: {color: 'blue'}
      })

      expect(sheet.indexOf(sheet.getRule('a'))).to.be(0)
      expect(sheet.indexOf(sheet.getRule('b'))).to.be(1)
      expect(sheet.indexOf(sheet.getRule('c'))).to.be(2)
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '.b-id {\n' +
        '  color: green;\n' +
        '}\n' +
        '.c-id {\n' +
        '  color: blue;\n' +
        '}'
      )
      expect(classNames).to.eql(['b-id', 'a-id', 'c-id'])
    })
  })

  describe('sheet.deleteRule()', () => {
    it('should delete a rule', () => {
      const sheet = jss.createStyleSheet({a: {color: 'red'}})
      expect(sheet.deleteRule('a')).to.be(true)
      expect(sheet.toString()).to.equal('')
    })
  })

  describe('sheet.toString()', () => {
    it('should compile all rule types to CSS', () => {
      const sheet = jss.createStyleSheet({
        '@charset': '"utf-8"',
        '@import': 'bla',
        '@namespace': 'bla',
        a: {
          float: 'left'
        },
        '@font-face': {
          'font-family': 'MyHelvetica',
          src: 'local("Helvetica")'
        },
        '@keyframes id': {
          from: {top: 0}
        },
        '@media print': {
          b: {display: 'none'}
        },
        '@supports ( display: flexbox )': {
          c: {
            display: 'none'
          }
        }
      }, {named: false})

      expect(sheet.toString()).to.be(
        '@charset "utf-8";\n' +
        '@import bla;\n' +
        '@namespace bla;\n' +
        '.a-id {\n  float: left;\n}\n' +
        '@font-face {\n  font-family: MyHelvetica;\n  src: local("Helvetica");\n}\n' +
        '@keyframes id {\n  from {\n    top: 0;\n  }\n}\n' +
        '@media print {\n  .b-id {\n    display: none;\n  }\n}\n' +
        '@supports ( display: flexbox ) {\n  .c-id {\n    display: none;\n  }\n}'
      )
    })

    it('should compile a single media query', () => {
      const sheet = jss.createStyleSheet({
        '@media (min-width: 1024px)': {a: {color: 'blue'}},
      })
      expect(sheet.toString()).to.be(
        '@media (min-width: 1024px) {\n' +
        '  .a-id {\n' +
        '    color: blue;\n' +
        '  }\n' +
        '}'
      )
    })

    it('should compile multiple media queries in unnamed sheet', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        '@media (min-width: 1024px)': {a: {color: 'blue'}},
        '@media (min-width: 1000px)': {a: {color: 'green'}}
      })
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '@media (min-width: 1024px) {\n' +
        '  .a-id {\n' +
        '    color: blue;\n' +
        '  }\n' +
        '}\n' +
        '@media (min-width: 1000px) {\n' +
        '  .a-id {\n' +
        '    color: green;\n' +
        '  }\n' +
        '}'
      )
    })

    it('should compile multiple media queries in named sheet', () => {
      const sheet = jss.createStyleSheet({
        a: {color: 'red'},
        '@media (min-width: 1024px)': {a: {color: 'blue'}},
        '@media (min-width: 1000px)': {a: {color: 'green'}}
      })
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  color: red;\n' +
        '}\n' +
        '@media (min-width: 1024px) {\n' +
        '  .a-id {\n' +
        '    color: blue;\n' +
        '  }\n' +
        '}\n' +
        '@media (min-width: 1000px) {\n' +
        '  .a-id {\n' +
        '    color: green;\n' +
        '  }\n' +
        '}'
      )
    })

    describe('class names of conditional rules', () => {
      let id
      const options = {generateClassName: () => id = Math.random()}

      it('should use the class name of a conditional child', () => {
        const sheet = create(options).createStyleSheet({
          '@media print': {
            a: {float: 'left'}
          },
          a: {color: 'red'}
        })
        expect(sheet.toString()).to.be(
          `@media print {\n` +
          `  .${id} {\n` +
          `    float: left;\n` +
          `  }\n` +
          `}\n` +
          `.${id} {\n` +
          `  color: red;\n` +
          `}`
        )
      })

      it('should use the class name of the first conditional child', () => {
        const sheet = create(options).createStyleSheet({
          '@media print': {
            a: {float: 'left'}
          },
          '@media screen': {
            a: {float: 'right'}
          }
        })
        expect(sheet.toString()).to.be(
          `@media print {\n` +
          `  .${id} {\n` +
          `    float: left;\n` +
          `  }\n` +
          `}\n` +
          `@media screen {\n` +
          `  .${id} {\n` +
          `    float: right;\n` +
          `  }\n` +
          `}`
        )
      })
    })

    describe('skip empty rules', () => {
      it('should skip empty rules', () => {
        const sheet = jss.createStyleSheet({
          a: {color: 'red'},
          b: {},
          c: {color: 'green'},
          d: {}
        })
        expect(sheet.toString()).to.be(
          '.a-id {\n' +
          '  color: red;\n' +
          '}\n' +
          '.c-id {\n' +
          '  color: green;\n' +
          '}'
        )
      })

      it('should skip empty font-face rule', () => {
        const sheet = jss.createStyleSheet({
          a: {color: 'red'},
          b: {},
          c: {color: 'green'},
          '@font-face': {}
        })
        expect(sheet.toString()).to.be(
          '.a-id {\n' +
          '  color: red;\n' +
          '}\n' +
          '.c-id {\n' +
          '  color: green;\n' +
          '}'
        )
      })

      it('should skip empty conditional rule', () => {
        const sheet = jss.createStyleSheet({
          a: {color: 'red'},
          '@media print': {}
        })
        expect(sheet.toString()).to.be(
          '.a-id {\n' +
          '  color: red;\n' +
          '}'
        )
      })
    })
  })

  describe('skip empty values', () => {
    it('should skip empty values', () => {
      const sheet = jss.createStyleSheet({
        a: {
          margin: 0,
          color: null
        }
      })
      expect(sheet.toString()).to.be(
        '.a-id {\n' +
        '  margin: 0;\n' +
        '}'
      )
    })

    it('should skip rule if empty value was skipped', () => {
      const sheet = jss.createStyleSheet({
        a: {
          color: null
        }
      })
      expect(sheet.toString()).to.be('')
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

module.exports =
/*@ngInject*/
function configure ($stateProvider) {
  $stateProvider
  .state('play-sw', {
    parent: 'app',
    templateUrl: 'sentences.play.html',
    controller: 'SentencePlayCtrl',
    url: '/play/sw?uid&student&anonymous',
    data: {
      authenticateUser: true
    }
  })
  .state('play-sw.results', {
    parent: 'app',
    templateUrl: 'sentences.results.html',
    controller: 'ResultsController',
    url: '/play/sw/results?uid&student'
  })
  .state('play-sw-gen.results', {
    parent: 'app',
    templateUrl: 'sentences.results.html',
    controller: 'ResultsController',
    url: '/play/sw/gen-results?passageId'
  })
  .state('play-sw-gen', {
    parent: 'app',
    templateUrl: 'sentences.play.html',
    controller: 'SentencePlayCtrl',
    url: '/play/sw/g/:ids?student&passageId&pfAllCorrect'
  });
};
<commit_msg>Fix #143, redirect to results page after finishing with no errors.<commit_after>'use strict';

module.exports =
/*@ngInject*/
function configure ($stateProvider) {
  $stateProvider
  .state('play-sw', {
    parent: 'app',
    templateUrl: 'sentences.play.html',
    controller: 'SentencePlayCtrl',
    url: '/play/sw?uid&student&anonymous',
    data: {
      authenticateUser: true
    }
  })
  .state('play-sw.results', {
    parent: 'app',
    templateUrl: 'sentences.results.html',
    controller: 'ResultsController',
    url: '/play/sw/results?uid&student'
  })
  .state('play-sw-gen.results', {
    parent: 'app',
    templateUrl: 'sentences.results.html',
    controller: 'ResultsController',
    url: '/play/sw/gen-results?passageId&student'
  })
  .state('play-sw-gen', {
    parent: 'app',
    templateUrl: 'sentences.play.html',
    controller: 'SentencePlayCtrl',
    url: '/play/sw/g/:ids?student&passageId&pfAllCorrect'
  });
};
<|endoftext|>