<commit_before>import _ from 'lodash';
import {
  boolValue,
  getInputMask,
  matchInputMask,
  getDateSetting
} from '../utils/utils';
import moment from 'moment';

export default {
  get: _.get,
  each: _.each,
  has: _.has,
  checkValidator(component, validator, setting, value, data) {
    let result = null;

    // Allow each component to override their own validators by implementing the validator.method
    if (validator.method && (typeof component[validator.method] === 'function')) {
      result = component[validator.method](setting, value, data);
    }
    else {
      result = validator.check.call(this, component, setting, value, data);
    }
    if (typeof result === 'string') {
      return result;
    }
    if (!result) {
      return validator.message.call(this, component, setting);
    }
    return '';
  },
  validate(component, validator, value, data) {
    if (validator.key && _.has(component.component, validator.key)) {
      const setting = this.get(component.component, validator.key);
      return this.checkValidator(component, validator, setting, value, data);
    }
    return this.checkValidator(component, validator, null, value, data);
  },
  check(component, data) {
    let result = '';
    const value = component.validationValue;
    data = data || component.data;
    _.each(component.validators, (name) => {
      if (this.validators.hasOwnProperty(name)) {
        const validator = this.validators[name];
        if (component.validateMultiple(value)) {
          _.each(value, (val) => {
            result = this.validate(component, validator, val, data);
            if (result) {
              return false;
            }
          });
        }
        else {
          result = this.validate(component, validator, value, data);
        }
        if (result) {
          return false;
        }
      }
    });

    const validateCustom = _.get(component, 'component.validate.custom');
    const customErrorMessage = _.get(component, 'component.validate.customMessage');
    if (result && (customErrorMessage || validateCustom)) {
      result = component.t(customErrorMessage || result, {
        data: component.data
      });
    }
    return result;
  },
  validators: {
    required: {
      key: 'validate.required',
      method: 'validateRequired',
      message(component) {
        return component.t(component.errorMessage('required'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        if (!boolValue(setting)) {
          return true;
        }
        return !component.isEmpty(value);
      }
    },
    min: {
      key: 'validate.min',
      message(component, setting) {
        return component.t(component.errorMessage('min'), {
          field: component.errorLabel,
          min: parseFloat(setting),
          data: component.data
        });
      },
      check(component, setting, value) {
        const min = parseFloat(setting);
        if (!min || (!_.isNumber(value))) {
          return true;
        }
        return parseFloat(value) >= min;
      }
    },
    max: {
      key: 'validate.max',
      message(component, setting) {
        return component.t(component.errorMessage('max'), {
          field: component.errorLabel,
          max: parseFloat(setting),
          data: component.data
        });
      },
      check(component, setting, value) {
        const max = parseFloat(setting);
        if (!max || (!_.isNumber(value))) {
          return true;
        }
        return parseFloat(value) <= max;
      }
    },
    minLength: {
      key: 'validate.minLength',
      message(component, setting) {
        return component.t(component.errorMessage('minLength'), {
          field: component.errorLabel,
          length: (setting - 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const minLength = parseInt(setting, 10);
        if (!minLength || (typeof value !== 'string')) {
          return true;
        }
        return (value.length >= minLength);
      }
    },
    maxLength: {
      key: 'validate.maxLength',
      message(component, setting) {
        return component.t(component.errorMessage('maxLength'), {
          field: component.errorLabel,
          length: (setting + 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const maxLength = parseInt(setting, 10);
        if (!maxLength || (typeof value !== 'string')) {
          return true;
        }
        return (value.length <= maxLength);
      }
    },
    maxWords: {
      key: 'validate.maxWords',
      message(component, setting) {
        return component.t(component.errorMessage('maxWords'), {
          field: component.errorLabel,
          length: (setting + 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const maxWords = parseInt(setting, 10);
        if (!maxWords || (typeof value !== 'string')) {
          return true;
        }
        return (value.trim().split(/\s+/).length <= maxWords);
      }
    },
    minWords: {
      key: 'validate.minWords',
      message(component, setting) {
        return component.t(component.errorMessage('minWords'), {
          field: component.errorLabel,
          length: (setting + 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const minWords = parseInt(setting, 10);
        if (!minWords || (typeof value !== 'string')) {
          return true;
        }
        return (value.trim().split(/\s+/).length >= minWords);
      }
    },
    email: {
      message(component) {
        return component.t(component.errorMessage('invalid_email'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        /* eslint-disable max-len */
        // From http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
        const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        /* eslint-enable max-len */

        // Allow emails to be valid if the component is pristine and no value is provided.
        return !value || re.test(value);
      }
    },
    url: {
      message(component) {
        return component.t(component.errorMessage('invalid_url'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        /* eslint-disable max-len */
        // From https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
        const re = /[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/;
        /* eslint-enable max-len */

        // Allow urls to be valid if the component is pristine and no value is provided.
        return !value || re.test(value);
      }
    },
    date: {
      message(component) {
        return component.t(component.errorMessage('invalid_date'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        return (value !== 'Invalid date');
      }
    },
    pattern: {
      key: 'validate.pattern',
      message(component, setting) {
        return component.t(_.get(component, 'component.validate.patternMessage', component.errorMessage('pattern'), {
          field: component.errorLabel,
          pattern: setting,
          data: component.data
        }));
      },
      check(component, setting, value) {
        const pattern = setting;
        if (!pattern) {
          return true;
        }
        const regex = new RegExp(`^${pattern}$`);
        return regex.test(value);
      }
    },
    json: {
      key: 'validate.json',
      check(component, setting, value, data) {
        if (!setting) {
          return true;
        }
        const valid = component.evaluate(setting, {
          data,
          input: value
        });
        if (valid === null) {
          return true;
        }
        return valid;
      }
    },
    mask: {
      message(component) {
        return component.t(component.errorMessage('mask'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        let inputMask;
        if (component.isMultipleMasksField) {
          const maskName = value ? value.maskName : undefined;
          const formioInputMask = component.getMaskByName(maskName);
          if (formioInputMask) {
            inputMask = getInputMask(formioInputMask);
          }
          value = value ? value.value : value;
        }
        else {
          inputMask = component.defaultMask;
        }
        if (value && inputMask) {
          return matchInputMask(value, inputMask);
        }
        return true;
      }
    },
    custom: {
      key: 'validate.custom',
      message(component) {
        return component.t(component.errorMessage('custom'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value, data) {
        if (!setting) {
          return true;
        }
        const valid = component.evaluate(setting, {
          valid: true,
          data,
          input: value
        }, 'valid', true);
        if (valid === null) {
          return true;
        }
        return valid;
      }
    },
    maxDate: {
      key: 'maxDate',
      message(component, setting) {
        const date = getDateSetting(setting);
        return component.t(component.errorMessage('maxDate'), {
          field: component.errorLabel,
          maxDate: moment(date).format(component.format),
        });
      },
      check(component, setting, value) {
        const date = moment(value);
        const maxDate = getDateSetting(setting);

        if (_.isNull(maxDate)) {
          return true;
        }
        else {
          maxDate.setHours(0,0,0,0);
        }

        return date.isBefore(maxDate) || date.isSame(maxDate);
      }
    },
    minDate: {
      key: 'minDate',
      message(component, setting) {
        const date = getDateSetting(setting);
        return component.t(component.errorMessage('minDate'), {
          field: component.errorLabel,
          minDate: moment(date).format(component.format),
        });
      },
      check(component, setting, value) {
        const date = moment(value);
        const minDate = getDateSetting(setting);
        if (_.isNull(minDate)) {
          return true;
        }
        else {
          minDate.setHours(0,0,0,0);
        }

        return date.isAfter(minDate) || date.isSame(minDate);
      }
    }
  }
};
<commit_msg>FOR-1821: Fixed Number component min and max validation.<commit_after>import _ from 'lodash';
import {
  boolValue,
  getInputMask,
  matchInputMask,
  getDateSetting
} from '../utils/utils';
import moment from 'moment';

export default {
  get: _.get,
  each: _.each,
  has: _.has,
  checkValidator(component, validator, setting, value, data) {
    let result = null;

    // Allow each component to override their own validators by implementing the validator.method
    if (validator.method && (typeof component[validator.method] === 'function')) {
      result = component[validator.method](setting, value, data);
    }
    else {
      result = validator.check.call(this, component, setting, value, data);
    }
    if (typeof result === 'string') {
      return result;
    }
    if (!result) {
      return validator.message.call(this, component, setting);
    }
    return '';
  },
  validate(component, validator, value, data) {
    if (validator.key && _.has(component.component, validator.key)) {
      const setting = this.get(component.component, validator.key);
      return this.checkValidator(component, validator, setting, value, data);
    }
    return this.checkValidator(component, validator, null, value, data);
  },
  check(component, data) {
    let result = '';
    const value = component.validationValue;
    data = data || component.data;
    _.each(component.validators, (name) => {
      if (this.validators.hasOwnProperty(name)) {
        const validator = this.validators[name];
        if (component.validateMultiple(value)) {
          _.each(value, (val) => {
            result = this.validate(component, validator, val, data);
            if (result) {
              return false;
            }
          });
        }
        else {
          result = this.validate(component, validator, value, data);
        }
        if (result) {
          return false;
        }
      }
    });

    const validateCustom = _.get(component, 'component.validate.custom');
    const customErrorMessage = _.get(component, 'component.validate.customMessage');
    if (result && (customErrorMessage || validateCustom)) {
      result = component.t(customErrorMessage || result, {
        data: component.data
      });
    }
    return result;
  },
  validators: {
    required: {
      key: 'validate.required',
      method: 'validateRequired',
      message(component) {
        return component.t(component.errorMessage('required'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        if (!boolValue(setting)) {
          return true;
        }
        return !component.isEmpty(value);
      }
    },
    min: {
      key: 'validate.min',
      message(component, setting) {
        return component.t(component.errorMessage('min'), {
          field: component.errorLabel,
          min: parseFloat(setting),
          data: component.data
        });
      },
      check(component, setting, value) {
        const min = parseFloat(setting);
        if (Number.isNaN(min) || (!_.isNumber(value))) {
          return true;
        }
        return parseFloat(value) >= min;
      }
    },
    max: {
      key: 'validate.max',
      message(component, setting) {
        return component.t(component.errorMessage('max'), {
          field: component.errorLabel,
          max: parseFloat(setting),
          data: component.data
        });
      },
      check(component, setting, value) {
        const max = parseFloat(setting);
        if (Number.isNaN(max) || (!_.isNumber(value))) {
          return true;
        }
        return parseFloat(value) <= max;
      }
    },
    minLength: {
      key: 'validate.minLength',
      message(component, setting) {
        return component.t(component.errorMessage('minLength'), {
          field: component.errorLabel,
          length: (setting - 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const minLength = parseInt(setting, 10);
        if (!minLength || (typeof value !== 'string')) {
          return true;
        }
        return (value.length >= minLength);
      }
    },
    maxLength: {
      key: 'validate.maxLength',
      message(component, setting) {
        return component.t(component.errorMessage('maxLength'), {
          field: component.errorLabel,
          length: (setting + 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const maxLength = parseInt(setting, 10);
        if (!maxLength || (typeof value !== 'string')) {
          return true;
        }
        return (value.length <= maxLength);
      }
    },
    maxWords: {
      key: 'validate.maxWords',
      message(component, setting) {
        return component.t(component.errorMessage('maxWords'), {
          field: component.errorLabel,
          length: (setting + 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const maxWords = parseInt(setting, 10);
        if (!maxWords || (typeof value !== 'string')) {
          return true;
        }
        return (value.trim().split(/\s+/).length <= maxWords);
      }
    },
    minWords: {
      key: 'validate.minWords',
      message(component, setting) {
        return component.t(component.errorMessage('minWords'), {
          field: component.errorLabel,
          length: (setting + 1),
          data: component.data
        });
      },
      check(component, setting, value) {
        const minWords = parseInt(setting, 10);
        if (!minWords || (typeof value !== 'string')) {
          return true;
        }
        return (value.trim().split(/\s+/).length >= minWords);
      }
    },
    email: {
      message(component) {
        return component.t(component.errorMessage('invalid_email'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        /* eslint-disable max-len */
        // From http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
        const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        /* eslint-enable max-len */

        // Allow emails to be valid if the component is pristine and no value is provided.
        return !value || re.test(value);
      }
    },
    url: {
      message(component) {
        return component.t(component.errorMessage('invalid_url'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        /* eslint-disable max-len */
        // From https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
        const re = /[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/;
        /* eslint-enable max-len */

        // Allow urls to be valid if the component is pristine and no value is provided.
        return !value || re.test(value);
      }
    },
    date: {
      message(component) {
        return component.t(component.errorMessage('invalid_date'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        return (value !== 'Invalid date');
      }
    },
    pattern: {
      key: 'validate.pattern',
      message(component, setting) {
        return component.t(_.get(component, 'component.validate.patternMessage', component.errorMessage('pattern'), {
          field: component.errorLabel,
          pattern: setting,
          data: component.data
        }));
      },
      check(component, setting, value) {
        const pattern = setting;
        if (!pattern) {
          return true;
        }
        const regex = new RegExp(`^${pattern}$`);
        return regex.test(value);
      }
    },
    json: {
      key: 'validate.json',
      check(component, setting, value, data) {
        if (!setting) {
          return true;
        }
        const valid = component.evaluate(setting, {
          data,
          input: value
        });
        if (valid === null) {
          return true;
        }
        return valid;
      }
    },
    mask: {
      message(component) {
        return component.t(component.errorMessage('mask'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value) {
        let inputMask;
        if (component.isMultipleMasksField) {
          const maskName = value ? value.maskName : undefined;
          const formioInputMask = component.getMaskByName(maskName);
          if (formioInputMask) {
            inputMask = getInputMask(formioInputMask);
          }
          value = value ? value.value : value;
        }
        else {
          inputMask = component.defaultMask;
        }
        if (value && inputMask) {
          return matchInputMask(value, inputMask);
        }
        return true;
      }
    },
    custom: {
      key: 'validate.custom',
      message(component) {
        return component.t(component.errorMessage('custom'), {
          field: component.errorLabel,
          data: component.data
        });
      },
      check(component, setting, value, data) {
        if (!setting) {
          return true;
        }
        const valid = component.evaluate(setting, {
          valid: true,
          data,
          input: value
        }, 'valid', true);
        if (valid === null) {
          return true;
        }
        return valid;
      }
    },
    maxDate: {
      key: 'maxDate',
      message(component, setting) {
        const date = getDateSetting(setting);
        return component.t(component.errorMessage('maxDate'), {
          field: component.errorLabel,
          maxDate: moment(date).format(component.format),
        });
      },
      check(component, setting, value) {
        const date = moment(value);
        const maxDate = getDateSetting(setting);

        if (_.isNull(maxDate)) {
          return true;
        }
        else {
          maxDate.setHours(0,0,0,0);
        }

        return date.isBefore(maxDate) || date.isSame(maxDate);
      }
    },
    minDate: {
      key: 'minDate',
      message(component, setting) {
        const date = getDateSetting(setting);
        return component.t(component.errorMessage('minDate'), {
          field: component.errorLabel,
          minDate: moment(date).format(component.format),
        });
      },
      check(component, setting, value) {
        const date = moment(value);
        const minDate = getDateSetting(setting);
        if (_.isNull(minDate)) {
          return true;
        }
        else {
          minDate.setHours(0,0,0,0);
        }

        return date.isAfter(minDate) || date.isSame(minDate);
      }
    }
  }
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import { editBook } from '../actions/index';
import { Link } from 'react-router';

class BookEdit extends Component{

    //like props, don't abuse it. Only use it with router
    static contextTypes = {
        router: PropTypes.object
    };

    onSubmit(props){
        props.reviewer = this.props.bookObject.reviews[0].reviewer;
        props.review_id = location.pathname.split('/').pop();
        props.dateEdited = new Date().toUTCString();
        this.props.editBook(props)
            .then(()=>{
                //blog Book has been created, navigate the user to the index
                this.context.router.push("/books/"+this.props.bookObject.book.id);
            });
    }

    render(){

        const { fields:{review}, handleSubmit } = this.props;

        return(
            <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>

Edit your review

                <div className={`form-group ${review.touched && review.invalid ? 'has-danger' : ''}`}>
                    review
                    <textarea className="form-control" { ...review }/>

                        {review.touched ? review.error : ''}

                <button type="submit" className="btn btn-primary">Submit</button>
                <Link to={`/books/${this.props.bookObject.book.id}`} className="btn btn-danger">Cancel</Link>
            </form>
        );
    }
}

function validate(values) {
    const errors = {};

    if(!values.review){
        errors.review = 'Enter some review';
    }

    return errors;
}

//recuxForm has the same behavior as "connect"
//connect: first argument is mapStateToProps, second argument is mapDispatchToProps
//reduxForm: 1st is form config, 2nd is mapStateToProps, 3rd is mapDispatchToProps

function mapStateToProps(state) {
    return {
        bookObject: state.books.book
    }
}

export default reduxForm({
    form: 'BooksNewForm',
    fields: ['review'],
    validate
}, mapStateToProps, { editBook})(BookEdit);<commit_msg>fixed bookEdit<commit_after>import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import { editBook } from '../actions/index';
import { Link } from 'react-router';
import AuthService from '../utils/AuthService'

class BookEdit extends Component{

    //like props, don't abuse it. Only use it with router
    static contextTypes = {
        router: PropTypes.object
    };

    static propTypes = {
        auth: PropTypes.instanceOf(AuthService)
    };

    constructor(props, context) {
        super(props, context);
        this.state = {
            profile: props.auth.getProfile()
        };
        // listen to profile_updated events to update internal state
        props.auth.on('profile_updated', (newProfile) => {
            this.setState({profile: newProfile})
        })
    }
    onSubmit(props){
        props.reviewer = this.state.profile;
        props.review_id = location.pathname.split('/').pop();
        props.dateEdited = new Date().toUTCString();
        this.props.editBook(props)
            .then(()=>{
                //blog Book has been created, navigate the user to the index
                this.context.router.push("/books/"+this.props.bookObject.book.id);
            });
    }

    render(){

        const { fields:{review}, handleSubmit } = this.props;

        return(
            <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>

Edit your review

                <div className={`form-group ${review.touched && review.invalid ? 'has-danger' : ''}`}>
                    review
                    <textarea className="form-control" { ...review }/>

                        {review.touched ? review.error : ''}

                <button type="submit" className="btn btn-primary">Submit</button>
                <Link to={`/books/${this.props.bookObject.book.id}`} className="btn btn-danger">Cancel</Link>
            </form>
        );
    }
}

function validate(values) {
    const errors = {};

    if(!values.review){
        errors.review = 'Enter some review';
    }

    return errors;
}

//recuxForm has the same behavior as "connect"
//connect: first argument is mapStateToProps, second argument is mapDispatchToProps
//reduxForm: 1st is form config, 2nd is mapStateToProps, 3rd is mapDispatchToProps

function mapStateToProps(state) {
    return {
        bookObject: state.books.book
    }
}

export default reduxForm({
    form: 'BooksNewForm',
    fields: ['review'],
    validate
}, mapStateToProps, { editBook})(BookEdit);<|endoftext|>


<commit_before>'use strict';

var ImageViz = require('lightning-image');
var utils = require('lightning-client-utils');
var validator = require("geojson-validation");
var _ = require('lodash');
var L;
var F;
var d3 = require('d3');

var fs = require('fs');
var css = fs.readFileSync(__dirname + '/style.css');
var template = _.template(fs.readFileSync(__dirname + '/templates/index.html'));

var hullAlgMap = {
    concave: 'Wildhoney/ConcaveHull',
    convex: 'brian3kb/graham_scan_js'
}

/*
 * Extend the base visualization object
 */
var Visualization = ImageViz.extend({

    init: function() {

        // wait until domready to require leaflet
        L = require('leaflet');
        F = require('leaflet.freedraw-browserify');
        F(L);

        this.identifier = utils.getUniqueId();
        var markup = template({identifier: this.identifier});
        this.$el = $(this.selector).first();
        this.$el.append(markup);
        this.render();
    },

    getDefaultOptions: function() {
        return {
            hullAlgorithm: 'concave'
        }
    },

    render: function() {
        this.img = new Image();
        this.img.onload = this.onImageLoad.bind(this);
        this.img.src = utils.cleanImageURL(this.images[0]);
    },

    css: css,

    onImageLoad: function() {

        var img = this.img
        var data = this.data
        var maxWidth = this.width
        var self = this

        // get image dimensions
        var imw = img.width;
        var imh = img.height;

        // use image dimensions to set css
        var w = maxWidth,
            h = maxWidth * (imh / imw);

        this.$el.find('#image-map-' + this.identifier).width(w).height(h);

        //create the map
        if(this.map) {
            this.map.remove();
        }
        this.map = L.map('image-map-' + this.identifier, {
            minZoom: 1,
            maxZoom: 8,
            center: [w/2, h/2],
            zoom: 1,
            attributionControl: false,
            zoomControl: false,
            crs: L.CRS.Simple,
        });

        var map = this.map;

        // calculate the edges of the image, in coordinate space
        var southWest = map.unproject([0, h], 1);
        var northEast = map.unproject([w, 0], 1);
        var bounds = new L.LatLngBounds(southWest, northEast);

        // add the image overlay to cover the map
        var overlay = L.imageOverlay(img.src, bounds);
        map.addLayer(overlay)

        // tell leaflet that the map is exactly as big as the image
        map.setMaxBounds(bounds);

        // add free drawing
        var freeDraw = new L.FreeDraw({
          mode: L.FreeDraw.MODES.CREATE | L.FreeDraw.MODES.DELETE | L.FreeDraw.MODES.DELETE,
        });

        // set free drawing options
        freeDraw.options.attemptMerge = false;
        freeDraw.options.setHullAlgorithm(hullAlgMap[this.options.hullAlgorithm]);
        freeDraw.options.setSmoothFactor(0);

        // add the free drawing layer
        map.addLayer(freeDraw);

        var COLOR_MODES

        // initialize with any polygons from the data
        if (!_.isEmpty(data)) {

            var polygons = data.polygons;

            polygons = polygons.map(function (g) {
                var converted = [];
                g.map(function (p) {
                    var newp = new L.point(p[0] / (imw / w), p[1] / (imh / h), false);
                    var newpoint = map.unproject(newp, 1);
                    converted.push(newpoint);
                });
                return converted;
            });

            freeDraw.options.simplifyPolygon = false;
            polygons.forEach(function (g) {
                freeDraw.createPolygon(g, true);
            });
            freeDraw.options.simplifyPolygon = true;

            COLOR_MODES = ['white', 'bright', 'data-white'];
            var colorIndex = 2;

            getUserData()

        } else {

            COLOR_MODES = ['white', 'bright'];
            var colorIndex = 0;

        }

        d3.select(this.$el[0]).on('keydown', keydown).on('keyup', keyup);

        updateStyles();

        function updateStyles() {

            var c;
            if(COLOR_MODES[colorIndex].indexOf('white') > -1) {
                c = d3.hsl('rgb(255,255,255)');
            } else if (COLOR_MODES[colorIndex].indexOf('bright') > -1) {
                c = d3.hsl('rgb(240,30,110)');
            }

            var isData = (data.color && COLOR_MODES[colorIndex].indexOf('data') > -1);

            d3.select(self.$el[0])
               .selectAll('.image-map g path.leaflet-freedraw-polygon')
               .style('stroke', function(d, i) {
                if(isData && i < data.color.length) {
                    return data.color[i];
                }
                return c;
               })
               .style('fill', function(d, i) {
                var fill;
                if(isData && i < data.color.length) {
                    fill = d3.hsl(data.color[i]);
                } else {
                    fill = c;
                }
                return fill.brighter(1.2).toString();
               });

        }

        var mod = function(x, n) {
            return ((x%n)+n)%n;
        };

        function keydown() {
            if (d3.event.altKey) {
                freeDraw.setMode(L.FreeDraw.MODES.EDIT);
            }
            if (d3.event.metaKey | d3.event.shiftKey) {
                freeDraw.setMode(L.FreeDraw.MODES.VIEW);
            }
            if (d3.event.shiftKey & (d3.event.keyCode == 37 | d3.event.keyCode == 39)) {
                d3.event.preventDefault();
                if (d3.event.keyCode == 37) {
                    colorIndex = mod(colorIndex - 1, COLOR_MODES.length);
                }
                if (d3.event.keyCode == 39) {
                    colorIndex = mod(colorIndex + 1, COLOR_MODES.length);
                }
                updateStyles();
            }
        }

        function keyup() {
            freeDraw.setMode(L.FreeDraw.MODES.CREATE | L.FreeDraw.MODES.DELETE)
        }

        this.emit('image:loaded');

        function getUserData() {
            // extract coordinates from regions
            var n = freeDraw.memory.states.length;
            var coords = freeDraw.memory.states[n-1].map( function(d) {
                var points = [];
                d.forEach(function (p) {
                    var newpoint = map.project(p, 1);
                    newpoint.x *= (imw / w);
                    newpoint.y *= (imh / h);
                    points.push([newpoint.x, newpoint.y]);
                });
                return points;
            });

            utils.sendCommMessage(self, 'selection', coords);
            utils.updateSettings(self, {
                coords: coords
            }, function(err) {
                if(err) {
                    console.log('err saving user data');
                    console.log(err);
                }
            });
        }

        this.$el.unbind().click(function() {
            getUserData()
        });

        var coords

        utils.getSettings(this, function(err, settings) {
            if(!err) {
                coords = settings.coords;
            }
        });

        freeDraw.on('markers', updateStyles);
        freeDraw.on('destroy', function(d) {

            var i = d.index;

            if(data.color && _.isArray(data.color)) {
                data.color.splice(i, 1);

                if(data.color.length === 0) {
                    colorIndex = 0;
                    COLOR_MODES = ['white', 'bright'];
                }
            }

            getUserData()
            updateStyles()
        })

        this.map = map
        this.bounds = bounds
        this.overlay = overlay
    },

    formatData: function(data) {
        if (!_.isEmpty(data)) {

            var polygons = []

            if (validator.isFeatureCollection(data)) {
                data.features.forEach(function(d) {
                    if (validator.isFeature(d)) {
                        if (validator.isPolygon(d.geometry)) {
                            polygons.push(d.geometry.coordinates[0])
                        }
                    }
                })
            } else if (data.coordinates) {
                polygons = data.coordinates
            } else {
                throw "Input data not understood"
            }

            var retColor = utils.getColorFromData(data);
            if (retColor.length == 0) {
                retColor = utils.getColors(polygons.length)
            } else if (retColor.length == 1) {
                retColor = _.range(polygons.length).map(function () { return retColor })
            }

            data.color = retColor
            data.polygons = polygons
        }

        return data
    },

    updateData: function(formattedData) {
        this.data = formattedData;
        /*
        // FILL IN Re-render your visualization
        */
    },

    appendData: function(formattedData) {
        /*
        // FILL IN Update this.data to include the newly formatted data
        // FILL IN Re-render the visualization
        */
    }

});

module.exports = Visualization;
<commit_msg>don't use global<commit_after>'use strict';

var ImageViz = require('lightning-image');
var utils = require('lightning-client-utils');
var validator = require("geojson-validation");
var _ = require('lodash');
var L;
var F;
var d3 = require('d3');
var $ = require('jquery');

var fs = require('fs');
var css = fs.readFileSync(__dirname + '/style.css');
var template = _.template(fs.readFileSync(__dirname + '/templates/index.html'));

var hullAlgMap = {
    concave: 'Wildhoney/ConcaveHull',
    convex: 'brian3kb/graham_scan_js'
}

/*
 * Extend the base visualization object
 */
var Visualization = ImageViz.extend({

    init: function() {

        // wait until domready to require leaflet
        L = require('leaflet');
        F = require('leaflet.freedraw-browserify');
        F(L);

        this.identifier = utils.getUniqueId();
        var markup = template({identifier: this.identifier});
        this.$el = $(this.selector).first();
        this.$el.append(markup);
        this.render();
    },

    getDefaultOptions: function() {
        return {
            hullAlgorithm: 'concave'
        }
    },

    render: function() {
        this.img = new Image();
        this.img.onload = this.onImageLoad.bind(this);
        this.img.src = utils.cleanImageURL(this.images[0]);
    },

    css: css,

    onImageLoad: function() {

        var img = this.img
        var data = this.data
        var maxWidth = this.width
        var self = this

        // get image dimensions
        var imw = img.width;
        var imh = img.height;

        // use image dimensions to set css
        var w = maxWidth,
            h = maxWidth * (imh / imw);

        this.$el.find('#image-map-' + this.identifier).width(w).height(h);

        //create the map
        if(this.map) {
            this.map.remove();
        }
        this.map = L.map('image-map-' + this.identifier, {
            minZoom: 1,
            maxZoom: 8,
            center: [w/2, h/2],
            zoom: 1,
            attributionControl: false,
            zoomControl: false,
            crs: L.CRS.Simple,
        });

        var map = this.map;

        // calculate the edges of the image, in coordinate space
        var southWest = map.unproject([0, h], 1);
        var northEast = map.unproject([w, 0], 1);
        var bounds = new L.LatLngBounds(southWest, northEast);

        // add the image overlay to cover the map
        var overlay = L.imageOverlay(img.src, bounds);
        map.addLayer(overlay)

        // tell leaflet that the map is exactly as big as the image
        map.setMaxBounds(bounds);

        // add free drawing
        var freeDraw = new L.FreeDraw({
          mode: L.FreeDraw.MODES.CREATE | L.FreeDraw.MODES.DELETE | L.FreeDraw.MODES.DELETE,
        });

        // set free drawing options
        freeDraw.options.attemptMerge = false;
        freeDraw.options.setHullAlgorithm(hullAlgMap[this.options.hullAlgorithm]);
        freeDraw.options.setSmoothFactor(0);

        // add the free drawing layer
        map.addLayer(freeDraw);

        var COLOR_MODES

        // initialize with any polygons from the data
        if (!_.isEmpty(data)) {

            var polygons = data.polygons;

            polygons = polygons.map(function (g) {
                var converted = [];
                g.map(function (p) {
                    var newp = new L.point(p[0] / (imw / w), p[1] / (imh / h), false);
                    var newpoint = map.unproject(newp, 1);
                    converted.push(newpoint);
                });
                return converted;
            });

            freeDraw.options.simplifyPolygon = false;
            polygons.forEach(function (g) {
                freeDraw.createPolygon(g, true);
            });
            freeDraw.options.simplifyPolygon = true;

            COLOR_MODES = ['white', 'bright', 'data-white'];
            var colorIndex = 2;

            getUserData()

        } else {

            COLOR_MODES = ['white', 'bright'];
            var colorIndex = 0;

        }

        d3.select(this.$el[0]).on('keydown', keydown).on('keyup', keyup);

        updateStyles();

        function updateStyles() {

            var c;
            if(COLOR_MODES[colorIndex].indexOf('white') > -1) {
                c = d3.hsl('rgb(255,255,255)');
            } else if (COLOR_MODES[colorIndex].indexOf('bright') > -1) {
                c = d3.hsl('rgb(240,30,110)');
            }

            var isData = (data.color && COLOR_MODES[colorIndex].indexOf('data') > -1);

            d3.select(self.$el[0])
               .selectAll('.image-map g path.leaflet-freedraw-polygon')
               .style('stroke', function(d, i) {
                if(isData && i < data.color.length) {
                    return data.color[i];
                }
                return c;
               })
               .style('fill', function(d, i) {
                var fill;
                if(isData && i < data.color.length) {
                    fill = d3.hsl(data.color[i]);
                } else {
                    fill = c;
                }
                return fill.brighter(1.2).toString();
               });

        }

        var mod = function(x, n) {
            return ((x%n)+n)%n;
        };

        function keydown() {
            if (d3.event.altKey) {
                freeDraw.setMode(L.FreeDraw.MODES.EDIT);
            }
            if (d3.event.metaKey | d3.event.shiftKey) {
                freeDraw.setMode(L.FreeDraw.MODES.VIEW);
            }
            if (d3.event.shiftKey & (d3.event.keyCode == 37 | d3.event.keyCode == 39)) {
                d3.event.preventDefault();
                if (d3.event.keyCode == 37) {
                    colorIndex = mod(colorIndex - 1, COLOR_MODES.length);
                }
                if (d3.event.keyCode == 39) {
                    colorIndex = mod(colorIndex + 1, COLOR_MODES.length);
                }
                updateStyles();
            }
        }

        function keyup() {
            freeDraw.setMode(L.FreeDraw.MODES.CREATE | L.FreeDraw.MODES.DELETE)
        }

        this.emit('image:loaded');

        function getUserData() {
            // extract coordinates from regions
            var n = freeDraw.memory.states.length;
            var coords = freeDraw.memory.states[n-1].map( function(d) {
                var points = [];
                d.forEach(function (p) {
                    var newpoint = map.project(p, 1);
                    newpoint.x *= (imw / w);
                    newpoint.y *= (imh / h);
                    points.push([newpoint.x, newpoint.y]);
                });
                return points;
            });

            utils.sendCommMessage(self, 'selection', coords);
            utils.updateSettings(self, {
                coords: coords
            }, function(err) {
                if(err) {
                    console.log('err saving user data');
                    console.log(err);
                }
            });
        }

        this.$el.unbind().click(function() {
            getUserData()
        });

        var coords

        utils.getSettings(this, function(err, settings) {
            if(!err && settings) {
                coords = settings.coords;
            }
        });

        freeDraw.on('markers', updateStyles);
        freeDraw.on('destroy', function(d) {

            var i = d.index;

            if(data.color && _.isArray(data.color)) {
                data.color.splice(i, 1);

                if(data.color.length === 0) {
                    colorIndex = 0;
                    COLOR_MODES = ['white', 'bright'];
                }
            }

            getUserData()
            updateStyles()
        })

        this.map = map
        this.bounds = bounds
        this.overlay = overlay
    },

    formatData: function(data) {
        if (!_.isEmpty(data)) {

            var polygons = []

            if (validator.isFeatureCollection(data)) {
                data.features.forEach(function(d) {
                    if (validator.isFeature(d)) {
                        if (validator.isPolygon(d.geometry)) {
                            polygons.push(d.geometry.coordinates[0])
                        }
                    }
                })
            } else if (data.coordinates) {
                polygons = data.coordinates
            } else {
                throw "Input data not understood"
            }

            var retColor = utils.getColorFromData(data);
            if (retColor.length == 0) {
                retColor = utils.getColors(polygons.length)
            } else if (retColor.length == 1) {
                retColor = _.range(polygons.length).map(function () { return retColor })
            }

            data.color = retColor
            data.polygons = polygons
        }

        return data
    },

    updateData: function(formattedData) {
        this.data = formattedData;
        /*
        // FILL IN Re-render your visualization
        */
    },

    appendData: function(formattedData) {
        /*
        // FILL IN Update this.data to include the newly formatted data
        // FILL IN Re-render the visualization
        */
    }

});

module.exports = Visualization;
<|endoftext|>


<commit_before>import shallowEqual from '../utils/shallowEqual';
import wrapActionCreators from '../utils/wrapActionCreators';
import invariant from 'invariant';
import _ from 'lodash';

const defaultMapStateToTarget = () => ({});
const defaultMapDispatchToTarget = dispatch => ({dispatch});

export default function Connector(store) {
  return (mapStateToTarget, mapDispatchToTarget) => {

    const finalMapStateToTarget = mapStateToTarget || defaultMapStateToTarget;

    const finalMapDispatchToTarget = _.isPlainObject(mapDispatchToTarget) ?
      wrapActionCreators(mapDispatchToTarget) :
      mapDispatchToTarget || defaultMapDispatchToTarget;

    invariant(
      _.isFunction(finalMapStateToTarget),
      'mapStateToTarget must be a Function. Instead received $s.', finalMapStateToTarget
      );

    invariant(
      _.isPlainObject(finalMapDispatchToTarget) || _.isFunction(finalMapDispatchToTarget),
      'mapDispatchToTarget must be a plain Object or a Function. Instead received $s.', finalMapDispatchToTarget
      );

    let slice = getStateSlice(store.getState(), finalMapStateToTarget);

    const boundActionCreators = finalMapDispatchToTarget(store.dispatch);

    return (target) => {

      invariant(
        _.isFunction(target) || _.isObject(target),
        'The target parameter passed to connect must be a Function or a plain object.'
        );

      //Initial update
      updateTarget(target, slice, boundActionCreators);

      const unsubscribe = store.subscribe(() => {
        const nextSlice = getStateSlice(store.getState(), finalMapStateToTarget);
        if (!shallowEqual(slice, nextSlice)) {
          slice = nextSlice;
          updateTarget(target, slice, boundActionCreators);
        }
      });
      return unsubscribe;
    }

  }
}

function updateTarget(target, StateSlice, dispatch) {
  if(_.isFunction(target)) {
    target(StateSlice, dispatch);
  } else {
    _.assign(target, StateSlice, dispatch);
  }
}

function getStateSlice(state, mapStateToScope) {
  const slice = mapStateToScope(state);

  invariant(
    _.isPlainObject(slice),
    '`mapStateToScope` must return an object. Instead received %s.',
    slice
    );

  return slice;
}<commit_msg>fix: Corrects target type to 'object' instead of 'plain object' in comment<commit_after>import shallowEqual from '../utils/shallowEqual';
import wrapActionCreators from '../utils/wrapActionCreators';
import invariant from 'invariant';
import _ from 'lodash';

const defaultMapStateToTarget = () => ({});
const defaultMapDispatchToTarget = dispatch => ({dispatch});

export default function Connector(store) {
  return (mapStateToTarget, mapDispatchToTarget) => {

    const finalMapStateToTarget = mapStateToTarget || defaultMapStateToTarget;

    const finalMapDispatchToTarget = _.isPlainObject(mapDispatchToTarget) ?
      wrapActionCreators(mapDispatchToTarget) :
      mapDispatchToTarget || defaultMapDispatchToTarget;

    invariant(
      _.isFunction(finalMapStateToTarget),
      'mapStateToTarget must be a Function. Instead received $s.', finalMapStateToTarget
      );

    invariant(
      _.isPlainObject(finalMapDispatchToTarget) || _.isFunction(finalMapDispatchToTarget),
      'mapDispatchToTarget must be a plain Object or a Function. Instead received $s.', finalMapDispatchToTarget
      );

    let slice = getStateSlice(store.getState(), finalMapStateToTarget);

    const boundActionCreators = finalMapDispatchToTarget(store.dispatch);

    return (target) => {

      invariant(
        _.isFunction(target) || _.isObject(target),
        'The target parameter passed to connect must be a Function or a object.'
        );

      //Initial update
      updateTarget(target, slice, boundActionCreators);

      const unsubscribe = store.subscribe(() => {
        const nextSlice = getStateSlice(store.getState(), finalMapStateToTarget);
        if (!shallowEqual(slice, nextSlice)) {
          slice = nextSlice;
          updateTarget(target, slice, boundActionCreators);
        }
      });
      return unsubscribe;
    }

  }
}

function updateTarget(target, StateSlice, dispatch) {
  if(_.isFunction(target)) {
    target(StateSlice, dispatch);
  } else {
    _.assign(target, StateSlice, dispatch);
  }
}

function getStateSlice(state, mapStateToScope) {
  const slice = mapStateToScope(state);

  invariant(
    _.isPlainObject(slice),
    '`mapStateToScope` must return an object. Instead received %s.',
    slice
    );

  return slice;
}<|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');

var Modal = require('react-bootstrap').Modal;
var ButtonGroup = require('react-bootstrap').ButtonGroup;
var Button = require('react-bootstrap').Button;
var ButtonToolbar = require('react-bootstrap').ButtonToolbar;
var Input = require('react-bootstrap').Input;
var Collapse = require('react-bootstrap').Collapse;
var Well = require('react-bootstrap').Well;

var MySmallModal = React.createClass({
    render() {
        return (
            <Modal {...this.props} bsSize="small" aria-labelledby="contained-modal-title-sm">
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-sm">Contact Form</Modal.Title>
                </Modal.Header>
                <Modal.Body>

<MyContactForm {...this.props} />

                </Modal.Body>
                <Modal.Footer>

                </Modal.Footer>
            </Modal>
        );
    }
});

/*Antibiotic 21.01.2016
* Collapsing Button in general use for Rules and Conditions
* But can extends any text
*/
class RulesAndConditions extends React.Component {
    constructor(...args) {
        super(...args);

        this.state = {};
    }

    render() {
        return (

                <Button onClick={ ()=> this.setState({ open: !this.state.open })} >
                    Rules and Conditions
                </Button>
                <Collapse in={this.state.open}>

                        <Well>
                            {this.props.children}
                        </Well>

                </Collapse>

        );
    }
}

/* Antibiotic 21.01.2016
 * Contact form
 * Extends props from Modal on call
 * The Close Button use extended props from Modal to close parent Modal
*/
var MyContactForm = React.createClass({

    getInitialState() {
        return {
            disabled: true
        };
    },

    handleChange(event) {
        var checked = event.target.checked
        if(checked) {
            this.setState({
                disabled: !event.target.checked
            });
        } else {
            this.setState({
                disabled: !event.target.checked
            });

        }
    },

    render: function() {
        return (
            <form>
                <Input type="text" label="Name" placeholder="Your Name" bsSize="large" />
                <Input type="email" label="Email" placeholder="Your Email" bsSize="large"/>
                <Input type="textarea" label="Massage" placeholder="Please tell me more" bsSize="large"/>

                <RulesAndConditions>Rules and Conditions</RulesAndConditions>
                <Input ref="MyCheckbox" onChange={this.handleChange} type="checkbox" label="Confirm" readOnly bsSize="large"/>

                <ButtonGroup vertical block>
                    <Button type="reset" bsStyle="warning" bsSize="large">Reset</Button>

                    <Button ref="submitButton" type="submit" bsStyle="success" bsSize="large" disabled={this.state.disabled}
                           >Submit</Button>

                    <Button onClick={this.props.onHide} bsStyle="danger" bsSize="large">Close</Button>
                </ButtonGroup>
            </form>
        )
    }
});

/* Antibiotic 21.01.2016
 * This App creating Button
 * And call Modal MySmallModal with passed props
*/
var App = React.createClass({
    getInitialState() {
        return { smShow: false};
    },

    showModal() {
        this.setState({show: true});
    },

    hideModal() {
        this.setState({show: false});
    },

    render() {
        let smClose = () => this.setState({ smShow: false });

        return (
            <ButtonToolbar>
                <Button bsStyle="primary" onClick={()=>this.setState({ smShow: true })}>
                    Contact Form
                </Button>

                <MySmallModal show={this.state.smShow} onHide={smClose} />
            </ButtonToolbar>
        );
    }
});

ReactDOM.render(<App />, document.getElementById('booking'));<commit_msg>enable button on two events<commit_after>var React = require('react');
var ReactDOM = require('react-dom');

var Modal = require('react-bootstrap').Modal;
var ButtonGroup = require('react-bootstrap').ButtonGroup;
var Button = require('react-bootstrap').Button;
var ButtonToolbar = require('react-bootstrap').ButtonToolbar;
var Input = require('react-bootstrap').Input;
var Collapse = require('react-bootstrap').Collapse;
var Well = require('react-bootstrap').Well;

var MySmallModal = React.createClass({
    render() {
        return (
            <Modal {...this.props} bsSize="small" aria-labelledby="contained-modal-title-sm">
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-sm">Contact Form</Modal.Title>
                </Modal.Header>
                <Modal.Body>

<MyContactForm {...this.props} />

                </Modal.Body>
                <Modal.Footer>

                </Modal.Footer>
            </Modal>
        );
    }
});

/*Antibiotic 21.01.2016
* Collapsing Button in general use for Rules and Conditions
* But can extends any text
*/
class RulesAndConditions extends React.Component {
    constructor(...args) {
        super(...args);

        this.state = {};
    }

    render() {
        return (

                <Button onClick={ ()=> this.setState({ open: !this.state.open })} >
                    Rules and Conditions
                </Button>
                <Collapse in={this.state.open}>

                        <Well>
                            {this.props.children}
                        </Well>

                </Collapse>

        );
    }
}

/* Antibiotic 21.01.2016
 * Contact form
 * Extends props from Modal on call
 * The Close Button use extended props from Modal to close parent Modal
*/
var MyContactForm = React.createClass({

    getInitialState() {
        return {
            disabled: true,
            style: null
        };
    },

    handleChange(event) {
        this.setState(this.validationState());

        var checked = event.target.checked;
        var style = this.validationState();

        if(checked && (JSON.stringify(style)!=='{"style":"error"}')) {
            this.setState({
                disabled: false
            });
        } else {
            this.setState({
                disabled: true
            });
        }
    },

    /* Antibiotic 26.01.2016
     * function to validate email input
     */
    validationState() {
        var mail = this.refs.mail.getValue();
        var style = "error";

        var re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

        if(!re.test(mail)){
            return{
                style
            }
        }else {
            style = null;
            return{
                style
            }
        }

    },

    render: function() {
        return (
            <form>
                <Input type="text" label="Name" placeholder="Your Name" bsSize="large" />
                <Input type="text" ref="mail" label="Email" placeholder="Your Email" bsSize="large" bsStyle={this.state.style}
                       onChange={this.handleChange} hasFeedback/>
                <Input type="textarea" label="Massage" placeholder="Please tell me more" bsSize="large"/>

                <RulesAndConditions>Rules and Conditions</RulesAndConditions>
                <Input ref="MyCheckbox" onChange={this.handleChange} type="checkbox" label="Confirm" readOnly bsSize="large"/>

                <ButtonGroup vertical block>
                    <Button type="reset" bsStyle="warning" bsSize="large">Reset</Button>

                    <Button ref="submitButton" type="submit" bsStyle="success" bsSize="large" disabled={this.state.disabled}
                           >Submit</Button>

                    <Button onClick={this.props.onHide} bsStyle="danger" bsSize="large">Close</Button>
                </ButtonGroup>
            </form>
        )
    }
});

/* Antibiotic 21.01.2016
 * This App creating Button
 * And call Modal MySmallModal with passed props
*/
var App = React.createClass({
    getInitialState() {
        return { smShow: false};
    },

    showModal() {
        this.setState({show: true});
    },

    hideModal() {
        this.setState({show: false});
    },

    render() {
        let smClose = () => this.setState({ smShow: false });

        return (
            <ButtonToolbar>
                <Button bsStyle="primary" onClick={()=>this.setState({ smShow: true })}>
                    Contact Form
                </Button>

                <MySmallModal show={this.state.smShow} onHide={smClose} />
            </ButtonToolbar>
        );
    }
});

ReactDOM.render(<App />, document.getElementById('booking'));<|endoftext|>


<commit_before>import _ from 'lodash';
import Component from '../_classes/component/Component';
import EventEmitter from 'eventemitter2';
import NativePromise from 'native-promise-only';
import { isMongoId, eachComponent } from '../../utils/utils';
import Formio from '../../Formio';
import Form from '../../Form';

export default class FormComponent extends Component {
  static schema(...extend) {
    return Component.schema({
      label: 'Form',
      type: 'form',
      key: 'form',
      src: '',
      reference: true,
      form: '',
      path: '',
      tableView: true,
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Nested Form',
      icon: 'wpforms',
      group: 'premium',
      documentation: 'http://help.form.io/userguide/#form',
      weight: 110,
      schema: FormComponent.schema()
    };
  }

  init() {
    super.init();
    this.formObj = {
      display: this.component.display,
      settings: this.component.settings,
      components: this.component.components
    };
    this.subForm = null;
    this.formSrc = '';
    if (this.component.src) {
      this.formSrc = this.component.src;
    }

    if (
      !this.component.src &&
      !this.options.formio &&
      (this.component.form || this.component.path)
    ) {
      if (this.component.project) {
        this.formSrc = Formio.getBaseUrl();
        // Check to see if it is a MongoID.
        if (isMongoId(this.component.project)) {
          this.formSrc += '/project';
        }
        this.formSrc += `/${this.component.project}`;
        this.options.project = this.formSrc;
      }
      else {
        this.formSrc = Formio.getProjectUrl();
        this.options.project = this.formSrc;
      }
      if (this.component.form) {
        this.formSrc += `/form/${this.component.form}`;
      }
      else if (this.component.path) {
        this.formSrc += `/${this.component.path}`;
      }
    }

    // Build the source based on the root src path.
    if (!this.formSrc && this.options.formio) {
      const rootSrc = this.options.formio.formsUrl;
      if (this.component.path) {
        const parts = rootSrc.split('/');
        parts.pop();
        this.formSrc = `${parts.join('/')}/${this.component.path}`;
      }
      if (this.component.form) {
        this.formSrc = `${rootSrc}/${this.component.form}`;
      }
    }

    // Add revision version if set.
    if (this.component.formRevision || this.component.formRevision === 0) {
      this.formSrc += `/v/${this.component.formRevision}`;
    }
  }

  get dataReady() {
    return this.subFormReady || NativePromise.resolve();
  }

  get defaultSchema() {
    return FormComponent.schema();
  }

  get emptyValue() {
    return { data: {} };
  }

  get ready() {
    return this.subFormReady || NativePromise.resolve();
  }

  getSubOptions(options = {}) {
    if (!this.options) {
      return options;
    }
    if (this.options.base) {
      options.base = this.options.base;
    }
    if (this.options.project) {
      options.project = this.options.project;
    }
    if (this.options.readOnly) {
      options.readOnly = this.options.readOnly;
    }
    if (this.options.breadcrumbSettings) {
      options.breadcrumbSettings = this.options.breadcrumbSettings;
    }
    if (this.options.buttonSettings) {
      options.buttonSettings = this.options.buttonSettings;
    }
    if (this.options.viewAsHtml) {
      options.viewAsHtml = this.options.viewAsHtml;
    }
    if (this.options.language) {
      options.language = this.options.language;
    }
    if (this.options.template) {
      options.template = this.options.template;
    }
    if (this.options.templates) {
      options.templates = this.options.templates;
    }
    if (this.options.renderMode) {
      options.renderMode = this.options.renderMode;
    }
    if (this.options.attachMode) {
      options.attachMode = this.options.attachMode;
    }
    if (this.options.iconset) {
      options.iconset = this.options.iconset;
    }
    options.events = this.createEmitter();
    return options;
  }

  render() {
    if (this.builderMode) {
      return super.render(this.component.label || 'Nested form');
    }
    const subform = this.subForm ? this.subForm.render() : this.renderTemplate('loading');
    return super.render(subform);
  }

  asString(value) {
    return this.getValueAsString(value);
  }

  /**
   * Prints out the value of form components as a datagrid value.
   */
  getValueAsString(value) {
    if (!Object.keys(value.data).length) {
      return 'No data provided';
    }
    const columns = Object.keys(value.data).map(column => {
      return {
        key: column,
        label: column,
        hideLabel: false
      };
    });

    return super.render(this.renderTemplate('datagrid', {
      rows: [value.data],
      columns: columns,
      visibleColumns: value.data,
      hasHeader: true,
      numColumns: Object.keys(value.data).length,
    }));
  }

  attach(element) {
    // Don't attach in builder.
    if (this.builderMode) {
      return super.attach(element);
    }
    return super.attach(element).then(() =>
      this.loadSubForm().then(() => {
        // Intentionally do not return... for some reason it doesn't resolve.
        this.subForm.attach(element);
      })
    );
  }

  detach() {
    if (this.subForm) {
      this.subForm.detach();
    }
    super.detach();
  }

  set root(inst) {
    if (!inst) {
      return;
    }
    this._root = inst;
    this.nosubmit = inst.nosubmit;
  }

  get root() {
    return this._root;
  }

  set nosubmit(value) {
    this._nosubmit = !!value;
    if (this.subForm) {
      this.subForm.nosubmit = this._nosubmit;
    }
  }

  get nosubmit() {
    return this._nosubmit || false;
  }

  get currentForm() {
    return this._currentForm;
  }

  set currentForm(instance) {
    this._currentForm = instance;
    if (!this.subForm) {
      return;
    }
    this.subForm.getComponents().forEach(component => {
      component.currentForm = this;
    });
  }

  destroy() {
    if (this.subForm) {
      this.subForm.destroy();
      this.subForm = null;
      this.subFormReady = null;
    }
    super.destroy();
  }

  redraw() {
    if (this.subForm) {
      this.subForm.form = this.formObj;
    }
    return super.redraw();
  }

  /**
   * Pass everyComponent to subform.
   * @param args
   * @returns {*|void}
   */
  everyComponent(...args) {
    if (this.subForm) {
      this.subForm.everyComponent(...args);
    }
  }

  /**
   * Render a subform.
   *
   * @param form
   * @param options
   */
  renderSubForm(form) {
    if (this.options.builder) {
      this.element.appendChild(this.ce('div', {
        class: 'text-muted text-center p-2'
      }, this.text(form.title)));
      return;
    }

    // Iterate through every component and hide the submit button.
    eachComponent(form.components, (component) => {
      if (
        (component.type === 'button') &&
        ((component.action === 'submit') || !component.action)
      ) {
        component.hidden = true;
      }
    });

    // Render the form.
    return (new Form(form, this.getSubOptions())).ready.then((instance) => {
      this.subForm = instance;
      this.subForm.currentForm = this;
      this.subForm.parent = this;
      this.subForm.parentVisible = this.visible;
      this.subForm.on('change', () => {
        if (this.subForm) {
          this.dataValue = this.subForm.getValue();
          this.triggerChange({
            noEmit: true
          });
        }
      });
      this.subForm.url = this.formSrc;
      this.subForm.nosubmit = this.nosubmit;
      this.redraw();
      this.subForm.root = this.root;
      return this.subForm;
    });
  }

  show(...args) {
    const state = super.show(...args);
    if (!this.subFormReady && state) {
      this.loadSubForm();
    }
    return state;
  }

  /**
   * Load the subform.
   */
  loadSubForm() {
    if (this.builderMode || this.isHidden()) {
      return NativePromise.resolve();
    }

    // Only load the subform if the subform isn't loaded and the conditions apply.
    if (this.subFormReady) {
      return this.subFormReady;
    }

    // Determine if we already have a loaded form object.
    if (
      this.formObj &&
      this.formObj.components &&
      Array.isArray(this.formObj.components) &&
      this.formObj.components.length
    ) {
      this.subFormReady = this.renderSubForm(this.formObj);
    }
    else if (this.formSrc) {
      this.subFormReady = (new Formio(this.formSrc)).loadForm({ params: { live: 1 } })
        .then((formObj) => {
          this.formObj = formObj;
          return this.renderSubForm(formObj);
        });
    }
    if (!this.subFormReady) {
      return new NativePromise(() => {});
    }
    return this.subFormReady.then(() => this.restoreValue());
  }

  checkComponentValidity(data, dirty) {
    if (this.subForm) {
      return this.subForm.checkValidity(this.dataValue.data, dirty);
    }

    return super.checkComponentValidity(data, dirty);
  }

  checkComponentConditions(data) {
    const visible = super.checkComponentConditions(data);

    // Return if already hidden
    if (!visible) {
      return visible;
    }

    if (this.subForm && this.subForm.hasCondition()) {
      return this.subForm.checkConditions(this.dataValue.data);
    }

    return visible;
  }

  calculateValue(data, flags) {
    if (this.subForm) {
      return this.subForm.calculateValue(this.dataValue.data, flags);
    }

    return super.calculateValue(data, flags);
  }

  setPristine(pristine) {
    super.setPristine(pristine);
    if (this.subForm) {
      this.subForm.setPristine(pristine);
    }
  }

  /**
   * Determine if the subform should be submitted.
   * @return {*|boolean}
   */
  get shouldSubmit() {
    return this.subFormReady && (!this.component.hasOwnProperty('reference') || this.component.reference);
  }

  /**
   * Returns the data for the subform.
   *
   * @return {*}
   */
  getSubFormData() {
    if (_.get(this.subForm, 'form.display') === 'pdf') {
      return this.subForm.getSubmission();
    }
    else {
      return NativePromise.resolve(this.dataValue);
    }
  }

  /**
   * Submit the subform if configured to do so.
   *
   * @return {*}
   */
  submitSubForm(rejectOnError) {
    // If we wish to submit the form on next page, then do that here.
    if (this.shouldSubmit) {
      return this.loadSubForm().then(() => {
        return this.subForm.submitForm().then(result => {
          this.subForm.loading = false;
          this.dataValue = result.submission;
          return this.dataValue;
        }).catch(err => {
          if (rejectOnError) {
            this.subForm.onSubmissionError(err);
            return NativePromise.reject(err);
          }
          else {
            return {};
          }
        });
      });
    }
    return this.getSubFormData();
  }

  /**
   * Submit the form before the next page is triggered.
   */
  beforePage(next) {
    return this.submitSubForm(true).then(() => super.beforePage(next));
  }

  /**
   * Submit the form before the whole form is triggered.
   */
  beforeSubmit() {
    const submission = this.dataValue;

    // This submission has already been submitted, so just return the reference data.
    if (submission && submission._id && submission.form) {
      this.dataValue = this.shouldSubmit ? {
        _id: submission._id,
        form: submission.form
      } : submission;
      return NativePromise.resolve(this.dataValue);
    }
    return this.submitSubForm(false)
      .then((data) => {
        if (data._id) {
          this.dataValue = {
            _id: data._id,
            form: data.form
          };
        }
        return this.dataValue;
      })
      .then(() => super.beforeSubmit());
  }

  isHidden() {
    if (!this.visible) {
      return true;
    }

    return !super.checkConditions(this.rootValue);
  }

  setValue(submission, flags) {
    const changed = super.setValue(submission, flags);
    if (this.subFormReady) {
      this.subFormReady.then((form) => {
        if (
          submission &&
          submission._id &&
          form.formio &&
          !flags.noload &&
          (_.isEmpty(submission.data) || this.shouldSubmit)
        ) {
          const submissionUrl = `${form.formio.formsUrl}/${submission.form}/submission/${submission._id}`;
          form.setUrl(submissionUrl, this.options);
          form.nosubmit = false;
          form.loadSubmission();
        }
        else {
          form.setValue(submission, flags);
        }
      });
    }
    return changed;
  }

  getValue() {
    if (this.subForm) {
      return this.subForm.getValue();
    }
    return this.dataValue;
  }

  getAllComponents() {
    if (!this.subForm) {
      return [];
    }
    return this.subForm.getAllComponents();
  }

  updateSubFormVisibility() {
    if (this.subForm) {
      this.subForm.parentVisible = this.visible;
    }
  }

  get visible() {
    return super.visible;
  }

  set visible(value) {
    super.visible = value;
    this.updateSubFormVisibility();
  }

  get parentVisible() {
    return super.parentVisible;
  }

  set parentVisible(value) {
    super.parentVisible = value;
    this.updateSubFormVisibility();
  }

  isInternalEvent(event) {
    switch (event) {
      case 'focus':
      case 'blur':
      case 'componentChange':
      case 'componentError':
      case 'error':
      case 'formLoad':
      case 'languageChanged':
      case 'render':
      case 'checkValidity':
      case 'initialized':
      case 'submit':
      case 'submitButton':
      case 'nosubmit':
      case 'updateComponent':
      case 'submitDone':
      case 'submissionDeleted':
      case 'requestDone':
      case 'nextPage':
      case 'prevPage':
      case 'wizardNavigationClicked':
      case 'updateWizardNav':
      case 'restoreDraft':
      case 'saveDraft':
      case 'saveComponent':
        return true;
      default:
        return false;
    }
  }

  createEmitter() {
    const emitter = new EventEmitter({
      wildcard: false,
      maxListeners: 0
    });
    const nativeEmit = emitter.emit;
    const that = this;
    emitter.emit = function(event, ...args) {
      const eventType = event.replace(`${that.options.namespace}.`, '');
      nativeEmit.call(this, event, ...args);
      if (!that.isInternalEvent(eventType)) {
        that.emit(eventType, ...args);
      }
    };

    return emitter;
  }

  deleteValue() {
    super.setValue(null, {
      noUpdateEvent: true,
      noDefault: true
    });
    _.unset(this.data, this.key);
  }
}
<commit_msg>Fixed the to string method for edit grid.<commit_after>import _ from 'lodash';
import Component from '../_classes/component/Component';
import EventEmitter from 'eventemitter2';
import NativePromise from 'native-promise-only';
import { isMongoId, eachComponent } from '../../utils/utils';
import Formio from '../../Formio';
import Form from '../../Form';

export default class FormComponent extends Component {
  static schema(...extend) {
    return Component.schema({
      label: 'Form',
      type: 'form',
      key: 'form',
      src: '',
      reference: true,
      form: '',
      path: '',
      tableView: true,
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Nested Form',
      icon: 'wpforms',
      group: 'premium',
      documentation: 'http://help.form.io/userguide/#form',
      weight: 110,
      schema: FormComponent.schema()
    };
  }

  init() {
    super.init();
    this.formObj = {
      display: this.component.display,
      settings: this.component.settings,
      components: this.component.components
    };
    this.subForm = null;
    this.formSrc = '';
    if (this.component.src) {
      this.formSrc = this.component.src;
    }

    if (
      !this.component.src &&
      !this.options.formio &&
      (this.component.form || this.component.path)
    ) {
      if (this.component.project) {
        this.formSrc = Formio.getBaseUrl();
        // Check to see if it is a MongoID.
        if (isMongoId(this.component.project)) {
          this.formSrc += '/project';
        }
        this.formSrc += `/${this.component.project}`;
        this.options.project = this.formSrc;
      }
      else {
        this.formSrc = Formio.getProjectUrl();
        this.options.project = this.formSrc;
      }
      if (this.component.form) {
        this.formSrc += `/form/${this.component.form}`;
      }
      else if (this.component.path) {
        this.formSrc += `/${this.component.path}`;
      }
    }

    // Build the source based on the root src path.
    if (!this.formSrc && this.options.formio) {
      const rootSrc = this.options.formio.formsUrl;
      if (this.component.path) {
        const parts = rootSrc.split('/');
        parts.pop();
        this.formSrc = `${parts.join('/')}/${this.component.path}`;
      }
      if (this.component.form) {
        this.formSrc = `${rootSrc}/${this.component.form}`;
      }
    }

    // Add revision version if set.
    if (this.component.formRevision || this.component.formRevision === 0) {
      this.formSrc += `/v/${this.component.formRevision}`;
    }
  }

  get dataReady() {
    return this.subFormReady || NativePromise.resolve();
  }

  get defaultSchema() {
    return FormComponent.schema();
  }

  get emptyValue() {
    return { data: {} };
  }

  get ready() {
    return this.subFormReady || NativePromise.resolve();
  }

  getSubOptions(options = {}) {
    if (!this.options) {
      return options;
    }
    if (this.options.base) {
      options.base = this.options.base;
    }
    if (this.options.project) {
      options.project = this.options.project;
    }
    if (this.options.readOnly) {
      options.readOnly = this.options.readOnly;
    }
    if (this.options.breadcrumbSettings) {
      options.breadcrumbSettings = this.options.breadcrumbSettings;
    }
    if (this.options.buttonSettings) {
      options.buttonSettings = this.options.buttonSettings;
    }
    if (this.options.viewAsHtml) {
      options.viewAsHtml = this.options.viewAsHtml;
    }
    if (this.options.language) {
      options.language = this.options.language;
    }
    if (this.options.template) {
      options.template = this.options.template;
    }
    if (this.options.templates) {
      options.templates = this.options.templates;
    }
    if (this.options.renderMode) {
      options.renderMode = this.options.renderMode;
    }
    if (this.options.attachMode) {
      options.attachMode = this.options.attachMode;
    }
    if (this.options.iconset) {
      options.iconset = this.options.iconset;
    }
    options.events = this.createEmitter();
    return options;
  }

  render() {
    if (this.builderMode) {
      return super.render(this.component.label || 'Nested form');
    }
    const subform = this.subForm ? this.subForm.render() : this.renderTemplate('loading');
    return super.render(subform);
  }

  asString(value) {
    return this.getValueAsString(value);
  }

  /**
   * Prints out the value of form components as a datagrid value.
   */
  getValueAsString(value) {
    if (!value) {
      return 'No data provided';
    }
    if (!value.data && value._id) {
      return value._id;
    }
    if (!value.data || !Object.keys(value.data).length) {
      return 'No data provided';
    }
    const columns = Object.keys(value.data).map(column => {
      return {
        key: column,
        label: column,
        hideLabel: false
      };
    });

    return super.render(this.renderTemplate('datagrid', {
      rows: [value.data],
      columns: columns,
      visibleColumns: value.data,
      hasHeader: true,
      numColumns: Object.keys(value.data).length,
    }));
  }

  attach(element) {
    // Don't attach in builder.
    if (this.builderMode) {
      return super.attach(element);
    }
    return super.attach(element).then(() =>
      this.loadSubForm().then(() => {
        // Intentionally do not return... for some reason it doesn't resolve.
        this.subForm.attach(element);
      })
    );
  }

  detach() {
    if (this.subForm) {
      this.subForm.detach();
    }
    super.detach();
  }

  set root(inst) {
    if (!inst) {
      return;
    }
    this._root = inst;
    this.nosubmit = inst.nosubmit;
  }

  get root() {
    return this._root;
  }

  set nosubmit(value) {
    this._nosubmit = !!value;
    if (this.subForm) {
      this.subForm.nosubmit = this._nosubmit;
    }
  }

  get nosubmit() {
    return this._nosubmit || false;
  }

  get currentForm() {
    return this._currentForm;
  }

  set currentForm(instance) {
    this._currentForm = instance;
    if (!this.subForm) {
      return;
    }
    this.subForm.getComponents().forEach(component => {
      component.currentForm = this;
    });
  }

  destroy() {
    if (this.subForm) {
      this.subForm.destroy();
      this.subForm = null;
      this.subFormReady = null;
    }
    super.destroy();
  }

  redraw() {
    if (this.subForm) {
      this.subForm.form = this.formObj;
    }
    return super.redraw();
  }

  /**
   * Pass everyComponent to subform.
   * @param args
   * @returns {*|void}
   */
  everyComponent(...args) {
    if (this.subForm) {
      this.subForm.everyComponent(...args);
    }
  }

  /**
   * Render a subform.
   *
   * @param form
   * @param options
   */
  renderSubForm(form) {
    if (this.options.builder) {
      this.element.appendChild(this.ce('div', {
        class: 'text-muted text-center p-2'
      }, this.text(form.title)));
      return;
    }

    // Iterate through every component and hide the submit button.
    eachComponent(form.components, (component) => {
      if (
        (component.type === 'button') &&
        ((component.action === 'submit') || !component.action)
      ) {
        component.hidden = true;
      }
    });

    // Render the form.
    return (new Form(form, this.getSubOptions())).ready.then((instance) => {
      this.subForm = instance;
      this.subForm.currentForm = this;
      this.subForm.parent = this;
      this.subForm.parentVisible = this.visible;
      this.subForm.on('change', () => {
        if (this.subForm) {
          this.dataValue = this.subForm.getValue();
          this.triggerChange({
            noEmit: true
          });
        }
      });
      this.subForm.url = this.formSrc;
      this.subForm.nosubmit = this.nosubmit;
      this.redraw();
      this.subForm.root = this.root;
      return this.subForm;
    });
  }

  show(...args) {
    const state = super.show(...args);
    if (!this.subFormReady && state) {
      this.loadSubForm();
    }
    return state;
  }

  /**
   * Load the subform.
   */
  loadSubForm() {
    if (this.builderMode || this.isHidden()) {
      return NativePromise.resolve();
    }

    // Only load the subform if the subform isn't loaded and the conditions apply.
    if (this.subFormReady) {
      return this.subFormReady;
    }

    // Determine if we already have a loaded form object.
    if (
      this.formObj &&
      this.formObj.components &&
      Array.isArray(this.formObj.components) &&
      this.formObj.components.length
    ) {
      this.subFormReady = this.renderSubForm(this.formObj);
    }
    else if (this.formSrc) {
      this.subFormReady = (new Formio(this.formSrc)).loadForm({ params: { live: 1 } })
        .then((formObj) => {
          this.formObj = formObj;
          return this.renderSubForm(formObj);
        });
    }
    if (!this.subFormReady) {
      return new NativePromise(() => {});
    }
    return this.subFormReady.then(() => this.restoreValue());
  }

  checkComponentValidity(data, dirty) {
    if (this.subForm) {
      return this.subForm.checkValidity(this.dataValue.data, dirty);
    }

    return super.checkComponentValidity(data, dirty);
  }

  checkComponentConditions(data) {
    const visible = super.checkComponentConditions(data);

    // Return if already hidden
    if (!visible) {
      return visible;
    }

    if (this.subForm && this.subForm.hasCondition()) {
      return this.subForm.checkConditions(this.dataValue.data);
    }

    return visible;
  }

  calculateValue(data, flags) {
    if (this.subForm) {
      return this.subForm.calculateValue(this.dataValue.data, flags);
    }

    return super.calculateValue(data, flags);
  }

  setPristine(pristine) {
    super.setPristine(pristine);
    if (this.subForm) {
      this.subForm.setPristine(pristine);
    }
  }

  /**
   * Determine if the subform should be submitted.
   * @return {*|boolean}
   */
  get shouldSubmit() {
    return this.subFormReady && (!this.component.hasOwnProperty('reference') || this.component.reference);
  }

  /**
   * Returns the data for the subform.
   *
   * @return {*}
   */
  getSubFormData() {
    if (_.get(this.subForm, 'form.display') === 'pdf') {
      return this.subForm.getSubmission();
    }
    else {
      return NativePromise.resolve(this.dataValue);
    }
  }

  /**
   * Submit the subform if configured to do so.
   *
   * @return {*}
   */
  submitSubForm(rejectOnError) {
    // If we wish to submit the form on next page, then do that here.
    if (this.shouldSubmit) {
      return this.loadSubForm().then(() => {
        return this.subForm.submitForm().then(result => {
          this.subForm.loading = false;
          this.dataValue = result.submission;
          return this.dataValue;
        }).catch(err => {
          if (rejectOnError) {
            this.subForm.onSubmissionError(err);
            return NativePromise.reject(err);
          }
          else {
            return {};
          }
        });
      });
    }
    return this.getSubFormData();
  }

  /**
   * Submit the form before the next page is triggered.
   */
  beforePage(next) {
    return this.submitSubForm(true).then(() => super.beforePage(next));
  }

  /**
   * Submit the form before the whole form is triggered.
   */
  beforeSubmit() {
    const submission = this.dataValue;

    // This submission has already been submitted, so just return the reference data.
    if (submission && submission._id && submission.form) {
      this.dataValue = this.shouldSubmit ? {
        _id: submission._id,
        form: submission.form
      } : submission;
      return NativePromise.resolve(this.dataValue);
    }
    return this.submitSubForm(false)
      .then((data) => {
        if (data._id) {
          this.dataValue = {
            _id: data._id,
            form: data.form
          };
        }
        return this.dataValue;
      })
      .then(() => super.beforeSubmit());
  }

  isHidden() {
    if (!this.visible) {
      return true;
    }

    return !super.checkConditions(this.rootValue);
  }

  setValue(submission, flags) {
    const changed = super.setValue(submission, flags);
    if (this.subFormReady) {
      this.subFormReady.then((form) => {
        if (
          submission &&
          submission._id &&
          form.formio &&
          !flags.noload &&
          (_.isEmpty(submission.data) || this.shouldSubmit)
        ) {
          const submissionUrl = `${form.formio.formsUrl}/${submission.form}/submission/${submission._id}`;
          form.setUrl(submissionUrl, this.options);
          form.nosubmit = false;
          form.loadSubmission();
        }
        else {
          form.setValue(submission, flags);
        }
      });
    }
    return changed;
  }

  getValue() {
    if (this.subForm) {
      return this.subForm.getValue();
    }
    return this.dataValue;
  }

  getAllComponents() {
    if (!this.subForm) {
      return [];
    }
    return this.subForm.getAllComponents();
  }

  updateSubFormVisibility() {
    if (this.subForm) {
      this.subForm.parentVisible = this.visible;
    }
  }

  get visible() {
    return super.visible;
  }

  set visible(value) {
    super.visible = value;
    this.updateSubFormVisibility();
  }

  get parentVisible() {
    return super.parentVisible;
  }

  set parentVisible(value) {
    super.parentVisible = value;
    this.updateSubFormVisibility();
  }

  isInternalEvent(event) {
    switch (event) {
      case 'focus':
      case 'blur':
      case 'componentChange':
      case 'componentError':
      case 'error':
      case 'formLoad':
      case 'languageChanged':
      case 'render':
      case 'checkValidity':
      case 'initialized':
      case 'submit':
      case 'submitButton':
      case 'nosubmit':
      case 'updateComponent':
      case 'submitDone':
      case 'submissionDeleted':
      case 'requestDone':
      case 'nextPage':
      case 'prevPage':
      case 'wizardNavigationClicked':
      case 'updateWizardNav':
      case 'restoreDraft':
      case 'saveDraft':
      case 'saveComponent':
        return true;
      default:
        return false;
    }
  }

  createEmitter() {
    const emitter = new EventEmitter({
      wildcard: false,
      maxListeners: 0
    });
    const nativeEmit = emitter.emit;
    const that = this;
    emitter.emit = function(event, ...args) {
      const eventType = event.replace(`${that.options.namespace}.`, '');
      nativeEmit.call(this, event, ...args);
      if (!that.isInternalEvent(eventType)) {
        that.emit(eventType, ...args);
      }
    };

    return emitter;
  }

  deleteValue() {
    super.setValue(null, {
      noUpdateEvent: true,
      noDefault: true
    });
    _.unset(this.data, this.key);
  }
}
<|endoftext|>