<commit_before>var RtmClient = require('@slack/client').RtmClient;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
var doge = require('dogefy');

var getTag = function(id){
  return '<@' + id + '>';
};

var isDirect = function(userId, messageText){
  return messageText && messageText.indexOf(userId) > -1;
};

module.exports = function(key){
  if(!key) throw new Error('You need to specify a Slack token');

  var rtm = new RtmClient(key);

  rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, function() {
    var team = rtm.dataStore.getTeamById(rtm.activeTeamId);
    var user = rtm.dataStore.getUserById(rtm.activeUserId);
    console.log('Connected to ' + team.name + ' as ' + user.name);
  });

  rtm.on(RTM_EVENTS.MESSAGE, function(message){
    var channel = rtm.dataStore.getChannelGroupOrDMById(message.channel);

    if(message.type === 'message' && message.text && (channel.is_im || isDirect(rtm.activeUserId, message.text))){
      var cleanedMessage = message.text.replace(getTag(rtm.activeUserId), '').replace(':', '').substring(0, 2000).trim();

      if(cleanedMessage){
        console.log('Dogefied: ' + cleanedMessage);
        rtm.sendMessage('``` \n' + doge(cleanedMessage) + '\n ```', message.channel);
      }
    }
  });

  rtm.start();
};
<commit_msg>chore: turn variables into functions<commit_after>var RtmClient = require('@slack/client').RtmClient;
var RTM_EVENTS = require('@slack/client').RTM_EVENTS;
var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
var doge = require('dogefy');

module.exports = function(key){
  if(!key) throw new Error('You need to specify a Slack token');

  var rtm = new RtmClient(key);

  rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, function() {
    var team = rtm.dataStore.getTeamById(rtm.activeTeamId);
    var user = rtm.dataStore.getUserById(rtm.activeUserId);
    console.log('Connected to ' + team.name + ' as ' + user.name);
  });

  rtm.on(RTM_EVENTS.MESSAGE, function(message){
    var channel = rtm.dataStore.getChannelGroupOrDMById(message.channel);

    if(message.type === 'message' && message.text && (channel.is_im || isDirect(rtm.activeUserId, message.text))){
      var cleanedMessage = message.text.replace(getTag(rtm.activeUserId), '').replace(':', '').substring(0, 2000).trim();

      if(cleanedMessage){
        console.log('Dogefied: ' + cleanedMessage);
        rtm.sendMessage('``` \n' + doge(cleanedMessage) + '\n ```', message.channel);
      }
    }
  });

  rtm.start();
};

function getTag(id){
  return '<@' + id + '>';
};

function isDirect(userId, messageText){
  return messageText && messageText.indexOf(userId) > -1;
};
<|endoftext|>


<commit_before>window.onload = function () {
    var CONSTANTS = {
        STAGE_WIDTH: 800,
        STAGE_HEIGHT: 600
    };

    var stage, layer, backgroundImageObj,
        player = new Image();

    function loadCanvas() {
        stage = new Kinetic.Stage({
            container: 'gameplay-container',
            width: CONSTANTS.STAGE_WIDTH,
            height: CONSTANTS.STAGE_HEIGHT
        });

        layer = new Kinetic.Layer();
    }

    function loadPlayer() {

    }

    function loadBackground() {
        backgroundImageObj = new Image();
        backgroundImageObj.width = 800;
        backgroundImageObj.src = "sources/images/canvas-bg.jpg";

        backgroundImageObj.onload = function () {
            var background = new Kinetic.Image({
                x: 0,
                y: 0,
                image: backgroundImageObj,
                width: CONSTANTS.STAGE_WIDTH,
                height: CONSTANTS.STAGE_HEIGHT
            });

            layer.add(background);
            stage.add(layer);
        };
    }

    function initialize() {
        loadCanvas();

        loadBackground();
        loadPlayer();
    }

    function run() {

    }

    (function () {
        initialize();
        run();
    }());
};<commit_msg>Minor changes made<commit_after>window.onload = function () {
    var CONSTANTS = {
        STAGE_WIDTH: 800,
        STAGE_HEIGHT: 600
    };

    var stage, layer, backgroundImageObj, playerImageObj;

    function loadCanvas() {
        var container = document.getElementById('gameplay-container');
        container.position =
        stage = new Kinetic.Stage({
            container: 'gameplay-container',
            width: CONSTANTS.STAGE_WIDTH,
            height: CONSTANTS.STAGE_HEIGHT
        });

        layer = new Kinetic.Layer();
    }

    function loadPlayer() {

    }

    function loadBackground() {
        backgroundImageObj = new Image();
        backgroundImageObj.src = "sources/images/canvas-bg.jpg";

        backgroundImageObj.onload = function () {
            var background = new Kinetic.Image({
                x: 0,
                y: 0,
                image: backgroundImageObj,
                width: CONSTANTS.STAGE_WIDTH,
                height: CONSTANTS.STAGE_HEIGHT
            });

            layer.add(background);
            stage.add(layer);
        };
    }

    function initialize() {
        loadCanvas();

        loadBackground();
        loadPlayer();
    }

    function run() {

    }

    (function () {
        initialize();
        run();
    }());
};<|endoftext|>


<commit_before>'use strict';

var CallbackStore = require('famous-utilities').CallbackStore;

var ELEMENT = 'element';
var ID = 'id';
var WIDTH = 'width';
var HEIGHT = 'height';
var OPACITY = 'opacity';
var PX = 'px';
var WITH = 'WITH';
var CHANGE_TRANSFORM = 'CHANGE_TRANSFORM';
var CHANGE_TRANSFORM_ORIGIN = 'CHANGE_TRANSFORM_ORIGIN';
var CHANGE_PROPERTY = 'CHANGE_PROPERTY';
var CHANGE_TAG = 'CHANGE_TAG';
var CHANGE_ATTRIBUTE = 'CHANGE_ATTRIBUTE';
var ADD_CLASS = 'ADD_CLASS';
var CHANGE_ATTRIBUTE = 'CHANGE_ATTRIBUTE';
var CHANGE_CONTENT = 'CHANGE_CONTENT';
var ADD_EVENT_LISTENER = 'ADD_EVENT_LISTENER';
var EVENT_METHODS = 'EVENT_METHODS';
var EVENT_PROPERTIES = 'EVENT_PROPERTIES';
var EVENT_END = 'EVENT_END';

/**
 * The Element class is responsible for providing the API for how
 *   a RenderNode will interact with the DOM API's.  The element is
 *   responsible for adding a set of commands to the renderer.
 *
 * @class Element
 * @constructor
 * @component
 * @param {RenderNode} RenderNode to which the instance of Element will be a component of
 */
function HTMLElement(dispatch) {
    this.dispatch = dispatch;
    this._id = dispatch.addRenderable(this);
    this._trueSized = false;
    this._size = [0, 0, 0];
    this.queue = [];
    this.callbacks = new CallbackStore();
    this.init();
}

// Return the name of the Element Class: 'element'
HTMLElement.toString = function toString() {
    return ELEMENT;
};

HTMLElement.prototype.init = function init() {
    var dispatch = this.dispatch;
    dispatch.onTransformChange(this._receiveTransformChange.bind(this));
    dispatch.onSizeChange(this._receiveSizeChange.bind(this));
    dispatch.onOpacityChange(this._receiveOpacityChange.bind(this));
    dispatch.onOriginChange(this._receiveOriginChange.bind(this));
    this._receiveTransformChange(dispatch.getContext()._transform);
    this._receiveOriginChange(dispatch.getContext()._origin);
    return this;
}
HTMLElement.prototype.clean = function clean() {
    var len = this.queue.length;
    if (len) {
    	var path = this.dispatch.getRenderPath();
    	this.dispatch.sendDrawCommand(WITH).sendDrawCommand(path);
    	for (var i = 0 ; i < len ; i++) {
    	    this.dispatch.sendDrawCommand(this.queue.shift());
        }
    }
    return !this.queue.length;
};

HTMLElement.prototype._receiveTransformChange = function _receiveTransformChange(transform) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_TRANSFORM);
    this.queue.push(transform._matrix[0]);
    this.queue.push(transform._matrix[1]);
    this.queue.push(transform._matrix[2]);
    this.queue.push(transform._matrix[3]);
    this.queue.push(transform._matrix[4]);
    this.queue.push(transform._matrix[5]);
    this.queue.push(transform._matrix[6]);
    this.queue.push(transform._matrix[7]);
    this.queue.push(transform._matrix[8]);
    this.queue.push(transform._matrix[9]);
    this.queue.push(transform._matrix[10]);
    this.queue.push(transform._matrix[11]);
    this.queue.push(transform._matrix[12]);
    this.queue.push(transform._matrix[13]);
    this.queue.push(transform._matrix[14]);
    this.queue.push(transform._matrix[15]);
};

HTMLElement.prototype._receiveSizeChange = function _receiveSizeChange(size) {
    if (!this.trueSized) {
    	var size = size.getTopDownSize();
    	this.property(WIDTH, Math.round(size[0]) + PX)
    	    .property(HEIGHT, Math.round(size[1]) + PX);
    	this._size[0] = size[0];
    	this._size[1] = size[1];
    }
};

HTMLElement.prototype._receiveOriginChange = function _receiveOriginChange(origin) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_TRANSFORM_ORIGIN);
    this.queue.push(origin.x);
    this.queue.push(origin.y);
};

HTMLElement.prototype._receiveOpacityChange = function _receiveOpacityChange(opacity) {
    this.property(OPACITY, opacity.value);
};

HTMLElement.prototype.getSize = function getSize() {
    return this._size;
};

HTMLElement.prototype.on = function on (ev, methods, properties) {
    this.eventListener(ev, methods, properties);
    return this;
};

/**
 * Set the value of a CSS property
 *
 * @method property
 * @chainable
 *
 * @param {String} key name of the property to set
 * @param {Any} value associated value for this property
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.property = function property(key, value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_PROPERTY);
    this.queue.push(key);
    this.queue.push(value);
    return this;
};

/**
 * The method by which a user tells the element to ignore the context
 *   size and get size from the content instead.
 *
 * @method trueSize
 * @chainable
 *
 * @return {HTMLElement} this
 */
HTMLElement.prototype.trueSize = function trueSize() {
    if (!this.trueSized) {
	this.trueSized = true;
	this.dispatch.dirtyRenderable(this._id);
    }
    return this;
};

