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

  /*---------------------
  ------- IMPORT --------
  ----------------------*/
  var { PIXI } = window.flatworld_libraries;
  var templates = window.flatworld.UIs.default.templates;
  var createVisibleHexagon = window.flatworld.extensions.hexagons.utils.createVisibleHexagon;
  var drawShapes = window.flatworld.UIs.default.utils.drawShapes;

  /*---------------------
  ------ VARIABLES ------
  ----------------------*/
  var styleSheetElement;
  var cssClasses = {
    select: "#dialog_select"
  };
  var elements = {};

  /*---------------------
  --------- API ---------
  ----------------------*/
  class UIDefault {
    /**
     * The simplest default UI implementation. Implemented UI functionalities for: showSelections, highlightSelectedObject
     *
     * @namespace flatworld.UIs
     * @class default
     * @constructor
     * @requires Handlebars
     * @requires hexagon extension
     * @param  {HTMLElement} modal      The modal used in this UI Theme
     * @param  {Flatworld} FTW          Instance of flatworld class
     * @param  {Object} options         optional options
     * @param  {Object} options.styles  styles for the UI
     */
    constructor(modal, FTW, options = { styles: "#F0F0F0" }) {
      styleSheetElement = this.addStyleElement();
      /* For testing. This is deeefinitely supposed to not be here, but it has stayed there for testing. */
      let createdCSS = `
        ${cssClasses.select} {
          z-index: 9999;
          opacity: 0.9;
          position: fixed;
          left: 0px;
          bottom: 0px;
          background-color: brown;
          border: 1px solid rgb(255, 186, 148);;
          border-bottom: 0px;
          padding:15px;
          margin-left:10px;
        }`;
      this.addCSSRulesToScriptTag(styleSheetElement, createdCSS);

      // Add a media (and/or media query) here if you'd like!
      // style.setAttribute("media", "screen")
      // style.setAttribute("media", "only screen and (max-width : 1024px)")

      this.FTW = FTW;
      this.modal = modal || document.getElementById("dialog_select");
      this.styles = options.styles;
    }
    /**
     * @method getTemplates
     * Required by the map/core/UI.js API
     */
    setFlatworld(FTW) {
      this.FTW = FTW;
    }
    /**
     * @method getTemplates
     * Required by the map/core/UI.js API
     */
    getTemplates() {
      return templates;
    }
    /**
     * Required by the map.UI API
     *
     * @method showSelections
     * @param  {Object} objects     Objects that have been selected. See core.UI for more information
     * @param {Object} getDatas       See explanation in core.UI
     * @param {Object} options        Extra options
     */
    showSelections(objects, getDatas, options) {
      var updateCB = this.FTW.drawOnNextTick.bind(this.FTW);
      var UILayer = this.FTW.getMovableLayer();
      var cb;

      /* We add the objects to be highlighted to the correct UI layer */
      //objectsToUI(UILayer, objects);

      if (objects && objects.length > 1) {
        cb = () => {
          this.modal.innerHTML = templates.multiSelection({
            title: "Objects",
            objects
          });

          this.showModal(this.modal, cssClasses);

          _getElement("select").style.display = 'block';
        };
      } else if (objects.length === 1) {
        cb = () => {
          this.highlightSelectedObject(objects[0]);
        };
      } else {
        cb = () => {
          UILayer.deleteUIObjects();
          updateCB();
          console.log("Error occured selecting the objects on this coordinates! Nothing found");
        };
      }

      _getElement("select").style.display = 'none';
      cb();
    }
    /**
     * Required by the map.UI API
     *
     * @method highlightSelectedObject
     * @param  {Object} object        Object that has been selected. See core.UI for more information
     * @param {Object} getDatas       See explanation in core.UI
     * @param {Object} options        Extra options. Like dropping a shadow etc.
     */
    highlightSelectedObject(object, getDatas, options = {shadow: { color: "0x0000", distance: 5, alpha: 0.55, angle: 45, blur: 5 }}) {
      var { shadow } = options;
      var highlightableObject, objectDatas;

      objectDatas = getDatas.allData(object);

      this.modal.innerHTML = templates.singleSelection({
        title: "Selected",
        object: {
          name: objectDatas.name
        }
      });
      this.showModal(this.modal, cssClasses);

      highlightableObject = this._highlightSelectedObject(object, this.FTW.getRenderer());

      highlightableObject.dropShadow({
        color: shadow.color,
        distance: shadow.distance,
        alpha: shadow.alpha,
        angle: shadow.angle,
        blur: shadow.blur
      });

      this.FTW.drawOnNextTick();

      _getElement("select").style.display = 'block';

      return highlightableObject;
    }
    /**
     * @method showUnitMovement
     * @param {PIXI.Point} to       Global coordinates that were clicked
     */
    showUnitMovement(object, to) {
      const UINAME = "movementArrow";
      var localTo, localFrom, currentArrow;

      localTo = this.FTW.getMovableLayer().toLocal(to);
      localFrom = this.FTW.getMovableLayer().toLocal(object.toGlobal(new PIXI.Point(0,0)));

      currentArrow = drawShapes.line(new PIXI.Graphics(), localFrom, localTo );

      this.FTW.removeUIObject(this.FTW.layerTypes.movableType.id, UINAME);

      this.FTW.addUIObject(this.FTW.layerTypes.movableType.id, currentArrow, UINAME);
      this.FTW.drawOnNextTick();
    }
    /**
     * @method init
     */
    init() {}

    /*----------------------
    ------- PRIVATE --------
    ----------------------*/
    /**
     * @private
     * @static
     * @method _highlightSelectedObject
     * @param  {Object} object
     * @param  {MapLayer} movableLayer
     * @param  {PIXI.Renderer} renderer
     */
    _highlightSelectedObject(object, renderer) {
      var movableLayer = this.FTW.getMovableLayer();
      var clonedObject;

      clonedObject = object.clone(renderer);
      clonedObject.__proto__ = object.__proto__;

      var coord = object.toGlobal(new PIXI.Point(0,0));
      coord = movableLayer.toLocal(coord);

      coord.x -= object.width * object.anchor.x;
      coord.y -= object.height * object.anchor.y;

      this.createHighlight(clonedObject, { coords: coord });

      return clonedObject;
    }
    /**
     * @private
     * @static
     * @method createHighlight
     */
    createHighlight(object, options = { coords: new PIXI.Point(0, 0) }) {
      const RADIUS = 47;
      const UI_CONTAINER_NAME = "unit highlight";
      const movableLayer = this.FTW.getMovableLayer();
      const container = new this.FTW.createSpecialLayer("UILayer", { toLayer: movableLayer});
      const objCoords = {
        x: Number(object.x),
        y: Number(object.y)
      };
      var highlighterObject;

      highlighterObject = createVisibleHexagon(RADIUS, { color: "#F0F0F0" });
      highlighterObject.x = objCoords.x + 32;
      highlighterObject.y = objCoords.y + 27;

      highlighterObject.alpha = 0.5;

      /* We add the children first to subcontainer, since it's much easier to handle the x and y in it, rather than
       * handle graphics x and y */
      container.addChild(highlighterObject);
      container.addChild(object);

      container.position = options.coords;

      this.FTW.removeUIObject(this.FTW.layerTypes.movableType.id);
      this.FTW.addUIObject(this.FTW.layerTypes.movableType.id, container, UI_CONTAINER_NAME);
    }
    /**
     * @method addCSSRulesToScriptTag
     *
     * @param {Object} sheet
     * @param {Object} rules
     */
    addCSSRulesToScriptTag(sheet, rules) {
      sheet.insertRule(rules, 0);
    }
    /**
     * @method addStyleElement
     */
    addStyleElement() {
      var _styleElement = document.createElement("style");
      // WebKit hack :(
      _styleElement.appendChild(document.createTextNode(""));
      document.head.appendChild(_styleElement);

      return _styleElement.sheet;
    }
    /**
     * @method showModal
     *
     * @param {HTMLElement} modalElem
     * @param {Object} cssClasses
     * @todo make sure / check, that modalElem.classList.add gets added only once
     */
    showModal(modalElem, cssClasses) {
      modalElem.classList.add(cssClasses.select);
      /* Would be HTML 5.1 standard, but that might be a long way
        this.modal.show();*/
    }
  }

  /*----------------------
  ------- PRIVATE --------
  ----------------------*/
  /**
   * @private
   * @static
   * @method _getElement
   * @param  {[type]} which [description]
   * @return {[type]}       [description]
   */
  function _getElement(which) {
    if (!elements[which]) {
      let element = document.querySelector(cssClasses[which]);
      elements[which] = element;
    }

    return elements[which];
  }

  window.flatworld.UIs.default.init = UIDefault;
})();<commit_msg>moved the element definition outside of default.js<commit_after>(function () {
  'use strict';

  /*---------------------
  ------- IMPORT --------
  ----------------------*/
  var { PIXI } = window.flatworld_libraries;
  var templates = window.flatworld.UIs.default.templates;
  var createVisibleHexagon = window.flatworld.extensions.hexagons.utils.createVisibleHexagon;
  var drawShapes = window.flatworld.UIs.default.utils.drawShapes;

  /*---------------------
  ------ VARIABLES ------
  ----------------------*/
  var styleSheetElement;
  var cssClasses;
  var elements = {};

  /*---------------------
  --------- API ---------
  ----------------------*/
  class UIDefault {
    /**
     * The simplest default UI implementation. Implemented UI functionalities for: showSelections, highlightSelectedObject
     *
     * @namespace flatworld.UIs
     * @class default
     * @constructor
     * @requires Handlebars
     * @requires hexagon extension
     * @param  {HTMLElement} modal      The modal used in this UI Theme
     * @param  {Flatworld} FTW          Instance of flatworld class
     * @param  {Object} options         optional options
     * @param  {Object} options.styles  styles for the UI
     */
    constructor(modal, FTW, { styles = "#F0F0F0" , elements }) {
      styleSheetElement = this.addStyleElement();
      /* For testing. This is deeefinitely supposed to not be here, but it has stayed there for testing. */
      let createdCSS = `
        ${cssClasses.select} {
          z-index: 9999;
          opacity: 0.9;
          position: fixed;
          left: 0px;
          bottom: 0px;
          background-color: brown;
          border: 1px solid rgb(255, 186, 148);;
          border-bottom: 0px;
          padding:15px;
          margin-left:10px;
        }`;
      cssClasses = elements;
      this.addCSSRulesToScriptTag(styleSheetElement, createdCSS);

      // Add a media (and/or media query) here if you'd like!
      // style.setAttribute("media", "screen")
      // style.setAttribute("media", "only screen and (max-width : 1024px)")

      this.FTW = FTW;
      this.modal = modal || document.getElementById("dialog_select");
      this.styles = styles;
    }
    /**
     * @method getTemplates
     * Required by the map/core/UI.js API
     */
    setFlatworld(FTW) {
      this.FTW = FTW;
    }
    /**
     * @method getTemplates
     * Required by the map/core/UI.js API
     */
    getTemplates() {
      return templates;
    }
    /**
     * Required by the map.UI API
     *
     * @method showSelections
     * @param  {Object} objects     Objects that have been selected. See core.UI for more information
     * @param {Object} getDatas       See explanation in core.UI
     * @param {Object} options        Extra options
     */
    showSelections(objects, getDatas, options) {
      var updateCB = this.FTW.drawOnNextTick.bind(this.FTW);
      var UILayer = this.FTW.getMovableLayer();
      var cb;

      /* We add the objects to be highlighted to the correct UI layer */
      //objectsToUI(UILayer, objects);

      if (objects && objects.length > 1) {
        cb = () => {
          this.modal.innerHTML = templates.multiSelection({
            title: "Objects",
            objects
          });

          this.showModal(this.modal, cssClasses);

          _getElement("select").style.display = 'block';
        };
      } else if (objects.length === 1) {
        cb = () => {
          this.highlightSelectedObject(objects[0]);
        };
      } else {
        cb = () => {
          UILayer.deleteUIObjects();
          updateCB();
          console.log("Error occured selecting the objects on this coordinates! Nothing found");
        };
      }

      _getElement("select").style.display = 'none';
      cb();
    }
    /**
     * Required by the map.UI API
     *
     * @method highlightSelectedObject
     * @param  {Object} object        Object that has been selected. See core.UI for more information
     * @param {Object} getDatas       See explanation in core.UI
     * @param {Object} options        Extra options. Like dropping a shadow etc.
     */
    highlightSelectedObject(object, getDatas, options = {shadow: { color: "0x0000", distance: 5, alpha: 0.55, angle: 45, blur: 5 }}) {
      var { shadow } = options;
      var highlightableObject, objectDatas;

      objectDatas = getDatas.allData(object);

      this.modal.innerHTML = templates.singleSelection({
        title: "Selected",
        object: {
          name: objectDatas.name
        }
      });
      this.showModal(this.modal, cssClasses);

      highlightableObject = this._highlightSelectedObject(object, this.FTW.getRenderer());

      highlightableObject.dropShadow({
        color: shadow.color,
        distance: shadow.distance,
        alpha: shadow.alpha,
        angle: shadow.angle,
        blur: shadow.blur
      });

      this.FTW.drawOnNextTick();

      _getElement("select").style.display = 'block';

      return highlightableObject;
    }
    /**
     * @method showUnitMovement
     * @param {PIXI.Point} to       Global coordinates that were clicked
     */
    showUnitMovement(object, to) {
      const UINAME = "movementArrow";
      var localTo, localFrom, currentArrow;

      localTo = this.FTW.getMovableLayer().toLocal(to);
      localFrom = this.FTW.getMovableLayer().toLocal(object.toGlobal(new PIXI.Point(0,0)));

      currentArrow = drawShapes.line(new PIXI.Graphics(), localFrom, localTo );

      this.FTW.removeUIObject(this.FTW.layerTypes.movableType.id, UINAME);

      this.FTW.addUIObject(this.FTW.layerTypes.movableType.id, currentArrow, UINAME);
      this.FTW.drawOnNextTick();
    }

    /*----------------------
    ------- PRIVATE --------
    ----------------------*/
    /**
     * @private
     * @static
     * @method _highlightSelectedObject
     * @param  {Object} object
     * @param  {MapLayer} movableLayer
     * @param  {PIXI.Renderer} renderer
     */
    _highlightSelectedObject(object, renderer) {
      var movableLayer = this.FTW.getMovableLayer();
      var clonedObject;

      clonedObject = object.clone(renderer);
      clonedObject.__proto__ = object.__proto__;

      var coord = object.toGlobal(new PIXI.Point(0,0));
      coord = movableLayer.toLocal(coord);

      coord.x -= object.width * object.anchor.x;
      coord.y -= object.height * object.anchor.y;

      this.createHighlight(clonedObject, { coords: coord });

      return clonedObject;
    }
    /**
     * @private
     * @static
     * @method createHighlight
     */
    createHighlight(object, options = { coords: new PIXI.Point(0, 0) }) {
      const RADIUS = 47;
      const UI_CONTAINER_NAME = "unit highlight";
      const movableLayer = this.FTW.getMovableLayer();
      const container = new this.FTW.createSpecialLayer("UILayer", { toLayer: movableLayer});
      const objCoords = {
        x: Number(object.x),
        y: Number(object.y)
      };
      var highlighterObject;

      highlighterObject = createVisibleHexagon(RADIUS, { color: "#F0F0F0" });
      highlighterObject.x = objCoords.x + 32;
      highlighterObject.y = objCoords.y + 27;

      highlighterObject.alpha = 0.5;

      /* We add the children first to subcontainer, since it's much easier to handle the x and y in it, rather than
       * handle graphics x and y */
      container.addChild(highlighterObject);
      container.addChild(object);

      container.position = options.coords;

      this.FTW.removeUIObject(this.FTW.layerTypes.movableType.id);
      this.FTW.addUIObject(this.FTW.layerTypes.movableType.id, container, UI_CONTAINER_NAME);
    }
    /**
     * @method addCSSRulesToScriptTag
     *
     * @param {Object} sheet
     * @param {Object} rules
     */
    addCSSRulesToScriptTag(sheet, rules) {
      sheet.insertRule(rules, 0);
    }
    /**
     * @method addStyleElement
     */
    addStyleElement() {
      var _styleElement = document.createElement("style");
      // WebKit hack :(
      _styleElement.appendChild(document.createTextNode(""));
      document.head.appendChild(_styleElement);

      return _styleElement.sheet;
    }
    /**
     * @method showModal
     *
     * @param {HTMLElement} modalElem
     * @param {Object} cssClasses
     * @todo make sure / check, that modalElem.classList.add gets added only once
     */
    showModal(modalElem, cssClasses) {
      modalElem.classList.add(cssClasses.select);
      /* Would be HTML 5.1 standard, but that might be a long way
        this.modal.show();*/
    }
  }

  /*----------------------
  ------- PRIVATE --------
  ----------------------*/
  /**
   * @private
   * @static
   * @method _getElement
   * @param  {[type]} which [description]
   * @return {[type]}       [description]
   */
  function _getElement(which) {
    if (!elements[which]) {
      let element = document.querySelector(cssClasses[which]);
      elements[which] = element;
    }

    return elements[which];
  }

  window.flatworld.UIs.default.init = UIDefault;
})();<|endoftext|>


<commit_before>import React, { Component } from 'react';
import AgreementEditModal from '../../components/agreement/AgreementEditModal';
import AgreementView from '../../components/agreement/AgreementView';
import Agreement from '../../components/agreement/Agreement';

//redux
import { connect } from "react-redux";
import { getAgreement, saveAgreement, updateAgreement, saveAttachment } from "./agreementActions";
import { getSupervisors } from "../supervisor/supervisorActions";
import { getStudyfields } from "../studyfield/studyfieldActions";

export class AgreementPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            newAgreement: false,
            originalAgreement: {},
            editMode: false,
            agreement: undefined
        }
    }

    componentDidMount() {
        document.title = "Agreement Page";
        if (this.props.user)
            this.props.getAgreement(this.props.user.id);
        this.props.getSupervisors();
        this.props.getStudyfields();
    }

    componentWillReceiveProps(newProps) {
        if (newProps && this.props !== newProps && newProps.agreement) {
            const agreement = newProps.agreement.find(agreement => agreement.personId === this.props.user.id)
            if (agreement) {
                this.setState(
                    {
                        agreement: agreement,
                        originalAgreement: Object.assign({}, agreement)
                    }
                );
            }
        }
    }

    parseResponseData = (data) => {
        var parsedData = data.agreement;
        //TODO: refactor this when we can distinguish between secondary and other supervisor
        for (let i = 0; i < data.persons.length; i++) {
            if (data.persons[i].personRoleId === data.agreement.responsibleSupervisorId) {
                parsedData.thesisSupervisorMain = data.persons[i].firstname + " " + data.persons[i].lastname
            } else if (parsedData.thesisSupervisorSecond === undefined) {
                parsedData.thesisSupervisorSecond = data.persons[i].firstname + " " + data.persons[i].lastname
            } else {
                parsedData.thesisSupervisorOther = data.persons[i].firstname + " " + data.persons[i].lastname
            }
        }
        return parsedData;
    }

    toggleEditModal = () => {
        var editable = !this.state.editMode;
        this.setState({ editMode: editable });
    }

    updateFormData = (data) => {
        this.setState({ agreement: data });
    }

    sendForm = () => {
        this.props.updateAgreement(this.state.agreement);
    }

    startNewAgreement = () => {
        this.setState({ newAgreement: !this.state.newAgreement });
    }

    handleSaveAgreement = (agreement) => {
        this.props.saveAgreement(agreement);
        this.props.saveAttachment(agreement.attachments);
    }

    render() {
        if (this.state.newAgreement) {
            return (

                    <button className="ui black button" onClick={this.startNewAgreement}> Back </button>
                    <Agreement
                        agreement={this.state.agreement}
                        supervisors={this.props.supervisors}
                        studyfields={this.props.studyfields}
                        user={this.props.user}
                        saveAgreement={this.handleSaveAgreement}
                    />

            );
        } else {
            //check if form data has changed
            /*
            console.log("this.state.agreement", this.state.agreement);
            console.log("this.state.originalAgreement", this.state.originalAgreement);
            console.log(Object.is(this.state.agreement, this.state.originalAgreement));
            */
            //doesn't work
            const disableSubmit = Object.is(this.state.agreement, this.state.originalAgreement);
            return (

                    <button className="ui black button" onClick={this.startNewAgreement}> New Agreement </button>
                    <AgreementEditModal showModal={this.state.editMode} closeModal={this.toggleEditModal} formData={this.state.agreement} originalAgreement={this.state.originalAgreement} updateFormData={this.updateFormData} />
                    {this.state.agreement ? <AgreementView agreementData={this.state.agreement} /> : undefined}

                        <button className="ui primary button" onClick={this.toggleEditModal}>Edit agreement</button>
                        <button className="ui primary button" type="submit" disabled={disableSubmit} onClick={this.sendForm}>Save Agreement</button>

            );
        }
    }
}