/**
 * Set the tag name of the element
 *
 * @method tagName
 * @chainable
 *
 * @param {String} value type of HTML tag
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.tagName = function tagName(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_TAG);
    this.queue.push(value);
    return this;
};

/**
 * Set an attribute on the DOM element
 *
 * @method attribute
 * @chainable
 *
 * @param {String} key name of the attribute to set
 * @param {Any} value associated value for this attribute
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.attribute = function attribute(key, value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_ATTRIBUTE);
    this.queue.push(key);
    this.queue.push(value);
    return this;
};

/**
 * Define a CSS class to be on the DOM element
 *
 * @method cssClass
 * @chainable
 *
 * @param {String} value name of the class
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.cssClass = function cssClass(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(ADD_CLASS);
    this.queue.push(value);
    return this;
};

/**
 * Define the id of the DOM element
 *
 * @method id
 * @chainable
 *
 * @param {String} value id
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.id = function id(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_ATTRIBUTE);
    this.queue.push(ID);
    this.queue.push(value);
    return this;
};

/**
 * Define the content of the DOM element
 *
 * @method content
 * @chainable
 *
 * @param {String | DOM element | Document Fragment} value content to be inserted into the DOM element
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.content = function content(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_CONTENT);
    this.queue.push(value);
    return this;
};

/**
 * Get a component of the RenderNode that the HTMLElement component is
 *   attached to by name.
 *
 * @method get
 *
 * @param {String} key name of the component to grab from the RenderNode
 * @return {Component} a component that exists on the RenderNode
 */
HTMLElement.prototype.get = function get (key) {
    return this.owner.get(key);
};

/**
 * Adds a command to add an eventListener to the current DOM HTMLElement.
 *   primarily used internally.
 *
 * @method eventListener
 * @chainable
 *
 * @param {String} ev the name of the DOM event to be targeted
 *
 * @return {Component} this
 */
HTMLElement.prototype.eventListener = function eventListener (ev, methods, properties) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(ADD_EVENT_LISTENER);
    this.queue.push(ev);
    this.queue.push(EVENT_METHODS);
    if (methods != null) {
        for(var i = 0, len = methods.length; i < len; i++) {
            this.queue.push(methods[i]);
        }
    }
    this.queue.push(EVENT_PROPERTIES);
    if (properties != null) {
        for(var i = 0, len = properties.length; i < len; i++) {
            this.queue.push(properties[i]);
        }
    }
    this.queue.push(EVENT_END);
    return this;
};

/**
 * isRenderable returns whether or not this HTMLElement currently has any Information to render
 *
 * @method isRenderable
 *
 * @return {Bool} whether or not this HTMLElement can be rendered
 */
HTMLElement.prototype.isRenderable = function isRenderable () {
    return !!this.queue.length;
};

/**
 * Clears the state on the HTMLElement so that it can be rendered next frame.
 *
 * @method clear
 * @chainable
 *
 * @return {HTMLElement} this
 */
HTMLElement.prototype.clear = function clear () {
    var queueLength = this.queue.length;
    var i = 0;

    this.target = null;
    this.trueSized = false;

    for (; i < queueLength; i++) {
	this.queue.pop();
    }

    return this;
};

module.exports = HTMLElement;
<commit_msg>feat: can destructure event objects<commit_after>'use strict';

var CallbackStore = require('famous-utilities').CallbackStore;

var ELEMENT = 'element';
var ID = 'id';
var WIDTH = 'width';
var HEIGHT = 'height';
var OPACITY = 'opacity';
var PX = 'px';
var WITH = 'WITH';
var CHANGE_TRANSFORM = 'CHANGE_TRANSFORM';
var CHANGE_TRANSFORM_ORIGIN = 'CHANGE_TRANSFORM_ORIGIN';
var CHANGE_PROPERTY = 'CHANGE_PROPERTY';
var CHANGE_TAG = 'CHANGE_TAG';
var CHANGE_ATTRIBUTE = 'CHANGE_ATTRIBUTE';
var ADD_CLASS = 'ADD_CLASS';
var CHANGE_ATTRIBUTE = 'CHANGE_ATTRIBUTE';
var CHANGE_CONTENT = 'CHANGE_CONTENT';
var ADD_EVENT_LISTENER = 'ADD_EVENT_LISTENER';
var EVENT_PROPERTIES = 'EVENT_PROPERTIES';
var EVENT_END = 'EVENT_END';

/**
 * The Element class is responsible for providing the API for how
 *   a RenderNode will interact with the DOM API's.  The element is
 *   responsible for adding a set of commands to the renderer.
 *
 * @class Element
 * @constructor
 * @component
 * @param {RenderNode} RenderNode to which the instance of Element will be a component of
 */
function HTMLElement(dispatch) {
    this.dispatch = dispatch;
    this._id = dispatch.addRenderable(this);
    this._trueSized = false;
    this._size = [0, 0, 0];
    this.queue = [];
    this.callbacks = new CallbackStore();
    this.init();
}

// Return the name of the Element Class: 'element'
HTMLElement.toString = function toString() {
    return ELEMENT;
};

HTMLElement.prototype.init = function init() {
    var dispatch = this.dispatch;
    dispatch.onTransformChange(this._receiveTransformChange.bind(this));
    dispatch.onSizeChange(this._receiveSizeChange.bind(this));
    dispatch.onOpacityChange(this._receiveOpacityChange.bind(this));
    dispatch.onOriginChange(this._receiveOriginChange.bind(this));
    this._receiveTransformChange(dispatch.getContext()._transform);
    this._receiveOriginChange(dispatch.getContext()._origin);
    return this;
}
HTMLElement.prototype.clean = function clean() {
    var len = this.queue.length;
    if (len) {
    	var path = this.dispatch.getRenderPath();
    	this.dispatch.sendDrawCommand(WITH).sendDrawCommand(path);
    	for (var i = 0 ; i < len ; i++) {
    	    this.dispatch.sendDrawCommand(this.queue.shift());
        }
    }
    return !this.queue.length;
};

HTMLElement.prototype._receiveTransformChange = function _receiveTransformChange(transform) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_TRANSFORM);
    this.queue.push(transform._matrix[0]);
    this.queue.push(transform._matrix[1]);
    this.queue.push(transform._matrix[2]);
    this.queue.push(transform._matrix[3]);
    this.queue.push(transform._matrix[4]);
    this.queue.push(transform._matrix[5]);
    this.queue.push(transform._matrix[6]);
    this.queue.push(transform._matrix[7]);
    this.queue.push(transform._matrix[8]);
    this.queue.push(transform._matrix[9]);
    this.queue.push(transform._matrix[10]);
    this.queue.push(transform._matrix[11]);
    this.queue.push(transform._matrix[12]);
    this.queue.push(transform._matrix[13]);
    this.queue.push(transform._matrix[14]);
    this.queue.push(transform._matrix[15]);
};

HTMLElement.prototype._receiveSizeChange = function _receiveSizeChange(size) {
    if (!this.trueSized) {
    	var size = size.getTopDownSize();
    	this.property(WIDTH, Math.round(size[0]) + PX)
    	    .property(HEIGHT, Math.round(size[1]) + PX);
    	this._size[0] = size[0];
    	this._size[1] = size[1];
    }
};

HTMLElement.prototype._receiveOriginChange = function _receiveOriginChange(origin) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_TRANSFORM_ORIGIN);
    this.queue.push(origin.x);
    this.queue.push(origin.y);
};

HTMLElement.prototype._receiveOpacityChange = function _receiveOpacityChange(opacity) {
    this.property(OPACITY, opacity.value);
};

HTMLElement.prototype.getSize = function getSize() {
    return this._size;
};

HTMLElement.prototype.on = function on (ev, methods, properties) {
    this.eventListener(ev, methods, properties);
    return this;
};

/**
 * Set the value of a CSS property
 *
 * @method property
 * @chainable
 *
 * @param {String} key name of the property to set
 * @param {Any} value associated value for this property
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.property = function property(key, value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_PROPERTY);
    this.queue.push(key);
    this.queue.push(value);
    return this;
};

/**
 * The method by which a user tells the element to ignore the context
 *   size and get size from the content instead.
 *
 * @method trueSize
 * @chainable
 *
 * @return {HTMLElement} this
 */
HTMLElement.prototype.trueSize = function trueSize() {
    if (!this.trueSized) {
	this.trueSized = true;
	this.dispatch.dirtyRenderable(this._id);
    }
    return this;
};

/**
 * Set the tag name of the element
 *
 * @method tagName
 * @chainable
 *
 * @param {String} value type of HTML tag
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.tagName = function tagName(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_TAG);
    this.queue.push(value);
    return this;
};

/**
 * Set an attribute on the DOM element
 *
 * @method attribute
 * @chainable
 *
 * @param {String} key name of the attribute to set
 * @param {Any} value associated value for this attribute
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.attribute = function attribute(key, value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_ATTRIBUTE);
    this.queue.push(key);
    this.queue.push(value);
    return this;
};

/**
 * Define a CSS class to be on the DOM element
 *
 * @method cssClass
 * @chainable
 *
 * @param {String} value name of the class
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.cssClass = function cssClass(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(ADD_CLASS);
    this.queue.push(value);
    return this;
};

/**
 * Define the id of the DOM element
 *
 * @method id
 * @chainable
 *
 * @param {String} value id
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.id = function id(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_ATTRIBUTE);
    this.queue.push(ID);
    this.queue.push(value);
    return this;
};

/**
 * Define the content of the DOM element
 *
 * @method content
 * @chainable
 *
 * @param {String | DOM element | Document Fragment} value content to be inserted into the DOM element
 * @return {HTMLElement} current HTMLElement
 */
HTMLElement.prototype.content = function content(value) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(CHANGE_CONTENT);
    this.queue.push(value);
    return this;
};

/**
 * Get a component of the RenderNode that the HTMLElement component is
 *   attached to by name.
 *
 * @method get
 *
 * @param {String} key name of the component to grab from the RenderNode
 * @return {Component} a component that exists on the RenderNode
 */
HTMLElement.prototype.get = function get (key) {
    return this.owner.get(key);
};

/**
 * Adds a command to add an eventListener to the current DOM HTMLElement.
 *   primarily used internally.
 *
 * @method eventListener
 * @chainable
 *
 * @param {String} ev the name of the DOM event to be targeted
 *
 * @return {Component} this
 */
HTMLElement.prototype.eventListener = function eventListener (ev, methods, properties) {
    this.dispatch.dirtyRenderable(this._id);
    this.queue.push(ADD_EVENT_LISTENER);
    this.queue.push(ev);
    if (methods != null) this.queue.push(methods);
    this.queue.push(EVENT_PROPERTIES);
    if (properties != null) this.queue.push(properties);
    this.queue.push(EVENT_END);
    return this;
};

/**
 * isRenderable returns whether or not this HTMLElement currently has any Information to render
 *
 * @method isRenderable
 *
 * @return {Bool} whether or not this HTMLElement can be rendered
 */
HTMLElement.prototype.isRenderable = function isRenderable () {
    return !!this.queue.length;
};

/**
 * Clears the state on the HTMLElement so that it can be rendered next frame.
 *
 * @method clear
 * @chainable
 *
 * @return {HTMLElement} this
 */
HTMLElement.prototype.clear = function clear () {
    var queueLength = this.queue.length;
    var i = 0;

    this.target = null;
    this.trueSized = false;

    for (; i < queueLength; i++) {
	this.queue.pop();
    }

    return this;
};