const mapDispatchToProps = (dispatch) => ({
    getAgreement(data) {
        dispatch(getAgreement(data));
    },
    saveAgreement(data) {
        dispatch(saveAgreement(data));
    },
    saveAttachment(data) {
        dispatch(saveAttachment(data));
    },
    updateAgreement(data) {
        dispatch(updateAgreement(data));
    },
    getSupervisors(data) {
        dispatch(getSupervisors(data));
    },
    getStudyfields(data) {
        dispatch(getStudyfields(data));
    }
});

const mapStateToProps = (state) => {
    return {
        agreement: state.agreement,
        supervisors: state.supervisors,
        studyfields: state.studyfield,
        user: state.user
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(AgreementPage);
<commit_msg>Fixed agreement view<commit_after>import React, { Component } from 'react';
import AgreementEditModal from '../../components/agreement/AgreementEditModal';
import AgreementView from '../../components/agreement/AgreementView';
import Agreement from '../../components/agreement/Agreement';

//redux
import { connect } from "react-redux";
import { getAgreement, saveAgreement, updateAgreement, saveAttachment } from "./agreementActions";
import { getSupervisors } from "../supervisor/supervisorActions";
import { getStudyfields } from "../studyfield/studyfieldActions";

export class AgreementPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            newAgreement: false,
            originalAgreement: {},
            editMode: false,
            agreement: undefined
        }
    }

    componentDidMount() {
        document.title = "Agreement Page";
        if (this.props.user)
            this.props.getAgreement(this.props.user.personId);
        this.props.getSupervisors();
        this.props.getStudyfields();
    }

    componentWillReceiveProps(newProps) {
        if (newProps && this.props !== newProps && newProps.agreement) {
            const agreement = newProps.agreement.find(agreement => agreement.personId === this.props.user.personId);
            if (agreement) {
                this.setState(
                    {
                        agreement: agreement,
                        originalAgreement: Object.assign({}, agreement)
                    }
                );
            }
        }
    }

    parseResponseData = (data) => {
        var parsedData = data.agreement;
        //TODO: refactor this when we can distinguish between secondary and other supervisor
        for (let i = 0; i < data.persons.length; i++) {
            if (data.persons[i].personRoleId === data.agreement.responsibleSupervisorId) {
                parsedData.thesisSupervisorMain = data.persons[i].firstname + " " + data.persons[i].lastname
            } else if (parsedData.thesisSupervisorSecond === undefined) {
                parsedData.thesisSupervisorSecond = data.persons[i].firstname + " " + data.persons[i].lastname
            } else {
                parsedData.thesisSupervisorOther = data.persons[i].firstname + " " + data.persons[i].lastname
            }
        }
        return parsedData;
    }

    toggleEditModal = () => {
        var editable = !this.state.editMode;
        this.setState({ editMode: editable });
    }

    updateFormData = (data) => {
        this.setState({ agreement: data });
    }

    sendForm = () => {
        this.props.updateAgreement(this.state.agreement);
    }

    startNewAgreement = () => {
        this.setState({ newAgreement: !this.state.newAgreement });
    }

    handleSaveAgreement = (agreement) => {
        this.props.saveAgreement(agreement);
        this.props.saveAttachment(agreement.attachments);
    }

    render() {
        if (this.state.newAgreement) {
            return (

                    <button className="ui black button" onClick={this.startNewAgreement}> Back </button>
                    <Agreement
                        agreement={this.state.agreement}
                        supervisors={this.props.supervisors}
                        studyfields={this.props.studyfields}
                        user={this.props.user}
                        saveAgreement={this.handleSaveAgreement}
                    />

            );
        } else {
            //check if form data has changed
            /*
            console.log("this.state.agreement", this.state.agreement);
            console.log("this.state.originalAgreement", this.state.originalAgreement);
            console.log(Object.is(this.state.agreement, this.state.originalAgreement));
            */
            //doesn't work
            const disableSubmit = Object.is(this.state.agreement, this.state.originalAgreement);
            return (

                    <button className="ui black button" onClick={this.startNewAgreement}> New Agreement </button>
                    <AgreementEditModal showModal={this.state.editMode} closeModal={this.toggleEditModal} formData={this.state.agreement} originalAgreement={this.state.originalAgreement} updateFormData={this.updateFormData} />
                    {this.state.agreement ? <AgreementView agreementData={this.state.agreement} /> : undefined}

                        <button className="ui primary button" onClick={this.toggleEditModal}>Edit agreement</button>
                        <button className="ui primary button" type="submit" disabled={disableSubmit} onClick={this.sendForm}>Save Agreement</button>

            );
        }
    }
}

const mapDispatchToProps = (dispatch) => ({
    getAgreement(data) {
        dispatch(getAgreement(data));
    },
    saveAgreement(data) {
        dispatch(saveAgreement(data));
    },
    saveAttachment(data) {
        dispatch(saveAttachment(data));
    },
    updateAgreement(data) {
        dispatch(updateAgreement(data));
    },
    getSupervisors(data) {
        dispatch(getSupervisors(data));
    },
    getStudyfields(data) {
        dispatch(getStudyfields(data));
    }
});