module.exports = HTMLElement;
<|endoftext|>


<commit_before>/* After some time tring to make this work without messing w/ checked property,
 * I ended up using it *only* when none is defined
 *
 * This way we try to be as pure as possible and not mess with consumer's logic
 * if they have any
 */

const first = require('lodash.first');
const isUndefined = require('lodash.isundefined');
const get = require('lodash.get');
const invariant = require('invariant');
const Item = require('./item');
const find = require('lodash.find');
const classNames = require('classnames');
const React = require('react');
const styles = require('./style.css');

const RadioGroup = React.createClass({
  propTypes: {
    children: React.PropTypes.node,
    className: React.PropTypes.string,
    id: React.PropTypes.string,
    name: React.PropTypes.string.isRequired,
    onChange: React.PropTypes.func,
    style: React.PropTypes.object
  },
  getInitialState: function() {
    return this.getState(this.props);
  },
  componentWillMount: function() {
    return this.checkValues(this.props);
  },
  componentWillReceiveProps: function(nextProps) {
    return this.setState(this.checkValues(nextProps));
  },
  getState: function(props) {
    const _children = React.Children.toArray(props.children).filter((child) => {
      return get(child, 'type.displayName') === 'Radio';
    });

    const hasChecked = _children.some((child) => {
      return !isUndefined(get(child, 'props.checked'));
    });

    if (hasChecked) {
      return {
        hasChecked
      };
    }

    const defaultChecked = get(find(_children, (child) => {
      return get(child, 'props.defaultChecked');
    }), 'props.value');

    const checked = (() => {
      const stateChecked = get(this, 'state.checked');
      const fallback = isUndefined(defaultChecked)
        ? get(first(_children), 'props.value')
        : defaultChecked;

      return !isUndefined(stateChecked) ? stateChecked : fallback;
    })();

    return {
      checked
    };
  },
  checkValues: function(props) {
    invariant(React.Children.toArray(props.children).every((child) => {
      return (child.type.name !== 'Radio') ? true : !!child.props.value;
    }), 'All <Radio> childs of <RadioGroup> must have a value property');

    return props;
  },
  handleChange: function(key) {
    return (ev) => {
      const {
        onChange = () => {}
      } = this.props;

      this.setState({
        checked: key
      }, () => {
        onChange(ev);
      });
    };
  },
  render: function() {
    const {
      name,
      children,
      className,
      id,
      style
    } = this.props;

    const {
      hasChecked,
      checked
    } = this.state;

    const {
      handleChange
    } = this;

    const cn = classNames(
      className,
      styles.group
    );

    const _children = React.Children.map(children, (child, i) => {
      if (child.type.name !== 'Radio') {
        return child;
      }

      const tabIndex = i + 1;
      const disabled = get(child, 'props.disabled');
      const value = get(child, 'props.value');

      const _handleChange = (!hasChecked && !disabled)
        ? handleChange(value)
        : undefined;

      const _child = hasChecked ? (
        React.cloneElement(child, {
          name
        })
      ) : (
        React.cloneElement(child, {
          onChange: _handleChange,
          checked: value === checked,
          defaultChecked: undefined,
          name
        })
      );

      const _checked = get(_child, 'props.checked');

      return (
        <Item
          checked={_checked}
          disabled={disabled}
          onClick={_handleChange}
          tabIndex={tabIndex}
        >
          {_child}
        </Item>
      );
    });

    return (
      <div
        className={cn}
        id={id}
        style={style}
      >
        {_children}
      </div>
    );
  }
});

module.exports = RadioGroup;
<commit_msg>remove `value` validation in <RadioGroup><commit_after>/* After some time tring to make this work without messing w/ checked property,
 * I ended up using it *only* when none is defined
 *
 * This way we try to be as pure as possible and not mess with consumer's logic
 * if they have any
 */

const first = require('lodash.first');
const isUndefined = require('lodash.isundefined');
const get = require('lodash.get');
const Item = require('./item');
const find = require('lodash.find');
const classNames = require('classnames');
const React = require('react');
const styles = require('./style.css');

const RadioGroup = React.createClass({
  propTypes: {
    children: React.PropTypes.node,
    className: React.PropTypes.string,
    id: React.PropTypes.string,
    name: React.PropTypes.string.isRequired,
    onChange: React.PropTypes.func,
    style: React.PropTypes.object
  },
  getInitialState: function() {
    return this.getState(this.props);
  },
  componentWillReceiveProps: function(nextProps) {
    return this.setState(nextProps);
  },
  getState: function(props) {
    const _children = React.Children.toArray(props.children).filter((child) => {
      return get(child, 'type.displayName') === 'Radio';
    });

    const hasChecked = _children.some((child) => {
      return !isUndefined(get(child, 'props.checked'));
    });

    if (hasChecked) {
      return {
        hasChecked
      };
    }

    const defaultChecked = get(find(_children, (child) => {
      return get(child, 'props.defaultChecked');
    }), 'props.value');

    const checked = (() => {
      const stateChecked = get(this, 'state.checked');
      const fallback = isUndefined(defaultChecked)
        ? get(first(_children), 'props.value')
        : defaultChecked;

      return !isUndefined(stateChecked) ? stateChecked : fallback;
    })();

    return {
      checked
    };
  },
  handleChange: function(key) {
    return (ev) => {
      const {
        onChange = () => {}
      } = this.props;

      this.setState({
        checked: key
      }, () => {
        onChange(ev);
      });
    };
  },
  render: function() {
    const {
      name,
      children,
      className,
      id,
      style
    } = this.props;

    const {
      hasChecked,
      checked
    } = this.state;

    const {
      handleChange
    } = this;

    const cn = classNames(
      className,
      styles.group
    );

    const _children = React.Children.map(children, (child, i) => {
      if (child.type.name !== 'Radio') {
        return child;
      }

      const tabIndex = i + 1;
      const disabled = get(child, 'props.disabled');
      const value = get(child, 'props.value');

      const _handleChange = (!hasChecked && !disabled)
        ? handleChange(value)
        : undefined;

      const _child = hasChecked ? (
        React.cloneElement(child, {
          name
        })
      ) : (
        React.cloneElement(child, {
          onChange: _handleChange,
          checked: value === checked,
          defaultChecked: undefined,
          name
        })
      );

      const _checked = get(_child, 'props.checked');

      return (
        <Item
          checked={_checked}
          disabled={disabled}
          onClick={_handleChange}
          tabIndex={tabIndex}
        >
          {_child}
        </Item>
      );
    });

    return (
      <div
        className={cn}
        id={id}
        style={style}
      >
        {_children}
      </div>
    );
  }
});

module.exports = RadioGroup;
<|endoftext|>


<commit_before>var gData = new appData();
var gRpcUrl = "json.rpc";
var gSliderContainer = "#sliderContainer";
var gSliderTemplate = '
';
gSliderTemplate += '###slider_Channel###';
gSliderTemplate += '<input id="###slider_Input_Id###" name="slider" class="custom-slider" channel-number="###channel_number###" value="###slider_Value###" min="0" max="100" type="range" data-highlight="true">';
gSliderTemplate += '
';

$(document).ready(function() {
    /*
    if (gData.checkConfig()) {
        gData.load();
    } else {
        gData.save();
    }

    guiBuild();
    guiUpdate();
    guiEventsInit();

       if(gData.checkDefault())
       {
    	   $( "#settingsPannel" ).trigger( "expand" );
       }
    */
    gCurrentButton = null;
    setInterval(OnButtonTimer, 50);
    eventBind();

    $('.button-frame').each(function(index, value) {
        updateButton(index + '');
    });

    remoteChannelGetAll(getChannelCallback);

});

function eventBind() {
    $('body').on('mousedown touchstart', '.function-increase', function(e) { OnIncrease(e); });
    $('body').on('mousedown touchstart', '.function-decrease', function(e) { OnDecrease(e); });
    $('body').on('mouseup touchend', '.function-increase', function(e) { OnIncrease(e); });
    $('body').on('mouseup touchend', '.function-decrease', function(e) { OnDecrease(e); });
    $('body').on('click', '.function-toggle', function(e) { OnToggle(e); });
}

var gCurrentChannel = null;
var gButtonState = 'sIdle';

function OnIncrease(event) {

    event.stopPropagation();
    switch (event.type) {
        case 'mousedown':
            gCurrentChannel = $(event.target).attr('tChnannelId');
            gButtonState = 'sIncrease';
            break;

        case 'mouseup':
        default:
            gButtonState = 'sIdle';
            gCurrentChannel = null;
            break;

    }

}

function OnDecrease(event) {

    event.stopPropagation();
    switch (event.type) {
        case 'mousedown':
            gCurrentChannel = $(event.target).attr('tChnannelId');
            gButtonState = 'sDecrease';
            break;

        case 'mouseup':
        default:
            gButtonState = 'sIdle';
            gCurrentChannel = null;
            break;

    }
}

function OnToggle(event) {

    var channelId = $(event.target).attr('tChnannelId');
    if (getButtonValue(channelId) === 0) {
        setButtonValue(channelId, getButtonValueBackup(channelId));
        remoteChannelSet(channelId, getButtonValue(channelId));
    } else {
        setButtonValueBackup(channelId, getButtonValue(channelId));
        setButtonValue(channelId, 0);
        remoteChannelSet(channelId, 0);
    }
    updateButton(channelId);
}

function OnButtonTimer() {

    if (gCurrentChannel === null) return;

    switch (gButtonState) {
        case 'sIdle':
            break;

        case 'sDecrease':
            decreaseChannelValue(gCurrentChannel);
            updateButton(gCurrentChannel);
            break;

        case 'sIncrease':
            increaseChannelValue(gCurrentChannel);
            updateButton(gCurrentChannel);
            break;

        default:
            break;
    }

}

function updateButton(channelId) {
    var value = getButtonValue(channelId);
    var root = $('#tChannel' + channelId);
    var text = root.find(".function-toggle p");
    if (value == 255) { //OSLL: Default state, need to get values from device...
        text[1].innerHTML = "...";
        root.addClass("button-frame-UNKNOWN");
    } else if (value > 0) {
        text[1].innerHTML = "ON";
        root.removeClass("button-frame-OFF");
        root.removeClass("button-frame-UNKNOWN");
        root.find(".button-path-text").removeClass("button-path-text-OFF");
        root.find(".button-svg").removeClass("button-svg-OFF");
        arcDraw(channelId, value);
    } else {
        text[1].innerHTML = "OFF";
        root.removeClass("button-frame-UNKNOWN");
        root.addClass("button-frame-OFF");
        root.find(".button-path-text").addClass("button-path-text-OFF");
        root.find(".button-svg").addClass("button-svg-OFF");
        arcDraw(channelId, value);
    }
}