const mapStateToProps = (state) => {
    return {
        agreement: state.agreement,
        supervisors: state.supervisors,
        studyfields: state.studyfield,
        user: state.user
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(AgreementPage);
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

'use strict';
import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element?module';

class MessagingSample extends LitElement {
  constructor() {
    super();
    this._localConnection = this._remoteConnection = this._localChannel = this._remoteChannel = null;
    this.connected = false;
  }

  disconnect() {
    this._localConnection.close();
    this._remoteConnection.close();
  }

  async connect() {
    try {
      const dataChannelParams = {ordered: true};
      this._localConnection = new RTCPeerConnection();
      this._localConnection.addEventListener('icecandidate', async e => {
        console.log('local connection ICE candidate: ', e.candidate);
        this._remoteConnection.addIceCandidate(e.candidate);
      });
      this._remoteConnection = new RTCPeerConnection();
      this._remoteConnection.addEventListener('icecandidate', async e => {
        console.log('remote connection ICE candidate: ', e.candidate);
        this._localConnection.addIceCandidate(e.candidate);
      });

      this._localChannel = this._localConnection
        .createDataChannel('messaging-channel', dataChannelParams);
      this._localChannel.binaryType = 'arraybuffer';
      this._localChannel.addEventListener('open', () => {
        console.log('Local channel open!');
        this.connected = true;
      });
      this._localChannel.addEventListener('close', () => {
        console.log('Local channel closed!');
        this.connected = false;
      });
      this._localChannel.addEventListener('message', e => this._onLocalMessageReceived(e));

      this._remoteConnection.addEventListener('datachannel', e => this._onRemoteDataChannel(e));

      const localOffer = await this._localConnection.createOffer();
      console.log(`Got local offer ${JSON.stringify(localOffer)}`);
      await this._localConnection.setLocalDescription(localOffer);
      await this._remoteConnection.setRemoteDescription(localOffer);

      const remoteOffer = await this._remoteConnection.createAnswer();
      console.log(`Got remote answer ${JSON.stringify(remoteOffer)}`);
      await this._remoteConnection.setLocalDescription(remoteOffer);
      await this._localConnection.setRemoteDescription(remoteOffer);
    } catch (e) {
      console.log(e);
    }
  }

  _onLocalMessageReceived(event) {
    console.log(`Remote message received by local: ${event.data}`);
    this.localMessages += event.data + '\n';
  }

  _onRemoteDataChannel(event) {
    console.log(`onRemoteDataChannel: ${JSON.stringify(event)}`);
    this._remoteChannel = event.channel;
    this._remoteChannel.binaryType = 'arraybuffer';
    this._remoteChannel.addEventListener('message', e => this._onRemoteMessageReceived(e));
    this._remoteChannel.addEventListener('close', () => {
      console.log('Remote channel closed!');
      this.connected = false;
    });
  }

  _onRemoteMessageReceived(event) {
    console.log(`Local message received by remote: ${event.data}`);
    this.remoteMessages += event.data + '\n';
  }

  static get properties() {
    return {
      connected: Boolean,
      localMessages: String,
      localOutgoingMessage: {
        type: String,
        notify: true
      },
      remoteMessages: String,
      remoteOutgoingMessage: {
        type: String,
        notify: true
      }
    };
  }

  _render({connected, localMessages, remoteMessages, remoteOutgoingMessage}) {
    return html`

      <button disabled="${connected}" on-click="${() => this.connect()}">Connect</button>
      <button disabled="${!connected}" on-click="${() => this.disconnect()}">Disconnect</button>

      Local outgoing message:
      <textarea class="message" id="localOutgoing"
                placeholder="Local outgoing message goes here."></textarea>
      <button disabled="${!connected}" on-click="${() => this._sendMessage(this.localOutgoing, this._localChannel)}
      id="sendLocal">Send message from local</button>

      Local incoming messages:
      <textarea class="message" id="localIncoming" disabled
                placeholder="Local incoming messages arrive here.">${localMessages}</textarea>

      Remote outgoing message:
      <textarea class="message" id="remoteOutgoing"
                placeholder="Remote outgoing message goes here."></textarea>
      <button disabled="${!connected}" on-click="${() => this._sendMessage(this.remoteOutgoing, this._remoteChannel)}"
      id="sendRemote">Send message from remote</button>

      Remote incoming messages:
      <textarea class="message" id="remoteIncoming" disabled
                placeholder="Remote incoming messages arrive here.">${remoteMessages}</textarea>

`;
  }

  get remoteOutgoing() {
    return this.shadowRoot.querySelector('#remoteOutgoing');
  }

  get localOutgoing() {
    return this.shadowRoot.querySelector('#localOutgoing');
  }

  _sendMessage(textarea, channel) {
    const value = textarea.value;
    if (value === '') {
      console.log('Not sending empty message!');
      return;
    }
    console.log('Sending remote message: ', value);
    channel.send(value);
    textarea.value = '';
  }
}

customElements.define('messaging-sample', MessagingSample);<commit_msg>Temporary eslint fix - wil remove once  eslint is updated<commit_after>/*
 *  Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */
/* eslint no-unused-expressions: 0 */

'use strict';
import {LitElement, html} from 'https://unpkg.com/@polymer/lit-element?module';

class MessagingSample extends LitElement {
  constructor() {
    super();
    this._localConnection = this._remoteConnection = this._localChannel = this._remoteChannel = null;
    this.connected = false;
  }

  disconnect() {
    this._localConnection.close();
    this._remoteConnection.close();
  }

  async connect() {
    try {
      const dataChannelParams = {ordered: true};
      this._localConnection = new RTCPeerConnection();
      this._localConnection.addEventListener('icecandidate', async e => {
        console.log('local connection ICE candidate: ', e.candidate);
        this._remoteConnection.addIceCandidate(e.candidate);
      });
      this._remoteConnection = new RTCPeerConnection();
      this._remoteConnection.addEventListener('icecandidate', async e => {
        console.log('remote connection ICE candidate: ', e.candidate);
        this._localConnection.addIceCandidate(e.candidate);
      });

      this._localChannel = this._localConnection
        .createDataChannel('messaging-channel', dataChannelParams);
      this._localChannel.binaryType = 'arraybuffer';
      this._localChannel.addEventListener('open', () => {
        console.log('Local channel open!');
        this.connected = true;
      });
      this._localChannel.addEventListener('close', () => {
        console.log('Local channel closed!');
        this.connected = false;
      });
      this._localChannel.addEventListener('message', e => this._onLocalMessageReceived(e));

      this._remoteConnection.addEventListener('datachannel', e => this._onRemoteDataChannel(e));

      const localOffer = await this._localConnection.createOffer();
      console.log(`Got local offer ${JSON.stringify(localOffer)}`);
      await this._localConnection.setLocalDescription(localOffer);
      await this._remoteConnection.setRemoteDescription(localOffer);

      const remoteOffer = await this._remoteConnection.createAnswer();
      console.log(`Got remote answer ${JSON.stringify(remoteOffer)}`);
      await this._remoteConnection.setLocalDescription(remoteOffer);
      await this._localConnection.setRemoteDescription(remoteOffer);
    } catch (e) {
      console.log(e);
    }
  }

  _onLocalMessageReceived(event) {
    console.log(`Remote message received by local: ${event.data}`);
    this.localMessages += event.data + '\n';
  }

  _onRemoteDataChannel(event) {
    console.log(`onRemoteDataChannel: ${JSON.stringify(event)}`);
    this._remoteChannel = event.channel;
    this._remoteChannel.binaryType = 'arraybuffer';
    this._remoteChannel.addEventListener('message', e => this._onRemoteMessageReceived(e));
    this._remoteChannel.addEventListener('close', () => {
      console.log('Remote channel closed!');
      this.connected = false;
    });
  }

  _onRemoteMessageReceived(event) {
    console.log(`Local message received by remote: ${event.data}`);
    this.remoteMessages += event.data + '\n';
  }

  static get properties() {
    return {
      connected: Boolean,
      localMessages: String,
      localOutgoingMessage: {
        type: String,
        notify: true
      },
      remoteMessages: String,
      remoteOutgoingMessage: {
        type: String,
        notify: true
      }
    };
  }

  _render({connected, localMessages, remoteMessages, remoteOutgoingMessage}) {
    return html`

      <button disabled="${connected}" on-click="${() => this.connect()}">Connect</button>
      <button disabled="${!connected}" on-click="${() => this.disconnect()}">Disconnect</button>

      Local outgoing message:
      <textarea class="message" id="localOutgoing"
                placeholder="Local outgoing message goes here."></textarea>
      <button disabled="${!connected}" on-click="${() => this._sendMessage(this.localOutgoing, this._localChannel)}
      id="sendLocal">Send message from local</button>

      Local incoming messages:
      <textarea class="message" id="localIncoming" disabled
                placeholder="Local incoming messages arrive here.">${localMessages}</textarea>

      Remote outgoing message:
      <textarea class="message" id="remoteOutgoing"
                placeholder="Remote outgoing message goes here."></textarea>
      <button disabled="${!connected}" on-click="${() => this._sendMessage(this.remoteOutgoing, this._remoteChannel)}"
      id="sendRemote">Send message from remote</button>

      Remote incoming messages:
      <textarea class="message" id="remoteIncoming" disabled
                placeholder="Remote incoming messages arrive here.">${remoteMessages}</textarea>

`;
  }

  get remoteOutgoing() {
    return this.shadowRoot.querySelector('#remoteOutgoing');
  }

  get localOutgoing() {
    return this.shadowRoot.querySelector('#localOutgoing');
  }

  _sendMessage(textarea, channel) {
    const value = textarea.value;
    if (value === '') {
      console.log('Not sending empty message!');
      return;
    }
    console.log('Sending remote message: ', value);
    channel.send(value);
    textarea.value = '';
  }
}

customElements.define('messaging-sample', MessagingSample);<|endoftext|>


<commit_before>import CalendarBase from '../CalendarBase'
import GoogleCalendar from '../GoogleCalendar'

import { FORMAT, URL } from '../../constants'
import { formatTime } from '../../utils/time'
import { getRrule } from '../../utils/ics'

import queryStringToObj from '../../../test_helpers/queryStringToObj'

describe('GoogleCalendar', () => {
  const baseOpts = {
    title: 'Test Event',
    description: 'Test Description',
    location: 'Rockefeller Center',
    start: '20150704T190000'
  }
  const baseParams = {
    text: 'Test Event',
    details: 'Test Description',
    location: 'Rockefeller Center',
    action: 'TEMPLATE'
  }

  let testObj
  afterEach(() => {
    testObj = undefined
  })

  it('should be a subclass of CalendarBase', () => {
    expect(new GoogleCalendar({})).toBeInstanceOf(CalendarBase)
  })

  describe('render()', () => {
    let result;

    afterEach(() => {
      result = undefined
    })

    it('should use the proper base URL', () => {
      testObj = new GoogleCalendar(baseOpts)

      result = testObj.render()
      let baseUrl = result.split('?')[0]

      expect(baseUrl).toBe(URL.GOOGLE)
    })

    it('should handle the text parts', () => {
      testObj = new GoogleCalendar(baseOpts)

      result = testObj.render()
      let queryString = result.split('?')[1]
      let paramsObj = queryStringToObj(queryString)

      expect(paramsObj).toMatchObject(baseParams)
    })

    describe('an all-day event', () => {

      it('should have start and end date formatted without time-of-day', () => {
        testObj = new GoogleCalendar(baseOpts)

        result = testObj.render()
        let queryString = result.split('?')[1]
        let paramsObj = queryStringToObj(queryString)

        let expectedDates = `${
          formatTime(testObj.start, FORMAT.DATE)
        }/${
          formatTime(testObj.end, FORMAT.DATE)
        }`

        expect(paramsObj.dates).toBe(expectedDates)
      })

    })

    describe('without recurrence', () => {

      it('should not include recur param', () => {
        testObj = new GoogleCalendar(baseOpts)

        result = testObj.render()
        let queryString = result.split('?')[1]
        let paramsObj = queryStringToObj(queryString)

        expect(paramsObj).not.toHaveProperty('recur')
      })
    })
  })
})
<commit_msg>Add recurrence rule test for GoogleCalendar spec<commit_after>import CalendarBase from '../CalendarBase'
import GoogleCalendar from '../GoogleCalendar'

import { FORMAT, RECURRENCE, URL } from '../../constants'
import { formatTime } from '../../utils/time'
import * as Ics from '../../utils/ics'
// import { getRrule } from '../../utils/ics'
jest.mock('../../utils/ics')

import queryStringToObj from '../../../test_helpers/queryStringToObj'

const { FREQUENCY: { DAILY } } = RECURRENCE
describe('GoogleCalendar', () => {
  const baseOpts = {
    title: 'Test Event',
    description: 'Test Description',
    location: 'Rockefeller Center',
    start: '20150704T190000'
  }
  const baseParams = {
    text: 'Test Event',
    details: 'Test Description',
    location: 'Rockefeller Center',
    action: 'TEMPLATE'
  }

  let testObj
  afterEach(() => {
    testObj = undefined
    jest.resetAllMocks()
  })

  it('should be a subclass of CalendarBase', () => {
    expect(new GoogleCalendar({})).toBeInstanceOf(CalendarBase)
  })

  describe('render()', () => {
    let result;

    afterEach(() => {
      result = undefined
    })

    it('should use the proper base URL', () => {
      testObj = new GoogleCalendar(baseOpts)

      result = testObj.render()
      let baseUrl = result.split('?')[0]

      expect(baseUrl).toBe(URL.GOOGLE)
    })

    it('should handle the text parts', () => {
      testObj = new GoogleCalendar(baseOpts)

      result = testObj.render()
      let queryString = result.split('?')[1]
      let paramsObj = queryStringToObj(queryString)

      expect(paramsObj).toMatchObject(baseParams)
    })

    describe('an all-day event', () => {

      it('should have start and end date formatted without time-of-day', () => {
        testObj = new GoogleCalendar(baseOpts)

        result = testObj.render()
        let queryString = result.split('?')[1]
        let paramsObj = queryStringToObj(queryString)

        let expectedDates = `${
          formatTime(testObj.start, FORMAT.DATE)
        }/${
          formatTime(testObj.end, FORMAT.DATE)
        }`

        expect(paramsObj.dates).toBe(expectedDates)
      })

    })

    describe('without recurrence', () => {

      it('should not include recur param', () => {
        testObj = new GoogleCalendar(baseOpts)

        result = testObj.render()
        let queryString = result.split('?')[1]
        let paramsObj = queryStringToObj(queryString)

        expect(paramsObj).not.toHaveProperty('recur')
      })
    })
    describe('with recurrence', () => {
      beforeEach(() => {
        Ics.getRrule.mockReturnValue('FREQ=DAILY;INTERVAL=1;COUNT=5')
      })

      it('should use the result of getRrule', () => {
        testObj = new GoogleCalendar({
          ...baseOpts,
          recurrence: {
            frequency: DAILY,
            interval: 1,
            count: 5,
          },
        })
        result = testObj.render()
        let queryString = result.split('?')[1]
        let paramsObj = queryStringToObj(queryString)
        let { recur } = paramsObj
        expect(Ics.getRrule).toHaveBeenCalledTimes(1)
        expect(Ics.getRrule).toHaveBeenCalledWith(testObj.recurrence)
        expect(recur).toBe('RRULE:FREQ=DAILY;INTERVAL=1;COUNT=5')
      })
    })
  })
})
<|endoftext|>


<commit_before>

function addConceptProgress(allProgress, concepts, checkResponses, dstConceptId, srcConceptId) {
  let conceptProgress = allProgress[dstConceptId];
  if (!conceptProgress) {
    allProgress[dstConceptId] = conceptProgress = { nTotal: 0, nCurrent: 0 };
  }

  const srcConcept = concepts[srcConceptId];
  if (!srcConcept) {
    console.error('referenced concept does not exist: ' + srcConceptId);
    debugger;
    return;
  }

  conceptProgress.nTotal += srcConcept.nChecks || 0;
  conceptProgress.nCurrent += (checkResponses && checkResponses[srcConceptId] &&
    _.sum(_.map(checkResponses[srcConceptId], response => response.progress || 0))) ||
    0;

  conceptProgress.progress = conceptProgress.nCurrent / conceptProgress.nTotal;

  // conceptProgress.srcConceptId = srcConceptId;
  // conceptProgress.dstConceptId = dstConceptId;
  // console.log(JSON.stringify(conceptProgress));
}

export function computeAllChecksProgress(concepts, checkResponses) {
  const allProgress = {};
  const childCounts = _.countBy(concepts, 'parentId');
  let queue = _.filter(_.keys(concepts),
    conceptId => !childCounts[conceptId]);

  // bottom-to-top BFS
  while (queue.length) {
    for (let i = 0; i < queue.length; ++i) {
      const conceptId = queue[i];
      const concept = concepts[conceptId];

      // compute own stats
      addConceptProgress(allProgress, concepts, checkResponses, conceptId, conceptId);
      if (concept.parentId) {
        // add to parent stats
        addConceptProgress(allProgress, concepts, checkResponses, concept.parentId, conceptId);
      }
    }
    queue = _.filter(_.uniq(_.map(queue,
      id => concepts[id] && concepts[id].parentId)), conceptId => !!conceptId);
  }
  return allProgress;
}<commit_msg>- minor updates<commit_after>import _ from 'lodash';

function addConceptProgress(allProgress, concepts, checkResponsesByConceptId, dstConceptId, srcConceptId) {
  let conceptProgress = allProgress[dstConceptId];
  if (!conceptProgress) {
    allProgress[dstConceptId] = conceptProgress = { nTotal: 0, nCurrent: 0 };
  }

  const srcConcept = concepts[srcConceptId];
  if (!srcConcept) {
    console.error('referenced concept does not exist: ' + srcConceptId);
    debugger;
    return;
  }

  conceptProgress.nTotal += srcConcept.nChecks || 0;
  conceptProgress.nCurrent += (checkResponsesByConceptId && checkResponsesByConceptId[srcConceptId] &&
    _.sum(_.map(checkResponsesByConceptId[srcConceptId], response => response.progress || 0))) ||
    0;

  conceptProgress.progress = conceptProgress.nCurrent / conceptProgress.nTotal;

  // conceptProgress.srcConceptId = srcConceptId;
  // conceptProgress.dstConceptId = dstConceptId;
  // console.log(JSON.stringify(conceptProgress));
}

export function computeAllChecksProgress(concepts, checkResponses) {

  // TODO: prep checkResponsesByConceptId

  const allProgress = {};
  const childCounts = _.countBy(concepts, 'parentId');
  let queue = _.filter(_.keys(concepts),
    conceptId => !childCounts[conceptId]);

  // bottom-to-top BFS
  while (queue.length) {
    for (let i = 0; i < queue.length; ++i) {
      const conceptId = queue[i];
      const concept = concepts[conceptId];

      // compute own stats
      addConceptProgress(allProgress, concepts, checkResponses, conceptId, conceptId);
      if (concept.parentId) {
        // add to parent stats
        addConceptProgress(allProgress, concepts, checkResponses, concept.parentId, conceptId);
      }
    }
    queue = _.filter(_.uniq(_.map(queue,
      id => concepts[id] && concepts[id].parentId)), conceptId => !!conceptId);
  }
  return allProgress;
}<|endoftext|>


<commit_before>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component } from 'react';
import FormField from 'grommet/components/FormField';
import CheckBox from 'grommet/components/CheckBox';
import RadioButton from 'grommet/components/RadioButton';
import TextInput from 'grommet/components/TextInput';
import Select from 'grommet/components/Select';
import NumberInput from 'grommet/components/NumberInput';
import Table from 'grommet/components/Table';
import Anchor from 'grommet/components/Anchor';
import DateTime from 'grommet/components/DateTime';

const VALUES = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
  'eight'];

export default class AllFieldTypes extends Component {

  constructor () {
    super();
    this._onChangeRange = this._onChangeRange.bind(this);
    this._onChange = this._onChange.bind(this);
    this._onSearchInputChange = this._onSearchInputChange.bind(this);
    this._onDateTimeChange = this._onDateTimeChange.bind(this);
    this._onTextInputDOMChange = this._onTextInputDOMChange.bind(this);
    this._onTextInputSelect = this._onTextInputSelect.bind(this);
    this._onSelectSearch = this._onSelectSearch.bind(this);
    this._onSelectChange = this._onSelectChange.bind(this);
    this.state = {
      rangeValue: 10,
      searchInput: { suggestions: VALUES },
      select: { options: VALUES },
      textInput: { suggestions: VALUES, value: '' },
      calendarDate: (new Date()).toISOString().slice(0, 10)
    };
  }

  _onChangeRange (event) {
    this.setState({rangeValue: parseInt(event.target.value, 10)});
  }

  _onChange (event) {
    // console.log('!!! FullForm changed', event.target, 'to',
    //   event.target.value);
  }

  _onSearchInputChange (value) {
    // console.log('!!! FullForm _onSearchInputChange', value);
    this.setState({
      searchInput: {
        value: value,
        suggestions: this._searchInputSuggestions
      }
    });
  }

  _onTextInputDOMChange (event) {
    const regexp = new RegExp('^' + event.target.value);
    const suggestions = VALUES.filter(val => {
      return regexp.test(val);
    });
    this.setState({
      textInput: { value: event.target.value, suggestions: suggestions }
    });
  }

  _onTextInputSelect (pseudoEvent) {
    this.setState({
      textInput: { value: pseudoEvent.suggestion, suggestions: VALUES }
    });
  }

  _onSelectSearch (event) {
    const regexp = new RegExp('^' + event.target.value);
    const options = VALUES.filter(val => regexp.test(val));
    this.setState({ select: { options: options } });
  }

  _onSelectChange (pseudoEvent) {
    this.setState({ select: { value: pseudoEvent.option, options: VALUES } });
  }

  _onDateTimeChange (value) {
    this.setState({ date: value });
  }

  render () {
    return (
      <fieldset>

        <legend>Text</legend>
        <FormField label='input' htmlFor='f-input'
          help={sample help <Anchor>learn more ...</Anchor>}>
          <input id='f-input' name='input' type='text'
            onChange={this._onChange} />
        </FormField>
        <FormField label='textarea' htmlFor='f-textarea'
          error='something is wrong'>
          <textarea id='f-textarea' name='textarea'/>
        </FormField>
        <FormField label='TextInput' htmlFor='text-input'>
          <TextInput id='text-input'
            value={this.state.textInput.value}
            suggestions={this.state.textInput.suggestions}
            onDOMChange={this._onTextInputDOMChange}
            onSelect={this._onTextInputSelect} />
        </FormField>

        <legend>Toggles</legend>
        <FormField>
          <CheckBox id='f-check-box' name='check' label='CheckBox'
            onChange={this._onChange} />
        </FormField>
        <FormField>
          <CheckBox id='f-toggle' name='toggle' label='CheckBox toggle'
            toggle={true} onChange={this._onChange} />
        </FormField>
        <FormField label='RadioButton'>
          <RadioButton id='f-radio-1' name='radio' label='RadioButton 1'
            onChange={this._onChange} />
          <RadioButton id='f-radio-2' name='radio' label='RadioButton 2'
            onChange={this._onChange} />
        </FormField>

        <legend>Other</legend>
        {/*}
        <FormField label='select' htmlFor='f-select'>
          <select id='f-select' name='select'>
            <option>first</option>
            <option>second</option>
            <option>third</option>
          </select>
        </FormField>
        {*/}
        <FormField label='Select' htmlFor='f-Select'>
          <Select id='f-Select' name='Select'
            value={this.state.select.value}
            options={this.state.select.options}
            onSearch={this._onSelectSearch}
            onChange={this._onSelectChange} />
        </FormField>
        <FormField label='NumberInput' htmlFor='f-number-input'>
          <NumberInput id='f-number-input' name='number'
            value={this.state.rangeValue}
            onChange={this._onChangeRange} />
        </FormField>
        <FormField label='DateTime' htmlFor='f-date-time'>
          <DateTime id='f-date-time' name='date-time'
            format='YYYY-MM-DD h:mm a' step={5}
            value={this.state.date}
            onChange={this._onDateTimeChange} />
        </FormField>
        <FormField label='input - range' htmlFor='f-range'
          help={this.state.rangeValue}>
          <input id='f-range' name='range' type='range'
            min='1' max='20' value={this.state.rangeValue}
            onChange={this._onChangeRange}
            onMouseUp={this._onChangeRange}/>
        </FormField>
        <FormField label='input - file' htmlFor='f-file'>
          <input id='f-file' name='file' type='file' />
        </FormField>

        <FormField label='Table'>

                first
                123

                second
                456

                third
                789

        </FormField>
      </fieldset>
    );
  }
};
<commit_msg>Added example of input type='color' to All Field Types form.<commit_after>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component } from 'react';
import FormField from 'grommet/components/FormField';
import CheckBox from 'grommet/components/CheckBox';
import RadioButton from 'grommet/components/RadioButton';
import TextInput from 'grommet/components/TextInput';
import Select from 'grommet/components/Select';
import NumberInput from 'grommet/components/NumberInput';
import Table from 'grommet/components/Table';
import Anchor from 'grommet/components/Anchor';
import DateTime from 'grommet/components/DateTime';