function increaseChannelValue(channelId) {
    var value = getButtonValue(channelId);
    if (value < 100) {
        value++;
        setButtonValue(channelId, value);
        remoteChannelSet(channelId, value);
    }
}

function decreaseChannelValue(channelId) {
    var value = getButtonValue(channelId);
    if (value > 1) {
        value--;
        setButtonValue(channelId, value);
        remoteChannelSet(channelId, value);
    }
}

function getButtonValue(channelId) {
    var value = $('#tChannel' + channelId).attr('tChannelValue');
    return parseInt(value);
}

function setButtonValue(channelId, value) {
    $('#tChannel' + channelId).attr('tChannelValue', value);
}

function getButtonValueBackup(channelId) {
    var value = $('#tChannel' + channelId).attr('tChannelBackupValue');
    return parseInt(value);
}

function setButtonValueBackup(channelId, value) {
    $('#tChannel' + channelId).attr('tChannelBackupValue', value);
}

function arcDraw(itemIndex, value) {

    if (value > 100) value = 100;
    if (value < 0) value = 0;

    var svg = $("#tSvg" + itemIndex);
    var x = svg.width() / 2;
    var y = svg.height() / 2;
    var r = svg.width() / 3.5;
    var a = (360.0 / 100.0) * value;
    var text = $("#tText" + itemIndex);
    text.attr("x", x);
    text.attr("y", y);
    text[0].innerHTML = value.toFixed(0) + "%";
    $("#tArc" + itemIndex)[0].setAttribute("d", describeArc(x, y, r, 0, a - 1));
}

//http://jsbin.com/cibicecuto/edit?html,js,output

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;

    return {
        x: centerX + (radius * Math.cos(angleInRadians)),
        y: centerY + (radius * Math.sin(angleInRadians))
    };
}

function describeArc(x, y, radius, startAngle, endAngle) {

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";

    var d = [
        "M", start.x, start.y,
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y
    ].join(" ");

    return d;
}
/*----------------------------------------------------------------------------------------------------------------*/
function getChannelCallback(reply) {

    if (reply.result.hasOwnProperty("duttyArray")) {
        for(var channelId = 0; channelId < reply.result.duttyArray.length; channelId++)
        {
            setButtonValue(channelId, reply.result.duttyArray[channelId]);
            updateButton(channelId);
        }
    }
}

function getAllChannelCallback(reply) {

}
/*----------------------------------------------------------------------------------------------------------------*/

__pwmSetRequest = function(channel, dutty, id)
    //{"jsonrpc": "2.0", "method": "pwmSet", "params": {"channel": 23, "dutty": 42}, "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pwmSet";
        this.params = { "channel": 0, "dutty": 0 };
        this.id = id;

        this.params.channel = channel;
        this.params.dutty = dutty;
    }

__pca9685SetRequest = function(channel, dutty, id)
    //{"jsonrpc": "2.0", "method": "pca9685Set", "params": {"channel": 23, "dutty": 42}, "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pca9685Set";
        this.params = { "channel": 0, "dutty": 0 };
        this.id = id;
        this.params.channel = channel;
        this.params.dutty = dutty;
    }

__pca9685GetRequest = function(channel, dutty, id)
    //{"jsonrpc": "2.0", "method": "pca9685Get", "params": {"channel": 23}, "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pca9685Get";
        this.params = { "channel": 0, "dutty": 0 };
        this.id = id;

        this.params.channel = channel;
        this.params.dutty = dutty;
    }

__pca9685GetAllRequest = function(id)
    //{"jsonrpc": "2.0", "method": "pca9685GetAll", "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pca9685GetAll";
        this.id = id;
    }

var gRpcId = 0;

function remoteChannelSet(channel, value) {
    if (typeof channel === 'string') channel = parseInt(channel);
    if (typeof value === 'string') value = parseInt(value);

    //var rpcRequest = new __pwmSetRequest(channel, value, gRpcId++);
    var rpcRequest = new __pca9685SetRequest(channel, value, gRpcId++);
    rpcRequest = JSON.stringify(rpcRequest);

    $.ajax({
        // la URL para la petición
        url: gRpcUrl,

        // la información a enviar
        // (también es posible utilizar una cadena de datos)
        data: rpcRequest,

        // especifica si será una petición POST o GET
        type: 'POST',

        // el tipo de información que se espera de respuesta
        dataType: 'json',

        // código a ejecutar si la petición es satisfactoria;
        // la respuesta es pasada como argumento a la función
        success: function(json) {
            console.log('ajax success');
        },

        // código a ejecutar si la petición falla;
        // son pasados como argumentos a la función
        // el objeto de la petición en crudo y código de estatus de la petición
        error: function(xhr, status) {
            console.log('ajax error: ' + status);
        },

        // código a ejecutar sin importar si la petición falló o no
        complete: function(xhr, status) {
            console.log('ajax complete');
        }
    });
}

function remoteChannelGet(channel, value, callback) {
    if (typeof channel === 'string') channel = parseInt(channel);
    if (typeof value === 'string') value = parseInt(value);

    var rpcRequest = new __pca9685GetRequest(channel, value, gRpcId++);
    rpcRequest = JSON.stringify(rpcRequest);

    $.ajax({
        // la URL para la petición
        url: gRpcUrl,

        // la información a enviar
        // (también es posible utilizar una cadena de datos)
        data: rpcRequest,

        // especifica si será una petición POST o GET
        type: 'POST',

        // el tipo de información que se espera de respuesta
        dataType: 'json',

        // código a ejecutar si la petición es satisfactoria;
        // la respuesta es pasada como argumento a la función
        success: function(json) {
            callback(json);
            console.log('ajax success');
        },

        // código a ejecutar si la petición falla;
        // son pasados como argumentos a la función
        // el objeto de la petición en crudo y código de estatus de la petición
        error: function(xhr, status) {
            console.log('ajax error: ' + status);
        },

        // código a ejecutar sin importar si la petición falló o no
        complete: function(xhr, status) {
            console.log('ajax complete');
        }
    });
}

function remoteChannelGetAll(callback) {
    if (typeof channel === 'string') channel = parseInt(channel);
    if (typeof value === 'string') value = parseInt(value);

    var rpcRequest = new __pca9685GetAllRequest(gRpcId++);
    rpcRequest = JSON.stringify(rpcRequest);

    $.ajax({
        // la URL para la petición
        url: gRpcUrl,

        // la información a enviar
        // (también es posible utilizar una cadena de datos)
        data: rpcRequest,

        // especifica si será una petición POST o GET
        type: 'POST',

        // el tipo de información que se espera de respuesta
        dataType: 'json',

        // código a ejecutar si la petición es satisfactoria;
        // la respuesta es pasada como argumento a la función
        success: function(json) {
            callback(json);
            console.log('ajax success');
        },

        // código a ejecutar si la petición falla;
        // son pasados como argumentos a la función
        // el objeto de la petición en crudo y código de estatus de la petición
        error: function(xhr, status) {
            console.log('ajax error: ' + status);
        },

        // código a ejecutar sin importar si la petición falló o no
        complete: function(xhr, status) {
            console.log('ajax complete');
        }
    });
}

function guiBuild() {
    var html = "";
    //html = $(gSliderContainer).html();

    var t = 0;

    var template = "";
    for (t = 0; t < gData.s_data.m_channelCount; t++) {
        var slider = "slider_Input_" + t;
        template = gSliderTemplate;
        template = template.replace("###slider_Input_Id###", slider);
        template = template.replace("###slider_Input_Id###", slider);
        template = template.replace("###slider_Channel###", "Channel " + (t + 1));
        template = template.replace("###slider_Value###", 0);
        template = template.replace("###channel_number###", "" + t);

        html += template;

        $(document).on('slidestop', '#' + slider, function(e, ui) {
            var cn = $(this).attr("channel-number");
            console.log("Channel " + cn + " , Value " + $(this).val());
            gData.s_data.a_channelPwm[cn] = $(this).val();
            targetChannelUpdate(cn, gData.s_data.a_channelPwm[cn]);
        });
    }

    $(gSliderContainer).empty().append(html).enhanceWithin();
}<commit_msg>Channel dutty auto update added<commit_after>var gData = new appData();
var gRpcUrl = "json.rpc";
var gSliderContainer = "#sliderContainer";
var gSliderTemplate = '
';
gSliderTemplate += '###slider_Channel###';
gSliderTemplate += '<input id="###slider_Input_Id###" name="slider" class="custom-slider" channel-number="###channel_number###" value="###slider_Value###" min="0" max="100" type="range" data-highlight="true">';
gSliderTemplate += '
';

$(document).ready(function() {
    /*
    if (gData.checkConfig()) {
        gData.load();
    } else {
        gData.save();
    }

    guiBuild();
    guiUpdate();
    guiEventsInit();

       if(gData.checkDefault())
       {
    	   $( "#settingsPannel" ).trigger( "expand" );
       }
    */
    gCurrentButton = null;
    setInterval(OnButtonTimer, 50);
    eventBind();

    $('.button-frame').each(function(index, value) {
        updateButton(index + '');
    });

    remoteChannelGetAll(getChannelCallback);
    setInterval(function() {
        remoteChannelGetAll(getChannelCallback);
    }, 1000);

});

function eventBind() {
    $('body').on('mousedown touchstart', '.function-increase', function(e) { OnIncrease(e); });
    $('body').on('mousedown touchstart', '.function-decrease', function(e) { OnDecrease(e); });
    $('body').on('mouseup touchend', '.function-increase', function(e) { OnIncrease(e); });
    $('body').on('mouseup touchend', '.function-decrease', function(e) { OnDecrease(e); });
    $('body').on('click', '.function-toggle', function(e) { OnToggle(e); });
}

var gCurrentChannel = null;
var gButtonState = 'sIdle';

function OnIncrease(event) {

    event.stopPropagation();
    switch (event.type) {
        case 'mousedown':
            gCurrentChannel = $(event.target).attr('tChnannelId');
            gButtonState = 'sIncrease';
            break;

        case 'mouseup':
        default:
            gButtonState = 'sIdle';
            gCurrentChannel = null;
            break;

    }

}

function OnDecrease(event) {

    event.stopPropagation();
    switch (event.type) {
        case 'mousedown':
            gCurrentChannel = $(event.target).attr('tChnannelId');
            gButtonState = 'sDecrease';
            break;

        case 'mouseup':
        default:
            gButtonState = 'sIdle';
            gCurrentChannel = null;
            break;

    }
}

function OnToggle(event) {

    var channelId = $(event.target).attr('tChnannelId');
    if (getButtonValue(channelId) === 0) {
        setButtonValue(channelId, getButtonValueBackup(channelId));
        remoteChannelSet(channelId, getButtonValue(channelId));
    } else {
        setButtonValueBackup(channelId, getButtonValue(channelId));
        setButtonValue(channelId, 0);
        remoteChannelSet(channelId, 0);
    }
    updateButton(channelId);
}