const VALUES = ['one', 'two', 'three', 'four', 'five', 'six', 'seven',
  'eight'];

export default class AllFieldTypes extends Component {

  constructor () {
    super();
    this._onChangeRange = this._onChangeRange.bind(this);
    this._onChange = this._onChange.bind(this);
    this._onSearchInputChange = this._onSearchInputChange.bind(this);
    this._onDateTimeChange = this._onDateTimeChange.bind(this);
    this._onTextInputDOMChange = this._onTextInputDOMChange.bind(this);
    this._onTextInputSelect = this._onTextInputSelect.bind(this);
    this._onSelectSearch = this._onSelectSearch.bind(this);
    this._onSelectChange = this._onSelectChange.bind(this);
    this.state = {
      rangeValue: 10,
      searchInput: { suggestions: VALUES },
      select: { options: VALUES },
      textInput: { suggestions: VALUES, value: '' },
      calendarDate: (new Date()).toISOString().slice(0, 10)
    };
  }

  _onChangeRange (event) {
    this.setState({rangeValue: parseInt(event.target.value, 10)});
  }

  _onChange (event) {
    // console.log('!!! FullForm changed', event.target, 'to',
    //   event.target.value);
  }

  _onSearchInputChange (value) {
    // console.log('!!! FullForm _onSearchInputChange', value);
    this.setState({
      searchInput: {
        value: value,
        suggestions: this._searchInputSuggestions
      }
    });
  }

  _onTextInputDOMChange (event) {
    const regexp = new RegExp('^' + event.target.value);
    const suggestions = VALUES.filter(val => {
      return regexp.test(val);
    });
    this.setState({
      textInput: { value: event.target.value, suggestions: suggestions }
    });
  }

  _onTextInputSelect (pseudoEvent) {
    this.setState({
      textInput: { value: pseudoEvent.suggestion, suggestions: VALUES }
    });
  }

  _onSelectSearch (event) {
    const regexp = new RegExp('^' + event.target.value);
    const options = VALUES.filter(val => regexp.test(val));
    this.setState({ select: { options: options } });
  }

  _onSelectChange (pseudoEvent) {
    this.setState({ select: { value: pseudoEvent.option, options: VALUES } });
  }

  _onDateTimeChange (value) {
    this.setState({ date: value });
  }

  render () {
    return (
      <fieldset>

        <legend>Text</legend>
        <FormField label='input' htmlFor='f-input'
          help={sample help <Anchor>learn more ...</Anchor>}>
          <input id='f-input' name='input' type='text'
            onChange={this._onChange} />
        </FormField>
        <FormField label='textarea' htmlFor='f-textarea'
          error='something is wrong'>
          <textarea id='f-textarea' name='textarea'/>
        </FormField>
        <FormField label='TextInput' htmlFor='text-input'>
          <TextInput id='text-input'
            value={this.state.textInput.value}
            suggestions={this.state.textInput.suggestions}
            onDOMChange={this._onTextInputDOMChange}
            onSelect={this._onTextInputSelect} />
        </FormField>

        <legend>Toggles</legend>
        <FormField>
          <CheckBox id='f-check-box' name='check' label='CheckBox'
            onChange={this._onChange} />
        </FormField>
        <FormField>
          <CheckBox id='f-toggle' name='toggle' label='CheckBox toggle'
            toggle={true} onChange={this._onChange} />
        </FormField>
        <FormField label='RadioButton'>
          <RadioButton id='f-radio-1' name='radio' label='RadioButton 1'
            onChange={this._onChange} />
          <RadioButton id='f-radio-2' name='radio' label='RadioButton 2'
            onChange={this._onChange} />
        </FormField>

        <legend>Other</legend>
        {/*}
        <FormField label='select' htmlFor='f-select'>
          <select id='f-select' name='select'>
            <option>first</option>
            <option>second</option>
            <option>third</option>
          </select>
        </FormField>
        {*/}
        <FormField label='Select' htmlFor='f-Select'>
          <Select id='f-Select' name='Select'
            value={this.state.select.value}
            options={this.state.select.options}
            onSearch={this._onSelectSearch}
            onChange={this._onSelectChange} />
        </FormField>
        <FormField label='NumberInput' htmlFor='f-number-input'>
          <NumberInput id='f-number-input' name='number'
            value={this.state.rangeValue}
            onChange={this._onChangeRange} />
        </FormField>
        <FormField label='DateTime' htmlFor='f-date-time'>
          <DateTime id='f-date-time' name='date-time'
            format='YYYY-MM-DD h:mm a' step={5}
            value={this.state.date}
            onChange={this._onDateTimeChange} />
        </FormField>
        <FormField label='input - range' htmlFor='f-range'
          help={this.state.rangeValue}>
          <input id='f-range' name='range' type='range'
            min='1' max='20' value={this.state.rangeValue}
            onChange={this._onChangeRange}
            onMouseUp={this._onChangeRange}/>
        </FormField>
        <FormField label='input - file' htmlFor='f-file'>
          <input id='f-file' name='file' type='file' />
        </FormField>
        <FormField label='input - color' htmlFor='f-color'>
          <input id='f-color' name='color' type='color' />
        </FormField>

        <FormField label='Table'>

                first
                123

                second
                456

                third
                789

        </FormField>
      </fieldset>
    );
  }
};
<|endoftext|>


<commit_before>/* eslint-env babel-eslint, node, mocha */

import _ from 'lodash'
import Promise from 'bluebird'
import Conversations from '../src/conversations'

const expect = require('chai').expect

let conversations = null

const user = n => ({ id: n })

const eventFrom = (user, txt = 'Default text') => ({
  platform: 'facebook',
  type: 'text',
  user: user,
  text: txt,
  raw: { message: txt }
})

const response = text => ({
  text: text,
  raw: null,
  type: 'text',
  platform: 'facebook'
})

describe('conversations', function() {
  let incoming = null
  let outgoing = null

  let middleware = {
    register: function({ handler }) {
      incoming = handler
    },

    sendOutgoing: function(event) {
      outgoing && outgoing(event)
    }
  }

  beforeEach(function() {
    conversations = Conversations({ middleware: middleware, clockSpeed: 5 })
  })

  afterEach(function() {
    conversations.destroy()
  })

  describe('start', function() {

    it('returns a conversation', function() {
      const convo = conversations.start(eventFrom(user(1)))
      expect(convo).not.to.be.null
      expect(convo).property('createThread').not.to.be.null
      expect(convo).property('switchTo').not.to.be.null
      expect(convo).property('next').not.to.be.null
      expect(convo).property('processIncoming').not.to.be.null
      expect(convo).property('say').not.to.be.null
      expect(convo).property('setTimeout').not.to.be.null
      expect(convo).property('get').not.to.be.null
      expect(convo).property('set').not.to.be.null
      expect(convo).property('activate').not.to.be.null
      expect(convo).property('on').not.to.be.null
    })

    it('expects an event to create a conversation', function() {
      const fn = () => conversations.start()
      expect(fn).to.throw(/event/i)
    })

    it('activated by default', function() {
      const convo = conversations.start(eventFrom(user(1)))
      expect(convo).property('status').to.equal('active')
    })

  })

  describe('create', function() {
    it('not activated', function() {
      const convo = conversations.create(eventFrom(user(1)))
      expect(convo).property('status').to.equal('new')
    })

    it('activate', function() {
      const convo = conversations.create(eventFrom(user(1)))

      convo.activate()

      expect(convo).property('status').to.equal('active')
    })
  })

  describe('incoming processing', function() {

    it('does not process if conversation new', function(done) {
      const convo = conversations.create(eventFrom(user(1)))

      convo.on('beforeProcessing', () => done('processing called'))
      incoming(eventFrom(user(1)))

      setTimeout(done, 5)
    })

    it('process when conversation active', function(done) {
      this.timeout(50)

      const convo = conversations.start(eventFrom(user(1)))
      convo.on('beforeProcessing', () => done())
      incoming(eventFrom(user(1)))
    })

    it('does not process if different plaform', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      const newEvent = eventFrom(user(1))
      newEvent.platform = 'random'

      convo.on('beforeProcessing', () => done('processing called'))
      incoming(newEvent)

      setTimeout(done, 5)
    })

    it('does not process if different users', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      const newEvent = eventFrom(user(2))

      convo.on('beforeProcessing', () => done('processing called'))
      incoming(newEvent)

      setTimeout(done, 5)
    })

  })

  describe('Flow - Default thread', function() {

    it('addMessage is not sent if not started', function(done) {
      const convo = conversations.create(eventFrom(user(1)))

      outgoing = event => done('Should not have been called')

      convo.defaultThread.addMessage(response('Hello'))

      setTimeout(done, 10)
    })

    it('On addMessage is sent', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => {
        expect(event).property('text').to.equal('Hello')
        done()
      }

      convo.defaultThread.addMessage(response('Hello'))
    })

    it('On addQuestion is sent', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => {
        expect(event).property('text').to.equal('Hello')
        done()
      }

      convo.defaultThread.addQuestion(response('Hello'), [])
    })

    it('Multiple messages are sent in a row and in order', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      let count = 0

      outgoing = event => {
        expect(parseInt(event.text)).to.equal(count++)
        if (count == 4) {
          done()
        }
      }

      convo.defaultThread.addMessage(response('0'))
      convo.defaultThread.addMessage(response('1'))
      convo.defaultThread.addMessage(response('2'))
      convo.defaultThread.addMessage(response('3'))
    })

    it('Questions wait for answer', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => {
        if (event.text === '0') {
          setTimeout(done, 10)
        }

        if (event.text === '1') {
          return done('Should not have been sent')
        }
      }

      convo.defaultThread.addQuestion(response('0'), [])
      convo.defaultThread.addMessage(response('1'))
    })

  })

  describe('Flow - Ask question', function() {

    it('Correct handler gets called', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = () => {}

      convo.defaultThread.addQuestion(response('Hello'), [
        { pattern: 'no', callback: () => done('Nope') },
        { pattern: 'yes', callback: () => done() }
      ])

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)
    })

    it('Only one gets called (first declared)', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = () => {}

      convo.defaultThread.addQuestion(response('Hello'), [
        { pattern: 'no', callback: () => done('Nope') },
        { pattern: /.+/i, callback: () => done() },
        { pattern: 'yes', callback: () => done('Nope') }
      ])

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)
    })

    it('Convo.next', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => event.text === 'done' && done()

      convo.defaultThread.addQuestion(response('Hello'), [
        { pattern: 'no', callback: () => done('Nope') },
        { pattern: 'yes', callback: () => {
          convo.next()
        } }
      ])

      convo.defaultThread.addMessage(response('done'))

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)
    })

  })

  describe('Thread switching', function() {

    it('Correct handler gets called', function(done) {
      const convo = conversations.create(eventFrom(user(1)))
      const thread = convo.createThread('hello')

      let handler = () => done('Not yet')

      thread.addQuestion(response('Anything'), [
        { pattern: 'yes', callback: () => handler() }
      ])

      convo.activate()

      handler = () => done()
      convo.switchTo('hello')

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)

    })

    it('Other thread doesnt get call if no switch', function(done) {
      conversations.start(eventFrom(user(1)), convo => {

        const thread = convo.createThread('hello')

        let handler = () => done('Not yet')

        thread.addQuestion(response('Anything'), [
          { pattern: 'yes', callback: () => handler() }
        ])

        setTimeout(() => {
          incoming(eventFrom(user(1), 'yes'))
        }, 5)

        setTimeout(done, 15)
      })
    })

  })

})
<commit_msg>Add test for convo.say() with simple string.<commit_after>/* eslint-env babel-eslint, node, mocha */