function OnButtonTimer() {

    if (gCurrentChannel === null) return;

    switch (gButtonState) {
        case 'sIdle':
            break;

        case 'sDecrease':
            decreaseChannelValue(gCurrentChannel);
            updateButton(gCurrentChannel);
            break;

        case 'sIncrease':
            increaseChannelValue(gCurrentChannel);
            updateButton(gCurrentChannel);
            break;

        default:
            break;
    }

}

function updateButton(channelId) {
    var value = getButtonValue(channelId);
    var root = $('#tChannel' + channelId);
    var text = root.find(".function-toggle p");
    if (value == 255) { //OSLL: Default state, need to get values from device...
        text[1].innerHTML = "...";
        root.addClass("button-frame-UNKNOWN");
    } else if (value > 0) {
        text[1].innerHTML = "ON";
        root.removeClass("button-frame-OFF");
        root.removeClass("button-frame-UNKNOWN");
        root.find(".button-path-text").removeClass("button-path-text-OFF");
        root.find(".button-svg").removeClass("button-svg-OFF");
        arcDraw(channelId, value);
    } else {
        text[1].innerHTML = "OFF";
        root.removeClass("button-frame-UNKNOWN");
        root.addClass("button-frame-OFF");
        root.find(".button-path-text").addClass("button-path-text-OFF");
        root.find(".button-svg").addClass("button-svg-OFF");
        arcDraw(channelId, value);
    }
}

function increaseChannelValue(channelId) {
    var value = getButtonValue(channelId);
    if (value < 100) {
        value++;
        setButtonValue(channelId, value);
        remoteChannelSet(channelId, value);
    }
}

function decreaseChannelValue(channelId) {
    var value = getButtonValue(channelId);
    if (value > 1) {
        value--;
        setButtonValue(channelId, value);
        remoteChannelSet(channelId, value);
    }
}

function getButtonValue(channelId) {
    var value = $('#tChannel' + channelId).attr('tChannelValue');
    return parseInt(value);
}

function setButtonValue(channelId, value) {
    $('#tChannel' + channelId).attr('tChannelValue', value);
}

function getButtonValueBackup(channelId) {
    var value = $('#tChannel' + channelId).attr('tChannelBackupValue');
    return parseInt(value);
}

function setButtonValueBackup(channelId, value) {
    $('#tChannel' + channelId).attr('tChannelBackupValue', value);
}

function arcDraw(itemIndex, value) {

    if (value > 100) value = 100;
    if (value < 0) value = 0;

    var svg = $("#tSvg" + itemIndex);
    var x = svg.width() / 2;
    var y = svg.height() / 2;
    var r = svg.width() / 3.5;
    var a = (360.0 / 100.0) * value;
    var text = $("#tText" + itemIndex);
    text.attr("x", x);
    text.attr("y", y);
    text[0].innerHTML = value.toFixed(0) + "%";
    $("#tArc" + itemIndex)[0].setAttribute("d", describeArc(x, y, r, 0, a - 1));
}

//http://jsbin.com/cibicecuto/edit?html,js,output

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
    var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;

    return {
        x: centerX + (radius * Math.cos(angleInRadians)),
        y: centerY + (radius * Math.sin(angleInRadians))
    };
}

function describeArc(x, y, radius, startAngle, endAngle) {

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";

    var d = [
        "M", start.x, start.y,
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y
    ].join(" ");

    return d;
}
/*----------------------------------------------------------------------------------------------------------------*/
function getChannelCallback(reply) {

    if (reply.result.hasOwnProperty("duttyArray")) {
        for (var channelId = 0; channelId < reply.result.duttyArray.length; channelId++) {
            setButtonValue(channelId, reply.result.duttyArray[channelId]);
            updateButton(channelId);
        }
    }
}

function getAllChannelCallback(reply) {

}
/*----------------------------------------------------------------------------------------------------------------*/

__pwmSetRequest = function(channel, dutty, id)
    //{"jsonrpc": "2.0", "method": "pwmSet", "params": {"channel": 23, "dutty": 42}, "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pwmSet";
        this.params = { "channel": 0, "dutty": 0 };
        this.id = id;

        this.params.channel = channel;
        this.params.dutty = dutty;
    }

__pca9685SetRequest = function(channel, dutty, id)
    //{"jsonrpc": "2.0", "method": "pca9685Set", "params": {"channel": 23, "dutty": 42}, "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pca9685Set";
        this.params = { "channel": 0, "dutty": 0 };
        this.id = id;
        this.params.channel = channel;
        this.params.dutty = dutty;
    }

__pca9685GetRequest = function(channel, dutty, id)
    //{"jsonrpc": "2.0", "method": "pca9685Get", "params": {"channel": 23}, "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pca9685Get";
        this.params = { "channel": 0, "dutty": 0 };
        this.id = id;

        this.params.channel = channel;
        this.params.dutty = dutty;
    }

__pca9685GetAllRequest = function(id)
    //{"jsonrpc": "2.0", "method": "pca9685GetAll", "id": 4}
    {
        this.jsonrpc = "2.0";
        this.method = "pca9685GetAll";
        this.id = id;
    }

var gRpcId = 0;

function remoteChannelSet(channel, value) {
    if (typeof channel === 'string') channel = parseInt(channel);
    if (typeof value === 'string') value = parseInt(value);

    //var rpcRequest = new __pwmSetRequest(channel, value, gRpcId++);
    var rpcRequest = new __pca9685SetRequest(channel, value, gRpcId++);
    rpcRequest = JSON.stringify(rpcRequest);

    $.ajax({
        // la URL para la petición
        url: gRpcUrl,

        // la información a enviar
        // (también es posible utilizar una cadena de datos)
        data: rpcRequest,

        // especifica si será una petición POST o GET
        type: 'POST',

        // el tipo de información que se espera de respuesta
        dataType: 'json',

        // código a ejecutar si la petición es satisfactoria;
        // la respuesta es pasada como argumento a la función
        success: function(json) {
            console.log('ajax success');
        },

        // código a ejecutar si la petición falla;
        // son pasados como argumentos a la función
        // el objeto de la petición en crudo y código de estatus de la petición
        error: function(xhr, status) {
            console.log('ajax error: ' + status);
        },

        // código a ejecutar sin importar si la petición falló o no
        complete: function(xhr, status) {
            console.log('ajax complete');
        }
    });
}

function remoteChannelGet(channel, value, callback) {
    if (typeof channel === 'string') channel = parseInt(channel);
    if (typeof value === 'string') value = parseInt(value);

    var rpcRequest = new __pca9685GetRequest(channel, value, gRpcId++);
    rpcRequest = JSON.stringify(rpcRequest);

    $.ajax({
        // la URL para la petición
        url: gRpcUrl,

        // la información a enviar
        // (también es posible utilizar una cadena de datos)
        data: rpcRequest,

        // especifica si será una petición POST o GET
        type: 'POST',

        // el tipo de información que se espera de respuesta
        dataType: 'json',

        // código a ejecutar si la petición es satisfactoria;
        // la respuesta es pasada como argumento a la función
        success: function(json) {
            callback(json);
            console.log('ajax success');
        },

        // código a ejecutar si la petición falla;
        // son pasados como argumentos a la función
        // el objeto de la petición en crudo y código de estatus de la petición
        error: function(xhr, status) {
            console.log('ajax error: ' + status);
        },

        // código a ejecutar sin importar si la petición falló o no
        complete: function(xhr, status) {
            console.log('ajax complete');
        }
    });
}

function remoteChannelGetAll(callback) {
    if (typeof channel === 'string') channel = parseInt(channel);
    if (typeof value === 'string') value = parseInt(value);

    var rpcRequest = new __pca9685GetAllRequest(gRpcId++);
    rpcRequest = JSON.stringify(rpcRequest);

    $.ajax({
        // la URL para la petición
        url: gRpcUrl,

        // la información a enviar
        // (también es posible utilizar una cadena de datos)
        data: rpcRequest,

        // especifica si será una petición POST o GET
        type: 'POST',

        // el tipo de información que se espera de respuesta
        dataType: 'json',

        // código a ejecutar si la petición es satisfactoria;
        // la respuesta es pasada como argumento a la función
        success: function(json) {
            callback(json);
            console.log('ajax success');
        },

        // código a ejecutar si la petición falla;
        // son pasados como argumentos a la función
        // el objeto de la petición en crudo y código de estatus de la petición
        error: function(xhr, status) {
            console.log('ajax error: ' + status);
        },

        // código a ejecutar sin importar si la petición falló o no
        complete: function(xhr, status) {
            console.log('ajax complete');
        }
    });
}

function guiBuild() {
    var html = "";
    //html = $(gSliderContainer).html();

    var t = 0;

    var template = "";
    for (t = 0; t < gData.s_data.m_channelCount; t++) {
        var slider = "slider_Input_" + t;
        template = gSliderTemplate;
        template = template.replace("###slider_Input_Id###", slider);
        template = template.replace("###slider_Input_Id###", slider);
        template = template.replace("###slider_Channel###", "Channel " + (t + 1));
        template = template.replace("###slider_Value###", 0);
        template = template.replace("###channel_number###", "" + t);

        html += template;

        $(document).on('slidestop', '#' + slider, function(e, ui) {
            var cn = $(this).attr("channel-number");
            console.log("Channel " + cn + " , Value " + $(this).val());
            gData.s_data.a_channelPwm[cn] = $(this).val();
            targetChannelUpdate(cn, gData.s_data.a_channelPwm[cn]);
        });
    }

    $(gSliderContainer).empty().append(html).enhanceWithin();
}<|endoftext|>


<commit_before>/*
    update.js <https://github.com/davidfig/update>
    License: MIT license <https://github.com/davidfig/update/license>
    Author: David Figatner
    Copyright (c) 2016 YOPEY YOPEY LLC
*/