import _ from 'lodash'
import Promise from 'bluebird'
import Conversations from '../src/conversations'

const expect = require('chai').expect

let conversations = null

const user = n => ({ id: n })

const eventFrom = (user, txt = 'Default text') => ({
  platform: 'facebook',
  type: 'text',
  user: user,
  text: txt,
  raw: { message: txt }
})

const response = text => ({
  text: text,
  raw: null,
  type: 'text',
  platform: 'facebook'
})

describe('conversations', function() {
  let incoming = null
  let outgoing = null

  let middleware = {
    register: function({ handler }) {
      incoming = handler
    },

    sendOutgoing: function(event) {
      outgoing && outgoing(event)
    }
  }

  beforeEach(function() {
    conversations = Conversations({ middleware: middleware, clockSpeed: 5 })
  })

  afterEach(function() {
    conversations.destroy()
  })

  describe('start', function() {

    it('returns a conversation', function() {
      const convo = conversations.start(eventFrom(user(1)))
      expect(convo).not.to.be.null
      expect(convo).property('createThread').not.to.be.null
      expect(convo).property('switchTo').not.to.be.null
      expect(convo).property('next').not.to.be.null
      expect(convo).property('processIncoming').not.to.be.null
      expect(convo).property('say').not.to.be.null
      expect(convo).property('setTimeout').not.to.be.null
      expect(convo).property('get').not.to.be.null
      expect(convo).property('set').not.to.be.null
      expect(convo).property('activate').not.to.be.null
      expect(convo).property('on').not.to.be.null
    })

    it('expects an event to create a conversation', function() {
      const fn = () => conversations.start()
      expect(fn).to.throw(/event/i)
    })

    it('activated by default', function() {
      const convo = conversations.start(eventFrom(user(1)))
      expect(convo).property('status').to.equal('active')
    })

  })

  describe('create', function() {
    it('not activated', function() {
      const convo = conversations.create(eventFrom(user(1)))
      expect(convo).property('status').to.equal('new')
    })

    it('activate', function() {
      const convo = conversations.create(eventFrom(user(1)))

      convo.activate()

      expect(convo).property('status').to.equal('active')
    })
  })

  describe('incoming processing', function() {

    it('does not process if conversation new', function(done) {
      const convo = conversations.create(eventFrom(user(1)))

      convo.on('beforeProcessing', () => done('processing called'))
      incoming(eventFrom(user(1)))

      setTimeout(done, 5)
    })

    it('process when conversation active', function(done) {
      this.timeout(50)

      const convo = conversations.start(eventFrom(user(1)))
      convo.on('beforeProcessing', () => done())
      incoming(eventFrom(user(1)))
    })

    it('does not process if different plaform', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      const newEvent = eventFrom(user(1))
      newEvent.platform = 'random'

      convo.on('beforeProcessing', () => done('processing called'))
      incoming(newEvent)

      setTimeout(done, 5)
    })

    it('does not process if different users', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      const newEvent = eventFrom(user(2))

      convo.on('beforeProcessing', () => done('processing called'))
      incoming(newEvent)

      setTimeout(done, 5)
    })

  })

  describe('Flow - Default thread', function() {

    it('addMessage is not sent if not started', function(done) {
      const convo = conversations.create(eventFrom(user(1)))

      outgoing = event => done('Should not have been called')

      convo.defaultThread.addMessage(response('Hello'))

      setTimeout(done, 10)
    })

    it('On addMessage is sent', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => {
        expect(event).property('text').to.equal('Hello')
        done()
      }

      convo.defaultThread.addMessage(response('Hello'))
    })

    it('On addQuestion is sent', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => {
        expect(event).property('text').to.equal('Hello')
        done()
      }

      convo.defaultThread.addQuestion(response('Hello'), [])
    })

    it('Multiple messages are sent in a row and in order', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      let count = 0

      outgoing = event => {
        expect(parseInt(event.text)).to.equal(count++)
        if (count == 4) {
          done()
        }
      }

      convo.defaultThread.addMessage(response('0'))
      convo.defaultThread.addMessage(response('1'))
      convo.defaultThread.addMessage(response('2'))
      convo.defaultThread.addMessage(response('3'))
    })

    it('Questions wait for answer', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => {
        if (event.text === '0') {
          setTimeout(done, 10)
        }

        if (event.text === '1') {
          return done('Should not have been sent')
        }
      }

      convo.defaultThread.addQuestion(response('0'), [])
      convo.defaultThread.addMessage(response('1'))
    })

  })

  describe('Flow - Ask question', function() {

    it('Correct handler gets called', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = () => {}

      convo.defaultThread.addQuestion(response('Hello'), [
        { pattern: 'no', callback: () => done('Nope') },
        { pattern: 'yes', callback: () => done() }
      ])

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)
    })

    it('Only one gets called (first declared)', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = () => {}

      convo.defaultThread.addQuestion(response('Hello'), [
        { pattern: 'no', callback: () => done('Nope') },
        { pattern: /.+/i, callback: () => done() },
        { pattern: 'yes', callback: () => done('Nope') }
      ])

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)
    })

    it('Convo.next', function(done) {
      const convo = conversations.start(eventFrom(user(1)))

      outgoing = event => event.text === 'done' && done()

      convo.defaultThread.addQuestion(response('Hello'), [
        { pattern: 'no', callback: () => done('Nope') },
        { pattern: 'yes', callback: () => {
          convo.next()
        } }
      ])

      convo.defaultThread.addMessage(response('done'))

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)
    })

  })

  describe('Thread switching', function() {

    it('Correct handler gets called', function(done) {
      const convo = conversations.create(eventFrom(user(1)))
      const thread = convo.createThread('hello')

      let handler = () => done('Not yet')

      thread.addQuestion(response('Anything'), [
        { pattern: 'yes', callback: () => handler() }
      ])

      convo.activate()

      handler = () => done()
      convo.switchTo('hello')

      setTimeout(() => {
        incoming(eventFrom(user(1), 'yes'))
      }, 5)

    })

    it('Other thread doesnt get call if no switch', function(done) {
      conversations.start(eventFrom(user(1)), convo => {

        const thread = convo.createThread('hello')

        let handler = () => done('Not yet')

        thread.addQuestion(response('Anything'), [
          { pattern: 'yes', callback: () => handler() }
        ])

        setTimeout(() => {
          incoming(eventFrom(user(1), 'yes'))
        }, 5)

        setTimeout(done, 15)
      })
    })

  })

  it('convo.say() supports simple string', function(done) {
    const convo = conversations.start(eventFrom(user(1)))

    outgoing = event => {
      expect(event).property('text').to.equal('Hello')
      done()
    }

    convo.say('Hello')
  })

})
<|endoftext|>


<commit_before>// Create the dom before requiring react
var DOM = require( './testdom');
DOM();

var React = require('react'),
	ReactAddons = require('react/addons'),
	Utils = React.addons.TestUtils,
	Datetime = require('../DateTime'),
	assert = require('assert'),
	moment = require('moment')
;

// Needs to receive react to work in Travis CI
var createDatetime = function( r, props ){
	document.body.innerHTML = '';

	r.render(
		r.createElement( Datetime, props ),
		document.body
	);

	return document.body.children[0];
};

var date = new Date( 2000, 0, 15 ),
	mDate = moment( date ),
	strDate = mDate.format('L') + ' ' + mDate.format('LT')
;

describe( 'Datetime', function(){
	it( 'Create Datetime', function(){
		var component = createDatetime( React, {});
		assert( component );
		assert.equal( component.children.length, 2 );
		assert.equal( component.children[0].tagName , 'INPUT' );
		assert.equal( component.children[1].tagName , 'DIV' );
	});

	it( 'input=false', function(){
		var component = createDatetime( React, { input: false });
		assert( component );
		assert.equal( component.children.length, 1 );
		assert.equal( component.children[0].tagName , 'DIV' );
	});

	it( 'Date value', function(){
		var component = createDatetime( React, { value: date }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'Moment value', function(){
		var component = createDatetime( React, { value: mDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'String value', function(){
		var component = createDatetime( React, { value: strDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'Date defaultValue', function(){
		var component = createDatetime( React, { defaultValue: date }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'Moment defaultValue', function(){
		var component = createDatetime( React, { defaultValue: mDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'String defaultValue', function(){
		var component = createDatetime( React, { defaultValue: strDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'dateFormat', function(){
		var component = createDatetime( React, { value: date, dateFormat: 'M&D' }),
			input = component.children[0]
		;
		assert.equal( input.value, mDate.format('M&D LT') );
	});

	it( 'dateFormat=false', function(){
		var component = createDatetime( React, { value: date, dateFormat: false }),
			input = component.children[0],
			view = component.children[1].children[0]
		;
		assert.equal( input.value, mDate.format('LT') );
		// The view must be the timepicker
		assert.equal( view.className, 'rdtTime' );
		// There must not be a date toggle
		assert.equal( view.querySelectorAll('thead').length, 0);
	});

	it( 'timeFormat', function(){
		var format = 'HH:mm:ss:SSS',
			component = createDatetime( React, { value: date, timeFormat: format }),
			input = component.children[0]
		;
		assert.equal( input.value, mDate.format('L ' + format) );
	});

	it( 'timeFormat=false', function(){
		var component = createDatetime( React, { value: date, timeFormat: false }),
			input = component.children[0],
			view = component.children[1].children[0]
		;
		assert.equal( input.value, mDate.format('L') );
		// The view must be the daypicker
		assert.equal( view.className, 'rdtDays' );
		// There must not be a time toggle
		assert.equal( view.querySelectorAll('.timeToggle').length, 0);
	});

	it( 'viewMode=years', function(){
		var component = createDatetime( React, { viewMode: 'years' }),
			view = component.children[1].children[0]
		;

		assert.equal( view.className, 'rdtYears' );
	});

	it( 'viewMode=months', function(){
		var component = createDatetime( React, { viewMode: 'months' }),
			view = component.children[1].children[0]
		;

		assert.equal( view.className, 'rdtMonths' );
	});

	it( 'viewMode=time', function(){
		var component = createDatetime( React, { viewMode: 'time' }),
			view = component.children[1].children[0]
		;

		assert.equal( view.className, 'rdtTime' );
	});

	it( 'className', function(){
		var component = createDatetime( React, { className: 'custom' });
		assert.notEqual( component.className.indexOf('custom'), -1 );
	});

	it( 'inputProps', function(){
		var component = createDatetime( React, { inputProps: { className: 'myInput', type: 'email' } }),
			input = component.children[0]
		;

		assert.equal( input.className, 'myInput' );
		assert.equal( input.type, 'email' );
	});

	it( 'renderDay', function(){
		var props, currentDate, selectedDate,
			component = createDatetime( React, { value: mDate, renderDay: function( p, current, selected ){
				props = p;
				currentDate = current;
				selectedDate = selected;

				return React.DOM.td( props, 'day' );
			}}),
			view = component.children[1].children[0]
		;

		// Last day should be 6th of february
		assert.equal( currentDate.day(), 6 );
		assert.equal( currentDate.month(), 1 );

		// The date must be the same
		assert.equal( selectedDate.isSame( mDate ), true );

		// There should be a onClick function in the props
		assert.equal( typeof props.onClick, 'function' );

		// The cell text should be 'day'
		assert.equal( view.querySelector('.day').innerHTML, 'day' );
	});

	it( 'renderMonth', function(){
		var props, month, year, selectedDate,
			component = createDatetime( React, { value: mDate, viewMode: 'months', renderMonth: function( p, m, y, selected ){
				props = p;
				month = m;
				year = y;
				selectedDate = selected;

				return React.DOM.td( props, 'month' );
			}}),
			view = component.children[1].children[0]
		;

		// The date must be the same
		assert.equal( selectedDate.isSame( mDate ), true );

		assert.equal( month, 11 );
		assert.equal( year, 2000 );

		// There should be a onClick function in the props
		assert.equal( typeof props.onClick, 'function' );

		// The cell text should be 'day'
		assert.equal( view.querySelector('.month').innerHTML, 'month' );
	});

	it( 'renderYear', function(){
		var props, year, selectedDate,
			component = createDatetime( React, { value: mDate, viewMode: 'years', renderYear: function( p, y, selected ){
				props = p;
				year = y;
				selectedDate = selected;

				return React.DOM.td( props, 'year' );
			}}),
			view = component.children[1].children[0]
		;

		// The date must be the same
		assert.equal( selectedDate.isSame( mDate ), true );

		assert.equal( year, 2010 );

		// There should be a onClick function in the props
		assert.equal( typeof props.onClick, 'function' );

		// The cell text should be 'day'
		assert.equal( view.querySelector('.year').innerHTML, 'year' );
	});
});

<commit_msg>Made React global to fulfill tests<commit_after>// Create the dom before requiring react
var DOM = require( './testdom');
DOM();

React = require('react');

var ReactAddons = require('react/addons'),
	Utils = React.addons.TestUtils,
	Datetime = require('../DateTime'),
	assert = require('assert'),
	moment = require('moment')
;

// Needs to receive react to work in Travis CI
var createDatetime = function( r, props ){
	document.body.innerHTML = '';

	r.render(
		r.createElement( Datetime, props ),
		document.body
	);

	return document.body.children[0];
};

var date = new Date( 2000, 0, 15 ),
	mDate = moment( date ),
	strDate = mDate.format('L') + ' ' + mDate.format('LT')
;

describe( 'Datetime', function(){
	it( 'Create Datetime', function(){
		var component = createDatetime( React, {});
		assert( component );
		assert.equal( component.children.length, 2 );
		assert.equal( component.children[0].tagName , 'INPUT' );
		assert.equal( component.children[1].tagName , 'DIV' );
	});

	it( 'input=false', function(){
		var component = createDatetime( React, { input: false });
		assert( component );
		assert.equal( component.children.length, 1 );
		assert.equal( component.children[0].tagName , 'DIV' );
	});

	it( 'Date value', function(){
		var component = createDatetime( React, { value: date }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'Moment value', function(){
		var component = createDatetime( React, { value: mDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'String value', function(){
		var component = createDatetime( React, { value: strDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'Date defaultValue', function(){
		var component = createDatetime( React, { defaultValue: date }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'Moment defaultValue', function(){
		var component = createDatetime( React, { defaultValue: mDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'String defaultValue', function(){
		var component = createDatetime( React, { defaultValue: strDate }),
			input = component.children[0]
		;
		assert.equal( input.value, strDate );
	});

	it( 'dateFormat', function(){
		var component = createDatetime( React, { value: date, dateFormat: 'M&D' }),
			input = component.children[0]
		;
		assert.equal( input.value, mDate.format('M&D LT') );
	});

	it( 'dateFormat=false', function(){
		var component = createDatetime( React, { value: date, dateFormat: false }),
			input = component.children[0],
			view = component.children[1].children[0]
		;
		assert.equal( input.value, mDate.format('LT') );
		// The view must be the timepicker
		assert.equal( view.className, 'rdtTime' );
		// There must not be a date toggle
		assert.equal( view.querySelectorAll('thead').length, 0);
	});

	it( 'timeFormat', function(){
		var format = 'HH:mm:ss:SSS',
			component = createDatetime( React, { value: date, timeFormat: format }),
			input = component.children[0]
		;
		assert.equal( input.value, mDate.format('L ' + format) );
	});

	it( 'timeFormat=false', function(){
		var component = createDatetime( React, { value: date, timeFormat: false }),
			input = component.children[0],
			view = component.children[1].children[0]
		;
		assert.equal( input.value, mDate.format('L') );
		// The view must be the daypicker
		assert.equal( view.className, 'rdtDays' );
		// There must not be a time toggle
		assert.equal( view.querySelectorAll('.timeToggle').length, 0);
	});

	it( 'viewMode=years', function(){
		var component = createDatetime( React, { viewMode: 'years' }),
			view = component.children[1].children[0]
		;

		assert.equal( view.className, 'rdtYears' );
	});

	it( 'viewMode=months', function(){
		var component = createDatetime( React, { viewMode: 'months' }),
			view = component.children[1].children[0]
		;

		assert.equal( view.className, 'rdtMonths' );
	});

	it( 'viewMode=time', function(){
		var component = createDatetime( React, { viewMode: 'time' }),
			view = component.children[1].children[0]
		;

		assert.equal( view.className, 'rdtTime' );
	});

	it( 'className', function(){
		var component = createDatetime( React, { className: 'custom' });
		assert.notEqual( component.className.indexOf('custom'), -1 );
	});

	it( 'inputProps', function(){
		var component = createDatetime( React, { inputProps: { className: 'myInput', type: 'email' } }),
			input = component.children[0]
		;

		assert.equal( input.className, 'myInput' );
		assert.equal( input.type, 'email' );
	});

	it( 'renderDay', function(){
		var props, currentDate, selectedDate,
			component = createDatetime( React, { value: mDate, renderDay: function( p, current, selected ){
				props = p;
				currentDate = current;
				selectedDate = selected;

				return React.DOM.td( props, 'day' );
			}}),
			view = component.children[1].children[0]
		;

		// Last day should be 6th of february
		assert.equal( currentDate.day(), 6 );
		assert.equal( currentDate.month(), 1 );

		// The date must be the same
		assert.equal( selectedDate.isSame( mDate ), true );

		// There should be a onClick function in the props
		assert.equal( typeof props.onClick, 'function' );

		// The cell text should be 'day'
		assert.equal( view.querySelector('.day').innerHTML, 'day' );
	});

	it( 'renderMonth', function(){
		var props, month, year, selectedDate,
			component = createDatetime( React, { value: mDate, viewMode: 'months', renderMonth: function( p, m, y, selected ){
				props = p;
				month = m;
				year = y;
				selectedDate = selected;

				return React.DOM.td( props, 'month' );
			}}),
			view = component.children[1].children[0]
		;

		// The date must be the same
		assert.equal( selectedDate.isSame( mDate ), true );

		assert.equal( month, 11 );
		assert.equal( year, 2000 );

		// There should be a onClick function in the props
		assert.equal( typeof props.onClick, 'function' );

		// The cell text should be 'day'
		assert.equal( view.querySelector('.month').innerHTML, 'month' );
	});

	it( 'renderYear', function(){
		var props, year, selectedDate,
			component = createDatetime( React, { value: mDate, viewMode: 'years', renderYear: function( p, y, selected ){
				props = p;
				year = y;
				selectedDate = selected;

				return React.DOM.td( props, 'year' );
			}}),
			view = component.children[1].children[0]
		;

		// The date must be the same
		assert.equal( selectedDate.isSame( mDate ), true );

		assert.equal( year, 2010 );

		// There should be a onClick function in the props
		assert.equal( typeof props.onClick, 'function' );

		// The cell text should be 'day'
		assert.equal( view.querySelector('.year').innerHTML, 'year' );
	});
});

<|endoftext|>