/* globals Debug, debugOne, performance, requestAnimationFrame, setTimeout, window, define, document */
var Update = {

    list: [],
    FPS: 60,
    pause: false,
    pauseRegistrations: [],
    pauseElapsed: 0,

    startTime: 0,
    frameNumber: 0,
    lastUpdate: 0,
    lastFPS: '--',

    tolerance: 1,

    maxChange: 100,

    panels: {fps: null, meter: null, percent: null},
    percentageList: [],

    // this is the number of entries to use in a rolling average to smooth the debug percentages
    rollingAverage: 500,

    /**
     * must call Update.init before using Update
     * @param {boolean} debug - whether to turn on debug support (requires github.com/davidfig/debug)
     * @param {boolean=false|string} count - show debug counts (can supply side for panel, e.g., 'topleft')
     * @param {boolean=false|string} percent - show debug percentage
     * @param {boolean=false|string} FPS - show debug FPS
     */
    init: function(options)
    {
        options = options || {};
        Update.checkVisibility();
        Update.FPSActual = 1000 / Update.FPS;
        if (options.debug)
        {
            Update.debug = {count: options.count, percent: options.percent, FPS: options.FPS};
            Update._debugInit();
        }
    },

    /**
     * register functions to call after Update pauses or resumes
     * @param {Function} pause
     * @param {Function} resume
     */
    registerPause: function(pause, resume)
    {
        Update.pauseRegistrations.push({ pause: pause, resume: resume});
    },

    /**
     * pauses all updates
     */
    pauseGame: function()
    {
        if (Update.pause !== true)
        {
            Update.pause = true;
            Update.pauseElapsed = performance.now() - Update.lastUpdate;
            Update.updateOff = false;
            if (Update.debug)
            {
                Update.debugPause();
            }
            for (var i = 0; i < Update.pauseRegistrations.length; i++)
            {
                Update.pauseRegistrations[i].pause();
            }
        }
    },

    /**
     * resumes all updates
     */
    resumeGame: function()
    {
        if (Update.pause === true)
        {
            Update.pause = false;
            Update.lastUpdate = performance.now() - Update.pauseElapsed;
            if (Update.debug.FPS)
            {
                Update.startTime = 0;
                Update.frameNumber = 0;
                Update.lastUpdate = 0;
                Update.lastFPS = '--';
            }
            for (var i = 0; i < Update.pauseRegistrations.length; i++)
            {
                Update.pauseRegistrations[i].resume();
            }
            if (Update.updateOff === true)
            {
                Update.update();
            }
        }
    },

    /**
     * loops through all updates
     */
    _updateAll: function(elapsed)
    {
        var i = 0, _i = Update.list.length;
        var other = 0, count = 0;
        while (i < _i)
        {
            var update = Update.list[i++];
            if (update.pause)
            {
                continue;
            }
            if (update.duration !== 0)
            {
                update.elapsed += elapsed;
                if (update.elapsed < update.duration)
                {
                    if (Update.debug.percent && update.options.percent)
                    {
                        var change = Update.percentageList[update.options.percent];
                        change.amounts[change.current++] = 0;
                        if (change.current === Update.rollingAverage)
                        {
                            change.current = 0;
                        }
                    }
                    continue;
                }
                else
                {
                    update.elapsed = 0;
                }
            }
            var start, result;
            if (Update.debug && Update.debug.percent)
            {
                start = performance.now();
                result = update.callback(elapsed, update.options);
                var current = performance.now() - start;
                if (update.options.percent)
                {
                    var change = Update.percentageList[update.options.percent];
                    change.amounts[change.current++] = current;
                    if (change.current === Update.rollingAverage)
                    {
                        change.current = 0;
                    }
                }
                else
                {
                    other += current;
                }
            }
            else
            {
                result = update.callback(elapsed, update.options);
            }
            if (update.once || result)
            {
                i--;
                _i--;
                Update.list.splice(i, 1);
            }
            count++;
        }
        if (Update.debug)
        {
            if (Update.debug.count && Update.lastCount !== count)
            {
                debugOne(count + ' updates', {panel: Update.panels.count});
                Update.lastCount = count;
            }
            if (Update.debug.percent)
            {
                Update._debugPercent(other);
            }
        }
    },

    /**
     * adds a function to the update loop
     * @param {Function} funct
     * @param {object} options
     * @param {number=0} options.time in milliseconds to call this function
     * @param {number=} options.FPS - this replaces options.time and calls the function at the desired FPS
     * @param {boolean=false} options.once - call only once and then remove from update queue
     * @param {string=} options.percent - name to track the percentage in the debug panel
     */
    add: function(funct, options)
    {
        options = options || {};
        var time = options.time || (options.FPS ? 1000 / options.FPS : 0);
        var update = {callback: funct, options: options, duration: time, elapsed: 0, once: options.once, pause: false};
        Update.list.push(update);
        if (Update.debug && options.percent)
        {
            Update.percentageList[options.percent] = {current: 0, amounts: []};
            var test = '';
            for (var key in Update.percentageList)
            {
                test += key + ': --%
';
            }
            debugOne(test, {panel: Update.panels.percent});
            Debug.resize();
        }
        return update;
    },

    /**
     * removes an update from the loop
     * @param {object} update - object returned by Update.add()
     */
    remove: function(update)
    {
        var index = Update.list.indexOf(update);
        Update.list.splice(index, 1);
    },

    /**
     * starts the update loop
     */
    update: function()
    {
        if (Update.pause === true)
        {
            Update.updateOff = true;
            return;
        }
        var current = performance.now();
        var elapsed;
        if (Update.lastUpdate === 0)
        {
            elapsed = 0;
        }
        else
        {
            elapsed = current - Update.lastUpdate;
            elapsed = elapsed > Update.maxChange ? Update.maxChange : elapsed;
        }
        if (Update.FPS === 60 || elapsed === 0 || elapsed >= Update.FPSActual)
        {
            if (Update.list.length)
            {
                Update._updateAll(elapsed);
            }
            Update.lastUpdate = current;
            if (Update.debug && Update.debug.FPS)
            {
                Update._debugUpdate(current);
            }
        }
        if (typeof requestAnimationFrame === 'function')
        {
            requestAnimationFrame(Update.update);
        }
        else
        {
            setTimeout(Update.update, Update.FPSActual);
        }
    },

    /**
     * Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. Also listens for window.onblur and window.onfocus.
     * based on Phaser: https://github.com/photonstorm/phaser (MIT license)
     */
    checkVisibility: function()
    {
        var hiddenVar;
        if (document.webkitHidden !== undefined)
        {
            hiddenVar = 'webkitvisibilitychange';
        }
        else if (document.mozHidden !== undefined)
        {
            hiddenVar = 'mozvisibilitychange';
        }
        else if (document.msHidden !== undefined)
        {
            hiddenVar = 'msvisibilitychange';
        }
        else if (document.hidden !== undefined)
        {
            hiddenVar = 'visibilitychange';
        }
        else
        {
            hiddenVar = null;
        }

        //  Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
        if (hiddenVar)
        {
            document.addEventListener(hiddenVar, Update.visibilityChange, false);
        }

        window.onblur = Update.visibilityChange;
        window.onfocus = Update.visibilityChange;

        window.onpagehide = Update.visibilityChange;
        window.onpageshow = Update.visibilityChange;
    },

    /**
     * Callback for checkVisibility()
     * based on Phaser: https://github.com/photonstorm/phaser (MIT license)
     */
    visibilityChange: function(event)
    {
        if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
        {
            if (event.type === 'pagehide' || event.type === 'blur')
            {
                Update.pauseGame();
            }
            else if (event.type === 'pageshow' || event.type === 'focus')
            {
                Update.resumeGame(event);
            }
            return;
        }

        if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === 'pause')
        {
            Update.pauseGame(event);
        }
    },

    /**
     * adds debug panels (uses github.com/davidfig/debug)
     */
    _debugInit: function()
    {
        if (Update.debug.FPS)
        {
            Update.panels.fps = Debug.add('FPS', {text: '-- FPS'});
            Update.panels.meter = Debug.addMeter('panel');
        }
        if (Update.debug.count)
        {
            Update.panels.count = Debug.add('Updates', {text: '0 updates'});
        }
        if (Update.debug.percent)
        {
            Update.panels.percent = Debug.add('percentages', {style: {textAlign: 'right'}});
            Update.percentageList['Other'] = {current: 0, amounts: []};
        }
    },

    debugPause: function()
    {
        debugOne('-- FPS', {panel: Update.panels.fps});
    },

    _debugUpdate: function(current)
    {
        Update.frameNumber++;
        var currentTime = performance.now() - Update.startTime;

        // skip the first half second to get rid of garbage
        if (currentTime > 500)
        {
            if (Update.startTime !== 0)
            {
                Update.lastFPS = Math.floor(Update.frameNumber / (currentTime / 1000));
                if (Update.lastFPS >= 60 - Update.tolerance && Update.lastFPS <= 60 + Update.tolerance)
                {
                    Update.lastFPS = 60;
                }
            }
            Update.startTime = performance.now();
            Update.frameNumber = 0;
        }
        debugOne(Update.lastFPS + ' FPS', {panel: Update.panels.fps});
        var time = performance.now() - current;

        // 16.7 is hard coded for 60 FPS. Probably should figure out the real amount for the current FPS
        var expected = (16.7 - time) / 16.7;
        Debug.meter(expected, {panel: Update.panels.meter});
    },

    /**
     * update percentage panel
     */
    _debugPercent: function(other)
    {
        var change = Update.percentageList['Other'];
        change.amounts[change.current++] = other;
        change.current %= Update.rollingAverage;
        var updates = [], all = 0;
        for (var name in Update.percentageList)
        {
            var change = Update.percentageList[name];
            var total = 0;
            for (var i = 0; i < change.amounts.length; i++)
            {
                total += change.amounts[i];
            }
            total /= change.amounts.length;
            all += total;
            updates.push({name: name, total: total});
        }
        var result = '';
        for (var i = 1; i < updates.length; i++)
        {
            var update = updates[i];
            result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
        }
        var update = updates[0];
        result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
        debugOne(result, {panel: Update.panels.percent});
    }
};

// add support for AMD (Asynchronous Module Definition) libraries such as require.js.
if (typeof define === 'function' && define.amd)
{
    define(function()
    {
        return {
            Update: Update
        };
    });
}

// add support for CommonJS libraries such as browserify.
if (typeof exports !== 'undefined')
{
    module.exports = Update;
}

// define globally in case AMD is not available or available but not used
if (typeof window !== 'undefined')
{
    window.Update = Update;
}<commit_msg>Fixed debugPause to only update FPS if options.FPS in init()<commit_after>/*
    update.js <https://github.com/davidfig/update>
    License: MIT license <https://github.com/davidfig/update/license>
    Author: David Figatner
    Copyright (c) 2016 YOPEY YOPEY LLC
*/

/* globals Debug, debugOne, performance, requestAnimationFrame, setTimeout, window, define, document */
var Update = {

    list: [],
    FPS: 60,
    pause: false,
    pauseRegistrations: [],
    pauseElapsed: 0,

    startTime: 0,
    frameNumber: 0,
    lastUpdate: 0,
    lastFPS: '--',

    tolerance: 1,

    maxChange: 100,

    panels: {fps: null, meter: null, percent: null},
    percentageList: [],

    // this is the number of entries to use in a rolling average to smooth the debug percentages
    rollingAverage: 500,

    /**
     * must call Update.init before using Update
     * @param {boolean} debug - whether to turn on debug support (requires github.com/davidfig/debug)
     * @param {boolean=false|string} count - show debug counts (can supply side for panel, e.g., 'topleft')
     * @param {boolean=false|string} percent - show debug percentage
     * @param {boolean=false|string} FPS - show debug FPS
     */
    init: function(options)
    {
        options = options || {};
        Update.checkVisibility();
        Update.FPSActual = 1000 / Update.FPS;
        if (options.debug)
        {
            Update.debug = {count: options.count, percent: options.percent, FPS: options.FPS};
            Update._debugInit();
        }
    },

    /**
     * register functions to call after Update pauses or resumes
     * @param {Function} pause
     * @param {Function} resume
     */
    registerPause: function(pause, resume)
    {
        Update.pauseRegistrations.push({ pause: pause, resume: resume});
    },

    /**
     * pauses all updates
     */
    pauseGame: function()
    {
        if (Update.pause !== true)
        {
            Update.pause = true;
            Update.pauseElapsed = performance.now() - Update.lastUpdate;
            Update.updateOff = false;
            if (Update.debug)
            {
                Update._debugPause();
            }
            for (var i = 0; i < Update.pauseRegistrations.length; i++)
            {
                Update.pauseRegistrations[i].pause();
            }
        }
    },

    /**
     * resumes all updates
     */
    resumeGame: function()
    {
        if (Update.pause === true)
        {
            Update.pause = false;
            Update.lastUpdate = performance.now() - Update.pauseElapsed;
            if (Update.debug.FPS)
            {
                Update.startTime = 0;
                Update.frameNumber = 0;
                Update.lastUpdate = 0;
                Update.lastFPS = '--';
            }
            for (var i = 0; i < Update.pauseRegistrations.length; i++)
            {
                Update.pauseRegistrations[i].resume();
            }
            if (Update.updateOff === true)
            {
                Update.update();
            }
        }
    },

    /**
     * loops through all updates
     */
    _updateAll: function(elapsed)
    {
        var i = 0, _i = Update.list.length;
        var other = 0, count = 0;
        while (i < _i)
        {
            var update = Update.list[i++];
            if (update.pause)
            {
                continue;
            }
            if (update.duration !== 0)
            {
                update.elapsed += elapsed;
                if (update.elapsed < update.duration)
                {
                    if (Update.debug.percent && update.options.percent)
                    {
                        var change = Update.percentageList[update.options.percent];
                        change.amounts[change.current++] = 0;
                        if (change.current === Update.rollingAverage)
                        {
                            change.current = 0;
                        }
                    }
                    continue;
                }
                else
                {
                    update.elapsed = 0;
                }
            }
            var start, result;
            if (Update.debug && Update.debug.percent)
            {
                start = performance.now();
                result = update.callback(elapsed, update.options);
                var current = performance.now() - start;
                if (update.options.percent)
                {
                    var change = Update.percentageList[update.options.percent];
                    change.amounts[change.current++] = current;
                    if (change.current === Update.rollingAverage)
                    {
                        change.current = 0;
                    }
                }
                else
                {
                    other += current;
                }
            }
            else
            {
                result = update.callback(elapsed, update.options);
            }
            if (update.once || result)
            {
                i--;
                _i--;
                Update.list.splice(i, 1);
            }
            count++;
        }
        if (Update.debug)
        {
            if (Update.debug.count && Update.lastCount !== count)
            {
                debugOne(count + ' updates', {panel: Update.panels.count});
                Update.lastCount = count;
            }
            if (Update.debug.percent)
            {
                Update._debugPercent(other);
            }
        }
    },

    /**
     * adds a function to the update loop
     * @param {Function} funct
     * @param {object} options
     * @param {number=0} options.time in milliseconds to call this function
     * @param {number=} options.FPS - this replaces options.time and calls the function at the desired FPS
     * @param {boolean=false} options.once - call only once and then remove from update queue
     * @param {string=} options.percent - name to track the percentage in the debug panel
     */
    add: function(funct, options)
    {
        options = options || {};
        var time = options.time || (options.FPS ? 1000 / options.FPS : 0);
        var update = {callback: funct, options: options, duration: time, elapsed: 0, once: options.once, pause: false};
        Update.list.push(update);
        if (Update.debug && options.percent)
        {
            Update.percentageList[options.percent] = {current: 0, amounts: []};
            var test = '';
            for (var key in Update.percentageList)
            {
                test += key + ': --%
';
            }
            debugOne(test, {panel: Update.panels.percent});
            Debug.resize();
        }
        return update;
    },

    /**
     * removes an update from the loop
     * @param {object} update - object returned by Update.add()
     */
    remove: function(update)
    {
        var index = Update.list.indexOf(update);
        Update.list.splice(index, 1);
    },

    /**
     * starts the update loop
     */
    update: function()
    {
        if (Update.pause === true)
        {
            Update.updateOff = true;
            return;
        }
        var current = performance.now();
        var elapsed;
        if (Update.lastUpdate === 0)
        {
            elapsed = 0;
        }
        else
        {
            elapsed = current - Update.lastUpdate;
            elapsed = elapsed > Update.maxChange ? Update.maxChange : elapsed;
        }
        if (Update.FPS === 60 || elapsed === 0 || elapsed >= Update.FPSActual)
        {
            if (Update.list.length)
            {
                Update._updateAll(elapsed);
            }
            Update.lastUpdate = current;
            if (Update.debug && Update.debug.FPS)
            {
                Update._debugUpdate(current);
            }
        }
        if (typeof requestAnimationFrame === 'function')
        {
            requestAnimationFrame(Update.update);
        }
        else
        {
            setTimeout(Update.update, Update.FPSActual);
        }
    },

    /**
     * Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser. Also listens for window.onblur and window.onfocus.
     * based on Phaser: https://github.com/photonstorm/phaser (MIT license)
     */
    checkVisibility: function()
    {
        var hiddenVar;
        if (document.webkitHidden !== undefined)
        {
            hiddenVar = 'webkitvisibilitychange';
        }
        else if (document.mozHidden !== undefined)
        {
            hiddenVar = 'mozvisibilitychange';
        }
        else if (document.msHidden !== undefined)
        {
            hiddenVar = 'msvisibilitychange';
        }
        else if (document.hidden !== undefined)
        {
            hiddenVar = 'visibilitychange';
        }
        else
        {
            hiddenVar = null;
        }

        //  Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
        if (hiddenVar)
        {
            document.addEventListener(hiddenVar, Update.visibilityChange, false);
        }

        window.onblur = Update.visibilityChange;
        window.onfocus = Update.visibilityChange;

        window.onpagehide = Update.visibilityChange;
        window.onpageshow = Update.visibilityChange;
    },

    /**
     * Callback for checkVisibility()
     * based on Phaser: https://github.com/photonstorm/phaser (MIT license)
     */
    visibilityChange: function(event)
    {
        if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
        {
            if (event.type === 'pagehide' || event.type === 'blur')
            {
                Update.pauseGame();
            }
            else if (event.type === 'pageshow' || event.type === 'focus')
            {
                Update.resumeGame(event);
            }
            return;
        }

        if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === 'pause')
        {
            Update.pauseGame(event);
        }
    },

    /**
     * adds debug panels (uses github.com/davidfig/debug)
     */
    _debugInit: function()
    {
        if (Update.debug.FPS)
        {
            Update.panels.fps = Debug.add('FPS', {text: '-- FPS'});
            Update.panels.meter = Debug.addMeter('panel');
        }
        if (Update.debug.count)
        {
            Update.panels.count = Debug.add('Updates', {text: '0 updates'});
        }
        if (Update.debug.percent)
        {
            Update.panels.percent = Debug.add('percentages', {style: {textAlign: 'right'}});
            Update.percentageList['Other'] = {current: 0, amounts: []};
        }
    },

    _debugPause: function()
    {
        if (Debug.debug.FPS)
        {
            debugOne('-- FPS', {panel: Update.panels.fps});
        }
    },

    _debugUpdate: function(current)
    {
        Update.frameNumber++;
        var currentTime = performance.now() - Update.startTime;

        // skip the first half second to get rid of garbage
        if (currentTime > 500)
        {
            if (Update.startTime !== 0)
            {
                Update.lastFPS = Math.floor(Update.frameNumber / (currentTime / 1000));
                if (Update.lastFPS >= 60 - Update.tolerance && Update.lastFPS <= 60 + Update.tolerance)
                {
                    Update.lastFPS = 60;
                }
            }
            Update.startTime = performance.now();
            Update.frameNumber = 0;
        }
        debugOne(Update.lastFPS + ' FPS', {panel: Update.panels.fps});
        var time = performance.now() - current;

        // 16.7 is hard coded for 60 FPS. Probably should figure out the real amount for the current FPS
        var expected = (16.7 - time) / 16.7;
        Debug.meter(expected, {panel: Update.panels.meter});
    },

    /**
     * update percentage panel
     */
    _debugPercent: function(other)
    {
        var change = Update.percentageList['Other'];
        change.amounts[change.current++] = other;
        change.current %= Update.rollingAverage;
        var updates = [], all = 0;
        for (var name in Update.percentageList)
        {
            var change = Update.percentageList[name];
            var total = 0;
            for (var i = 0; i < change.amounts.length; i++)
            {
                total += change.amounts[i];
            }
            total /= change.amounts.length;
            all += total;
            updates.push({name: name, total: total});
        }
        var result = '';
        for (var i = 1; i < updates.length; i++)
        {
            var update = updates[i];
            result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
        }
        var update = updates[0];
        result += update.name + ': ' + Math.round(update.total / all * 100) + '%
';
        debugOne(result, {panel: Update.panels.percent});
    }
};

// add support for AMD (Asynchronous Module Definition) libraries such as require.js.
if (typeof define === 'function' && define.amd)
{
    define(function()
    {
        return {
            Update: Update
        };
    });
}

// add support for CommonJS libraries such as browserify.
if (typeof exports !== 'undefined')
{
    module.exports = Update;
}

// define globally in case AMD is not available or available but not used
if (typeof window !== 'undefined')
{
    window.Update = Update;
}<|endoftext|>


<commit_before>import React from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { shallow } from 'enzyme';
import R from 'ramda';

const componentory = (Component, props) => shallow(<Component {...props} />);
const getActual = (...props) => R.mergeAll(props);

const getActualComponentFactory = (Component, defaultProps) => R.compose(
  R.partial(componentory, [Component]),
  R.partial(getActual, [defaultProps]),
);

export {
  getActualComponentFactory as default,
  getActual,
};
<commit_msg>Update testUtils<commit_after>import React from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { shallow } from 'enzyme';
import R from 'ramda';

const componentory = (Component, props) => shallow(<Component {...props} />);
const merge = (defaultProps, props) => R.mergeAll([defaultProps, props]);

const getActualComponentFactory = (Component, defaultProps) => R.compose(
  R.partial(componentory, [Component]),
  R.partial(merge, [defaultProps]),
);

export default getActualComponentFactory;
<|endoftext|>


<commit_before>define([
], function(
) {
  model.keyboardSettingPairs = ko.computed(function() {
    return model.keyboardSettingsItems().map(function(item) {
      var label = loc(item.title())
      return {
        label: label + ' (' + item.value() + ')',
        value: label,
        item: item,
      }
    })
  })

  model.comboToAssign = ko.observable()

  model.comboToAssign.subscribe(function(combo) {
    if (combo && combo != '') {
      $("#function-finder-dialog").dialog('open')
    } else {
      $("#function-finder-dialog").dialog('close')
    }
  })

  return {
    ready: function() {
      $("#function-finder-dialog").dialog({
        modal: true,
        autoOpen: false,
      });

      $('#function-finder').autocomplete({
        source: model.keyboardSettingPairs(),
        select: function(ev, ui) {
          ui.item.item.value(model.comboToAssign())

          model.comboToAssign(null)

          // clear input
          $(this).val('')
          return false
        },
      })

      model.keyboardSettingPairs.subscribe(function(newValue) {
        $('#function-finder').autocomplete("option", "source", newValue);
      });
    },
    open: function() {
      $("#function-finder-dialog").dialog('open')
    },
  }
})
<commit_msg>do not show empty parens for unbound keys<commit_after>define([
], function(
) {
  model.keyboardSettingPairs = ko.computed(function() {
    return model.keyboardSettingsItems().map(function(item) {
      var label = loc(item.title())
      var existing = item.value()
      if (existing) {
        existing = ' (' + item.value() + ')'
      }
      return {
        label: label + existing,
        value: label,
        item: item,
      }
    })
  })

  model.comboToAssign = ko.observable()

  model.comboToAssign.subscribe(function(combo) {
    if (combo && combo != '') {
      $("#function-finder-dialog").dialog('open')
    } else {
      $("#function-finder-dialog").dialog('close')
    }
  })

  return {
    ready: function() {
      $("#function-finder-dialog").dialog({
        modal: true,
        autoOpen: false,
      });

      $('#function-finder').autocomplete({
        source: model.keyboardSettingPairs(),
        select: function(ev, ui) {
          ui.item.item.value(model.comboToAssign())

          model.comboToAssign(null)

          // clear input
          $(this).val('')
          return false
        },
      })

      model.keyboardSettingPairs.subscribe(function(newValue) {
        $('#function-finder').autocomplete("option", "source", newValue);
      });
    },
    open: function() {
      $("#function-finder-dialog").dialog('open')
    },
  }
})
<|endoftext|>


<commit_before>Template['chat'].helpers({
    chatroom: function(){
        return Session.get("name")
    },
    nickname: function(){
        return Session.get('nickname');
    },
    prettyTime: function(datetime){
        if(typeof datetime === 'object'){
            var minutes = (datetime.getMinutes()<10 ?'0':'') + datetime.getMinutes()
            return "" + datetime.getHours() + ":" + minutes
            }
        else{
            return datetime
        }
    }
});

Template['chat'].events({
    // send message
    'keydown #message' : function (event) {
        if (event.which == 13) { // 13 is the enter key event
            Template.chat.extras.enterMessage();
        }
    },

    'click #send-btn' : function (event) {
        Template.chat.extras.enterMessage();
    },

    // change nickname
    'keydown #nickname' : function (event) {
        if (event.which == 13 ) {
            Template.chat.extras.updateNickname();
        }
    },
    'blur #nickname' : function (event) {
        Template.chat.extras.updateNickname();
    }
});

Template.chat.rendered = function () {

    // set the nickname, if not set
    var nickname = Session.get("nickname");
    if (typeof nickname == 'undefined') {
        // is set on startup; we set it here if the startup routine hasn't run yet
        $('#nickname').val('Anonymous');
    }

    $('#message').focus();
    $('.toggle-name-input').click(function(e) {
        e.preventDefault();
        $('.chat-options').toggleClass('hide');
    });

    // disable auto-scrolling if they scroll up
    $(window).scroll(function(){

        var height = $(window).scrollTop();
        var docHeight = $(document).height();

//         console.log("H" + height + " DH:" +  docHeight + " WH:" + winHeight);
        if (docHeight - height > 900) {
            window.enableAutoscroll = false;
        }

        if (docHeight - height < 600) {
            window.enableAutoscroll = true;
        }

    });

    setInterval(function(){
        if (window.enableAutoscroll) {
            $("html, body").animate({ scrollTop: $(document).height()-$(window).height() })
        }
    }, 1000);
}

Template.chat.extras = {
    updateNickname: function() {
        var nickname = $('#nickname').val();
        if (nickname != '') {
            Session.set("nickname", nickname);
            ReactiveStore.set("clink-nickname", nickname);
            $('.chat-options').addClass('hide');    // hide the options
        }
    },
    enterMessage: function() {
        var nickname = Session.get("nickname");
        var message = $('#message').val();
        // Strip out HTML tags
        message = message.replace(/(<([^>]+)>)/ig,"");
        if (message != '') {
            Chat.update({_id: Session.get("id")}, {$push:{messages:{name: nickname, message: message, time: new Date}}}, null, function() {
               $("html, body").animate({ scrollTop: $(document).height()-$(window).height() });
            });
            var ourLastChatRecord = $('.msg-container').last();
        }
        $('#message').val('');  // reset the message
    }
};<commit_msg>autoscroll tweak<commit_after>Template['chat'].helpers({
    chatroom: function(){
        return Session.get("name")
    },
    nickname: function(){
        return Session.get('nickname');
    },
    prettyTime: function(datetime){
        if(typeof datetime === 'object'){
            var minutes = (datetime.getMinutes()<10 ?'0':'') + datetime.getMinutes()
            return "" + datetime.getHours() + ":" + minutes
            }
        else{
            return datetime
        }
    }
});

Template['chat'].events({
    // send message
    'keydown #message' : function (event) {
        if (event.which == 13) { // 13 is the enter key event
            Template.chat.extras.enterMessage();
        }
    },

    'click #send-btn' : function (event) {
        Template.chat.extras.enterMessage();
    },

    // change nickname
    'keydown #nickname' : function (event) {
        if (event.which == 13 ) {
            Template.chat.extras.updateNickname();
        }
    },
    'blur #nickname' : function (event) {
        Template.chat.extras.updateNickname();
    }
});

Template.chat.rendered = function () {

    // set the nickname, if not set
    var nickname = Session.get("nickname");
    if (typeof nickname == 'undefined') {
        // is set on startup; we set it here if the startup routine hasn't run yet
        $('#nickname').val('Anonymous');
    }

    $('#message').focus();
    $('.toggle-name-input').click(function(e) {
        e.preventDefault();
        $('.chat-options').toggleClass('hide');
    });

    // disable auto-scrolling if they scroll up
    $(window).scroll(function(){

        var height = $(window).scrollTop();
        var docHeight = $(document).height();

//         console.log("H" + height + " DH:" +  docHeight + " WH:" + winHeight);
        if (docHeight - height > 900) {
            window.enableAutoscroll = false;
        }

        if (docHeight - height < 600) {
            window.enableAutoscroll = true;
        }

    });

    setInterval(function(){
        if (window.enableAutoscroll) {
            $("html, body").animate({ scrollTop: $(document).height()-$(window).height() })
        }
    }, 1500);
}

Template.chat.extras = {
    updateNickname: function() {
        var nickname = $('#nickname').val();
        if (nickname != '') {
            Session.set("nickname", nickname);
            ReactiveStore.set("clink-nickname", nickname);
            $('.chat-options').addClass('hide');    // hide the options
        }
    },
    enterMessage: function() {
        var nickname = Session.get("nickname");
        var message = $('#message').val();
        // Strip out HTML tags
        message = message.replace(/(<([^>]+)>)/ig,"");
        if (message != '') {
            Chat.update({_id: Session.get("id")}, {$push:{messages:{name: nickname, message: message, time: new Date}}}, null, function() {
               $("html, body").animate({ scrollTop: $(document).height()-$(window).height() });
            });
            var ourLastChatRecord = $('.msg-container').last();
        }
        $('#message').val('');  // reset the message
    }
};<|endoftext|>


<commit_before>/**
 * Created by timmimim on 04.02.17.
 */
$('#saveCode').on('click', function () {
	saveR();
});

function saveR()
{

	var uniqueKey = document.getElementById('uniqueKey').value;

	var fName = document.getElementById('fileName').value;
	var code = document.getElementById('codearea').value;

	var data = {
		fName: fName,
		code: code
	};

	$.ajax({
		type: "POST",
		data: data,
		url: '/api/saveRCode/'+uniqueKey,
		timeout: 10000,
		success: function(data, textStatus){
			console.log("saved R code to RScript file : " + textStatus);
			//TODO: Trigger Data Tree Update
		},
		error: function(xhr, textStatus, errorThrown){
			console.log("saving failed");
			console.log(errorThrown);
		}
	})

}

$('#saveTXT').on('click', function () {
	saveTxt();
});

function saveTxt()
{
	var uniKey = document.getElementById('uniqueKey').value;
	var fName = document.getElementById('noteFName').value;
	var note = document.getElementById('txtview').value;

	var data = {
		fName: fName,
		note: note
	};

	$.ajax({
		type: "POST",
		data: data,
		url: '/api/saveNote/'+uniKey,
		timeout: 10000,
		success: function(data, textStatus){
			console.log("saved note to txtFiles : " + textStatus);
			//TODO: Trigger Data Tree Update
		},
		error: function(xhr, textStatus, errorThrown){
			console.log("saving failed");
			console.log(errorThrown);
		}
	})
}<commit_msg>Last little fixes<commit_after>/**
 * Created by timmimim on 04.02.17.
 */
$('#saveCode').on('click', function () {
	saveR();

    alert("Please reload the project to get the data in the treestructure!");
});

function saveR()
{

	var uniqueKey = document.getElementById('uniqueKey').value;

	var fName = document.getElementById('fileName').value;
	var code = document.getElementById('codearea').value;

	var data = {
		fName: fName,
		code: code
	};

	$.ajax({
		type: "POST",
		data: data,
		url: '/api/saveRCode/'+uniqueKey,
		timeout: 10000,
		success: function(data, textStatus){
			console.log("saved R code to RScript file : " + textStatus);
			//TODO: Trigger Data Tree Update
		},
		error: function(xhr, textStatus, errorThrown){
			console.log("saving failed");
			console.log(errorThrown);
		}
	})

}

$('#saveTXT').on('click', function () {
	saveTxt();
    alert("Please reload the project to get the data in the treestructure!");
});

function saveTxt()
{
	var uniKey = document.getElementById('uniqueKey').value;
	var fName = document.getElementById('noteFName').value;
	var note = document.getElementById('txtview').value;

	var data = {
		fName: fName,
		note: note
	};

	$.ajax({
		type: "POST",
		data: data,
		url: '/api/saveNote/'+uniKey,
		timeout: 10000,
		success: function(data, textStatus){
			console.log("saved note to txtFiles : " + textStatus);
			//TODO: Trigger Data Tree Update
		},
		error: function(xhr, textStatus, errorThrown){
			console.log("saving failed");
			console.log(errorThrown);
		}
	})
}<|endoftext|>